Merged from the latest developing branch.
[MacVim/KaoriYa.git] / src / eval.c
blobe4024986e27bf364524b8c8d3742fb3f7c74d8a9
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(MSWIN)
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 */
36 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
37 * This avoids adding a pointer to the hashtab item.
38 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
39 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
40 * HI2DI() converts a hashitem pointer to a dictitem pointer.
42 static dictitem_T dumdi;
43 #define DI2HIKEY(di) ((di)->di_key)
44 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
45 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
48 * Structure returned by get_lval() and used by set_var_lval().
49 * For a plain name:
50 * "name" points to the variable name.
51 * "exp_name" is NULL.
52 * "tv" is NULL
53 * For a magic braces name:
54 * "name" points to the expanded variable name.
55 * "exp_name" is non-NULL, to be freed later.
56 * "tv" is NULL
57 * For an index in a list:
58 * "name" points to the (expanded) variable name.
59 * "exp_name" NULL or non-NULL, to be freed later.
60 * "tv" points to the (first) list item value
61 * "li" points to the (first) list item
62 * "range", "n1", "n2" and "empty2" indicate what items are used.
63 * For an existing Dict item:
64 * "name" points to the (expanded) variable name.
65 * "exp_name" NULL or non-NULL, to be freed later.
66 * "tv" points to the dict item value
67 * "newkey" is NULL
68 * For a non-existing Dict item:
69 * "name" points to the (expanded) variable name.
70 * "exp_name" NULL or non-NULL, to be freed later.
71 * "tv" points to the Dictionary typval_T
72 * "newkey" is the key for the new item.
74 typedef struct lval_S
76 char_u *ll_name; /* start of variable name (can be NULL) */
77 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
78 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
79 isn't NULL it's the Dict to which to add
80 the item. */
81 listitem_T *ll_li; /* The list item or NULL. */
82 list_T *ll_list; /* The list or NULL. */
83 int ll_range; /* TRUE when a [i:j] range was used */
84 long ll_n1; /* First index for list */
85 long ll_n2; /* Second index for list range */
86 int ll_empty2; /* Second index is empty: [i:] */
87 dict_T *ll_dict; /* The Dictionary or NULL */
88 dictitem_T *ll_di; /* The dictitem or NULL */
89 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
90 } lval_T;
93 static char *e_letunexp = N_("E18: Unexpected characters in :let");
94 static char *e_listidx = N_("E684: list index out of range: %ld");
95 static char *e_undefvar = N_("E121: Undefined variable: %s");
96 static char *e_missbrac = N_("E111: Missing ']'");
97 static char *e_listarg = N_("E686: Argument of %s must be a List");
98 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
99 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
100 static char *e_listreq = N_("E714: List required");
101 static char *e_dictreq = N_("E715: Dictionary required");
102 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
103 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
104 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
105 static char *e_funcdict = N_("E717: Dictionary entry already exists");
106 static char *e_funcref = N_("E718: Funcref required");
107 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
108 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
109 static char *e_nofunc = N_("E130: Unknown function: %s");
110 static char *e_illvar = N_("E461: Illegal variable name: %s");
113 * All user-defined global variables are stored in dictionary "globvardict".
114 * "globvars_var" is the variable that is used for "g:".
116 static dict_T globvardict;
117 static dictitem_T globvars_var;
118 #define globvarht globvardict.dv_hashtab
121 * Old Vim variables such as "v:version" are also available without the "v:".
122 * Also in functions. We need a special hashtable for them.
124 static hashtab_T compat_hashtab;
127 * When recursively copying lists and dicts we need to remember which ones we
128 * have done to avoid endless recursiveness. This unique ID is used for that.
130 static int current_copyID = 0;
133 * Array to hold the hashtab with variables local to each sourced script.
134 * Each item holds a variable (nameless) that points to the dict_T.
136 typedef struct
138 dictitem_T sv_var;
139 dict_T sv_dict;
140 } scriptvar_T;
142 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T), 4, NULL};
143 #define SCRIPT_SV(id) (((scriptvar_T *)ga_scripts.ga_data)[(id) - 1])
144 #define SCRIPT_VARS(id) (SCRIPT_SV(id).sv_dict.dv_hashtab)
146 static int echo_attr = 0; /* attributes used for ":echo" */
148 /* Values for trans_function_name() argument: */
149 #define TFN_INT 1 /* internal function name OK */
150 #define TFN_QUIET 2 /* no error messages */
153 * Structure to hold info for a user function.
155 typedef struct ufunc ufunc_T;
157 struct ufunc
159 int uf_varargs; /* variable nr of arguments */
160 int uf_flags;
161 int uf_calls; /* nr of active calls */
162 garray_T uf_args; /* arguments */
163 garray_T uf_lines; /* function lines */
164 #ifdef FEAT_PROFILE
165 int uf_profiling; /* TRUE when func is being profiled */
166 /* profiling the function as a whole */
167 int uf_tm_count; /* nr of calls */
168 proftime_T uf_tm_total; /* time spent in function + children */
169 proftime_T uf_tm_self; /* time spent in function itself */
170 proftime_T uf_tm_children; /* time spent in children this call */
171 /* profiling the function per line */
172 int *uf_tml_count; /* nr of times line was executed */
173 proftime_T *uf_tml_total; /* time spent in a line + children */
174 proftime_T *uf_tml_self; /* time spent in a line itself */
175 proftime_T uf_tml_start; /* start time for current line */
176 proftime_T uf_tml_children; /* time spent in children for this line */
177 proftime_T uf_tml_wait; /* start wait time for current line */
178 int uf_tml_idx; /* index of line being timed; -1 if none */
179 int uf_tml_execed; /* line being timed was executed */
180 #endif
181 scid_T uf_script_ID; /* ID of script where function was defined,
182 used for s: variables */
183 int uf_refcount; /* for numbered function: reference count */
184 char_u uf_name[1]; /* name of function (actually longer); can
185 start with <SNR>123_ (<SNR> is K_SPECIAL
186 KS_EXTRA KE_SNR) */
189 /* function flags */
190 #define FC_ABORT 1 /* abort function on error */
191 #define FC_RANGE 2 /* function accepts range */
192 #define FC_DICT 4 /* Dict function, uses "self" */
195 * All user-defined functions are found in this hashtable.
197 static hashtab_T func_hashtab;
199 /* The names of packages that once were loaded are remembered. */
200 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
202 /* list heads for garbage collection */
203 static dict_T *first_dict = NULL; /* list of all dicts */
204 static list_T *first_list = NULL; /* list of all lists */
206 /* From user function to hashitem and back. */
207 static ufunc_T dumuf;
208 #define UF2HIKEY(fp) ((fp)->uf_name)
209 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
210 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
212 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
213 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
215 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
216 #define VAR_SHORT_LEN 20 /* short variable name length */
217 #define FIXVAR_CNT 12 /* number of fixed variables */
219 /* structure to hold info for a function that is currently being executed. */
220 typedef struct funccall_S funccall_T;
222 struct funccall_S
224 ufunc_T *func; /* function being called */
225 int linenr; /* next line to be executed */
226 int returned; /* ":return" used */
227 struct /* fixed variables for arguments */
229 dictitem_T var; /* variable (without room for name) */
230 char_u room[VAR_SHORT_LEN]; /* room for the name */
231 } fixvar[FIXVAR_CNT];
232 dict_T l_vars; /* l: local function variables */
233 dictitem_T l_vars_var; /* variable for l: scope */
234 dict_T l_avars; /* a: argument variables */
235 dictitem_T l_avars_var; /* variable for a: scope */
236 list_T l_varlist; /* list for a:000 */
237 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
238 typval_T *rettv; /* return value */
239 linenr_T breakpoint; /* next line with breakpoint or zero */
240 int dbg_tick; /* debug_tick when breakpoint was set */
241 int level; /* top nesting level of executed function */
242 #ifdef FEAT_PROFILE
243 proftime_T prof_child; /* time spent in a child */
244 #endif
245 funccall_T *caller; /* calling function or NULL */
249 * Info used by a ":for" loop.
251 typedef struct
253 int fi_semicolon; /* TRUE if ending in '; var]' */
254 int fi_varcount; /* nr of variables in the list */
255 listwatch_T fi_lw; /* keep an eye on the item used. */
256 list_T *fi_list; /* list being used */
257 } forinfo_T;
260 * Struct used by trans_function_name()
262 typedef struct
264 dict_T *fd_dict; /* Dictionary used */
265 char_u *fd_newkey; /* new key in "dict" in allocated memory */
266 dictitem_T *fd_di; /* Dictionary item used */
267 } funcdict_T;
271 * Array to hold the value of v: variables.
272 * The value is in a dictitem, so that it can also be used in the v: scope.
273 * The reason to use this table anyway is for very quick access to the
274 * variables with the VV_ defines.
276 #include "version.h"
278 /* values for vv_flags: */
279 #define VV_COMPAT 1 /* compatible, also used without "v:" */
280 #define VV_RO 2 /* read-only */
281 #define VV_RO_SBX 4 /* read-only in the sandbox */
283 #define VV_NAME(s, t) s, {{t}}, {0}
285 static struct vimvar
287 char *vv_name; /* name of variable, without v: */
288 dictitem_T vv_di; /* value and name for key */
289 char vv_filler[16]; /* space for LONGEST name below!!! */
290 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
291 } vimvars[VV_LEN] =
294 * The order here must match the VV_ defines in vim.h!
295 * Initializing a union does not work, leave tv.vval empty to get zero's.
297 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
298 {VV_NAME("count1", VAR_NUMBER), VV_RO},
299 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
300 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
301 {VV_NAME("warningmsg", VAR_STRING), 0},
302 {VV_NAME("statusmsg", VAR_STRING), 0},
303 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
304 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
305 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
306 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
307 {VV_NAME("termresponse", VAR_STRING), VV_RO},
308 {VV_NAME("fname", VAR_STRING), VV_RO},
309 {VV_NAME("lang", VAR_STRING), VV_RO},
310 {VV_NAME("lc_time", VAR_STRING), VV_RO},
311 {VV_NAME("ctype", VAR_STRING), VV_RO},
312 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
313 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
314 {VV_NAME("fname_in", VAR_STRING), VV_RO},
315 {VV_NAME("fname_out", VAR_STRING), VV_RO},
316 {VV_NAME("fname_new", VAR_STRING), VV_RO},
317 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
318 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
319 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
320 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
321 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
322 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
323 {VV_NAME("progname", VAR_STRING), VV_RO},
324 {VV_NAME("servername", VAR_STRING), VV_RO},
325 {VV_NAME("dying", VAR_NUMBER), VV_RO},
326 {VV_NAME("exception", VAR_STRING), VV_RO},
327 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
328 {VV_NAME("register", VAR_STRING), VV_RO},
329 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
330 {VV_NAME("insertmode", VAR_STRING), VV_RO},
331 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
332 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
333 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
334 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
335 {VV_NAME("fcs_choice", VAR_STRING), 0},
336 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
337 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
338 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
339 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
340 {VV_NAME("beval_text", VAR_STRING), VV_RO},
341 {VV_NAME("scrollstart", VAR_STRING), 0},
342 {VV_NAME("swapname", VAR_STRING), VV_RO},
343 {VV_NAME("swapchoice", VAR_STRING), 0},
344 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
345 {VV_NAME("char", VAR_STRING), VV_RO},
346 {VV_NAME("mouse_win", VAR_NUMBER), 0},
347 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
348 {VV_NAME("mouse_col", VAR_NUMBER), 0},
349 {VV_NAME("operator", VAR_STRING), VV_RO},
350 {VV_NAME("searchforward", VAR_NUMBER), 0},
353 /* shorthand */
354 #define vv_type vv_di.di_tv.v_type
355 #define vv_nr vv_di.di_tv.vval.v_number
356 #define vv_float vv_di.di_tv.vval.v_float
357 #define vv_str vv_di.di_tv.vval.v_string
358 #define vv_tv vv_di.di_tv
361 * The v: variables are stored in dictionary "vimvardict".
362 * "vimvars_var" is the variable that is used for the "l:" scope.
364 static dict_T vimvardict;
365 static dictitem_T vimvars_var;
366 #define vimvarht vimvardict.dv_hashtab
368 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
369 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
370 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
371 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
372 #endif
373 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
374 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
375 static char_u *skip_var_one __ARGS((char_u *arg));
376 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
377 static void list_glob_vars __ARGS((int *first));
378 static void list_buf_vars __ARGS((int *first));
379 static void list_win_vars __ARGS((int *first));
380 #ifdef FEAT_WINDOWS
381 static void list_tab_vars __ARGS((int *first));
382 #endif
383 static void list_vim_vars __ARGS((int *first));
384 static void list_script_vars __ARGS((int *first));
385 static void list_func_vars __ARGS((int *first));
386 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
387 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
388 static int check_changedtick __ARGS((char_u *arg));
389 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
390 static void clear_lval __ARGS((lval_T *lp));
391 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
392 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
393 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
394 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
395 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
396 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
397 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
398 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
399 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
400 static int tv_islocked __ARGS((typval_T *tv));
402 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
403 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
404 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
405 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
406 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
407 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
408 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
409 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
411 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
412 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
414 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int rettv_list_alloc __ARGS((typval_T *rettv));
417 static listitem_T *listitem_alloc __ARGS((void));
418 static void listitem_free __ARGS((listitem_T *item));
419 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
420 static long list_len __ARGS((list_T *l));
421 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
422 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
423 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
424 static listitem_T *list_find __ARGS((list_T *l, long n));
425 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
426 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
427 static void list_append __ARGS((list_T *l, listitem_T *item));
428 static int list_append_tv __ARGS((list_T *l, typval_T *tv));
429 static int list_append_string __ARGS((list_T *l, char_u *str, int len));
430 static int list_append_number __ARGS((list_T *l, varnumber_T n));
431 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
432 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
433 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
434 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
435 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
436 static char_u *list2string __ARGS((typval_T *tv, int copyID));
437 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
438 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
439 static void set_ref_in_list __ARGS((list_T *l, int copyID));
440 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
441 static void dict_unref __ARGS((dict_T *d));
442 static void dict_free __ARGS((dict_T *d, int recurse));
443 static dictitem_T *dictitem_alloc __ARGS((char_u *key));
444 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
445 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
446 static void dictitem_free __ARGS((dictitem_T *item));
447 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
448 static int dict_add __ARGS((dict_T *d, dictitem_T *item));
449 static long dict_len __ARGS((dict_T *d));
450 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
451 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
452 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
453 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
454 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
455 static char_u *string_quote __ARGS((char_u *str, int function));
456 #ifdef FEAT_FLOAT
457 static int string2float __ARGS((char_u *text, float_T *value));
458 #endif
459 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
460 static int find_internal_func __ARGS((char_u *name));
461 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
462 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));
463 static int call_func __ARGS((char_u *name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
464 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
466 #ifdef FEAT_FLOAT
467 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
468 #endif
469 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
470 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
471 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
472 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
473 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
474 #ifdef FEAT_FLOAT
475 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
476 #endif
477 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
478 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
481 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
484 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
488 #ifdef FEAT_FLOAT
489 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
490 #endif
491 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
494 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
495 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
496 #if defined(FEAT_INS_EXPAND)
497 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
500 #endif
501 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
503 #ifdef FEAT_FLOAT
504 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
505 #endif
506 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
508 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
509 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
510 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
511 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
516 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
517 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
520 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
521 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
523 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
524 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
525 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
526 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
528 #ifdef FEAT_FLOAT
529 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
531 #endif
532 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
548 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
549 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
551 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
552 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
603 #ifdef FEAT_FLOAT
604 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
605 #endif
606 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
618 #ifdef vim_mkdir
619 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
620 #endif
621 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
623 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
624 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
625 #ifdef FEAT_FLOAT
626 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
627 #endif
628 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
638 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
639 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
640 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
641 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
642 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
643 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
644 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
645 #ifdef FEAT_FLOAT
646 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
647 #endif
648 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
649 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
650 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
651 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
667 #ifdef FEAT_FLOAT
668 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
669 #endif
670 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
671 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
675 #ifdef FEAT_FLOAT
676 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
678 #endif
679 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
680 #ifdef HAVE_STRFTIME
681 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
682 #endif
683 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
690 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
691 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
692 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
693 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
698 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
699 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
701 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
702 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
703 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
704 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
705 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
706 #ifdef FEAT_FLOAT
707 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
708 #endif
709 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
724 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
725 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
726 static int get_env_len __ARGS((char_u **arg));
727 static int get_id_len __ARGS((char_u **arg));
728 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
729 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
730 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
731 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
732 valid character */
733 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
734 static int eval_isnamec __ARGS((int c));
735 static int eval_isnamec1 __ARGS((int c));
736 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
737 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
738 static typval_T *alloc_tv __ARGS((void));
739 static typval_T *alloc_string_tv __ARGS((char_u *string));
740 static void init_tv __ARGS((typval_T *varp));
741 static long get_tv_number __ARGS((typval_T *varp));
742 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
743 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
744 static char_u *get_tv_string __ARGS((typval_T *varp));
745 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
746 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
747 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
748 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
749 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
750 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
751 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
752 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
753 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
754 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
755 static int var_check_ro __ARGS((int flags, char_u *name));
756 static int var_check_fixed __ARGS((int flags, char_u *name));
757 static int tv_check_lock __ARGS((int lock, char_u *name));
758 static void copy_tv __ARGS((typval_T *from, typval_T *to));
759 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
760 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
761 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
762 static int eval_fname_script __ARGS((char_u *p));
763 static int eval_fname_sid __ARGS((char_u *p));
764 static void list_func_head __ARGS((ufunc_T *fp, int indent));
765 static ufunc_T *find_func __ARGS((char_u *name));
766 static int function_exists __ARGS((char_u *name));
767 static int builtin_function __ARGS((char_u *name));
768 #ifdef FEAT_PROFILE
769 static void func_do_profile __ARGS((ufunc_T *fp));
770 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
771 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
772 static int
773 # ifdef __BORLANDC__
774 _RTLENTRYF
775 # endif
776 prof_total_cmp __ARGS((const void *s1, const void *s2));
777 static int
778 # ifdef __BORLANDC__
779 _RTLENTRYF
780 # endif
781 prof_self_cmp __ARGS((const void *s1, const void *s2));
782 #endif
783 static int script_autoload __ARGS((char_u *name, int reload));
784 static char_u *autoload_name __ARGS((char_u *name));
785 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
786 static void func_free __ARGS((ufunc_T *fp));
787 static void func_unref __ARGS((char_u *name));
788 static void func_ref __ARGS((char_u *name));
789 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));
790 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
791 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
792 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
793 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
794 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
795 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
797 /* Character used as separated in autoload function/variable names. */
798 #define AUTOLOAD_CHAR '#'
801 * Initialize the global and v: variables.
803 void
804 eval_init()
806 int i;
807 struct vimvar *p;
809 init_var_dict(&globvardict, &globvars_var);
810 init_var_dict(&vimvardict, &vimvars_var);
811 hash_init(&compat_hashtab);
812 hash_init(&func_hashtab);
814 for (i = 0; i < VV_LEN; ++i)
816 p = &vimvars[i];
817 STRCPY(p->vv_di.di_key, p->vv_name);
818 if (p->vv_flags & VV_RO)
819 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
820 else if (p->vv_flags & VV_RO_SBX)
821 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
822 else
823 p->vv_di.di_flags = DI_FLAGS_FIX;
825 /* add to v: scope dict, unless the value is not always available */
826 if (p->vv_type != VAR_UNKNOWN)
827 hash_add(&vimvarht, p->vv_di.di_key);
828 if (p->vv_flags & VV_COMPAT)
829 /* add to compat scope dict */
830 hash_add(&compat_hashtab, p->vv_di.di_key);
832 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
835 #if defined(EXITFREE) || defined(PROTO)
836 void
837 eval_clear()
839 int i;
840 struct vimvar *p;
842 for (i = 0; i < VV_LEN; ++i)
844 p = &vimvars[i];
845 if (p->vv_di.di_tv.v_type == VAR_STRING)
847 vim_free(p->vv_di.di_tv.vval.v_string);
848 p->vv_di.di_tv.vval.v_string = NULL;
851 hash_clear(&vimvarht);
852 hash_clear(&compat_hashtab);
854 /* script-local variables */
855 for (i = 1; i <= ga_scripts.ga_len; ++i)
856 vars_clear(&SCRIPT_VARS(i));
857 ga_clear(&ga_scripts);
858 free_scriptnames();
860 /* global variables */
861 vars_clear(&globvarht);
863 /* autoloaded script names */
864 ga_clear_strings(&ga_loaded);
866 /* unreferenced lists and dicts */
867 (void)garbage_collect();
869 /* functions */
870 free_all_functions();
871 hash_clear(&func_hashtab);
873 #endif
876 * Return the name of the executed function.
878 char_u *
879 func_name(cookie)
880 void *cookie;
882 return ((funccall_T *)cookie)->func->uf_name;
886 * Return the address holding the next breakpoint line for a funccall cookie.
888 linenr_T *
889 func_breakpoint(cookie)
890 void *cookie;
892 return &((funccall_T *)cookie)->breakpoint;
896 * Return the address holding the debug tick for a funccall cookie.
898 int *
899 func_dbg_tick(cookie)
900 void *cookie;
902 return &((funccall_T *)cookie)->dbg_tick;
906 * Return the nesting level for a funccall cookie.
909 func_level(cookie)
910 void *cookie;
912 return ((funccall_T *)cookie)->level;
915 /* pointer to funccal for currently active function */
916 funccall_T *current_funccal = NULL;
919 * Return TRUE when a function was ended by a ":return" command.
922 current_func_returned()
924 return current_funccal->returned;
929 * Set an internal variable to a string value. Creates the variable if it does
930 * not already exist.
932 void
933 set_internal_string_var(name, value)
934 char_u *name;
935 char_u *value;
937 char_u *val;
938 typval_T *tvp;
940 val = vim_strsave(value);
941 if (val != NULL)
943 tvp = alloc_string_tv(val);
944 if (tvp != NULL)
946 set_var(name, tvp, FALSE);
947 free_tv(tvp);
952 static lval_T *redir_lval = NULL;
953 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
954 static char_u *redir_endp = NULL;
955 static char_u *redir_varname = NULL;
958 * Start recording command output to a variable
959 * Returns OK if successfully completed the setup. FAIL otherwise.
962 var_redir_start(name, append)
963 char_u *name;
964 int append; /* append to an existing variable */
966 int save_emsg;
967 int err;
968 typval_T tv;
970 /* Make sure a valid variable name is specified */
971 if (!eval_isnamec1(*name))
973 EMSG(_(e_invarg));
974 return FAIL;
977 redir_varname = vim_strsave(name);
978 if (redir_varname == NULL)
979 return FAIL;
981 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
982 if (redir_lval == NULL)
984 var_redir_stop();
985 return FAIL;
988 /* The output is stored in growarray "redir_ga" until redirection ends. */
989 ga_init2(&redir_ga, (int)sizeof(char), 500);
991 /* Parse the variable name (can be a dict or list entry). */
992 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
993 FNE_CHECK_START);
994 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
996 if (redir_endp != NULL && *redir_endp != NUL)
997 /* Trailing characters are present after the variable name */
998 EMSG(_(e_trailing));
999 else
1000 EMSG(_(e_invarg));
1001 var_redir_stop();
1002 return FAIL;
1005 /* check if we can write to the variable: set it to or append an empty
1006 * string */
1007 save_emsg = did_emsg;
1008 did_emsg = FALSE;
1009 tv.v_type = VAR_STRING;
1010 tv.vval.v_string = (char_u *)"";
1011 if (append)
1012 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1013 else
1014 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1015 err = did_emsg;
1016 did_emsg |= save_emsg;
1017 if (err)
1019 var_redir_stop();
1020 return FAIL;
1022 if (redir_lval->ll_newkey != NULL)
1024 /* Dictionary item was created, don't do it again. */
1025 vim_free(redir_lval->ll_newkey);
1026 redir_lval->ll_newkey = NULL;
1029 return OK;
1033 * Append "value[value_len]" to the variable set by var_redir_start().
1034 * The actual appending is postponed until redirection ends, because the value
1035 * appended may in fact be the string we write to, changing it may cause freed
1036 * memory to be used:
1037 * :redir => foo
1038 * :let foo
1039 * :redir END
1041 void
1042 var_redir_str(value, value_len)
1043 char_u *value;
1044 int value_len;
1046 int len;
1048 if (redir_lval == NULL)
1049 return;
1051 if (value_len == -1)
1052 len = (int)STRLEN(value); /* Append the entire string */
1053 else
1054 len = value_len; /* Append only "value_len" characters */
1056 if (ga_grow(&redir_ga, len) == OK)
1058 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1059 redir_ga.ga_len += len;
1061 else
1062 var_redir_stop();
1066 * Stop redirecting command output to a variable.
1068 void
1069 var_redir_stop()
1071 typval_T tv;
1073 if (redir_lval != NULL)
1075 /* Append the trailing NUL. */
1076 ga_append(&redir_ga, NUL);
1078 /* Assign the text to the variable. */
1079 tv.v_type = VAR_STRING;
1080 tv.vval.v_string = redir_ga.ga_data;
1081 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1082 vim_free(tv.vval.v_string);
1084 clear_lval(redir_lval);
1085 vim_free(redir_lval);
1086 redir_lval = NULL;
1088 vim_free(redir_varname);
1089 redir_varname = NULL;
1092 # if defined(FEAT_MBYTE) || defined(PROTO)
1094 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1095 char_u *enc_from;
1096 char_u *enc_to;
1097 char_u *fname_from;
1098 char_u *fname_to;
1100 int err = FALSE;
1102 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1103 set_vim_var_string(VV_CC_TO, enc_to, -1);
1104 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1105 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1106 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1107 err = TRUE;
1108 set_vim_var_string(VV_CC_FROM, NULL, -1);
1109 set_vim_var_string(VV_CC_TO, NULL, -1);
1110 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1111 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1113 if (err)
1114 return FAIL;
1115 return OK;
1117 # endif
1119 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1121 eval_printexpr(fname, args)
1122 char_u *fname;
1123 char_u *args;
1125 int err = FALSE;
1127 set_vim_var_string(VV_FNAME_IN, fname, -1);
1128 set_vim_var_string(VV_CMDARG, args, -1);
1129 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1130 err = TRUE;
1131 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1132 set_vim_var_string(VV_CMDARG, NULL, -1);
1134 if (err)
1136 mch_remove(fname);
1137 return FAIL;
1139 return OK;
1141 # endif
1143 # if defined(FEAT_DIFF) || defined(PROTO)
1144 void
1145 eval_diff(origfile, newfile, outfile)
1146 char_u *origfile;
1147 char_u *newfile;
1148 char_u *outfile;
1150 int err = FALSE;
1152 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1153 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1154 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1155 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1156 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1157 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1158 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1161 void
1162 eval_patch(origfile, difffile, outfile)
1163 char_u *origfile;
1164 char_u *difffile;
1165 char_u *outfile;
1167 int err;
1169 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1170 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1171 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1172 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1173 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1174 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1175 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1177 # endif
1180 * Top level evaluation function, returning a boolean.
1181 * Sets "error" to TRUE if there was an error.
1182 * Return TRUE or FALSE.
1185 eval_to_bool(arg, error, nextcmd, skip)
1186 char_u *arg;
1187 int *error;
1188 char_u **nextcmd;
1189 int skip; /* only parse, don't execute */
1191 typval_T tv;
1192 int retval = FALSE;
1194 if (skip)
1195 ++emsg_skip;
1196 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1197 *error = TRUE;
1198 else
1200 *error = FALSE;
1201 if (!skip)
1203 retval = (get_tv_number_chk(&tv, error) != 0);
1204 clear_tv(&tv);
1207 if (skip)
1208 --emsg_skip;
1210 return retval;
1214 * Top level evaluation function, returning a string. If "skip" is TRUE,
1215 * only parsing to "nextcmd" is done, without reporting errors. Return
1216 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1218 char_u *
1219 eval_to_string_skip(arg, nextcmd, skip)
1220 char_u *arg;
1221 char_u **nextcmd;
1222 int skip; /* only parse, don't execute */
1224 typval_T tv;
1225 char_u *retval;
1227 if (skip)
1228 ++emsg_skip;
1229 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1230 retval = NULL;
1231 else
1233 retval = vim_strsave(get_tv_string(&tv));
1234 clear_tv(&tv);
1236 if (skip)
1237 --emsg_skip;
1239 return retval;
1243 * Skip over an expression at "*pp".
1244 * Return FAIL for an error, OK otherwise.
1247 skip_expr(pp)
1248 char_u **pp;
1250 typval_T rettv;
1252 *pp = skipwhite(*pp);
1253 return eval1(pp, &rettv, FALSE);
1257 * Top level evaluation function, returning a string.
1258 * Return pointer to allocated memory, or NULL for failure.
1260 char_u *
1261 eval_to_string(arg, nextcmd, dolist)
1262 char_u *arg;
1263 char_u **nextcmd;
1264 int dolist; /* turn List into sequence of lines */
1266 typval_T tv;
1267 char_u *retval;
1268 garray_T ga;
1270 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1271 retval = NULL;
1272 else
1274 if (dolist && tv.v_type == VAR_LIST)
1276 ga_init2(&ga, (int)sizeof(char), 80);
1277 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1278 ga_append(&ga, NUL);
1279 retval = (char_u *)ga.ga_data;
1281 else
1282 retval = vim_strsave(get_tv_string(&tv));
1283 clear_tv(&tv);
1286 return retval;
1290 * Call eval_to_string() without using current local variables and using
1291 * textlock. When "use_sandbox" is TRUE use the sandbox.
1293 char_u *
1294 eval_to_string_safe(arg, nextcmd, use_sandbox)
1295 char_u *arg;
1296 char_u **nextcmd;
1297 int use_sandbox;
1299 char_u *retval;
1300 void *save_funccalp;
1302 save_funccalp = save_funccal();
1303 if (use_sandbox)
1304 ++sandbox;
1305 ++textlock;
1306 retval = eval_to_string(arg, nextcmd, FALSE);
1307 if (use_sandbox)
1308 --sandbox;
1309 --textlock;
1310 restore_funccal(save_funccalp);
1311 return retval;
1315 * Top level evaluation function, returning a number.
1316 * Evaluates "expr" silently.
1317 * Returns -1 for an error.
1320 eval_to_number(expr)
1321 char_u *expr;
1323 typval_T rettv;
1324 int retval;
1325 char_u *p = skipwhite(expr);
1327 ++emsg_off;
1329 if (eval1(&p, &rettv, TRUE) == FAIL)
1330 retval = -1;
1331 else
1333 retval = get_tv_number_chk(&rettv, NULL);
1334 clear_tv(&rettv);
1336 --emsg_off;
1338 return retval;
1342 * Prepare v: variable "idx" to be used.
1343 * Save the current typeval in "save_tv".
1344 * When not used yet add the variable to the v: hashtable.
1346 static void
1347 prepare_vimvar(idx, save_tv)
1348 int idx;
1349 typval_T *save_tv;
1351 *save_tv = vimvars[idx].vv_tv;
1352 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1353 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1357 * Restore v: variable "idx" to typeval "save_tv".
1358 * When no longer defined, remove the variable from the v: hashtable.
1360 static void
1361 restore_vimvar(idx, save_tv)
1362 int idx;
1363 typval_T *save_tv;
1365 hashitem_T *hi;
1367 vimvars[idx].vv_tv = *save_tv;
1368 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1370 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1371 if (HASHITEM_EMPTY(hi))
1372 EMSG2(_(e_intern2), "restore_vimvar()");
1373 else
1374 hash_remove(&vimvarht, hi);
1378 #if defined(FEAT_SPELL) || defined(PROTO)
1380 * Evaluate an expression to a list with suggestions.
1381 * For the "expr:" part of 'spellsuggest'.
1383 list_T *
1384 eval_spell_expr(badword, expr)
1385 char_u *badword;
1386 char_u *expr;
1388 typval_T save_val;
1389 typval_T rettv;
1390 list_T *list = NULL;
1391 char_u *p = skipwhite(expr);
1393 /* Set "v:val" to the bad word. */
1394 prepare_vimvar(VV_VAL, &save_val);
1395 vimvars[VV_VAL].vv_type = VAR_STRING;
1396 vimvars[VV_VAL].vv_str = badword;
1397 if (p_verbose == 0)
1398 ++emsg_off;
1400 if (eval1(&p, &rettv, TRUE) == OK)
1402 if (rettv.v_type != VAR_LIST)
1403 clear_tv(&rettv);
1404 else
1405 list = rettv.vval.v_list;
1408 if (p_verbose == 0)
1409 --emsg_off;
1410 restore_vimvar(VV_VAL, &save_val);
1412 return list;
1416 * "list" is supposed to contain two items: a word and a number. Return the
1417 * word in "pp" and the number as the return value.
1418 * Return -1 if anything isn't right.
1419 * Used to get the good word and score from the eval_spell_expr() result.
1422 get_spellword(list, pp)
1423 list_T *list;
1424 char_u **pp;
1426 listitem_T *li;
1428 li = list->lv_first;
1429 if (li == NULL)
1430 return -1;
1431 *pp = get_tv_string(&li->li_tv);
1433 li = li->li_next;
1434 if (li == NULL)
1435 return -1;
1436 return get_tv_number(&li->li_tv);
1438 #endif
1441 * Top level evaluation function.
1442 * Returns an allocated typval_T with the result.
1443 * Returns NULL when there is an error.
1445 typval_T *
1446 eval_expr(arg, nextcmd)
1447 char_u *arg;
1448 char_u **nextcmd;
1450 typval_T *tv;
1452 tv = (typval_T *)alloc(sizeof(typval_T));
1453 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1455 vim_free(tv);
1456 tv = NULL;
1459 return tv;
1463 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1464 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1466 * Call some vimL function and return the result in "*rettv".
1467 * Uses argv[argc] for the function arguments. Only Number and String
1468 * arguments are currently supported.
1469 * Returns OK or FAIL.
1471 static int
1472 call_vim_function(func, argc, argv, safe, rettv)
1473 char_u *func;
1474 int argc;
1475 char_u **argv;
1476 int safe; /* use the sandbox */
1477 typval_T *rettv;
1479 typval_T *argvars;
1480 long n;
1481 int len;
1482 int i;
1483 int doesrange;
1484 void *save_funccalp = NULL;
1485 int ret;
1487 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1488 if (argvars == NULL)
1489 return FAIL;
1491 for (i = 0; i < argc; i++)
1493 /* Pass a NULL or empty argument as an empty string */
1494 if (argv[i] == NULL || *argv[i] == NUL)
1496 argvars[i].v_type = VAR_STRING;
1497 argvars[i].vval.v_string = (char_u *)"";
1498 continue;
1501 /* Recognize a number argument, the others must be strings. */
1502 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1503 if (len != 0 && len == (int)STRLEN(argv[i]))
1505 argvars[i].v_type = VAR_NUMBER;
1506 argvars[i].vval.v_number = n;
1508 else
1510 argvars[i].v_type = VAR_STRING;
1511 argvars[i].vval.v_string = argv[i];
1515 if (safe)
1517 save_funccalp = save_funccal();
1518 ++sandbox;
1521 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1522 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1523 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1524 &doesrange, TRUE, NULL);
1525 if (safe)
1527 --sandbox;
1528 restore_funccal(save_funccalp);
1530 vim_free(argvars);
1532 if (ret == FAIL)
1533 clear_tv(rettv);
1535 return ret;
1538 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1540 * Call vimL function "func" and return the result as a string.
1541 * Returns NULL when calling the function fails.
1542 * Uses argv[argc] for the function arguments.
1544 void *
1545 call_func_retstr(func, argc, argv, safe)
1546 char_u *func;
1547 int argc;
1548 char_u **argv;
1549 int safe; /* use the sandbox */
1551 typval_T rettv;
1552 char_u *retval;
1554 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1555 return NULL;
1557 retval = vim_strsave(get_tv_string(&rettv));
1558 clear_tv(&rettv);
1559 return retval;
1561 # endif
1563 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1565 * Call vimL function "func" and return the result as a number.
1566 * Returns -1 when calling the function fails.
1567 * Uses argv[argc] for the function arguments.
1569 long
1570 call_func_retnr(func, argc, argv, safe)
1571 char_u *func;
1572 int argc;
1573 char_u **argv;
1574 int safe; /* use the sandbox */
1576 typval_T rettv;
1577 long retval;
1579 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1580 return -1;
1582 retval = get_tv_number_chk(&rettv, NULL);
1583 clear_tv(&rettv);
1584 return retval;
1586 # endif
1589 * Call vimL function "func" and return the result as a list
1590 * Uses argv[argc] for the function arguments.
1592 void *
1593 call_func_retlist(func, argc, argv, safe)
1594 char_u *func;
1595 int argc;
1596 char_u **argv;
1597 int safe; /* use the sandbox */
1599 typval_T rettv;
1601 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1602 return NULL;
1604 if (rettv.v_type != VAR_LIST)
1606 clear_tv(&rettv);
1607 return NULL;
1610 return rettv.vval.v_list;
1612 #endif
1616 * Save the current function call pointer, and set it to NULL.
1617 * Used when executing autocommands and for ":source".
1619 void *
1620 save_funccal()
1622 funccall_T *fc = current_funccal;
1624 current_funccal = NULL;
1625 return (void *)fc;
1628 void
1629 restore_funccal(vfc)
1630 void *vfc;
1632 funccall_T *fc = (funccall_T *)vfc;
1634 current_funccal = fc;
1637 #if defined(FEAT_PROFILE) || defined(PROTO)
1639 * Prepare profiling for entering a child or something else that is not
1640 * counted for the script/function itself.
1641 * Should always be called in pair with prof_child_exit().
1643 void
1644 prof_child_enter(tm)
1645 proftime_T *tm; /* place to store waittime */
1647 funccall_T *fc = current_funccal;
1649 if (fc != NULL && fc->func->uf_profiling)
1650 profile_start(&fc->prof_child);
1651 script_prof_save(tm);
1655 * Take care of time spent in a child.
1656 * Should always be called after prof_child_enter().
1658 void
1659 prof_child_exit(tm)
1660 proftime_T *tm; /* where waittime was stored */
1662 funccall_T *fc = current_funccal;
1664 if (fc != NULL && fc->func->uf_profiling)
1666 profile_end(&fc->prof_child);
1667 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1668 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1669 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1671 script_prof_restore(tm);
1673 #endif
1676 #ifdef FEAT_FOLDING
1678 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1679 * it in "*cp". Doesn't give error messages.
1682 eval_foldexpr(arg, cp)
1683 char_u *arg;
1684 int *cp;
1686 typval_T tv;
1687 int retval;
1688 char_u *s;
1689 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1690 OPT_LOCAL);
1692 ++emsg_off;
1693 if (use_sandbox)
1694 ++sandbox;
1695 ++textlock;
1696 *cp = NUL;
1697 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1698 retval = 0;
1699 else
1701 /* If the result is a number, just return the number. */
1702 if (tv.v_type == VAR_NUMBER)
1703 retval = tv.vval.v_number;
1704 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1705 retval = 0;
1706 else
1708 /* If the result is a string, check if there is a non-digit before
1709 * the number. */
1710 s = tv.vval.v_string;
1711 if (!VIM_ISDIGIT(*s) && *s != '-')
1712 *cp = *s++;
1713 retval = atol((char *)s);
1715 clear_tv(&tv);
1717 --emsg_off;
1718 if (use_sandbox)
1719 --sandbox;
1720 --textlock;
1722 return retval;
1724 #endif
1727 * ":let" list all variable values
1728 * ":let var1 var2" list variable values
1729 * ":let var = expr" assignment command.
1730 * ":let var += expr" assignment command.
1731 * ":let var -= expr" assignment command.
1732 * ":let var .= expr" assignment command.
1733 * ":let [var1, var2] = expr" unpack list.
1735 void
1736 ex_let(eap)
1737 exarg_T *eap;
1739 char_u *arg = eap->arg;
1740 char_u *expr = NULL;
1741 typval_T rettv;
1742 int i;
1743 int var_count = 0;
1744 int semicolon = 0;
1745 char_u op[2];
1746 char_u *argend;
1747 int first = TRUE;
1749 argend = skip_var_list(arg, &var_count, &semicolon);
1750 if (argend == NULL)
1751 return;
1752 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1753 --argend;
1754 expr = vim_strchr(argend, '=');
1755 if (expr == NULL)
1758 * ":let" without "=": list variables
1760 if (*arg == '[')
1761 EMSG(_(e_invarg));
1762 else if (!ends_excmd(*arg))
1763 /* ":let var1 var2" */
1764 arg = list_arg_vars(eap, arg, &first);
1765 else if (!eap->skip)
1767 /* ":let" */
1768 list_glob_vars(&first);
1769 list_buf_vars(&first);
1770 list_win_vars(&first);
1771 #ifdef FEAT_WINDOWS
1772 list_tab_vars(&first);
1773 #endif
1774 list_script_vars(&first);
1775 list_func_vars(&first);
1776 list_vim_vars(&first);
1778 eap->nextcmd = check_nextcmd(arg);
1780 else
1782 op[0] = '=';
1783 op[1] = NUL;
1784 if (expr > argend)
1786 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1787 op[0] = expr[-1]; /* +=, -= or .= */
1789 expr = skipwhite(expr + 1);
1791 if (eap->skip)
1792 ++emsg_skip;
1793 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1794 if (eap->skip)
1796 if (i != FAIL)
1797 clear_tv(&rettv);
1798 --emsg_skip;
1800 else if (i != FAIL)
1802 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1803 op);
1804 clear_tv(&rettv);
1810 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1811 * Handles both "var" with any type and "[var, var; var]" with a list type.
1812 * When "nextchars" is not NULL it points to a string with characters that
1813 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1814 * or concatenate.
1815 * Returns OK or FAIL;
1817 static int
1818 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1819 char_u *arg_start;
1820 typval_T *tv;
1821 int copy; /* copy values from "tv", don't move */
1822 int semicolon; /* from skip_var_list() */
1823 int var_count; /* from skip_var_list() */
1824 char_u *nextchars;
1826 char_u *arg = arg_start;
1827 list_T *l;
1828 int i;
1829 listitem_T *item;
1830 typval_T ltv;
1832 if (*arg != '[')
1835 * ":let var = expr" or ":for var in list"
1837 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1838 return FAIL;
1839 return OK;
1843 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1845 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1847 EMSG(_(e_listreq));
1848 return FAIL;
1851 i = list_len(l);
1852 if (semicolon == 0 && var_count < i)
1854 EMSG(_("E687: Less targets than List items"));
1855 return FAIL;
1857 if (var_count - semicolon > i)
1859 EMSG(_("E688: More targets than List items"));
1860 return FAIL;
1863 item = l->lv_first;
1864 while (*arg != ']')
1866 arg = skipwhite(arg + 1);
1867 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1868 item = item->li_next;
1869 if (arg == NULL)
1870 return FAIL;
1872 arg = skipwhite(arg);
1873 if (*arg == ';')
1875 /* Put the rest of the list (may be empty) in the var after ';'.
1876 * Create a new list for this. */
1877 l = list_alloc();
1878 if (l == NULL)
1879 return FAIL;
1880 while (item != NULL)
1882 list_append_tv(l, &item->li_tv);
1883 item = item->li_next;
1886 ltv.v_type = VAR_LIST;
1887 ltv.v_lock = 0;
1888 ltv.vval.v_list = l;
1889 l->lv_refcount = 1;
1891 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1892 (char_u *)"]", nextchars);
1893 clear_tv(&ltv);
1894 if (arg == NULL)
1895 return FAIL;
1896 break;
1898 else if (*arg != ',' && *arg != ']')
1900 EMSG2(_(e_intern2), "ex_let_vars()");
1901 return FAIL;
1905 return OK;
1909 * Skip over assignable variable "var" or list of variables "[var, var]".
1910 * Used for ":let varvar = expr" and ":for varvar in expr".
1911 * For "[var, var]" increment "*var_count" for each variable.
1912 * for "[var, var; var]" set "semicolon".
1913 * Return NULL for an error.
1915 static char_u *
1916 skip_var_list(arg, var_count, semicolon)
1917 char_u *arg;
1918 int *var_count;
1919 int *semicolon;
1921 char_u *p, *s;
1923 if (*arg == '[')
1925 /* "[var, var]": find the matching ']'. */
1926 p = arg;
1927 for (;;)
1929 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1930 s = skip_var_one(p);
1931 if (s == p)
1933 EMSG2(_(e_invarg2), p);
1934 return NULL;
1936 ++*var_count;
1938 p = skipwhite(s);
1939 if (*p == ']')
1940 break;
1941 else if (*p == ';')
1943 if (*semicolon == 1)
1945 EMSG(_("Double ; in list of variables"));
1946 return NULL;
1948 *semicolon = 1;
1950 else if (*p != ',')
1952 EMSG2(_(e_invarg2), p);
1953 return NULL;
1956 return p + 1;
1958 else
1959 return skip_var_one(arg);
1963 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
1964 * l[idx].
1966 static char_u *
1967 skip_var_one(arg)
1968 char_u *arg;
1970 if (*arg == '@' && arg[1] != NUL)
1971 return arg + 2;
1972 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
1973 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
1977 * List variables for hashtab "ht" with prefix "prefix".
1978 * If "empty" is TRUE also list NULL strings as empty strings.
1980 static void
1981 list_hashtable_vars(ht, prefix, empty, first)
1982 hashtab_T *ht;
1983 char_u *prefix;
1984 int empty;
1985 int *first;
1987 hashitem_T *hi;
1988 dictitem_T *di;
1989 int todo;
1991 todo = (int)ht->ht_used;
1992 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
1994 if (!HASHITEM_EMPTY(hi))
1996 --todo;
1997 di = HI2DI(hi);
1998 if (empty || di->di_tv.v_type != VAR_STRING
1999 || di->di_tv.vval.v_string != NULL)
2000 list_one_var(di, prefix, first);
2006 * List global variables.
2008 static void
2009 list_glob_vars(first)
2010 int *first;
2012 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2016 * List buffer variables.
2018 static void
2019 list_buf_vars(first)
2020 int *first;
2022 char_u numbuf[NUMBUFLEN];
2024 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2025 TRUE, first);
2027 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2028 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2029 numbuf, first);
2033 * List window variables.
2035 static void
2036 list_win_vars(first)
2037 int *first;
2039 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2040 (char_u *)"w:", TRUE, first);
2043 #ifdef FEAT_WINDOWS
2045 * List tab page variables.
2047 static void
2048 list_tab_vars(first)
2049 int *first;
2051 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2052 (char_u *)"t:", TRUE, first);
2054 #endif
2057 * List Vim variables.
2059 static void
2060 list_vim_vars(first)
2061 int *first;
2063 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2067 * List script-local variables, if there is a script.
2069 static void
2070 list_script_vars(first)
2071 int *first;
2073 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2074 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2075 (char_u *)"s:", FALSE, first);
2079 * List function variables, if there is a function.
2081 static void
2082 list_func_vars(first)
2083 int *first;
2085 if (current_funccal != NULL)
2086 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2087 (char_u *)"l:", FALSE, first);
2091 * List variables in "arg".
2093 static char_u *
2094 list_arg_vars(eap, arg, first)
2095 exarg_T *eap;
2096 char_u *arg;
2097 int *first;
2099 int error = FALSE;
2100 int len;
2101 char_u *name;
2102 char_u *name_start;
2103 char_u *arg_subsc;
2104 char_u *tofree;
2105 typval_T tv;
2107 while (!ends_excmd(*arg) && !got_int)
2109 if (error || eap->skip)
2111 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2112 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2114 emsg_severe = TRUE;
2115 EMSG(_(e_trailing));
2116 break;
2119 else
2121 /* get_name_len() takes care of expanding curly braces */
2122 name_start = name = arg;
2123 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2124 if (len <= 0)
2126 /* This is mainly to keep test 49 working: when expanding
2127 * curly braces fails overrule the exception error message. */
2128 if (len < 0 && !aborting())
2130 emsg_severe = TRUE;
2131 EMSG2(_(e_invarg2), arg);
2132 break;
2134 error = TRUE;
2136 else
2138 if (tofree != NULL)
2139 name = tofree;
2140 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2141 error = TRUE;
2142 else
2144 /* handle d.key, l[idx], f(expr) */
2145 arg_subsc = arg;
2146 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2147 error = TRUE;
2148 else
2150 if (arg == arg_subsc && len == 2 && name[1] == ':')
2152 switch (*name)
2154 case 'g': list_glob_vars(first); break;
2155 case 'b': list_buf_vars(first); break;
2156 case 'w': list_win_vars(first); break;
2157 #ifdef FEAT_WINDOWS
2158 case 't': list_tab_vars(first); break;
2159 #endif
2160 case 'v': list_vim_vars(first); break;
2161 case 's': list_script_vars(first); break;
2162 case 'l': list_func_vars(first); break;
2163 default:
2164 EMSG2(_("E738: Can't list variables for %s"), name);
2167 else
2169 char_u numbuf[NUMBUFLEN];
2170 char_u *tf;
2171 int c;
2172 char_u *s;
2174 s = echo_string(&tv, &tf, numbuf, 0);
2175 c = *arg;
2176 *arg = NUL;
2177 list_one_var_a((char_u *)"",
2178 arg == arg_subsc ? name : name_start,
2179 tv.v_type,
2180 s == NULL ? (char_u *)"" : s,
2181 first);
2182 *arg = c;
2183 vim_free(tf);
2185 clear_tv(&tv);
2190 vim_free(tofree);
2193 arg = skipwhite(arg);
2196 return arg;
2200 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2201 * Returns a pointer to the char just after the var name.
2202 * Returns NULL if there is an error.
2204 static char_u *
2205 ex_let_one(arg, tv, copy, endchars, op)
2206 char_u *arg; /* points to variable name */
2207 typval_T *tv; /* value to assign to variable */
2208 int copy; /* copy value from "tv" */
2209 char_u *endchars; /* valid chars after variable name or NULL */
2210 char_u *op; /* "+", "-", "." or NULL*/
2212 int c1;
2213 char_u *name;
2214 char_u *p;
2215 char_u *arg_end = NULL;
2216 int len;
2217 int opt_flags;
2218 char_u *tofree = NULL;
2221 * ":let $VAR = expr": Set environment variable.
2223 if (*arg == '$')
2225 /* Find the end of the name. */
2226 ++arg;
2227 name = arg;
2228 len = get_env_len(&arg);
2229 if (len == 0)
2230 EMSG2(_(e_invarg2), name - 1);
2231 else
2233 if (op != NULL && (*op == '+' || *op == '-'))
2234 EMSG2(_(e_letwrong), op);
2235 else if (endchars != NULL
2236 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2237 EMSG(_(e_letunexp));
2238 else
2240 c1 = name[len];
2241 name[len] = NUL;
2242 p = get_tv_string_chk(tv);
2243 if (p != NULL && op != NULL && *op == '.')
2245 int mustfree = FALSE;
2246 char_u *s = vim_getenv(name, &mustfree);
2248 if (s != NULL)
2250 p = tofree = concat_str(s, p);
2251 if (mustfree)
2252 vim_free(s);
2255 if (p != NULL)
2257 vim_setenv(name, p);
2258 if (STRICMP(name, "HOME") == 0)
2259 init_homedir();
2260 else if (didset_vim && STRICMP(name, "VIM") == 0)
2261 didset_vim = FALSE;
2262 else if (didset_vimruntime
2263 && STRICMP(name, "VIMRUNTIME") == 0)
2264 didset_vimruntime = FALSE;
2265 arg_end = arg;
2267 name[len] = c1;
2268 vim_free(tofree);
2274 * ":let &option = expr": Set option value.
2275 * ":let &l:option = expr": Set local option value.
2276 * ":let &g:option = expr": Set global option value.
2278 else if (*arg == '&')
2280 /* Find the end of the name. */
2281 p = find_option_end(&arg, &opt_flags);
2282 if (p == NULL || (endchars != NULL
2283 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2284 EMSG(_(e_letunexp));
2285 else
2287 long n;
2288 int opt_type;
2289 long numval;
2290 char_u *stringval = NULL;
2291 char_u *s;
2293 c1 = *p;
2294 *p = NUL;
2296 n = get_tv_number(tv);
2297 s = get_tv_string_chk(tv); /* != NULL if number or string */
2298 if (s != NULL && op != NULL && *op != '=')
2300 opt_type = get_option_value(arg, &numval,
2301 &stringval, opt_flags);
2302 if ((opt_type == 1 && *op == '.')
2303 || (opt_type == 0 && *op != '.'))
2304 EMSG2(_(e_letwrong), op);
2305 else
2307 if (opt_type == 1) /* number */
2309 if (*op == '+')
2310 n = numval + n;
2311 else
2312 n = numval - n;
2314 else if (opt_type == 0 && stringval != NULL) /* string */
2316 s = concat_str(stringval, s);
2317 vim_free(stringval);
2318 stringval = s;
2322 if (s != NULL)
2324 set_option_value(arg, n, s, opt_flags);
2325 arg_end = p;
2327 *p = c1;
2328 vim_free(stringval);
2333 * ":let @r = expr": Set register contents.
2335 else if (*arg == '@')
2337 ++arg;
2338 if (op != NULL && (*op == '+' || *op == '-'))
2339 EMSG2(_(e_letwrong), op);
2340 else if (endchars != NULL
2341 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2342 EMSG(_(e_letunexp));
2343 else
2345 char_u *ptofree = NULL;
2346 char_u *s;
2348 p = get_tv_string_chk(tv);
2349 if (p != NULL && op != NULL && *op == '.')
2351 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2352 if (s != NULL)
2354 p = ptofree = concat_str(s, p);
2355 vim_free(s);
2358 if (p != NULL)
2360 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2361 arg_end = arg + 1;
2363 vim_free(ptofree);
2368 * ":let var = expr": Set internal variable.
2369 * ":let {expr} = expr": Idem, name made with curly braces
2371 else if (eval_isnamec1(*arg) || *arg == '{')
2373 lval_T lv;
2375 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2376 if (p != NULL && lv.ll_name != NULL)
2378 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2379 EMSG(_(e_letunexp));
2380 else
2382 set_var_lval(&lv, p, tv, copy, op);
2383 arg_end = p;
2386 clear_lval(&lv);
2389 else
2390 EMSG2(_(e_invarg2), arg);
2392 return arg_end;
2396 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2398 static int
2399 check_changedtick(arg)
2400 char_u *arg;
2402 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2404 EMSG2(_(e_readonlyvar), arg);
2405 return TRUE;
2407 return FALSE;
2411 * Get an lval: variable, Dict item or List item that can be assigned a value
2412 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2413 * "name.key", "name.key[expr]" etc.
2414 * Indexing only works if "name" is an existing List or Dictionary.
2415 * "name" points to the start of the name.
2416 * If "rettv" is not NULL it points to the value to be assigned.
2417 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2418 * wrong; must end in space or cmd separator.
2420 * Returns a pointer to just after the name, including indexes.
2421 * When an evaluation error occurs "lp->ll_name" is NULL;
2422 * Returns NULL for a parsing error. Still need to free items in "lp"!
2424 static char_u *
2425 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2426 char_u *name;
2427 typval_T *rettv;
2428 lval_T *lp;
2429 int unlet;
2430 int skip;
2431 int quiet; /* don't give error messages */
2432 int fne_flags; /* flags for find_name_end() */
2434 char_u *p;
2435 char_u *expr_start, *expr_end;
2436 int cc;
2437 dictitem_T *v;
2438 typval_T var1;
2439 typval_T var2;
2440 int empty1 = FALSE;
2441 listitem_T *ni;
2442 char_u *key = NULL;
2443 int len;
2444 hashtab_T *ht;
2446 /* Clear everything in "lp". */
2447 vim_memset(lp, 0, sizeof(lval_T));
2449 if (skip)
2451 /* When skipping just find the end of the name. */
2452 lp->ll_name = name;
2453 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2456 /* Find the end of the name. */
2457 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2458 if (expr_start != NULL)
2460 /* Don't expand the name when we already know there is an error. */
2461 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2462 && *p != '[' && *p != '.')
2464 EMSG(_(e_trailing));
2465 return NULL;
2468 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2469 if (lp->ll_exp_name == NULL)
2471 /* Report an invalid expression in braces, unless the
2472 * expression evaluation has been cancelled due to an
2473 * aborting error, an interrupt, or an exception. */
2474 if (!aborting() && !quiet)
2476 emsg_severe = TRUE;
2477 EMSG2(_(e_invarg2), name);
2478 return NULL;
2481 lp->ll_name = lp->ll_exp_name;
2483 else
2484 lp->ll_name = name;
2486 /* Without [idx] or .key we are done. */
2487 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2488 return p;
2490 cc = *p;
2491 *p = NUL;
2492 v = find_var(lp->ll_name, &ht);
2493 if (v == NULL && !quiet)
2494 EMSG2(_(e_undefvar), lp->ll_name);
2495 *p = cc;
2496 if (v == NULL)
2497 return NULL;
2500 * Loop until no more [idx] or .key is following.
2502 lp->ll_tv = &v->di_tv;
2503 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2505 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2506 && !(lp->ll_tv->v_type == VAR_DICT
2507 && lp->ll_tv->vval.v_dict != NULL))
2509 if (!quiet)
2510 EMSG(_("E689: Can only index a List or Dictionary"));
2511 return NULL;
2513 if (lp->ll_range)
2515 if (!quiet)
2516 EMSG(_("E708: [:] must come last"));
2517 return NULL;
2520 len = -1;
2521 if (*p == '.')
2523 key = p + 1;
2524 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2526 if (len == 0)
2528 if (!quiet)
2529 EMSG(_(e_emptykey));
2530 return NULL;
2532 p = key + len;
2534 else
2536 /* Get the index [expr] or the first index [expr: ]. */
2537 p = skipwhite(p + 1);
2538 if (*p == ':')
2539 empty1 = TRUE;
2540 else
2542 empty1 = FALSE;
2543 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2544 return NULL;
2545 if (get_tv_string_chk(&var1) == NULL)
2547 /* not a number or string */
2548 clear_tv(&var1);
2549 return NULL;
2553 /* Optionally get the second index [ :expr]. */
2554 if (*p == ':')
2556 if (lp->ll_tv->v_type == VAR_DICT)
2558 if (!quiet)
2559 EMSG(_(e_dictrange));
2560 if (!empty1)
2561 clear_tv(&var1);
2562 return NULL;
2564 if (rettv != NULL && (rettv->v_type != VAR_LIST
2565 || rettv->vval.v_list == NULL))
2567 if (!quiet)
2568 EMSG(_("E709: [:] requires a List value"));
2569 if (!empty1)
2570 clear_tv(&var1);
2571 return NULL;
2573 p = skipwhite(p + 1);
2574 if (*p == ']')
2575 lp->ll_empty2 = TRUE;
2576 else
2578 lp->ll_empty2 = FALSE;
2579 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2581 if (!empty1)
2582 clear_tv(&var1);
2583 return NULL;
2585 if (get_tv_string_chk(&var2) == NULL)
2587 /* not a number or string */
2588 if (!empty1)
2589 clear_tv(&var1);
2590 clear_tv(&var2);
2591 return NULL;
2594 lp->ll_range = TRUE;
2596 else
2597 lp->ll_range = FALSE;
2599 if (*p != ']')
2601 if (!quiet)
2602 EMSG(_(e_missbrac));
2603 if (!empty1)
2604 clear_tv(&var1);
2605 if (lp->ll_range && !lp->ll_empty2)
2606 clear_tv(&var2);
2607 return NULL;
2610 /* Skip to past ']'. */
2611 ++p;
2614 if (lp->ll_tv->v_type == VAR_DICT)
2616 if (len == -1)
2618 /* "[key]": get key from "var1" */
2619 key = get_tv_string(&var1); /* is number or string */
2620 if (*key == NUL)
2622 if (!quiet)
2623 EMSG(_(e_emptykey));
2624 clear_tv(&var1);
2625 return NULL;
2628 lp->ll_list = NULL;
2629 lp->ll_dict = lp->ll_tv->vval.v_dict;
2630 lp->ll_di = dict_find(lp->ll_dict, key, len);
2631 if (lp->ll_di == NULL)
2633 /* Key does not exist in dict: may need to add it. */
2634 if (*p == '[' || *p == '.' || unlet)
2636 if (!quiet)
2637 EMSG2(_(e_dictkey), key);
2638 if (len == -1)
2639 clear_tv(&var1);
2640 return NULL;
2642 if (len == -1)
2643 lp->ll_newkey = vim_strsave(key);
2644 else
2645 lp->ll_newkey = vim_strnsave(key, len);
2646 if (len == -1)
2647 clear_tv(&var1);
2648 if (lp->ll_newkey == NULL)
2649 p = NULL;
2650 break;
2652 if (len == -1)
2653 clear_tv(&var1);
2654 lp->ll_tv = &lp->ll_di->di_tv;
2656 else
2659 * Get the number and item for the only or first index of the List.
2661 if (empty1)
2662 lp->ll_n1 = 0;
2663 else
2665 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2666 clear_tv(&var1);
2668 lp->ll_dict = NULL;
2669 lp->ll_list = lp->ll_tv->vval.v_list;
2670 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2671 if (lp->ll_li == NULL)
2673 if (lp->ll_n1 < 0)
2675 lp->ll_n1 = 0;
2676 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2679 if (lp->ll_li == NULL)
2681 if (lp->ll_range && !lp->ll_empty2)
2682 clear_tv(&var2);
2683 return NULL;
2687 * May need to find the item or absolute index for the second
2688 * index of a range.
2689 * When no index given: "lp->ll_empty2" is TRUE.
2690 * Otherwise "lp->ll_n2" is set to the second index.
2692 if (lp->ll_range && !lp->ll_empty2)
2694 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2695 clear_tv(&var2);
2696 if (lp->ll_n2 < 0)
2698 ni = list_find(lp->ll_list, lp->ll_n2);
2699 if (ni == NULL)
2700 return NULL;
2701 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2704 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2705 if (lp->ll_n1 < 0)
2706 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2707 if (lp->ll_n2 < lp->ll_n1)
2708 return NULL;
2711 lp->ll_tv = &lp->ll_li->li_tv;
2715 return p;
2719 * Clear lval "lp" that was filled by get_lval().
2721 static void
2722 clear_lval(lp)
2723 lval_T *lp;
2725 vim_free(lp->ll_exp_name);
2726 vim_free(lp->ll_newkey);
2730 * Set a variable that was parsed by get_lval() to "rettv".
2731 * "endp" points to just after the parsed name.
2732 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2734 static void
2735 set_var_lval(lp, endp, rettv, copy, op)
2736 lval_T *lp;
2737 char_u *endp;
2738 typval_T *rettv;
2739 int copy;
2740 char_u *op;
2742 int cc;
2743 listitem_T *ri;
2744 dictitem_T *di;
2746 if (lp->ll_tv == NULL)
2748 if (!check_changedtick(lp->ll_name))
2750 cc = *endp;
2751 *endp = NUL;
2752 if (op != NULL && *op != '=')
2754 typval_T tv;
2756 /* handle +=, -= and .= */
2757 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2758 &tv, TRUE) == OK)
2760 if (tv_op(&tv, rettv, op) == OK)
2761 set_var(lp->ll_name, &tv, FALSE);
2762 clear_tv(&tv);
2765 else
2766 set_var(lp->ll_name, rettv, copy);
2767 *endp = cc;
2770 else if (tv_check_lock(lp->ll_newkey == NULL
2771 ? lp->ll_tv->v_lock
2772 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2774 else if (lp->ll_range)
2777 * Assign the List values to the list items.
2779 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2781 if (op != NULL && *op != '=')
2782 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2783 else
2785 clear_tv(&lp->ll_li->li_tv);
2786 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2788 ri = ri->li_next;
2789 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2790 break;
2791 if (lp->ll_li->li_next == NULL)
2793 /* Need to add an empty item. */
2794 if (list_append_number(lp->ll_list, 0) == FAIL)
2796 ri = NULL;
2797 break;
2800 lp->ll_li = lp->ll_li->li_next;
2801 ++lp->ll_n1;
2803 if (ri != NULL)
2804 EMSG(_("E710: List value has more items than target"));
2805 else if (lp->ll_empty2
2806 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2807 : lp->ll_n1 != lp->ll_n2)
2808 EMSG(_("E711: List value has not enough items"));
2810 else
2813 * Assign to a List or Dictionary item.
2815 if (lp->ll_newkey != NULL)
2817 if (op != NULL && *op != '=')
2819 EMSG2(_(e_letwrong), op);
2820 return;
2823 /* Need to add an item to the Dictionary. */
2824 di = dictitem_alloc(lp->ll_newkey);
2825 if (di == NULL)
2826 return;
2827 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2829 vim_free(di);
2830 return;
2832 lp->ll_tv = &di->di_tv;
2834 else if (op != NULL && *op != '=')
2836 tv_op(lp->ll_tv, rettv, op);
2837 return;
2839 else
2840 clear_tv(lp->ll_tv);
2843 * Assign the value to the variable or list item.
2845 if (copy)
2846 copy_tv(rettv, lp->ll_tv);
2847 else
2849 *lp->ll_tv = *rettv;
2850 lp->ll_tv->v_lock = 0;
2851 init_tv(rettv);
2857 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2858 * Returns OK or FAIL.
2860 static int
2861 tv_op(tv1, tv2, op)
2862 typval_T *tv1;
2863 typval_T *tv2;
2864 char_u *op;
2866 long n;
2867 char_u numbuf[NUMBUFLEN];
2868 char_u *s;
2870 /* Can't do anything with a Funcref or a Dict on the right. */
2871 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2873 switch (tv1->v_type)
2875 case VAR_DICT:
2876 case VAR_FUNC:
2877 break;
2879 case VAR_LIST:
2880 if (*op != '+' || tv2->v_type != VAR_LIST)
2881 break;
2882 /* List += List */
2883 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2884 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2885 return OK;
2887 case VAR_NUMBER:
2888 case VAR_STRING:
2889 if (tv2->v_type == VAR_LIST)
2890 break;
2891 if (*op == '+' || *op == '-')
2893 /* nr += nr or nr -= nr*/
2894 n = get_tv_number(tv1);
2895 #ifdef FEAT_FLOAT
2896 if (tv2->v_type == VAR_FLOAT)
2898 float_T f = n;
2900 if (*op == '+')
2901 f += tv2->vval.v_float;
2902 else
2903 f -= tv2->vval.v_float;
2904 clear_tv(tv1);
2905 tv1->v_type = VAR_FLOAT;
2906 tv1->vval.v_float = f;
2908 else
2909 #endif
2911 if (*op == '+')
2912 n += get_tv_number(tv2);
2913 else
2914 n -= get_tv_number(tv2);
2915 clear_tv(tv1);
2916 tv1->v_type = VAR_NUMBER;
2917 tv1->vval.v_number = n;
2920 else
2922 if (tv2->v_type == VAR_FLOAT)
2923 break;
2925 /* str .= str */
2926 s = get_tv_string(tv1);
2927 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2928 clear_tv(tv1);
2929 tv1->v_type = VAR_STRING;
2930 tv1->vval.v_string = s;
2932 return OK;
2934 #ifdef FEAT_FLOAT
2935 case VAR_FLOAT:
2937 float_T f;
2939 if (*op == '.' || (tv2->v_type != VAR_FLOAT
2940 && tv2->v_type != VAR_NUMBER
2941 && tv2->v_type != VAR_STRING))
2942 break;
2943 if (tv2->v_type == VAR_FLOAT)
2944 f = tv2->vval.v_float;
2945 else
2946 f = get_tv_number(tv2);
2947 if (*op == '+')
2948 tv1->vval.v_float += f;
2949 else
2950 tv1->vval.v_float -= f;
2952 return OK;
2953 #endif
2957 EMSG2(_(e_letwrong), op);
2958 return FAIL;
2962 * Add a watcher to a list.
2964 static void
2965 list_add_watch(l, lw)
2966 list_T *l;
2967 listwatch_T *lw;
2969 lw->lw_next = l->lv_watch;
2970 l->lv_watch = lw;
2974 * Remove a watcher from a list.
2975 * No warning when it isn't found...
2977 static void
2978 list_rem_watch(l, lwrem)
2979 list_T *l;
2980 listwatch_T *lwrem;
2982 listwatch_T *lw, **lwp;
2984 lwp = &l->lv_watch;
2985 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
2987 if (lw == lwrem)
2989 *lwp = lw->lw_next;
2990 break;
2992 lwp = &lw->lw_next;
2997 * Just before removing an item from a list: advance watchers to the next
2998 * item.
3000 static void
3001 list_fix_watch(l, item)
3002 list_T *l;
3003 listitem_T *item;
3005 listwatch_T *lw;
3007 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3008 if (lw->lw_item == item)
3009 lw->lw_item = item->li_next;
3013 * Evaluate the expression used in a ":for var in expr" command.
3014 * "arg" points to "var".
3015 * Set "*errp" to TRUE for an error, FALSE otherwise;
3016 * Return a pointer that holds the info. Null when there is an error.
3018 void *
3019 eval_for_line(arg, errp, nextcmdp, skip)
3020 char_u *arg;
3021 int *errp;
3022 char_u **nextcmdp;
3023 int skip;
3025 forinfo_T *fi;
3026 char_u *expr;
3027 typval_T tv;
3028 list_T *l;
3030 *errp = TRUE; /* default: there is an error */
3032 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3033 if (fi == NULL)
3034 return NULL;
3036 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3037 if (expr == NULL)
3038 return fi;
3040 expr = skipwhite(expr);
3041 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3043 EMSG(_("E690: Missing \"in\" after :for"));
3044 return fi;
3047 if (skip)
3048 ++emsg_skip;
3049 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3051 *errp = FALSE;
3052 if (!skip)
3054 l = tv.vval.v_list;
3055 if (tv.v_type != VAR_LIST || l == NULL)
3057 EMSG(_(e_listreq));
3058 clear_tv(&tv);
3060 else
3062 /* No need to increment the refcount, it's already set for the
3063 * list being used in "tv". */
3064 fi->fi_list = l;
3065 list_add_watch(l, &fi->fi_lw);
3066 fi->fi_lw.lw_item = l->lv_first;
3070 if (skip)
3071 --emsg_skip;
3073 return fi;
3077 * Use the first item in a ":for" list. Advance to the next.
3078 * Assign the values to the variable (list). "arg" points to the first one.
3079 * Return TRUE when a valid item was found, FALSE when at end of list or
3080 * something wrong.
3083 next_for_item(fi_void, arg)
3084 void *fi_void;
3085 char_u *arg;
3087 forinfo_T *fi = (forinfo_T *)fi_void;
3088 int result;
3089 listitem_T *item;
3091 item = fi->fi_lw.lw_item;
3092 if (item == NULL)
3093 result = FALSE;
3094 else
3096 fi->fi_lw.lw_item = item->li_next;
3097 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3098 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3100 return result;
3104 * Free the structure used to store info used by ":for".
3106 void
3107 free_for_info(fi_void)
3108 void *fi_void;
3110 forinfo_T *fi = (forinfo_T *)fi_void;
3112 if (fi != NULL && fi->fi_list != NULL)
3114 list_rem_watch(fi->fi_list, &fi->fi_lw);
3115 list_unref(fi->fi_list);
3117 vim_free(fi);
3120 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3122 void
3123 set_context_for_expression(xp, arg, cmdidx)
3124 expand_T *xp;
3125 char_u *arg;
3126 cmdidx_T cmdidx;
3128 int got_eq = FALSE;
3129 int c;
3130 char_u *p;
3132 if (cmdidx == CMD_let)
3134 xp->xp_context = EXPAND_USER_VARS;
3135 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3137 /* ":let var1 var2 ...": find last space. */
3138 for (p = arg + STRLEN(arg); p >= arg; )
3140 xp->xp_pattern = p;
3141 mb_ptr_back(arg, p);
3142 if (vim_iswhite(*p))
3143 break;
3145 return;
3148 else
3149 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3150 : EXPAND_EXPRESSION;
3151 while ((xp->xp_pattern = vim_strpbrk(arg,
3152 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3154 c = *xp->xp_pattern;
3155 if (c == '&')
3157 c = xp->xp_pattern[1];
3158 if (c == '&')
3160 ++xp->xp_pattern;
3161 xp->xp_context = cmdidx != CMD_let || got_eq
3162 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3164 else if (c != ' ')
3166 xp->xp_context = EXPAND_SETTINGS;
3167 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3168 xp->xp_pattern += 2;
3172 else if (c == '$')
3174 /* environment variable */
3175 xp->xp_context = EXPAND_ENV_VARS;
3177 else if (c == '=')
3179 got_eq = TRUE;
3180 xp->xp_context = EXPAND_EXPRESSION;
3182 else if (c == '<'
3183 && xp->xp_context == EXPAND_FUNCTIONS
3184 && vim_strchr(xp->xp_pattern, '(') == NULL)
3186 /* Function name can start with "<SNR>" */
3187 break;
3189 else if (cmdidx != CMD_let || got_eq)
3191 if (c == '"') /* string */
3193 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3194 if (c == '\\' && xp->xp_pattern[1] != NUL)
3195 ++xp->xp_pattern;
3196 xp->xp_context = EXPAND_NOTHING;
3198 else if (c == '\'') /* literal string */
3200 /* Trick: '' is like stopping and starting a literal string. */
3201 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3202 /* skip */ ;
3203 xp->xp_context = EXPAND_NOTHING;
3205 else if (c == '|')
3207 if (xp->xp_pattern[1] == '|')
3209 ++xp->xp_pattern;
3210 xp->xp_context = EXPAND_EXPRESSION;
3212 else
3213 xp->xp_context = EXPAND_COMMANDS;
3215 else
3216 xp->xp_context = EXPAND_EXPRESSION;
3218 else
3219 /* Doesn't look like something valid, expand as an expression
3220 * anyway. */
3221 xp->xp_context = EXPAND_EXPRESSION;
3222 arg = xp->xp_pattern;
3223 if (*arg != NUL)
3224 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3225 /* skip */ ;
3227 xp->xp_pattern = arg;
3230 #endif /* FEAT_CMDL_COMPL */
3233 * ":1,25call func(arg1, arg2)" function call.
3235 void
3236 ex_call(eap)
3237 exarg_T *eap;
3239 char_u *arg = eap->arg;
3240 char_u *startarg;
3241 char_u *name;
3242 char_u *tofree;
3243 int len;
3244 typval_T rettv;
3245 linenr_T lnum;
3246 int doesrange;
3247 int failed = FALSE;
3248 funcdict_T fudi;
3250 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3251 if (fudi.fd_newkey != NULL)
3253 /* Still need to give an error message for missing key. */
3254 EMSG2(_(e_dictkey), fudi.fd_newkey);
3255 vim_free(fudi.fd_newkey);
3257 if (tofree == NULL)
3258 return;
3260 /* Increase refcount on dictionary, it could get deleted when evaluating
3261 * the arguments. */
3262 if (fudi.fd_dict != NULL)
3263 ++fudi.fd_dict->dv_refcount;
3265 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3266 len = (int)STRLEN(tofree);
3267 name = deref_func_name(tofree, &len);
3269 /* Skip white space to allow ":call func ()". Not good, but required for
3270 * backward compatibility. */
3271 startarg = skipwhite(arg);
3272 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3274 if (*startarg != '(')
3276 EMSG2(_("E107: Missing braces: %s"), eap->arg);
3277 goto end;
3281 * When skipping, evaluate the function once, to find the end of the
3282 * arguments.
3283 * When the function takes a range, this is discovered after the first
3284 * call, and the loop is broken.
3286 if (eap->skip)
3288 ++emsg_skip;
3289 lnum = eap->line2; /* do it once, also with an invalid range */
3291 else
3292 lnum = eap->line1;
3293 for ( ; lnum <= eap->line2; ++lnum)
3295 if (!eap->skip && eap->addr_count > 0)
3297 curwin->w_cursor.lnum = lnum;
3298 curwin->w_cursor.col = 0;
3300 arg = startarg;
3301 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3302 eap->line1, eap->line2, &doesrange,
3303 !eap->skip, fudi.fd_dict) == FAIL)
3305 failed = TRUE;
3306 break;
3309 /* Handle a function returning a Funcref, Dictionary or List. */
3310 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3312 failed = TRUE;
3313 break;
3316 clear_tv(&rettv);
3317 if (doesrange || eap->skip)
3318 break;
3320 /* Stop when immediately aborting on error, or when an interrupt
3321 * occurred or an exception was thrown but not caught.
3322 * get_func_tv() returned OK, so that the check for trailing
3323 * characters below is executed. */
3324 if (aborting())
3325 break;
3327 if (eap->skip)
3328 --emsg_skip;
3330 if (!failed)
3332 /* Check for trailing illegal characters and a following command. */
3333 if (!ends_excmd(*arg))
3335 emsg_severe = TRUE;
3336 EMSG(_(e_trailing));
3338 else
3339 eap->nextcmd = check_nextcmd(arg);
3342 end:
3343 dict_unref(fudi.fd_dict);
3344 vim_free(tofree);
3348 * ":unlet[!] var1 ... " command.
3350 void
3351 ex_unlet(eap)
3352 exarg_T *eap;
3354 ex_unletlock(eap, eap->arg, 0);
3358 * ":lockvar" and ":unlockvar" commands
3360 void
3361 ex_lockvar(eap)
3362 exarg_T *eap;
3364 char_u *arg = eap->arg;
3365 int deep = 2;
3367 if (eap->forceit)
3368 deep = -1;
3369 else if (vim_isdigit(*arg))
3371 deep = getdigits(&arg);
3372 arg = skipwhite(arg);
3375 ex_unletlock(eap, arg, deep);
3379 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3381 static void
3382 ex_unletlock(eap, argstart, deep)
3383 exarg_T *eap;
3384 char_u *argstart;
3385 int deep;
3387 char_u *arg = argstart;
3388 char_u *name_end;
3389 int error = FALSE;
3390 lval_T lv;
3394 /* Parse the name and find the end. */
3395 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3396 FNE_CHECK_START);
3397 if (lv.ll_name == NULL)
3398 error = TRUE; /* error but continue parsing */
3399 if (name_end == NULL || (!vim_iswhite(*name_end)
3400 && !ends_excmd(*name_end)))
3402 if (name_end != NULL)
3404 emsg_severe = TRUE;
3405 EMSG(_(e_trailing));
3407 if (!(eap->skip || error))
3408 clear_lval(&lv);
3409 break;
3412 if (!error && !eap->skip)
3414 if (eap->cmdidx == CMD_unlet)
3416 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3417 error = TRUE;
3419 else
3421 if (do_lock_var(&lv, name_end, deep,
3422 eap->cmdidx == CMD_lockvar) == FAIL)
3423 error = TRUE;
3427 if (!eap->skip)
3428 clear_lval(&lv);
3430 arg = skipwhite(name_end);
3431 } while (!ends_excmd(*arg));
3433 eap->nextcmd = check_nextcmd(arg);
3436 static int
3437 do_unlet_var(lp, name_end, forceit)
3438 lval_T *lp;
3439 char_u *name_end;
3440 int forceit;
3442 int ret = OK;
3443 int cc;
3445 if (lp->ll_tv == NULL)
3447 cc = *name_end;
3448 *name_end = NUL;
3450 /* Normal name or expanded name. */
3451 if (check_changedtick(lp->ll_name))
3452 ret = FAIL;
3453 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3454 ret = FAIL;
3455 *name_end = cc;
3457 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3458 return FAIL;
3459 else if (lp->ll_range)
3461 listitem_T *li;
3463 /* Delete a range of List items. */
3464 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3466 li = lp->ll_li->li_next;
3467 listitem_remove(lp->ll_list, lp->ll_li);
3468 lp->ll_li = li;
3469 ++lp->ll_n1;
3472 else
3474 if (lp->ll_list != NULL)
3475 /* unlet a List item. */
3476 listitem_remove(lp->ll_list, lp->ll_li);
3477 else
3478 /* unlet a Dictionary item. */
3479 dictitem_remove(lp->ll_dict, lp->ll_di);
3482 return ret;
3486 * "unlet" a variable. Return OK if it existed, FAIL if not.
3487 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3490 do_unlet(name, forceit)
3491 char_u *name;
3492 int forceit;
3494 hashtab_T *ht;
3495 hashitem_T *hi;
3496 char_u *varname;
3497 dictitem_T *di;
3499 ht = find_var_ht(name, &varname);
3500 if (ht != NULL && *varname != NUL)
3502 hi = hash_find(ht, varname);
3503 if (!HASHITEM_EMPTY(hi))
3505 di = HI2DI(hi);
3506 if (var_check_fixed(di->di_flags, name)
3507 || var_check_ro(di->di_flags, name))
3508 return FAIL;
3509 delete_var(ht, hi);
3510 return OK;
3513 if (forceit)
3514 return OK;
3515 EMSG2(_("E108: No such variable: \"%s\""), name);
3516 return FAIL;
3520 * Lock or unlock variable indicated by "lp".
3521 * "deep" is the levels to go (-1 for unlimited);
3522 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3524 static int
3525 do_lock_var(lp, name_end, deep, lock)
3526 lval_T *lp;
3527 char_u *name_end;
3528 int deep;
3529 int lock;
3531 int ret = OK;
3532 int cc;
3533 dictitem_T *di;
3535 if (deep == 0) /* nothing to do */
3536 return OK;
3538 if (lp->ll_tv == NULL)
3540 cc = *name_end;
3541 *name_end = NUL;
3543 /* Normal name or expanded name. */
3544 if (check_changedtick(lp->ll_name))
3545 ret = FAIL;
3546 else
3548 di = find_var(lp->ll_name, NULL);
3549 if (di == NULL)
3550 ret = FAIL;
3551 else
3553 if (lock)
3554 di->di_flags |= DI_FLAGS_LOCK;
3555 else
3556 di->di_flags &= ~DI_FLAGS_LOCK;
3557 item_lock(&di->di_tv, deep, lock);
3560 *name_end = cc;
3562 else if (lp->ll_range)
3564 listitem_T *li = lp->ll_li;
3566 /* (un)lock a range of List items. */
3567 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3569 item_lock(&li->li_tv, deep, lock);
3570 li = li->li_next;
3571 ++lp->ll_n1;
3574 else if (lp->ll_list != NULL)
3575 /* (un)lock a List item. */
3576 item_lock(&lp->ll_li->li_tv, deep, lock);
3577 else
3578 /* un(lock) a Dictionary item. */
3579 item_lock(&lp->ll_di->di_tv, deep, lock);
3581 return ret;
3585 * Lock or unlock an item. "deep" is nr of levels to go.
3587 static void
3588 item_lock(tv, deep, lock)
3589 typval_T *tv;
3590 int deep;
3591 int lock;
3593 static int recurse = 0;
3594 list_T *l;
3595 listitem_T *li;
3596 dict_T *d;
3597 hashitem_T *hi;
3598 int todo;
3600 if (recurse >= DICT_MAXNEST)
3602 EMSG(_("E743: variable nested too deep for (un)lock"));
3603 return;
3605 if (deep == 0)
3606 return;
3607 ++recurse;
3609 /* lock/unlock the item itself */
3610 if (lock)
3611 tv->v_lock |= VAR_LOCKED;
3612 else
3613 tv->v_lock &= ~VAR_LOCKED;
3615 switch (tv->v_type)
3617 case VAR_LIST:
3618 if ((l = tv->vval.v_list) != NULL)
3620 if (lock)
3621 l->lv_lock |= VAR_LOCKED;
3622 else
3623 l->lv_lock &= ~VAR_LOCKED;
3624 if (deep < 0 || deep > 1)
3625 /* recursive: lock/unlock the items the List contains */
3626 for (li = l->lv_first; li != NULL; li = li->li_next)
3627 item_lock(&li->li_tv, deep - 1, lock);
3629 break;
3630 case VAR_DICT:
3631 if ((d = tv->vval.v_dict) != NULL)
3633 if (lock)
3634 d->dv_lock |= VAR_LOCKED;
3635 else
3636 d->dv_lock &= ~VAR_LOCKED;
3637 if (deep < 0 || deep > 1)
3639 /* recursive: lock/unlock the items the List contains */
3640 todo = (int)d->dv_hashtab.ht_used;
3641 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3643 if (!HASHITEM_EMPTY(hi))
3645 --todo;
3646 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3652 --recurse;
3656 * Return TRUE if typeval "tv" is locked: Either tha value is locked itself or
3657 * it refers to a List or Dictionary that is locked.
3659 static int
3660 tv_islocked(tv)
3661 typval_T *tv;
3663 return (tv->v_lock & VAR_LOCKED)
3664 || (tv->v_type == VAR_LIST
3665 && tv->vval.v_list != NULL
3666 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3667 || (tv->v_type == VAR_DICT
3668 && tv->vval.v_dict != NULL
3669 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3672 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3674 * Delete all "menutrans_" variables.
3676 void
3677 del_menutrans_vars()
3679 hashitem_T *hi;
3680 int todo;
3682 hash_lock(&globvarht);
3683 todo = (int)globvarht.ht_used;
3684 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3686 if (!HASHITEM_EMPTY(hi))
3688 --todo;
3689 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3690 delete_var(&globvarht, hi);
3693 hash_unlock(&globvarht);
3695 #endif
3697 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3700 * Local string buffer for the next two functions to store a variable name
3701 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3702 * get_user_var_name().
3705 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3707 static char_u *varnamebuf = NULL;
3708 static int varnamebuflen = 0;
3711 * Function to concatenate a prefix and a variable name.
3713 static char_u *
3714 cat_prefix_varname(prefix, name)
3715 int prefix;
3716 char_u *name;
3718 int len;
3720 len = (int)STRLEN(name) + 3;
3721 if (len > varnamebuflen)
3723 vim_free(varnamebuf);
3724 len += 10; /* some additional space */
3725 varnamebuf = alloc(len);
3726 if (varnamebuf == NULL)
3728 varnamebuflen = 0;
3729 return NULL;
3731 varnamebuflen = len;
3733 *varnamebuf = prefix;
3734 varnamebuf[1] = ':';
3735 STRCPY(varnamebuf + 2, name);
3736 return varnamebuf;
3740 * Function given to ExpandGeneric() to obtain the list of user defined
3741 * (global/buffer/window/built-in) variable names.
3743 /*ARGSUSED*/
3744 char_u *
3745 get_user_var_name(xp, idx)
3746 expand_T *xp;
3747 int idx;
3749 static long_u gdone;
3750 static long_u bdone;
3751 static long_u wdone;
3752 #ifdef FEAT_WINDOWS
3753 static long_u tdone;
3754 #endif
3755 static int vidx;
3756 static hashitem_T *hi;
3757 hashtab_T *ht;
3759 if (idx == 0)
3761 gdone = bdone = wdone = vidx = 0;
3762 #ifdef FEAT_WINDOWS
3763 tdone = 0;
3764 #endif
3767 /* Global variables */
3768 if (gdone < globvarht.ht_used)
3770 if (gdone++ == 0)
3771 hi = globvarht.ht_array;
3772 else
3773 ++hi;
3774 while (HASHITEM_EMPTY(hi))
3775 ++hi;
3776 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3777 return cat_prefix_varname('g', hi->hi_key);
3778 return hi->hi_key;
3781 /* b: variables */
3782 ht = &curbuf->b_vars.dv_hashtab;
3783 if (bdone < ht->ht_used)
3785 if (bdone++ == 0)
3786 hi = ht->ht_array;
3787 else
3788 ++hi;
3789 while (HASHITEM_EMPTY(hi))
3790 ++hi;
3791 return cat_prefix_varname('b', hi->hi_key);
3793 if (bdone == ht->ht_used)
3795 ++bdone;
3796 return (char_u *)"b:changedtick";
3799 /* w: variables */
3800 ht = &curwin->w_vars.dv_hashtab;
3801 if (wdone < ht->ht_used)
3803 if (wdone++ == 0)
3804 hi = ht->ht_array;
3805 else
3806 ++hi;
3807 while (HASHITEM_EMPTY(hi))
3808 ++hi;
3809 return cat_prefix_varname('w', hi->hi_key);
3812 #ifdef FEAT_WINDOWS
3813 /* t: variables */
3814 ht = &curtab->tp_vars.dv_hashtab;
3815 if (tdone < ht->ht_used)
3817 if (tdone++ == 0)
3818 hi = ht->ht_array;
3819 else
3820 ++hi;
3821 while (HASHITEM_EMPTY(hi))
3822 ++hi;
3823 return cat_prefix_varname('t', hi->hi_key);
3825 #endif
3827 /* v: variables */
3828 if (vidx < VV_LEN)
3829 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3831 vim_free(varnamebuf);
3832 varnamebuf = NULL;
3833 varnamebuflen = 0;
3834 return NULL;
3837 #endif /* FEAT_CMDL_COMPL */
3840 * types for expressions.
3842 typedef enum
3844 TYPE_UNKNOWN = 0
3845 , TYPE_EQUAL /* == */
3846 , TYPE_NEQUAL /* != */
3847 , TYPE_GREATER /* > */
3848 , TYPE_GEQUAL /* >= */
3849 , TYPE_SMALLER /* < */
3850 , TYPE_SEQUAL /* <= */
3851 , TYPE_MATCH /* =~ */
3852 , TYPE_NOMATCH /* !~ */
3853 } exptype_T;
3856 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3857 * executed. The function may return OK, but the rettv will be of type
3858 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3862 * Handle zero level expression.
3863 * This calls eval1() and handles error message and nextcmd.
3864 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3865 * Note: "rettv.v_lock" is not set.
3866 * Return OK or FAIL.
3868 static int
3869 eval0(arg, rettv, nextcmd, evaluate)
3870 char_u *arg;
3871 typval_T *rettv;
3872 char_u **nextcmd;
3873 int evaluate;
3875 int ret;
3876 char_u *p;
3878 p = skipwhite(arg);
3879 ret = eval1(&p, rettv, evaluate);
3880 if (ret == FAIL || !ends_excmd(*p))
3882 if (ret != FAIL)
3883 clear_tv(rettv);
3885 * Report the invalid expression unless the expression evaluation has
3886 * been cancelled due to an aborting error, an interrupt, or an
3887 * exception.
3889 if (!aborting())
3890 EMSG2(_(e_invexpr2), arg);
3891 ret = FAIL;
3893 if (nextcmd != NULL)
3894 *nextcmd = check_nextcmd(p);
3896 return ret;
3900 * Handle top level expression:
3901 * expr1 ? expr0 : expr0
3903 * "arg" must point to the first non-white of the expression.
3904 * "arg" is advanced to the next non-white after the recognized expression.
3906 * Note: "rettv.v_lock" is not set.
3908 * Return OK or FAIL.
3910 static int
3911 eval1(arg, rettv, evaluate)
3912 char_u **arg;
3913 typval_T *rettv;
3914 int evaluate;
3916 int result;
3917 typval_T var2;
3920 * Get the first variable.
3922 if (eval2(arg, rettv, evaluate) == FAIL)
3923 return FAIL;
3925 if ((*arg)[0] == '?')
3927 result = FALSE;
3928 if (evaluate)
3930 int error = FALSE;
3932 if (get_tv_number_chk(rettv, &error) != 0)
3933 result = TRUE;
3934 clear_tv(rettv);
3935 if (error)
3936 return FAIL;
3940 * Get the second variable.
3942 *arg = skipwhite(*arg + 1);
3943 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
3944 return FAIL;
3947 * Check for the ":".
3949 if ((*arg)[0] != ':')
3951 EMSG(_("E109: Missing ':' after '?'"));
3952 if (evaluate && result)
3953 clear_tv(rettv);
3954 return FAIL;
3958 * Get the third variable.
3960 *arg = skipwhite(*arg + 1);
3961 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
3963 if (evaluate && result)
3964 clear_tv(rettv);
3965 return FAIL;
3967 if (evaluate && !result)
3968 *rettv = var2;
3971 return OK;
3975 * Handle first level expression:
3976 * expr2 || expr2 || expr2 logical OR
3978 * "arg" must point to the first non-white of the expression.
3979 * "arg" is advanced to the next non-white after the recognized expression.
3981 * Return OK or FAIL.
3983 static int
3984 eval2(arg, rettv, evaluate)
3985 char_u **arg;
3986 typval_T *rettv;
3987 int evaluate;
3989 typval_T var2;
3990 long result;
3991 int first;
3992 int error = FALSE;
3995 * Get the first variable.
3997 if (eval3(arg, rettv, evaluate) == FAIL)
3998 return FAIL;
4001 * Repeat until there is no following "||".
4003 first = TRUE;
4004 result = FALSE;
4005 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4007 if (evaluate && first)
4009 if (get_tv_number_chk(rettv, &error) != 0)
4010 result = TRUE;
4011 clear_tv(rettv);
4012 if (error)
4013 return FAIL;
4014 first = FALSE;
4018 * Get the second variable.
4020 *arg = skipwhite(*arg + 2);
4021 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4022 return FAIL;
4025 * Compute the result.
4027 if (evaluate && !result)
4029 if (get_tv_number_chk(&var2, &error) != 0)
4030 result = TRUE;
4031 clear_tv(&var2);
4032 if (error)
4033 return FAIL;
4035 if (evaluate)
4037 rettv->v_type = VAR_NUMBER;
4038 rettv->vval.v_number = result;
4042 return OK;
4046 * Handle second level expression:
4047 * expr3 && expr3 && expr3 logical AND
4049 * "arg" must point to the first non-white of the expression.
4050 * "arg" is advanced to the next non-white after the recognized expression.
4052 * Return OK or FAIL.
4054 static int
4055 eval3(arg, rettv, evaluate)
4056 char_u **arg;
4057 typval_T *rettv;
4058 int evaluate;
4060 typval_T var2;
4061 long result;
4062 int first;
4063 int error = FALSE;
4066 * Get the first variable.
4068 if (eval4(arg, rettv, evaluate) == FAIL)
4069 return FAIL;
4072 * Repeat until there is no following "&&".
4074 first = TRUE;
4075 result = TRUE;
4076 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4078 if (evaluate && first)
4080 if (get_tv_number_chk(rettv, &error) == 0)
4081 result = FALSE;
4082 clear_tv(rettv);
4083 if (error)
4084 return FAIL;
4085 first = FALSE;
4089 * Get the second variable.
4091 *arg = skipwhite(*arg + 2);
4092 if (eval4(arg, &var2, evaluate && result) == FAIL)
4093 return FAIL;
4096 * Compute the result.
4098 if (evaluate && result)
4100 if (get_tv_number_chk(&var2, &error) == 0)
4101 result = FALSE;
4102 clear_tv(&var2);
4103 if (error)
4104 return FAIL;
4106 if (evaluate)
4108 rettv->v_type = VAR_NUMBER;
4109 rettv->vval.v_number = result;
4113 return OK;
4117 * Handle third level expression:
4118 * var1 == var2
4119 * var1 =~ var2
4120 * var1 != var2
4121 * var1 !~ var2
4122 * var1 > var2
4123 * var1 >= var2
4124 * var1 < var2
4125 * var1 <= var2
4126 * var1 is var2
4127 * var1 isnot var2
4129 * "arg" must point to the first non-white of the expression.
4130 * "arg" is advanced to the next non-white after the recognized expression.
4132 * Return OK or FAIL.
4134 static int
4135 eval4(arg, rettv, evaluate)
4136 char_u **arg;
4137 typval_T *rettv;
4138 int evaluate;
4140 typval_T var2;
4141 char_u *p;
4142 int i;
4143 exptype_T type = TYPE_UNKNOWN;
4144 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4145 int len = 2;
4146 long n1, n2;
4147 char_u *s1, *s2;
4148 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4149 regmatch_T regmatch;
4150 int ic;
4151 char_u *save_cpo;
4154 * Get the first variable.
4156 if (eval5(arg, rettv, evaluate) == FAIL)
4157 return FAIL;
4159 p = *arg;
4160 switch (p[0])
4162 case '=': if (p[1] == '=')
4163 type = TYPE_EQUAL;
4164 else if (p[1] == '~')
4165 type = TYPE_MATCH;
4166 break;
4167 case '!': if (p[1] == '=')
4168 type = TYPE_NEQUAL;
4169 else if (p[1] == '~')
4170 type = TYPE_NOMATCH;
4171 break;
4172 case '>': if (p[1] != '=')
4174 type = TYPE_GREATER;
4175 len = 1;
4177 else
4178 type = TYPE_GEQUAL;
4179 break;
4180 case '<': if (p[1] != '=')
4182 type = TYPE_SMALLER;
4183 len = 1;
4185 else
4186 type = TYPE_SEQUAL;
4187 break;
4188 case 'i': if (p[1] == 's')
4190 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4191 len = 5;
4192 if (!vim_isIDc(p[len]))
4194 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4195 type_is = TRUE;
4198 break;
4202 * If there is a comparative operator, use it.
4204 if (type != TYPE_UNKNOWN)
4206 /* extra question mark appended: ignore case */
4207 if (p[len] == '?')
4209 ic = TRUE;
4210 ++len;
4212 /* extra '#' appended: match case */
4213 else if (p[len] == '#')
4215 ic = FALSE;
4216 ++len;
4218 /* nothing appended: use 'ignorecase' */
4219 else
4220 ic = p_ic;
4223 * Get the second variable.
4225 *arg = skipwhite(p + len);
4226 if (eval5(arg, &var2, evaluate) == FAIL)
4228 clear_tv(rettv);
4229 return FAIL;
4232 if (evaluate)
4234 if (type_is && rettv->v_type != var2.v_type)
4236 /* For "is" a different type always means FALSE, for "notis"
4237 * it means TRUE. */
4238 n1 = (type == TYPE_NEQUAL);
4240 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4242 if (type_is)
4244 n1 = (rettv->v_type == var2.v_type
4245 && rettv->vval.v_list == var2.vval.v_list);
4246 if (type == TYPE_NEQUAL)
4247 n1 = !n1;
4249 else if (rettv->v_type != var2.v_type
4250 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4252 if (rettv->v_type != var2.v_type)
4253 EMSG(_("E691: Can only compare List with List"));
4254 else
4255 EMSG(_("E692: Invalid operation for Lists"));
4256 clear_tv(rettv);
4257 clear_tv(&var2);
4258 return FAIL;
4260 else
4262 /* Compare two Lists for being equal or unequal. */
4263 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4264 if (type == TYPE_NEQUAL)
4265 n1 = !n1;
4269 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4271 if (type_is)
4273 n1 = (rettv->v_type == var2.v_type
4274 && rettv->vval.v_dict == var2.vval.v_dict);
4275 if (type == TYPE_NEQUAL)
4276 n1 = !n1;
4278 else if (rettv->v_type != var2.v_type
4279 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4281 if (rettv->v_type != var2.v_type)
4282 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4283 else
4284 EMSG(_("E736: Invalid operation for Dictionary"));
4285 clear_tv(rettv);
4286 clear_tv(&var2);
4287 return FAIL;
4289 else
4291 /* Compare two Dictionaries for being equal or unequal. */
4292 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4293 if (type == TYPE_NEQUAL)
4294 n1 = !n1;
4298 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4300 if (rettv->v_type != var2.v_type
4301 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4303 if (rettv->v_type != var2.v_type)
4304 EMSG(_("E693: Can only compare Funcref with Funcref"));
4305 else
4306 EMSG(_("E694: Invalid operation for Funcrefs"));
4307 clear_tv(rettv);
4308 clear_tv(&var2);
4309 return FAIL;
4311 else
4313 /* Compare two Funcrefs for being equal or unequal. */
4314 if (rettv->vval.v_string == NULL
4315 || var2.vval.v_string == NULL)
4316 n1 = FALSE;
4317 else
4318 n1 = STRCMP(rettv->vval.v_string,
4319 var2.vval.v_string) == 0;
4320 if (type == TYPE_NEQUAL)
4321 n1 = !n1;
4325 #ifdef FEAT_FLOAT
4327 * If one of the two variables is a float, compare as a float.
4328 * When using "=~" or "!~", always compare as string.
4330 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4331 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4333 float_T f1, f2;
4335 if (rettv->v_type == VAR_FLOAT)
4336 f1 = rettv->vval.v_float;
4337 else
4338 f1 = get_tv_number(rettv);
4339 if (var2.v_type == VAR_FLOAT)
4340 f2 = var2.vval.v_float;
4341 else
4342 f2 = get_tv_number(&var2);
4343 n1 = FALSE;
4344 switch (type)
4346 case TYPE_EQUAL: n1 = (f1 == f2); break;
4347 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4348 case TYPE_GREATER: n1 = (f1 > f2); break;
4349 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4350 case TYPE_SMALLER: n1 = (f1 < f2); break;
4351 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4352 case TYPE_UNKNOWN:
4353 case TYPE_MATCH:
4354 case TYPE_NOMATCH: break; /* avoid gcc warning */
4357 #endif
4360 * If one of the two variables is a number, compare as a number.
4361 * When using "=~" or "!~", always compare as string.
4363 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4364 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4366 n1 = get_tv_number(rettv);
4367 n2 = get_tv_number(&var2);
4368 switch (type)
4370 case TYPE_EQUAL: n1 = (n1 == n2); break;
4371 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4372 case TYPE_GREATER: n1 = (n1 > n2); break;
4373 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4374 case TYPE_SMALLER: n1 = (n1 < n2); break;
4375 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4376 case TYPE_UNKNOWN:
4377 case TYPE_MATCH:
4378 case TYPE_NOMATCH: break; /* avoid gcc warning */
4381 else
4383 s1 = get_tv_string_buf(rettv, buf1);
4384 s2 = get_tv_string_buf(&var2, buf2);
4385 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4386 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4387 else
4388 i = 0;
4389 n1 = FALSE;
4390 switch (type)
4392 case TYPE_EQUAL: n1 = (i == 0); break;
4393 case TYPE_NEQUAL: n1 = (i != 0); break;
4394 case TYPE_GREATER: n1 = (i > 0); break;
4395 case TYPE_GEQUAL: n1 = (i >= 0); break;
4396 case TYPE_SMALLER: n1 = (i < 0); break;
4397 case TYPE_SEQUAL: n1 = (i <= 0); break;
4399 case TYPE_MATCH:
4400 case TYPE_NOMATCH:
4401 /* avoid 'l' flag in 'cpoptions' */
4402 save_cpo = p_cpo;
4403 p_cpo = (char_u *)"";
4404 regmatch.regprog = vim_regcomp(s2,
4405 RE_MAGIC + RE_STRING);
4406 regmatch.rm_ic = ic;
4407 if (regmatch.regprog != NULL)
4409 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4410 vim_free(regmatch.regprog);
4411 if (type == TYPE_NOMATCH)
4412 n1 = !n1;
4414 p_cpo = save_cpo;
4415 break;
4417 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4420 clear_tv(rettv);
4421 clear_tv(&var2);
4422 rettv->v_type = VAR_NUMBER;
4423 rettv->vval.v_number = n1;
4427 return OK;
4431 * Handle fourth level expression:
4432 * + number addition
4433 * - number subtraction
4434 * . string concatenation
4436 * "arg" must point to the first non-white of the expression.
4437 * "arg" is advanced to the next non-white after the recognized expression.
4439 * Return OK or FAIL.
4441 static int
4442 eval5(arg, rettv, evaluate)
4443 char_u **arg;
4444 typval_T *rettv;
4445 int evaluate;
4447 typval_T var2;
4448 typval_T var3;
4449 int op;
4450 long n1, n2;
4451 #ifdef FEAT_FLOAT
4452 float_T f1 = 0, f2 = 0;
4453 #endif
4454 char_u *s1, *s2;
4455 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4456 char_u *p;
4459 * Get the first variable.
4461 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4462 return FAIL;
4465 * Repeat computing, until no '+', '-' or '.' is following.
4467 for (;;)
4469 op = **arg;
4470 if (op != '+' && op != '-' && op != '.')
4471 break;
4473 if ((op != '+' || rettv->v_type != VAR_LIST)
4474 #ifdef FEAT_FLOAT
4475 && (op == '.' || rettv->v_type != VAR_FLOAT)
4476 #endif
4479 /* For "list + ...", an illegal use of the first operand as
4480 * a number cannot be determined before evaluating the 2nd
4481 * operand: if this is also a list, all is ok.
4482 * For "something . ...", "something - ..." or "non-list + ...",
4483 * we know that the first operand needs to be a string or number
4484 * without evaluating the 2nd operand. So check before to avoid
4485 * side effects after an error. */
4486 if (evaluate && get_tv_string_chk(rettv) == NULL)
4488 clear_tv(rettv);
4489 return FAIL;
4494 * Get the second variable.
4496 *arg = skipwhite(*arg + 1);
4497 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4499 clear_tv(rettv);
4500 return FAIL;
4503 if (evaluate)
4506 * Compute the result.
4508 if (op == '.')
4510 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4511 s2 = get_tv_string_buf_chk(&var2, buf2);
4512 if (s2 == NULL) /* type error ? */
4514 clear_tv(rettv);
4515 clear_tv(&var2);
4516 return FAIL;
4518 p = concat_str(s1, s2);
4519 clear_tv(rettv);
4520 rettv->v_type = VAR_STRING;
4521 rettv->vval.v_string = p;
4523 else if (op == '+' && rettv->v_type == VAR_LIST
4524 && var2.v_type == VAR_LIST)
4526 /* concatenate Lists */
4527 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4528 &var3) == FAIL)
4530 clear_tv(rettv);
4531 clear_tv(&var2);
4532 return FAIL;
4534 clear_tv(rettv);
4535 *rettv = var3;
4537 else
4539 int error = FALSE;
4541 #ifdef FEAT_FLOAT
4542 if (rettv->v_type == VAR_FLOAT)
4544 f1 = rettv->vval.v_float;
4545 n1 = 0;
4547 else
4548 #endif
4550 n1 = get_tv_number_chk(rettv, &error);
4551 if (error)
4553 /* This can only happen for "list + non-list". For
4554 * "non-list + ..." or "something - ...", we returned
4555 * before evaluating the 2nd operand. */
4556 clear_tv(rettv);
4557 return FAIL;
4559 #ifdef FEAT_FLOAT
4560 if (var2.v_type == VAR_FLOAT)
4561 f1 = n1;
4562 #endif
4564 #ifdef FEAT_FLOAT
4565 if (var2.v_type == VAR_FLOAT)
4567 f2 = var2.vval.v_float;
4568 n2 = 0;
4570 else
4571 #endif
4573 n2 = get_tv_number_chk(&var2, &error);
4574 if (error)
4576 clear_tv(rettv);
4577 clear_tv(&var2);
4578 return FAIL;
4580 #ifdef FEAT_FLOAT
4581 if (rettv->v_type == VAR_FLOAT)
4582 f2 = n2;
4583 #endif
4585 clear_tv(rettv);
4587 #ifdef FEAT_FLOAT
4588 /* If there is a float on either side the result is a float. */
4589 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4591 if (op == '+')
4592 f1 = f1 + f2;
4593 else
4594 f1 = f1 - f2;
4595 rettv->v_type = VAR_FLOAT;
4596 rettv->vval.v_float = f1;
4598 else
4599 #endif
4601 if (op == '+')
4602 n1 = n1 + n2;
4603 else
4604 n1 = n1 - n2;
4605 rettv->v_type = VAR_NUMBER;
4606 rettv->vval.v_number = n1;
4609 clear_tv(&var2);
4612 return OK;
4616 * Handle fifth level expression:
4617 * * number multiplication
4618 * / number division
4619 * % number modulo
4621 * "arg" must point to the first non-white of the expression.
4622 * "arg" is advanced to the next non-white after the recognized expression.
4624 * Return OK or FAIL.
4626 static int
4627 eval6(arg, rettv, evaluate, want_string)
4628 char_u **arg;
4629 typval_T *rettv;
4630 int evaluate;
4631 int want_string; /* after "." operator */
4633 typval_T var2;
4634 int op;
4635 long n1, n2;
4636 #ifdef FEAT_FLOAT
4637 int use_float = FALSE;
4638 float_T f1 = 0, f2;
4639 #endif
4640 int error = FALSE;
4643 * Get the first variable.
4645 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4646 return FAIL;
4649 * Repeat computing, until no '*', '/' or '%' is following.
4651 for (;;)
4653 op = **arg;
4654 if (op != '*' && op != '/' && op != '%')
4655 break;
4657 if (evaluate)
4659 #ifdef FEAT_FLOAT
4660 if (rettv->v_type == VAR_FLOAT)
4662 f1 = rettv->vval.v_float;
4663 use_float = TRUE;
4664 n1 = 0;
4666 else
4667 #endif
4668 n1 = get_tv_number_chk(rettv, &error);
4669 clear_tv(rettv);
4670 if (error)
4671 return FAIL;
4673 else
4674 n1 = 0;
4677 * Get the second variable.
4679 *arg = skipwhite(*arg + 1);
4680 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4681 return FAIL;
4683 if (evaluate)
4685 #ifdef FEAT_FLOAT
4686 if (var2.v_type == VAR_FLOAT)
4688 if (!use_float)
4690 f1 = n1;
4691 use_float = TRUE;
4693 f2 = var2.vval.v_float;
4694 n2 = 0;
4696 else
4697 #endif
4699 n2 = get_tv_number_chk(&var2, &error);
4700 clear_tv(&var2);
4701 if (error)
4702 return FAIL;
4703 #ifdef FEAT_FLOAT
4704 if (use_float)
4705 f2 = n2;
4706 #endif
4710 * Compute the result.
4711 * When either side is a float the result is a float.
4713 #ifdef FEAT_FLOAT
4714 if (use_float)
4716 if (op == '*')
4717 f1 = f1 * f2;
4718 else if (op == '/')
4720 /* We rely on the floating point library to handle divide
4721 * by zero to result in "inf" and not a crash. */
4722 f1 = f1 / f2;
4724 else
4726 EMSG(_("E804: Cannot use % with float"));
4727 return FAIL;
4729 rettv->v_type = VAR_FLOAT;
4730 rettv->vval.v_float = f1;
4732 else
4733 #endif
4735 if (op == '*')
4736 n1 = n1 * n2;
4737 else if (op == '/')
4739 if (n2 == 0) /* give an error message? */
4741 if (n1 == 0)
4742 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4743 else if (n1 < 0)
4744 n1 = -0x7fffffffL;
4745 else
4746 n1 = 0x7fffffffL;
4748 else
4749 n1 = n1 / n2;
4751 else
4753 if (n2 == 0) /* give an error message? */
4754 n1 = 0;
4755 else
4756 n1 = n1 % n2;
4758 rettv->v_type = VAR_NUMBER;
4759 rettv->vval.v_number = n1;
4764 return OK;
4768 * Handle sixth level expression:
4769 * number number constant
4770 * "string" string constant
4771 * 'string' literal string constant
4772 * &option-name option value
4773 * @r register contents
4774 * identifier variable value
4775 * function() function call
4776 * $VAR environment variable
4777 * (expression) nested expression
4778 * [expr, expr] List
4779 * {key: val, key: val} Dictionary
4781 * Also handle:
4782 * ! in front logical NOT
4783 * - in front unary minus
4784 * + in front unary plus (ignored)
4785 * trailing [] subscript in String or List
4786 * trailing .name entry in Dictionary
4788 * "arg" must point to the first non-white of the expression.
4789 * "arg" is advanced to the next non-white after the recognized expression.
4791 * Return OK or FAIL.
4793 static int
4794 eval7(arg, rettv, evaluate, want_string)
4795 char_u **arg;
4796 typval_T *rettv;
4797 int evaluate;
4798 int want_string; /* after "." operator */
4800 long n;
4801 int len;
4802 char_u *s;
4803 char_u *start_leader, *end_leader;
4804 int ret = OK;
4805 char_u *alias;
4808 * Initialise variable so that clear_tv() can't mistake this for a
4809 * string and free a string that isn't there.
4811 rettv->v_type = VAR_UNKNOWN;
4814 * Skip '!' and '-' characters. They are handled later.
4816 start_leader = *arg;
4817 while (**arg == '!' || **arg == '-' || **arg == '+')
4818 *arg = skipwhite(*arg + 1);
4819 end_leader = *arg;
4821 switch (**arg)
4824 * Number constant.
4826 case '0':
4827 case '1':
4828 case '2':
4829 case '3':
4830 case '4':
4831 case '5':
4832 case '6':
4833 case '7':
4834 case '8':
4835 case '9':
4837 #ifdef FEAT_FLOAT
4838 char_u *p = skipdigits(*arg + 1);
4839 int get_float = FALSE;
4841 /* We accept a float when the format matches
4842 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4843 * strict to avoid backwards compatibility problems.
4844 * Don't look for a float after the "." operator, so that
4845 * ":let vers = 1.2.3" doesn't fail. */
4846 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4848 get_float = TRUE;
4849 p = skipdigits(p + 2);
4850 if (*p == 'e' || *p == 'E')
4852 ++p;
4853 if (*p == '-' || *p == '+')
4854 ++p;
4855 if (!vim_isdigit(*p))
4856 get_float = FALSE;
4857 else
4858 p = skipdigits(p + 1);
4860 if (ASCII_ISALPHA(*p) || *p == '.')
4861 get_float = FALSE;
4863 if (get_float)
4865 float_T f;
4867 *arg += string2float(*arg, &f);
4868 if (evaluate)
4870 rettv->v_type = VAR_FLOAT;
4871 rettv->vval.v_float = f;
4874 else
4875 #endif
4877 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4878 *arg += len;
4879 if (evaluate)
4881 rettv->v_type = VAR_NUMBER;
4882 rettv->vval.v_number = n;
4885 break;
4889 * String constant: "string".
4891 case '"': ret = get_string_tv(arg, rettv, evaluate);
4892 break;
4895 * Literal string constant: 'str''ing'.
4897 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4898 break;
4901 * List: [expr, expr]
4903 case '[': ret = get_list_tv(arg, rettv, evaluate);
4904 break;
4907 * Dictionary: {key: val, key: val}
4909 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4910 break;
4913 * Option value: &name
4915 case '&': ret = get_option_tv(arg, rettv, evaluate);
4916 break;
4919 * Environment variable: $VAR.
4921 case '$': ret = get_env_tv(arg, rettv, evaluate);
4922 break;
4925 * Register contents: @r.
4927 case '@': ++*arg;
4928 if (evaluate)
4930 rettv->v_type = VAR_STRING;
4931 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4933 if (**arg != NUL)
4934 ++*arg;
4935 break;
4938 * nested expression: (expression).
4940 case '(': *arg = skipwhite(*arg + 1);
4941 ret = eval1(arg, rettv, evaluate); /* recursive! */
4942 if (**arg == ')')
4943 ++*arg;
4944 else if (ret == OK)
4946 EMSG(_("E110: Missing ')'"));
4947 clear_tv(rettv);
4948 ret = FAIL;
4950 break;
4952 default: ret = NOTDONE;
4953 break;
4956 if (ret == NOTDONE)
4959 * Must be a variable or function name.
4960 * Can also be a curly-braces kind of name: {expr}.
4962 s = *arg;
4963 len = get_name_len(arg, &alias, evaluate, TRUE);
4964 if (alias != NULL)
4965 s = alias;
4967 if (len <= 0)
4968 ret = FAIL;
4969 else
4971 if (**arg == '(') /* recursive! */
4973 /* If "s" is the name of a variable of type VAR_FUNC
4974 * use its contents. */
4975 s = deref_func_name(s, &len);
4977 /* Invoke the function. */
4978 ret = get_func_tv(s, len, rettv, arg,
4979 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
4980 &len, evaluate, NULL);
4981 /* Stop the expression evaluation when immediately
4982 * aborting on error, or when an interrupt occurred or
4983 * an exception was thrown but not caught. */
4984 if (aborting())
4986 if (ret == OK)
4987 clear_tv(rettv);
4988 ret = FAIL;
4991 else if (evaluate)
4992 ret = get_var_tv(s, len, rettv, TRUE);
4993 else
4994 ret = OK;
4997 if (alias != NULL)
4998 vim_free(alias);
5001 *arg = skipwhite(*arg);
5003 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5004 * expr(expr). */
5005 if (ret == OK)
5006 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5009 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5011 if (ret == OK && evaluate && end_leader > start_leader)
5013 int error = FALSE;
5014 int val = 0;
5015 #ifdef FEAT_FLOAT
5016 float_T f = 0.0;
5018 if (rettv->v_type == VAR_FLOAT)
5019 f = rettv->vval.v_float;
5020 else
5021 #endif
5022 val = get_tv_number_chk(rettv, &error);
5023 if (error)
5025 clear_tv(rettv);
5026 ret = FAIL;
5028 else
5030 while (end_leader > start_leader)
5032 --end_leader;
5033 if (*end_leader == '!')
5035 #ifdef FEAT_FLOAT
5036 if (rettv->v_type == VAR_FLOAT)
5037 f = !f;
5038 else
5039 #endif
5040 val = !val;
5042 else if (*end_leader == '-')
5044 #ifdef FEAT_FLOAT
5045 if (rettv->v_type == VAR_FLOAT)
5046 f = -f;
5047 else
5048 #endif
5049 val = -val;
5052 #ifdef FEAT_FLOAT
5053 if (rettv->v_type == VAR_FLOAT)
5055 clear_tv(rettv);
5056 rettv->vval.v_float = f;
5058 else
5059 #endif
5061 clear_tv(rettv);
5062 rettv->v_type = VAR_NUMBER;
5063 rettv->vval.v_number = val;
5068 return ret;
5072 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5073 * "*arg" points to the '[' or '.'.
5074 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5076 static int
5077 eval_index(arg, rettv, evaluate, verbose)
5078 char_u **arg;
5079 typval_T *rettv;
5080 int evaluate;
5081 int verbose; /* give error messages */
5083 int empty1 = FALSE, empty2 = FALSE;
5084 typval_T var1, var2;
5085 long n1, n2 = 0;
5086 long len = -1;
5087 int range = FALSE;
5088 char_u *s;
5089 char_u *key = NULL;
5091 if (rettv->v_type == VAR_FUNC
5092 #ifdef FEAT_FLOAT
5093 || rettv->v_type == VAR_FLOAT
5094 #endif
5097 if (verbose)
5098 EMSG(_("E695: Cannot index a Funcref"));
5099 return FAIL;
5102 if (**arg == '.')
5105 * dict.name
5107 key = *arg + 1;
5108 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5110 if (len == 0)
5111 return FAIL;
5112 *arg = skipwhite(key + len);
5114 else
5117 * something[idx]
5119 * Get the (first) variable from inside the [].
5121 *arg = skipwhite(*arg + 1);
5122 if (**arg == ':')
5123 empty1 = TRUE;
5124 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5125 return FAIL;
5126 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5128 /* not a number or string */
5129 clear_tv(&var1);
5130 return FAIL;
5134 * Get the second variable from inside the [:].
5136 if (**arg == ':')
5138 range = TRUE;
5139 *arg = skipwhite(*arg + 1);
5140 if (**arg == ']')
5141 empty2 = TRUE;
5142 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5144 if (!empty1)
5145 clear_tv(&var1);
5146 return FAIL;
5148 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5150 /* not a number or string */
5151 if (!empty1)
5152 clear_tv(&var1);
5153 clear_tv(&var2);
5154 return FAIL;
5158 /* Check for the ']'. */
5159 if (**arg != ']')
5161 if (verbose)
5162 EMSG(_(e_missbrac));
5163 clear_tv(&var1);
5164 if (range)
5165 clear_tv(&var2);
5166 return FAIL;
5168 *arg = skipwhite(*arg + 1); /* skip the ']' */
5171 if (evaluate)
5173 n1 = 0;
5174 if (!empty1 && rettv->v_type != VAR_DICT)
5176 n1 = get_tv_number(&var1);
5177 clear_tv(&var1);
5179 if (range)
5181 if (empty2)
5182 n2 = -1;
5183 else
5185 n2 = get_tv_number(&var2);
5186 clear_tv(&var2);
5190 switch (rettv->v_type)
5192 case VAR_NUMBER:
5193 case VAR_STRING:
5194 s = get_tv_string(rettv);
5195 len = (long)STRLEN(s);
5196 if (range)
5198 /* The resulting variable is a substring. If the indexes
5199 * are out of range the result is empty. */
5200 if (n1 < 0)
5202 n1 = len + n1;
5203 if (n1 < 0)
5204 n1 = 0;
5206 if (n2 < 0)
5207 n2 = len + n2;
5208 else if (n2 >= len)
5209 n2 = len;
5210 if (n1 >= len || n2 < 0 || n1 > n2)
5211 s = NULL;
5212 else
5213 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5215 else
5217 /* The resulting variable is a string of a single
5218 * character. If the index is too big or negative the
5219 * result is empty. */
5220 if (n1 >= len || n1 < 0)
5221 s = NULL;
5222 else
5223 s = vim_strnsave(s + n1, 1);
5225 clear_tv(rettv);
5226 rettv->v_type = VAR_STRING;
5227 rettv->vval.v_string = s;
5228 break;
5230 case VAR_LIST:
5231 len = list_len(rettv->vval.v_list);
5232 if (n1 < 0)
5233 n1 = len + n1;
5234 if (!empty1 && (n1 < 0 || n1 >= len))
5236 /* For a range we allow invalid values and return an empty
5237 * list. A list index out of range is an error. */
5238 if (!range)
5240 if (verbose)
5241 EMSGN(_(e_listidx), n1);
5242 return FAIL;
5244 n1 = len;
5246 if (range)
5248 list_T *l;
5249 listitem_T *item;
5251 if (n2 < 0)
5252 n2 = len + n2;
5253 else if (n2 >= len)
5254 n2 = len - 1;
5255 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5256 n2 = -1;
5257 l = list_alloc();
5258 if (l == NULL)
5259 return FAIL;
5260 for (item = list_find(rettv->vval.v_list, n1);
5261 n1 <= n2; ++n1)
5263 if (list_append_tv(l, &item->li_tv) == FAIL)
5265 list_free(l, TRUE);
5266 return FAIL;
5268 item = item->li_next;
5270 clear_tv(rettv);
5271 rettv->v_type = VAR_LIST;
5272 rettv->vval.v_list = l;
5273 ++l->lv_refcount;
5275 else
5277 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5278 clear_tv(rettv);
5279 *rettv = var1;
5281 break;
5283 case VAR_DICT:
5284 if (range)
5286 if (verbose)
5287 EMSG(_(e_dictrange));
5288 if (len == -1)
5289 clear_tv(&var1);
5290 return FAIL;
5293 dictitem_T *item;
5295 if (len == -1)
5297 key = get_tv_string(&var1);
5298 if (*key == NUL)
5300 if (verbose)
5301 EMSG(_(e_emptykey));
5302 clear_tv(&var1);
5303 return FAIL;
5307 item = dict_find(rettv->vval.v_dict, key, (int)len);
5309 if (item == NULL && verbose)
5310 EMSG2(_(e_dictkey), key);
5311 if (len == -1)
5312 clear_tv(&var1);
5313 if (item == NULL)
5314 return FAIL;
5316 copy_tv(&item->di_tv, &var1);
5317 clear_tv(rettv);
5318 *rettv = var1;
5320 break;
5324 return OK;
5328 * Get an option value.
5329 * "arg" points to the '&' or '+' before the option name.
5330 * "arg" is advanced to character after the option name.
5331 * Return OK or FAIL.
5333 static int
5334 get_option_tv(arg, rettv, evaluate)
5335 char_u **arg;
5336 typval_T *rettv; /* when NULL, only check if option exists */
5337 int evaluate;
5339 char_u *option_end;
5340 long numval;
5341 char_u *stringval;
5342 int opt_type;
5343 int c;
5344 int working = (**arg == '+'); /* has("+option") */
5345 int ret = OK;
5346 int opt_flags;
5349 * Isolate the option name and find its value.
5351 option_end = find_option_end(arg, &opt_flags);
5352 if (option_end == NULL)
5354 if (rettv != NULL)
5355 EMSG2(_("E112: Option name missing: %s"), *arg);
5356 return FAIL;
5359 if (!evaluate)
5361 *arg = option_end;
5362 return OK;
5365 c = *option_end;
5366 *option_end = NUL;
5367 opt_type = get_option_value(*arg, &numval,
5368 rettv == NULL ? NULL : &stringval, opt_flags);
5370 if (opt_type == -3) /* invalid name */
5372 if (rettv != NULL)
5373 EMSG2(_("E113: Unknown option: %s"), *arg);
5374 ret = FAIL;
5376 else if (rettv != NULL)
5378 if (opt_type == -2) /* hidden string option */
5380 rettv->v_type = VAR_STRING;
5381 rettv->vval.v_string = NULL;
5383 else if (opt_type == -1) /* hidden number option */
5385 rettv->v_type = VAR_NUMBER;
5386 rettv->vval.v_number = 0;
5388 else if (opt_type == 1) /* number option */
5390 rettv->v_type = VAR_NUMBER;
5391 rettv->vval.v_number = numval;
5393 else /* string option */
5395 rettv->v_type = VAR_STRING;
5396 rettv->vval.v_string = stringval;
5399 else if (working && (opt_type == -2 || opt_type == -1))
5400 ret = FAIL;
5402 *option_end = c; /* put back for error messages */
5403 *arg = option_end;
5405 return ret;
5409 * Allocate a variable for a string constant.
5410 * Return OK or FAIL.
5412 static int
5413 get_string_tv(arg, rettv, evaluate)
5414 char_u **arg;
5415 typval_T *rettv;
5416 int evaluate;
5418 char_u *p;
5419 char_u *name;
5420 int extra = 0;
5423 * Find the end of the string, skipping backslashed characters.
5425 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5427 if (*p == '\\' && p[1] != NUL)
5429 ++p;
5430 /* A "\<x>" form occupies at least 4 characters, and produces up
5431 * to 6 characters: reserve space for 2 extra */
5432 if (*p == '<')
5433 extra += 2;
5437 if (*p != '"')
5439 EMSG2(_("E114: Missing quote: %s"), *arg);
5440 return FAIL;
5443 /* If only parsing, set *arg and return here */
5444 if (!evaluate)
5446 *arg = p + 1;
5447 return OK;
5451 * Copy the string into allocated memory, handling backslashed
5452 * characters.
5454 name = alloc((unsigned)(p - *arg + extra));
5455 if (name == NULL)
5456 return FAIL;
5457 rettv->v_type = VAR_STRING;
5458 rettv->vval.v_string = name;
5460 for (p = *arg + 1; *p != NUL && *p != '"'; )
5462 if (*p == '\\')
5464 switch (*++p)
5466 case 'b': *name++ = BS; ++p; break;
5467 case 'e': *name++ = ESC; ++p; break;
5468 case 'f': *name++ = FF; ++p; break;
5469 case 'n': *name++ = NL; ++p; break;
5470 case 'r': *name++ = CAR; ++p; break;
5471 case 't': *name++ = TAB; ++p; break;
5473 case 'X': /* hex: "\x1", "\x12" */
5474 case 'x':
5475 case 'u': /* Unicode: "\u0023" */
5476 case 'U':
5477 if (vim_isxdigit(p[1]))
5479 int n, nr;
5480 int c = toupper(*p);
5482 if (c == 'X')
5483 n = 2;
5484 else
5485 n = 4;
5486 nr = 0;
5487 while (--n >= 0 && vim_isxdigit(p[1]))
5489 ++p;
5490 nr = (nr << 4) + hex2nr(*p);
5492 ++p;
5493 #ifdef FEAT_MBYTE
5494 /* For "\u" store the number according to
5495 * 'encoding'. */
5496 if (c != 'X')
5497 name += (*mb_char2bytes)(nr, name);
5498 else
5499 #endif
5500 *name++ = nr;
5502 break;
5504 /* octal: "\1", "\12", "\123" */
5505 case '0':
5506 case '1':
5507 case '2':
5508 case '3':
5509 case '4':
5510 case '5':
5511 case '6':
5512 case '7': *name = *p++ - '0';
5513 if (*p >= '0' && *p <= '7')
5515 *name = (*name << 3) + *p++ - '0';
5516 if (*p >= '0' && *p <= '7')
5517 *name = (*name << 3) + *p++ - '0';
5519 ++name;
5520 break;
5522 /* Special key, e.g.: "\<C-W>" */
5523 case '<': extra = trans_special(&p, name, TRUE);
5524 if (extra != 0)
5526 name += extra;
5527 break;
5529 /* FALLTHROUGH */
5531 default: MB_COPY_CHAR(p, name);
5532 break;
5535 else
5536 MB_COPY_CHAR(p, name);
5539 *name = NUL;
5540 *arg = p + 1;
5542 return OK;
5546 * Allocate a variable for a 'str''ing' constant.
5547 * Return OK or FAIL.
5549 static int
5550 get_lit_string_tv(arg, rettv, evaluate)
5551 char_u **arg;
5552 typval_T *rettv;
5553 int evaluate;
5555 char_u *p;
5556 char_u *str;
5557 int reduce = 0;
5560 * Find the end of the string, skipping ''.
5562 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5564 if (*p == '\'')
5566 if (p[1] != '\'')
5567 break;
5568 ++reduce;
5569 ++p;
5573 if (*p != '\'')
5575 EMSG2(_("E115: Missing quote: %s"), *arg);
5576 return FAIL;
5579 /* If only parsing return after setting "*arg" */
5580 if (!evaluate)
5582 *arg = p + 1;
5583 return OK;
5587 * Copy the string into allocated memory, handling '' to ' reduction.
5589 str = alloc((unsigned)((p - *arg) - reduce));
5590 if (str == NULL)
5591 return FAIL;
5592 rettv->v_type = VAR_STRING;
5593 rettv->vval.v_string = str;
5595 for (p = *arg + 1; *p != NUL; )
5597 if (*p == '\'')
5599 if (p[1] != '\'')
5600 break;
5601 ++p;
5603 MB_COPY_CHAR(p, str);
5605 *str = NUL;
5606 *arg = p + 1;
5608 return OK;
5612 * Allocate a variable for a List and fill it from "*arg".
5613 * Return OK or FAIL.
5615 static int
5616 get_list_tv(arg, rettv, evaluate)
5617 char_u **arg;
5618 typval_T *rettv;
5619 int evaluate;
5621 list_T *l = NULL;
5622 typval_T tv;
5623 listitem_T *item;
5625 if (evaluate)
5627 l = list_alloc();
5628 if (l == NULL)
5629 return FAIL;
5632 *arg = skipwhite(*arg + 1);
5633 while (**arg != ']' && **arg != NUL)
5635 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5636 goto failret;
5637 if (evaluate)
5639 item = listitem_alloc();
5640 if (item != NULL)
5642 item->li_tv = tv;
5643 item->li_tv.v_lock = 0;
5644 list_append(l, item);
5646 else
5647 clear_tv(&tv);
5650 if (**arg == ']')
5651 break;
5652 if (**arg != ',')
5654 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5655 goto failret;
5657 *arg = skipwhite(*arg + 1);
5660 if (**arg != ']')
5662 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5663 failret:
5664 if (evaluate)
5665 list_free(l, TRUE);
5666 return FAIL;
5669 *arg = skipwhite(*arg + 1);
5670 if (evaluate)
5672 rettv->v_type = VAR_LIST;
5673 rettv->vval.v_list = l;
5674 ++l->lv_refcount;
5677 return OK;
5681 * Allocate an empty header for a list.
5682 * Caller should take care of the reference count.
5684 list_T *
5685 list_alloc()
5687 list_T *l;
5689 l = (list_T *)alloc_clear(sizeof(list_T));
5690 if (l != NULL)
5692 /* Prepend the list to the list of lists for garbage collection. */
5693 if (first_list != NULL)
5694 first_list->lv_used_prev = l;
5695 l->lv_used_prev = NULL;
5696 l->lv_used_next = first_list;
5697 first_list = l;
5699 return l;
5703 * Allocate an empty list for a return value.
5704 * Returns OK or FAIL.
5706 static int
5707 rettv_list_alloc(rettv)
5708 typval_T *rettv;
5710 list_T *l = list_alloc();
5712 if (l == NULL)
5713 return FAIL;
5715 rettv->vval.v_list = l;
5716 rettv->v_type = VAR_LIST;
5717 ++l->lv_refcount;
5718 return OK;
5722 * Unreference a list: decrement the reference count and free it when it
5723 * becomes zero.
5725 void
5726 list_unref(l)
5727 list_T *l;
5729 if (l != NULL && --l->lv_refcount <= 0)
5730 list_free(l, TRUE);
5734 * Free a list, including all items it points to.
5735 * Ignores the reference count.
5737 void
5738 list_free(l, recurse)
5739 list_T *l;
5740 int recurse; /* Free Lists and Dictionaries recursively. */
5742 listitem_T *item;
5744 /* Remove the list from the list of lists for garbage collection. */
5745 if (l->lv_used_prev == NULL)
5746 first_list = l->lv_used_next;
5747 else
5748 l->lv_used_prev->lv_used_next = l->lv_used_next;
5749 if (l->lv_used_next != NULL)
5750 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5752 for (item = l->lv_first; item != NULL; item = l->lv_first)
5754 /* Remove the item before deleting it. */
5755 l->lv_first = item->li_next;
5756 if (recurse || (item->li_tv.v_type != VAR_LIST
5757 && item->li_tv.v_type != VAR_DICT))
5758 clear_tv(&item->li_tv);
5759 vim_free(item);
5761 vim_free(l);
5765 * Allocate a list item.
5767 static listitem_T *
5768 listitem_alloc()
5770 return (listitem_T *)alloc(sizeof(listitem_T));
5774 * Free a list item. Also clears the value. Does not notify watchers.
5776 static void
5777 listitem_free(item)
5778 listitem_T *item;
5780 clear_tv(&item->li_tv);
5781 vim_free(item);
5785 * Remove a list item from a List and free it. Also clears the value.
5787 static void
5788 listitem_remove(l, item)
5789 list_T *l;
5790 listitem_T *item;
5792 list_remove(l, item, item);
5793 listitem_free(item);
5797 * Get the number of items in a list.
5799 static long
5800 list_len(l)
5801 list_T *l;
5803 if (l == NULL)
5804 return 0L;
5805 return l->lv_len;
5809 * Return TRUE when two lists have exactly the same values.
5811 static int
5812 list_equal(l1, l2, ic)
5813 list_T *l1;
5814 list_T *l2;
5815 int ic; /* ignore case for strings */
5817 listitem_T *item1, *item2;
5819 if (l1 == l2)
5820 return TRUE;
5821 if (list_len(l1) != list_len(l2))
5822 return FALSE;
5824 for (item1 = l1->lv_first, item2 = l2->lv_first;
5825 item1 != NULL && item2 != NULL;
5826 item1 = item1->li_next, item2 = item2->li_next)
5827 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5828 return FALSE;
5829 return item1 == NULL && item2 == NULL;
5832 #if defined(FEAT_PYTHON) || defined(PROTO)
5834 * Return the dictitem that an entry in a hashtable points to.
5836 dictitem_T *
5837 dict_lookup(hi)
5838 hashitem_T *hi;
5840 return HI2DI(hi);
5842 #endif
5845 * Return TRUE when two dictionaries have exactly the same key/values.
5847 static int
5848 dict_equal(d1, d2, ic)
5849 dict_T *d1;
5850 dict_T *d2;
5851 int ic; /* ignore case for strings */
5853 hashitem_T *hi;
5854 dictitem_T *item2;
5855 int todo;
5857 if (d1 == d2)
5858 return TRUE;
5859 if (dict_len(d1) != dict_len(d2))
5860 return FALSE;
5862 todo = (int)d1->dv_hashtab.ht_used;
5863 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5865 if (!HASHITEM_EMPTY(hi))
5867 item2 = dict_find(d2, hi->hi_key, -1);
5868 if (item2 == NULL)
5869 return FALSE;
5870 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5871 return FALSE;
5872 --todo;
5875 return TRUE;
5879 * Return TRUE if "tv1" and "tv2" have the same value.
5880 * Compares the items just like "==" would compare them, but strings and
5881 * numbers are different. Floats and numbers are also different.
5883 static int
5884 tv_equal(tv1, tv2, ic)
5885 typval_T *tv1;
5886 typval_T *tv2;
5887 int ic; /* ignore case */
5889 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5890 char_u *s1, *s2;
5891 static int recursive = 0; /* cach recursive loops */
5892 int r;
5894 if (tv1->v_type != tv2->v_type)
5895 return FALSE;
5896 /* Catch lists and dicts that have an endless loop by limiting
5897 * recursiveness to 1000. We guess they are equal then. */
5898 if (recursive >= 1000)
5899 return TRUE;
5901 switch (tv1->v_type)
5903 case VAR_LIST:
5904 ++recursive;
5905 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5906 --recursive;
5907 return r;
5909 case VAR_DICT:
5910 ++recursive;
5911 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5912 --recursive;
5913 return r;
5915 case VAR_FUNC:
5916 return (tv1->vval.v_string != NULL
5917 && tv2->vval.v_string != NULL
5918 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5920 case VAR_NUMBER:
5921 return tv1->vval.v_number == tv2->vval.v_number;
5923 #ifdef FEAT_FLOAT
5924 case VAR_FLOAT:
5925 return tv1->vval.v_float == tv2->vval.v_float;
5926 #endif
5928 case VAR_STRING:
5929 s1 = get_tv_string_buf(tv1, buf1);
5930 s2 = get_tv_string_buf(tv2, buf2);
5931 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5934 EMSG2(_(e_intern2), "tv_equal()");
5935 return TRUE;
5939 * Locate item with index "n" in list "l" and return it.
5940 * A negative index is counted from the end; -1 is the last item.
5941 * Returns NULL when "n" is out of range.
5943 static listitem_T *
5944 list_find(l, n)
5945 list_T *l;
5946 long n;
5948 listitem_T *item;
5949 long idx;
5951 if (l == NULL)
5952 return NULL;
5954 /* Negative index is relative to the end. */
5955 if (n < 0)
5956 n = l->lv_len + n;
5958 /* Check for index out of range. */
5959 if (n < 0 || n >= l->lv_len)
5960 return NULL;
5962 /* When there is a cached index may start search from there. */
5963 if (l->lv_idx_item != NULL)
5965 if (n < l->lv_idx / 2)
5967 /* closest to the start of the list */
5968 item = l->lv_first;
5969 idx = 0;
5971 else if (n > (l->lv_idx + l->lv_len) / 2)
5973 /* closest to the end of the list */
5974 item = l->lv_last;
5975 idx = l->lv_len - 1;
5977 else
5979 /* closest to the cached index */
5980 item = l->lv_idx_item;
5981 idx = l->lv_idx;
5984 else
5986 if (n < l->lv_len / 2)
5988 /* closest to the start of the list */
5989 item = l->lv_first;
5990 idx = 0;
5992 else
5994 /* closest to the end of the list */
5995 item = l->lv_last;
5996 idx = l->lv_len - 1;
6000 while (n > idx)
6002 /* search forward */
6003 item = item->li_next;
6004 ++idx;
6006 while (n < idx)
6008 /* search backward */
6009 item = item->li_prev;
6010 --idx;
6013 /* cache the used index */
6014 l->lv_idx = idx;
6015 l->lv_idx_item = item;
6017 return item;
6021 * Get list item "l[idx]" as a number.
6023 static long
6024 list_find_nr(l, idx, errorp)
6025 list_T *l;
6026 long idx;
6027 int *errorp; /* set to TRUE when something wrong */
6029 listitem_T *li;
6031 li = list_find(l, idx);
6032 if (li == NULL)
6034 if (errorp != NULL)
6035 *errorp = TRUE;
6036 return -1L;
6038 return get_tv_number_chk(&li->li_tv, errorp);
6042 * Locate "item" list "l" and return its index.
6043 * Returns -1 when "item" is not in the list.
6045 static long
6046 list_idx_of_item(l, item)
6047 list_T *l;
6048 listitem_T *item;
6050 long idx = 0;
6051 listitem_T *li;
6053 if (l == NULL)
6054 return -1;
6055 idx = 0;
6056 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6057 ++idx;
6058 if (li == NULL)
6059 return -1;
6060 return idx;
6064 * Append item "item" to the end of list "l".
6066 static void
6067 list_append(l, item)
6068 list_T *l;
6069 listitem_T *item;
6071 if (l->lv_last == NULL)
6073 /* empty list */
6074 l->lv_first = item;
6075 l->lv_last = item;
6076 item->li_prev = NULL;
6078 else
6080 l->lv_last->li_next = item;
6081 item->li_prev = l->lv_last;
6082 l->lv_last = item;
6084 ++l->lv_len;
6085 item->li_next = NULL;
6089 * Append typval_T "tv" to the end of list "l".
6090 * Return FAIL when out of memory.
6092 static int
6093 list_append_tv(l, tv)
6094 list_T *l;
6095 typval_T *tv;
6097 listitem_T *li = listitem_alloc();
6099 if (li == NULL)
6100 return FAIL;
6101 copy_tv(tv, &li->li_tv);
6102 list_append(l, li);
6103 return OK;
6107 * Add a dictionary to a list. Used by getqflist().
6108 * Return FAIL when out of memory.
6111 list_append_dict(list, dict)
6112 list_T *list;
6113 dict_T *dict;
6115 listitem_T *li = listitem_alloc();
6117 if (li == NULL)
6118 return FAIL;
6119 li->li_tv.v_type = VAR_DICT;
6120 li->li_tv.v_lock = 0;
6121 li->li_tv.vval.v_dict = dict;
6122 list_append(list, li);
6123 ++dict->dv_refcount;
6124 return OK;
6128 * Make a copy of "str" and append it as an item to list "l".
6129 * When "len" >= 0 use "str[len]".
6130 * Returns FAIL when out of memory.
6132 static int
6133 list_append_string(l, str, len)
6134 list_T *l;
6135 char_u *str;
6136 int len;
6138 listitem_T *li = listitem_alloc();
6140 if (li == NULL)
6141 return FAIL;
6142 list_append(l, li);
6143 li->li_tv.v_type = VAR_STRING;
6144 li->li_tv.v_lock = 0;
6145 if (str == NULL)
6146 li->li_tv.vval.v_string = NULL;
6147 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6148 : vim_strsave(str))) == NULL)
6149 return FAIL;
6150 return OK;
6154 * Append "n" to list "l".
6155 * Returns FAIL when out of memory.
6157 static int
6158 list_append_number(l, n)
6159 list_T *l;
6160 varnumber_T n;
6162 listitem_T *li;
6164 li = listitem_alloc();
6165 if (li == NULL)
6166 return FAIL;
6167 li->li_tv.v_type = VAR_NUMBER;
6168 li->li_tv.v_lock = 0;
6169 li->li_tv.vval.v_number = n;
6170 list_append(l, li);
6171 return OK;
6175 * Insert typval_T "tv" in list "l" before "item".
6176 * If "item" is NULL append at the end.
6177 * Return FAIL when out of memory.
6179 static int
6180 list_insert_tv(l, tv, item)
6181 list_T *l;
6182 typval_T *tv;
6183 listitem_T *item;
6185 listitem_T *ni = listitem_alloc();
6187 if (ni == NULL)
6188 return FAIL;
6189 copy_tv(tv, &ni->li_tv);
6190 if (item == NULL)
6191 /* Append new item at end of list. */
6192 list_append(l, ni);
6193 else
6195 /* Insert new item before existing item. */
6196 ni->li_prev = item->li_prev;
6197 ni->li_next = item;
6198 if (item->li_prev == NULL)
6200 l->lv_first = ni;
6201 ++l->lv_idx;
6203 else
6205 item->li_prev->li_next = ni;
6206 l->lv_idx_item = NULL;
6208 item->li_prev = ni;
6209 ++l->lv_len;
6211 return OK;
6215 * Extend "l1" with "l2".
6216 * If "bef" is NULL append at the end, otherwise insert before this item.
6217 * Returns FAIL when out of memory.
6219 static int
6220 list_extend(l1, l2, bef)
6221 list_T *l1;
6222 list_T *l2;
6223 listitem_T *bef;
6225 listitem_T *item;
6227 for (item = l2->lv_first; item != NULL; item = item->li_next)
6228 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6229 return FAIL;
6230 return OK;
6234 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6235 * Return FAIL when out of memory.
6237 static int
6238 list_concat(l1, l2, tv)
6239 list_T *l1;
6240 list_T *l2;
6241 typval_T *tv;
6243 list_T *l;
6245 /* make a copy of the first list. */
6246 l = list_copy(l1, FALSE, 0);
6247 if (l == NULL)
6248 return FAIL;
6249 tv->v_type = VAR_LIST;
6250 tv->vval.v_list = l;
6252 /* append all items from the second list */
6253 return list_extend(l, l2, NULL);
6257 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6258 * The refcount of the new list is set to 1.
6259 * See item_copy() for "copyID".
6260 * Returns NULL when out of memory.
6262 static list_T *
6263 list_copy(orig, deep, copyID)
6264 list_T *orig;
6265 int deep;
6266 int copyID;
6268 list_T *copy;
6269 listitem_T *item;
6270 listitem_T *ni;
6272 if (orig == NULL)
6273 return NULL;
6275 copy = list_alloc();
6276 if (copy != NULL)
6278 if (copyID != 0)
6280 /* Do this before adding the items, because one of the items may
6281 * refer back to this list. */
6282 orig->lv_copyID = copyID;
6283 orig->lv_copylist = copy;
6285 for (item = orig->lv_first; item != NULL && !got_int;
6286 item = item->li_next)
6288 ni = listitem_alloc();
6289 if (ni == NULL)
6290 break;
6291 if (deep)
6293 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6295 vim_free(ni);
6296 break;
6299 else
6300 copy_tv(&item->li_tv, &ni->li_tv);
6301 list_append(copy, ni);
6303 ++copy->lv_refcount;
6304 if (item != NULL)
6306 list_unref(copy);
6307 copy = NULL;
6311 return copy;
6315 * Remove items "item" to "item2" from list "l".
6316 * Does not free the listitem or the value!
6318 static void
6319 list_remove(l, item, item2)
6320 list_T *l;
6321 listitem_T *item;
6322 listitem_T *item2;
6324 listitem_T *ip;
6326 /* notify watchers */
6327 for (ip = item; ip != NULL; ip = ip->li_next)
6329 --l->lv_len;
6330 list_fix_watch(l, ip);
6331 if (ip == item2)
6332 break;
6335 if (item2->li_next == NULL)
6336 l->lv_last = item->li_prev;
6337 else
6338 item2->li_next->li_prev = item->li_prev;
6339 if (item->li_prev == NULL)
6340 l->lv_first = item2->li_next;
6341 else
6342 item->li_prev->li_next = item2->li_next;
6343 l->lv_idx_item = NULL;
6347 * Return an allocated string with the string representation of a list.
6348 * May return NULL.
6350 static char_u *
6351 list2string(tv, copyID)
6352 typval_T *tv;
6353 int copyID;
6355 garray_T ga;
6357 if (tv->vval.v_list == NULL)
6358 return NULL;
6359 ga_init2(&ga, (int)sizeof(char), 80);
6360 ga_append(&ga, '[');
6361 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6363 vim_free(ga.ga_data);
6364 return NULL;
6366 ga_append(&ga, ']');
6367 ga_append(&ga, NUL);
6368 return (char_u *)ga.ga_data;
6372 * Join list "l" into a string in "*gap", using separator "sep".
6373 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6374 * Return FAIL or OK.
6376 static int
6377 list_join(gap, l, sep, echo, copyID)
6378 garray_T *gap;
6379 list_T *l;
6380 char_u *sep;
6381 int echo;
6382 int copyID;
6384 int first = TRUE;
6385 char_u *tofree;
6386 char_u numbuf[NUMBUFLEN];
6387 listitem_T *item;
6388 char_u *s;
6390 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6392 if (first)
6393 first = FALSE;
6394 else
6395 ga_concat(gap, sep);
6397 if (echo)
6398 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6399 else
6400 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6401 if (s != NULL)
6402 ga_concat(gap, s);
6403 vim_free(tofree);
6404 if (s == NULL)
6405 return FAIL;
6407 return OK;
6411 * Garbage collection for lists and dictionaries.
6413 * We use reference counts to be able to free most items right away when they
6414 * are no longer used. But for composite items it's possible that it becomes
6415 * unused while the reference count is > 0: When there is a recursive
6416 * reference. Example:
6417 * :let l = [1, 2, 3]
6418 * :let d = {9: l}
6419 * :let l[1] = d
6421 * Since this is quite unusual we handle this with garbage collection: every
6422 * once in a while find out which lists and dicts are not referenced from any
6423 * variable.
6425 * Here is a good reference text about garbage collection (refers to Python
6426 * but it applies to all reference-counting mechanisms):
6427 * http://python.ca/nas/python/gc/
6431 * Do garbage collection for lists and dicts.
6432 * Return TRUE if some memory was freed.
6435 garbage_collect()
6437 dict_T *dd;
6438 list_T *ll;
6439 int copyID = ++current_copyID;
6440 buf_T *buf;
6441 win_T *wp;
6442 int i;
6443 funccall_T *fc;
6444 int did_free = FALSE;
6445 #ifdef FEAT_WINDOWS
6446 tabpage_T *tp;
6447 #endif
6449 /* Only do this once. */
6450 want_garbage_collect = FALSE;
6451 may_garbage_collect = FALSE;
6452 garbage_collect_at_exit = FALSE;
6455 * 1. Go through all accessible variables and mark all lists and dicts
6456 * with copyID.
6458 /* script-local variables */
6459 for (i = 1; i <= ga_scripts.ga_len; ++i)
6460 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6462 /* buffer-local variables */
6463 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6464 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6466 /* window-local variables */
6467 FOR_ALL_TAB_WINDOWS(tp, wp)
6468 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6470 #ifdef FEAT_WINDOWS
6471 /* tabpage-local variables */
6472 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6473 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6474 #endif
6476 /* global variables */
6477 set_ref_in_ht(&globvarht, copyID);
6479 /* function-local variables */
6480 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6482 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6483 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6487 * 2. Go through the list of dicts and free items without the copyID.
6489 for (dd = first_dict; dd != NULL; )
6490 if (dd->dv_copyID != copyID)
6492 /* Free the Dictionary and ordinary items it contains, but don't
6493 * recurse into Lists and Dictionaries, they will be in the list
6494 * of dicts or list of lists. */
6495 dict_free(dd, FALSE);
6496 did_free = TRUE;
6498 /* restart, next dict may also have been freed */
6499 dd = first_dict;
6501 else
6502 dd = dd->dv_used_next;
6505 * 3. Go through the list of lists and free items without the copyID.
6506 * But don't free a list that has a watcher (used in a for loop), these
6507 * are not referenced anywhere.
6509 for (ll = first_list; ll != NULL; )
6510 if (ll->lv_copyID != copyID && ll->lv_watch == NULL)
6512 /* Free the List and ordinary items it contains, but don't recurse
6513 * into Lists and Dictionaries, they will be in the list of dicts
6514 * or list of lists. */
6515 list_free(ll, FALSE);
6516 did_free = TRUE;
6518 /* restart, next list may also have been freed */
6519 ll = first_list;
6521 else
6522 ll = ll->lv_used_next;
6524 return did_free;
6528 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6530 static void
6531 set_ref_in_ht(ht, copyID)
6532 hashtab_T *ht;
6533 int copyID;
6535 int todo;
6536 hashitem_T *hi;
6538 todo = (int)ht->ht_used;
6539 for (hi = ht->ht_array; todo > 0; ++hi)
6540 if (!HASHITEM_EMPTY(hi))
6542 --todo;
6543 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6548 * Mark all lists and dicts referenced through list "l" with "copyID".
6550 static void
6551 set_ref_in_list(l, copyID)
6552 list_T *l;
6553 int copyID;
6555 listitem_T *li;
6557 for (li = l->lv_first; li != NULL; li = li->li_next)
6558 set_ref_in_item(&li->li_tv, copyID);
6562 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6564 static void
6565 set_ref_in_item(tv, copyID)
6566 typval_T *tv;
6567 int copyID;
6569 dict_T *dd;
6570 list_T *ll;
6572 switch (tv->v_type)
6574 case VAR_DICT:
6575 dd = tv->vval.v_dict;
6576 if (dd->dv_copyID != copyID)
6578 /* Didn't see this dict yet. */
6579 dd->dv_copyID = copyID;
6580 set_ref_in_ht(&dd->dv_hashtab, copyID);
6582 break;
6584 case VAR_LIST:
6585 ll = tv->vval.v_list;
6586 if (ll->lv_copyID != copyID)
6588 /* Didn't see this list yet. */
6589 ll->lv_copyID = copyID;
6590 set_ref_in_list(ll, copyID);
6592 break;
6594 return;
6598 * Allocate an empty header for a dictionary.
6600 dict_T *
6601 dict_alloc()
6603 dict_T *d;
6605 d = (dict_T *)alloc(sizeof(dict_T));
6606 if (d != NULL)
6608 /* Add the list to the list of dicts for garbage collection. */
6609 if (first_dict != NULL)
6610 first_dict->dv_used_prev = d;
6611 d->dv_used_next = first_dict;
6612 d->dv_used_prev = NULL;
6613 first_dict = d;
6615 hash_init(&d->dv_hashtab);
6616 d->dv_lock = 0;
6617 d->dv_refcount = 0;
6618 d->dv_copyID = 0;
6620 return d;
6624 * Unreference a Dictionary: decrement the reference count and free it when it
6625 * becomes zero.
6627 static void
6628 dict_unref(d)
6629 dict_T *d;
6631 if (d != NULL && --d->dv_refcount <= 0)
6632 dict_free(d, TRUE);
6636 * Free a Dictionary, including all items it contains.
6637 * Ignores the reference count.
6639 static void
6640 dict_free(d, recurse)
6641 dict_T *d;
6642 int recurse; /* Free Lists and Dictionaries recursively. */
6644 int todo;
6645 hashitem_T *hi;
6646 dictitem_T *di;
6648 /* Remove the dict from the list of dicts for garbage collection. */
6649 if (d->dv_used_prev == NULL)
6650 first_dict = d->dv_used_next;
6651 else
6652 d->dv_used_prev->dv_used_next = d->dv_used_next;
6653 if (d->dv_used_next != NULL)
6654 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6656 /* Lock the hashtab, we don't want it to resize while freeing items. */
6657 hash_lock(&d->dv_hashtab);
6658 todo = (int)d->dv_hashtab.ht_used;
6659 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6661 if (!HASHITEM_EMPTY(hi))
6663 /* Remove the item before deleting it, just in case there is
6664 * something recursive causing trouble. */
6665 di = HI2DI(hi);
6666 hash_remove(&d->dv_hashtab, hi);
6667 if (recurse || (di->di_tv.v_type != VAR_LIST
6668 && di->di_tv.v_type != VAR_DICT))
6669 clear_tv(&di->di_tv);
6670 vim_free(di);
6671 --todo;
6674 hash_clear(&d->dv_hashtab);
6675 vim_free(d);
6679 * Allocate a Dictionary item.
6680 * The "key" is copied to the new item.
6681 * Note that the value of the item "di_tv" still needs to be initialized!
6682 * Returns NULL when out of memory.
6684 static dictitem_T *
6685 dictitem_alloc(key)
6686 char_u *key;
6688 dictitem_T *di;
6690 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6691 if (di != NULL)
6693 STRCPY(di->di_key, key);
6694 di->di_flags = 0;
6696 return di;
6700 * Make a copy of a Dictionary item.
6702 static dictitem_T *
6703 dictitem_copy(org)
6704 dictitem_T *org;
6706 dictitem_T *di;
6708 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6709 + STRLEN(org->di_key)));
6710 if (di != NULL)
6712 STRCPY(di->di_key, org->di_key);
6713 di->di_flags = 0;
6714 copy_tv(&org->di_tv, &di->di_tv);
6716 return di;
6720 * Remove item "item" from Dictionary "dict" and free it.
6722 static void
6723 dictitem_remove(dict, item)
6724 dict_T *dict;
6725 dictitem_T *item;
6727 hashitem_T *hi;
6729 hi = hash_find(&dict->dv_hashtab, item->di_key);
6730 if (HASHITEM_EMPTY(hi))
6731 EMSG2(_(e_intern2), "dictitem_remove()");
6732 else
6733 hash_remove(&dict->dv_hashtab, hi);
6734 dictitem_free(item);
6738 * Free a dict item. Also clears the value.
6740 static void
6741 dictitem_free(item)
6742 dictitem_T *item;
6744 clear_tv(&item->di_tv);
6745 vim_free(item);
6749 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6750 * The refcount of the new dict is set to 1.
6751 * See item_copy() for "copyID".
6752 * Returns NULL when out of memory.
6754 static dict_T *
6755 dict_copy(orig, deep, copyID)
6756 dict_T *orig;
6757 int deep;
6758 int copyID;
6760 dict_T *copy;
6761 dictitem_T *di;
6762 int todo;
6763 hashitem_T *hi;
6765 if (orig == NULL)
6766 return NULL;
6768 copy = dict_alloc();
6769 if (copy != NULL)
6771 if (copyID != 0)
6773 orig->dv_copyID = copyID;
6774 orig->dv_copydict = copy;
6776 todo = (int)orig->dv_hashtab.ht_used;
6777 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6779 if (!HASHITEM_EMPTY(hi))
6781 --todo;
6783 di = dictitem_alloc(hi->hi_key);
6784 if (di == NULL)
6785 break;
6786 if (deep)
6788 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6789 copyID) == FAIL)
6791 vim_free(di);
6792 break;
6795 else
6796 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6797 if (dict_add(copy, di) == FAIL)
6799 dictitem_free(di);
6800 break;
6805 ++copy->dv_refcount;
6806 if (todo > 0)
6808 dict_unref(copy);
6809 copy = NULL;
6813 return copy;
6817 * Add item "item" to Dictionary "d".
6818 * Returns FAIL when out of memory and when key already existed.
6820 static int
6821 dict_add(d, item)
6822 dict_T *d;
6823 dictitem_T *item;
6825 return hash_add(&d->dv_hashtab, item->di_key);
6829 * Add a number or string entry to dictionary "d".
6830 * When "str" is NULL use number "nr", otherwise use "str".
6831 * Returns FAIL when out of memory and when key already exists.
6834 dict_add_nr_str(d, key, nr, str)
6835 dict_T *d;
6836 char *key;
6837 long nr;
6838 char_u *str;
6840 dictitem_T *item;
6842 item = dictitem_alloc((char_u *)key);
6843 if (item == NULL)
6844 return FAIL;
6845 item->di_tv.v_lock = 0;
6846 if (str == NULL)
6848 item->di_tv.v_type = VAR_NUMBER;
6849 item->di_tv.vval.v_number = nr;
6851 else
6853 item->di_tv.v_type = VAR_STRING;
6854 item->di_tv.vval.v_string = vim_strsave(str);
6856 if (dict_add(d, item) == FAIL)
6858 dictitem_free(item);
6859 return FAIL;
6861 return OK;
6865 * Get the number of items in a Dictionary.
6867 static long
6868 dict_len(d)
6869 dict_T *d;
6871 if (d == NULL)
6872 return 0L;
6873 return (long)d->dv_hashtab.ht_used;
6877 * Find item "key[len]" in Dictionary "d".
6878 * If "len" is negative use strlen(key).
6879 * Returns NULL when not found.
6881 static dictitem_T *
6882 dict_find(d, key, len)
6883 dict_T *d;
6884 char_u *key;
6885 int len;
6887 #define AKEYLEN 200
6888 char_u buf[AKEYLEN];
6889 char_u *akey;
6890 char_u *tofree = NULL;
6891 hashitem_T *hi;
6893 if (len < 0)
6894 akey = key;
6895 else if (len >= AKEYLEN)
6897 tofree = akey = vim_strnsave(key, len);
6898 if (akey == NULL)
6899 return NULL;
6901 else
6903 /* Avoid a malloc/free by using buf[]. */
6904 vim_strncpy(buf, key, len);
6905 akey = buf;
6908 hi = hash_find(&d->dv_hashtab, akey);
6909 vim_free(tofree);
6910 if (HASHITEM_EMPTY(hi))
6911 return NULL;
6912 return HI2DI(hi);
6916 * Get a string item from a dictionary.
6917 * When "save" is TRUE allocate memory for it.
6918 * Returns NULL if the entry doesn't exist or out of memory.
6920 char_u *
6921 get_dict_string(d, key, save)
6922 dict_T *d;
6923 char_u *key;
6924 int save;
6926 dictitem_T *di;
6927 char_u *s;
6929 di = dict_find(d, key, -1);
6930 if (di == NULL)
6931 return NULL;
6932 s = get_tv_string(&di->di_tv);
6933 if (save && s != NULL)
6934 s = vim_strsave(s);
6935 return s;
6939 * Get a number item from a dictionary.
6940 * Returns 0 if the entry doesn't exist or out of memory.
6942 long
6943 get_dict_number(d, key)
6944 dict_T *d;
6945 char_u *key;
6947 dictitem_T *di;
6949 di = dict_find(d, key, -1);
6950 if (di == NULL)
6951 return 0;
6952 return get_tv_number(&di->di_tv);
6956 * Return an allocated string with the string representation of a Dictionary.
6957 * May return NULL.
6959 static char_u *
6960 dict2string(tv, copyID)
6961 typval_T *tv;
6962 int copyID;
6964 garray_T ga;
6965 int first = TRUE;
6966 char_u *tofree;
6967 char_u numbuf[NUMBUFLEN];
6968 hashitem_T *hi;
6969 char_u *s;
6970 dict_T *d;
6971 int todo;
6973 if ((d = tv->vval.v_dict) == NULL)
6974 return NULL;
6975 ga_init2(&ga, (int)sizeof(char), 80);
6976 ga_append(&ga, '{');
6978 todo = (int)d->dv_hashtab.ht_used;
6979 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6981 if (!HASHITEM_EMPTY(hi))
6983 --todo;
6985 if (first)
6986 first = FALSE;
6987 else
6988 ga_concat(&ga, (char_u *)", ");
6990 tofree = string_quote(hi->hi_key, FALSE);
6991 if (tofree != NULL)
6993 ga_concat(&ga, tofree);
6994 vim_free(tofree);
6996 ga_concat(&ga, (char_u *)": ");
6997 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
6998 if (s != NULL)
6999 ga_concat(&ga, s);
7000 vim_free(tofree);
7001 if (s == NULL)
7002 break;
7005 if (todo > 0)
7007 vim_free(ga.ga_data);
7008 return NULL;
7011 ga_append(&ga, '}');
7012 ga_append(&ga, NUL);
7013 return (char_u *)ga.ga_data;
7017 * Allocate a variable for a Dictionary and fill it from "*arg".
7018 * Return OK or FAIL. Returns NOTDONE for {expr}.
7020 static int
7021 get_dict_tv(arg, rettv, evaluate)
7022 char_u **arg;
7023 typval_T *rettv;
7024 int evaluate;
7026 dict_T *d = NULL;
7027 typval_T tvkey;
7028 typval_T tv;
7029 char_u *key = NULL;
7030 dictitem_T *item;
7031 char_u *start = skipwhite(*arg + 1);
7032 char_u buf[NUMBUFLEN];
7035 * First check if it's not a curly-braces thing: {expr}.
7036 * Must do this without evaluating, otherwise a function may be called
7037 * twice. Unfortunately this means we need to call eval1() twice for the
7038 * first item.
7039 * But {} is an empty Dictionary.
7041 if (*start != '}')
7043 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7044 return FAIL;
7045 if (*start == '}')
7046 return NOTDONE;
7049 if (evaluate)
7051 d = dict_alloc();
7052 if (d == NULL)
7053 return FAIL;
7055 tvkey.v_type = VAR_UNKNOWN;
7056 tv.v_type = VAR_UNKNOWN;
7058 *arg = skipwhite(*arg + 1);
7059 while (**arg != '}' && **arg != NUL)
7061 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7062 goto failret;
7063 if (**arg != ':')
7065 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7066 clear_tv(&tvkey);
7067 goto failret;
7069 if (evaluate)
7071 key = get_tv_string_buf_chk(&tvkey, buf);
7072 if (key == NULL || *key == NUL)
7074 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7075 if (key != NULL)
7076 EMSG(_(e_emptykey));
7077 clear_tv(&tvkey);
7078 goto failret;
7082 *arg = skipwhite(*arg + 1);
7083 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7085 if (evaluate)
7086 clear_tv(&tvkey);
7087 goto failret;
7089 if (evaluate)
7091 item = dict_find(d, key, -1);
7092 if (item != NULL)
7094 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7095 clear_tv(&tvkey);
7096 clear_tv(&tv);
7097 goto failret;
7099 item = dictitem_alloc(key);
7100 clear_tv(&tvkey);
7101 if (item != NULL)
7103 item->di_tv = tv;
7104 item->di_tv.v_lock = 0;
7105 if (dict_add(d, item) == FAIL)
7106 dictitem_free(item);
7110 if (**arg == '}')
7111 break;
7112 if (**arg != ',')
7114 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7115 goto failret;
7117 *arg = skipwhite(*arg + 1);
7120 if (**arg != '}')
7122 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7123 failret:
7124 if (evaluate)
7125 dict_free(d, TRUE);
7126 return FAIL;
7129 *arg = skipwhite(*arg + 1);
7130 if (evaluate)
7132 rettv->v_type = VAR_DICT;
7133 rettv->vval.v_dict = d;
7134 ++d->dv_refcount;
7137 return OK;
7141 * Return a string with the string representation of a variable.
7142 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7143 * "numbuf" is used for a number.
7144 * Does not put quotes around strings, as ":echo" displays values.
7145 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7146 * May return NULL.
7148 static char_u *
7149 echo_string(tv, tofree, numbuf, copyID)
7150 typval_T *tv;
7151 char_u **tofree;
7152 char_u *numbuf;
7153 int copyID;
7155 static int recurse = 0;
7156 char_u *r = NULL;
7158 if (recurse >= DICT_MAXNEST)
7160 EMSG(_("E724: variable nested too deep for displaying"));
7161 *tofree = NULL;
7162 return NULL;
7164 ++recurse;
7166 switch (tv->v_type)
7168 case VAR_FUNC:
7169 *tofree = NULL;
7170 r = tv->vval.v_string;
7171 break;
7173 case VAR_LIST:
7174 if (tv->vval.v_list == NULL)
7176 *tofree = NULL;
7177 r = NULL;
7179 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7181 *tofree = NULL;
7182 r = (char_u *)"[...]";
7184 else
7186 tv->vval.v_list->lv_copyID = copyID;
7187 *tofree = list2string(tv, copyID);
7188 r = *tofree;
7190 break;
7192 case VAR_DICT:
7193 if (tv->vval.v_dict == NULL)
7195 *tofree = NULL;
7196 r = NULL;
7198 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7200 *tofree = NULL;
7201 r = (char_u *)"{...}";
7203 else
7205 tv->vval.v_dict->dv_copyID = copyID;
7206 *tofree = dict2string(tv, copyID);
7207 r = *tofree;
7209 break;
7211 case VAR_STRING:
7212 case VAR_NUMBER:
7213 *tofree = NULL;
7214 r = get_tv_string_buf(tv, numbuf);
7215 break;
7217 #ifdef FEAT_FLOAT
7218 case VAR_FLOAT:
7219 *tofree = NULL;
7220 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7221 r = numbuf;
7222 break;
7223 #endif
7225 default:
7226 EMSG2(_(e_intern2), "echo_string()");
7227 *tofree = NULL;
7230 --recurse;
7231 return r;
7235 * Return a string with the string representation of a variable.
7236 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7237 * "numbuf" is used for a number.
7238 * Puts quotes around strings, so that they can be parsed back by eval().
7239 * May return NULL.
7241 static char_u *
7242 tv2string(tv, tofree, numbuf, copyID)
7243 typval_T *tv;
7244 char_u **tofree;
7245 char_u *numbuf;
7246 int copyID;
7248 switch (tv->v_type)
7250 case VAR_FUNC:
7251 *tofree = string_quote(tv->vval.v_string, TRUE);
7252 return *tofree;
7253 case VAR_STRING:
7254 *tofree = string_quote(tv->vval.v_string, FALSE);
7255 return *tofree;
7256 #ifdef FEAT_FLOAT
7257 case VAR_FLOAT:
7258 *tofree = NULL;
7259 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7260 return numbuf;
7261 #endif
7262 case VAR_NUMBER:
7263 case VAR_LIST:
7264 case VAR_DICT:
7265 break;
7266 default:
7267 EMSG2(_(e_intern2), "tv2string()");
7269 return echo_string(tv, tofree, numbuf, copyID);
7273 * Return string "str" in ' quotes, doubling ' characters.
7274 * If "str" is NULL an empty string is assumed.
7275 * If "function" is TRUE make it function('string').
7277 static char_u *
7278 string_quote(str, function)
7279 char_u *str;
7280 int function;
7282 unsigned len;
7283 char_u *p, *r, *s;
7285 len = (function ? 13 : 3);
7286 if (str != NULL)
7288 len += (unsigned)STRLEN(str);
7289 for (p = str; *p != NUL; mb_ptr_adv(p))
7290 if (*p == '\'')
7291 ++len;
7293 s = r = alloc(len);
7294 if (r != NULL)
7296 if (function)
7298 STRCPY(r, "function('");
7299 r += 10;
7301 else
7302 *r++ = '\'';
7303 if (str != NULL)
7304 for (p = str; *p != NUL; )
7306 if (*p == '\'')
7307 *r++ = '\'';
7308 MB_COPY_CHAR(p, r);
7310 *r++ = '\'';
7311 if (function)
7312 *r++ = ')';
7313 *r++ = NUL;
7315 return s;
7318 #ifdef FEAT_FLOAT
7320 * Convert the string "text" to a floating point number.
7321 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7322 * this always uses a decimal point.
7323 * Returns the length of the text that was consumed.
7325 static int
7326 string2float(text, value)
7327 char_u *text;
7328 float_T *value; /* result stored here */
7330 char *s = (char *)text;
7331 float_T f;
7333 f = strtod(s, &s);
7334 *value = f;
7335 return (int)((char_u *)s - text);
7337 #endif
7340 * Get the value of an environment variable.
7341 * "arg" is pointing to the '$'. It is advanced to after the name.
7342 * If the environment variable was not set, silently assume it is empty.
7343 * Always return OK.
7345 static int
7346 get_env_tv(arg, rettv, evaluate)
7347 char_u **arg;
7348 typval_T *rettv;
7349 int evaluate;
7351 char_u *string = NULL;
7352 int len;
7353 int cc;
7354 char_u *name;
7355 int mustfree = FALSE;
7357 ++*arg;
7358 name = *arg;
7359 len = get_env_len(arg);
7360 if (evaluate)
7362 if (len != 0)
7364 cc = name[len];
7365 name[len] = NUL;
7366 /* first try vim_getenv(), fast for normal environment vars */
7367 string = vim_getenv(name, &mustfree);
7368 if (string != NULL && *string != NUL)
7370 if (!mustfree)
7371 string = vim_strsave(string);
7373 else
7375 if (mustfree)
7376 vim_free(string);
7378 /* next try expanding things like $VIM and ${HOME} */
7379 string = expand_env_save(name - 1);
7380 if (string != NULL && *string == '$')
7382 vim_free(string);
7383 string = NULL;
7386 name[len] = cc;
7388 rettv->v_type = VAR_STRING;
7389 rettv->vval.v_string = string;
7392 return OK;
7396 * Array with names and number of arguments of all internal functions
7397 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7399 static struct fst
7401 char *f_name; /* function name */
7402 char f_min_argc; /* minimal number of arguments */
7403 char f_max_argc; /* maximal number of arguments */
7404 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7405 /* implementation of function */
7406 } functions[] =
7408 #ifdef FEAT_FLOAT
7409 {"abs", 1, 1, f_abs},
7410 #endif
7411 {"add", 2, 2, f_add},
7412 {"append", 2, 2, f_append},
7413 {"argc", 0, 0, f_argc},
7414 {"argidx", 0, 0, f_argidx},
7415 {"argv", 0, 1, f_argv},
7416 #ifdef FEAT_FLOAT
7417 {"atan", 1, 1, f_atan},
7418 #endif
7419 {"browse", 4, 4, f_browse},
7420 {"browsedir", 2, 2, f_browsedir},
7421 {"bufexists", 1, 1, f_bufexists},
7422 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7423 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7424 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7425 {"buflisted", 1, 1, f_buflisted},
7426 {"bufloaded", 1, 1, f_bufloaded},
7427 {"bufname", 1, 1, f_bufname},
7428 {"bufnr", 1, 2, f_bufnr},
7429 {"bufwinnr", 1, 1, f_bufwinnr},
7430 {"byte2line", 1, 1, f_byte2line},
7431 {"byteidx", 2, 2, f_byteidx},
7432 {"call", 2, 3, f_call},
7433 #ifdef FEAT_FLOAT
7434 {"ceil", 1, 1, f_ceil},
7435 #endif
7436 {"changenr", 0, 0, f_changenr},
7437 {"char2nr", 1, 1, f_char2nr},
7438 {"cindent", 1, 1, f_cindent},
7439 {"clearmatches", 0, 0, f_clearmatches},
7440 {"col", 1, 1, f_col},
7441 #if defined(FEAT_INS_EXPAND)
7442 {"complete", 2, 2, f_complete},
7443 {"complete_add", 1, 1, f_complete_add},
7444 {"complete_check", 0, 0, f_complete_check},
7445 #endif
7446 {"confirm", 1, 4, f_confirm},
7447 {"copy", 1, 1, f_copy},
7448 #ifdef FEAT_FLOAT
7449 {"cos", 1, 1, f_cos},
7450 #endif
7451 {"count", 2, 4, f_count},
7452 {"cscope_connection",0,3, f_cscope_connection},
7453 {"cursor", 1, 3, f_cursor},
7454 {"deepcopy", 1, 2, f_deepcopy},
7455 {"delete", 1, 1, f_delete},
7456 {"did_filetype", 0, 0, f_did_filetype},
7457 {"diff_filler", 1, 1, f_diff_filler},
7458 {"diff_hlID", 2, 2, f_diff_hlID},
7459 {"empty", 1, 1, f_empty},
7460 {"escape", 2, 2, f_escape},
7461 {"eval", 1, 1, f_eval},
7462 {"eventhandler", 0, 0, f_eventhandler},
7463 {"executable", 1, 1, f_executable},
7464 {"exists", 1, 1, f_exists},
7465 {"expand", 1, 2, f_expand},
7466 {"extend", 2, 3, f_extend},
7467 {"feedkeys", 1, 2, f_feedkeys},
7468 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7469 {"filereadable", 1, 1, f_filereadable},
7470 {"filewritable", 1, 1, f_filewritable},
7471 {"filter", 2, 2, f_filter},
7472 {"finddir", 1, 3, f_finddir},
7473 {"findfile", 1, 3, f_findfile},
7474 #ifdef FEAT_FLOAT
7475 {"float2nr", 1, 1, f_float2nr},
7476 {"floor", 1, 1, f_floor},
7477 #endif
7478 {"fnameescape", 1, 1, f_fnameescape},
7479 {"fnamemodify", 2, 2, f_fnamemodify},
7480 {"foldclosed", 1, 1, f_foldclosed},
7481 {"foldclosedend", 1, 1, f_foldclosedend},
7482 {"foldlevel", 1, 1, f_foldlevel},
7483 {"foldtext", 0, 0, f_foldtext},
7484 {"foldtextresult", 1, 1, f_foldtextresult},
7485 {"foreground", 0, 0, f_foreground},
7486 {"function", 1, 1, f_function},
7487 {"garbagecollect", 0, 1, f_garbagecollect},
7488 {"get", 2, 3, f_get},
7489 {"getbufline", 2, 3, f_getbufline},
7490 {"getbufvar", 2, 2, f_getbufvar},
7491 {"getchar", 0, 1, f_getchar},
7492 {"getcharmod", 0, 0, f_getcharmod},
7493 {"getcmdline", 0, 0, f_getcmdline},
7494 {"getcmdpos", 0, 0, f_getcmdpos},
7495 {"getcmdtype", 0, 0, f_getcmdtype},
7496 {"getcwd", 0, 0, f_getcwd},
7497 {"getfontname", 0, 1, f_getfontname},
7498 {"getfperm", 1, 1, f_getfperm},
7499 {"getfsize", 1, 1, f_getfsize},
7500 {"getftime", 1, 1, f_getftime},
7501 {"getftype", 1, 1, f_getftype},
7502 {"getline", 1, 2, f_getline},
7503 {"getloclist", 1, 1, f_getqflist},
7504 {"getmatches", 0, 0, f_getmatches},
7505 {"getpid", 0, 0, f_getpid},
7506 {"getpos", 1, 1, f_getpos},
7507 {"getqflist", 0, 0, f_getqflist},
7508 {"getreg", 0, 2, f_getreg},
7509 {"getregtype", 0, 1, f_getregtype},
7510 {"gettabwinvar", 3, 3, f_gettabwinvar},
7511 {"getwinposx", 0, 0, f_getwinposx},
7512 {"getwinposy", 0, 0, f_getwinposy},
7513 {"getwinvar", 2, 2, f_getwinvar},
7514 {"glob", 1, 1, f_glob},
7515 {"globpath", 2, 2, f_globpath},
7516 {"has", 1, 1, f_has},
7517 {"has_key", 2, 2, f_has_key},
7518 {"haslocaldir", 0, 0, f_haslocaldir},
7519 {"hasmapto", 1, 3, f_hasmapto},
7520 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7521 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7522 {"histadd", 2, 2, f_histadd},
7523 {"histdel", 1, 2, f_histdel},
7524 {"histget", 1, 2, f_histget},
7525 {"histnr", 1, 1, f_histnr},
7526 {"hlID", 1, 1, f_hlID},
7527 {"hlexists", 1, 1, f_hlexists},
7528 {"hostname", 0, 0, f_hostname},
7529 {"iconv", 3, 3, f_iconv},
7530 {"indent", 1, 1, f_indent},
7531 {"index", 2, 4, f_index},
7532 {"input", 1, 3, f_input},
7533 {"inputdialog", 1, 3, f_inputdialog},
7534 {"inputlist", 1, 1, f_inputlist},
7535 {"inputrestore", 0, 0, f_inputrestore},
7536 {"inputsave", 0, 0, f_inputsave},
7537 {"inputsecret", 1, 2, f_inputsecret},
7538 {"insert", 2, 3, f_insert},
7539 {"isdirectory", 1, 1, f_isdirectory},
7540 {"islocked", 1, 1, f_islocked},
7541 {"items", 1, 1, f_items},
7542 {"join", 1, 2, f_join},
7543 {"keys", 1, 1, f_keys},
7544 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7545 {"len", 1, 1, f_len},
7546 {"libcall", 3, 3, f_libcall},
7547 {"libcallnr", 3, 3, f_libcallnr},
7548 {"line", 1, 1, f_line},
7549 {"line2byte", 1, 1, f_line2byte},
7550 {"lispindent", 1, 1, f_lispindent},
7551 {"localtime", 0, 0, f_localtime},
7552 #ifdef FEAT_FLOAT
7553 {"log10", 1, 1, f_log10},
7554 #endif
7555 {"map", 2, 2, f_map},
7556 {"maparg", 1, 3, f_maparg},
7557 {"mapcheck", 1, 3, f_mapcheck},
7558 {"match", 2, 4, f_match},
7559 {"matchadd", 2, 4, f_matchadd},
7560 {"matcharg", 1, 1, f_matcharg},
7561 {"matchdelete", 1, 1, f_matchdelete},
7562 {"matchend", 2, 4, f_matchend},
7563 {"matchlist", 2, 4, f_matchlist},
7564 {"matchstr", 2, 4, f_matchstr},
7565 {"max", 1, 1, f_max},
7566 {"min", 1, 1, f_min},
7567 #ifdef vim_mkdir
7568 {"mkdir", 1, 3, f_mkdir},
7569 #endif
7570 {"mode", 0, 1, f_mode},
7571 {"nextnonblank", 1, 1, f_nextnonblank},
7572 {"nr2char", 1, 1, f_nr2char},
7573 {"pathshorten", 1, 1, f_pathshorten},
7574 #ifdef FEAT_FLOAT
7575 {"pow", 2, 2, f_pow},
7576 #endif
7577 {"prevnonblank", 1, 1, f_prevnonblank},
7578 {"printf", 2, 19, f_printf},
7579 {"pumvisible", 0, 0, f_pumvisible},
7580 {"range", 1, 3, f_range},
7581 {"readfile", 1, 3, f_readfile},
7582 {"reltime", 0, 2, f_reltime},
7583 {"reltimestr", 1, 1, f_reltimestr},
7584 {"remote_expr", 2, 3, f_remote_expr},
7585 {"remote_foreground", 1, 1, f_remote_foreground},
7586 {"remote_peek", 1, 2, f_remote_peek},
7587 {"remote_read", 1, 1, f_remote_read},
7588 {"remote_send", 2, 3, f_remote_send},
7589 {"remove", 2, 3, f_remove},
7590 {"rename", 2, 2, f_rename},
7591 {"repeat", 2, 2, f_repeat},
7592 {"resolve", 1, 1, f_resolve},
7593 {"reverse", 1, 1, f_reverse},
7594 #ifdef FEAT_FLOAT
7595 {"round", 1, 1, f_round},
7596 #endif
7597 {"search", 1, 4, f_search},
7598 {"searchdecl", 1, 3, f_searchdecl},
7599 {"searchpair", 3, 7, f_searchpair},
7600 {"searchpairpos", 3, 7, f_searchpairpos},
7601 {"searchpos", 1, 4, f_searchpos},
7602 {"server2client", 2, 2, f_server2client},
7603 {"serverlist", 0, 0, f_serverlist},
7604 {"setbufvar", 3, 3, f_setbufvar},
7605 {"setcmdpos", 1, 1, f_setcmdpos},
7606 {"setline", 2, 2, f_setline},
7607 {"setloclist", 2, 3, f_setloclist},
7608 {"setmatches", 1, 1, f_setmatches},
7609 {"setpos", 2, 2, f_setpos},
7610 {"setqflist", 1, 2, f_setqflist},
7611 {"setreg", 2, 3, f_setreg},
7612 {"settabwinvar", 4, 4, f_settabwinvar},
7613 {"setwinvar", 3, 3, f_setwinvar},
7614 {"shellescape", 1, 1, f_shellescape},
7615 {"simplify", 1, 1, f_simplify},
7616 #ifdef FEAT_FLOAT
7617 {"sin", 1, 1, f_sin},
7618 #endif
7619 {"sort", 1, 2, f_sort},
7620 {"soundfold", 1, 1, f_soundfold},
7621 {"spellbadword", 0, 1, f_spellbadword},
7622 {"spellsuggest", 1, 3, f_spellsuggest},
7623 {"split", 1, 3, f_split},
7624 #ifdef FEAT_FLOAT
7625 {"sqrt", 1, 1, f_sqrt},
7626 {"str2float", 1, 1, f_str2float},
7627 #endif
7628 {"str2nr", 1, 2, f_str2nr},
7629 #ifdef HAVE_STRFTIME
7630 {"strftime", 1, 2, f_strftime},
7631 #endif
7632 {"stridx", 2, 3, f_stridx},
7633 {"string", 1, 1, f_string},
7634 {"strlen", 1, 1, f_strlen},
7635 {"strpart", 2, 3, f_strpart},
7636 {"strridx", 2, 3, f_strridx},
7637 {"strtrans", 1, 1, f_strtrans},
7638 {"submatch", 1, 1, f_submatch},
7639 {"substitute", 4, 4, f_substitute},
7640 {"synID", 3, 3, f_synID},
7641 {"synIDattr", 2, 3, f_synIDattr},
7642 {"synIDtrans", 1, 1, f_synIDtrans},
7643 {"synstack", 2, 2, f_synstack},
7644 {"system", 1, 2, f_system},
7645 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7646 {"tabpagenr", 0, 1, f_tabpagenr},
7647 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7648 {"tagfiles", 0, 0, f_tagfiles},
7649 {"taglist", 1, 1, f_taglist},
7650 {"tempname", 0, 0, f_tempname},
7651 {"test", 1, 1, f_test},
7652 {"tolower", 1, 1, f_tolower},
7653 {"toupper", 1, 1, f_toupper},
7654 {"tr", 3, 3, f_tr},
7655 #ifdef FEAT_FLOAT
7656 {"trunc", 1, 1, f_trunc},
7657 #endif
7658 {"type", 1, 1, f_type},
7659 {"values", 1, 1, f_values},
7660 {"virtcol", 1, 1, f_virtcol},
7661 {"visualmode", 0, 1, f_visualmode},
7662 {"winbufnr", 1, 1, f_winbufnr},
7663 {"wincol", 0, 0, f_wincol},
7664 {"winheight", 1, 1, f_winheight},
7665 {"winline", 0, 0, f_winline},
7666 {"winnr", 0, 1, f_winnr},
7667 {"winrestcmd", 0, 0, f_winrestcmd},
7668 {"winrestview", 1, 1, f_winrestview},
7669 {"winsaveview", 0, 0, f_winsaveview},
7670 {"winwidth", 1, 1, f_winwidth},
7671 {"writefile", 2, 3, f_writefile},
7674 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7677 * Function given to ExpandGeneric() to obtain the list of internal
7678 * or user defined function names.
7680 char_u *
7681 get_function_name(xp, idx)
7682 expand_T *xp;
7683 int idx;
7685 static int intidx = -1;
7686 char_u *name;
7688 if (idx == 0)
7689 intidx = -1;
7690 if (intidx < 0)
7692 name = get_user_func_name(xp, idx);
7693 if (name != NULL)
7694 return name;
7696 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7698 STRCPY(IObuff, functions[intidx].f_name);
7699 STRCAT(IObuff, "(");
7700 if (functions[intidx].f_max_argc == 0)
7701 STRCAT(IObuff, ")");
7702 return IObuff;
7705 return NULL;
7709 * Function given to ExpandGeneric() to obtain the list of internal or
7710 * user defined variable or function names.
7712 /*ARGSUSED*/
7713 char_u *
7714 get_expr_name(xp, idx)
7715 expand_T *xp;
7716 int idx;
7718 static int intidx = -1;
7719 char_u *name;
7721 if (idx == 0)
7722 intidx = -1;
7723 if (intidx < 0)
7725 name = get_function_name(xp, idx);
7726 if (name != NULL)
7727 return name;
7729 return get_user_var_name(xp, ++intidx);
7732 #endif /* FEAT_CMDL_COMPL */
7735 * Find internal function in table above.
7736 * Return index, or -1 if not found
7738 static int
7739 find_internal_func(name)
7740 char_u *name; /* name of the function */
7742 int first = 0;
7743 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7744 int cmp;
7745 int x;
7748 * Find the function name in the table. Binary search.
7750 while (first <= last)
7752 x = first + ((unsigned)(last - first) >> 1);
7753 cmp = STRCMP(name, functions[x].f_name);
7754 if (cmp < 0)
7755 last = x - 1;
7756 else if (cmp > 0)
7757 first = x + 1;
7758 else
7759 return x;
7761 return -1;
7765 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7766 * name it contains, otherwise return "name".
7768 static char_u *
7769 deref_func_name(name, lenp)
7770 char_u *name;
7771 int *lenp;
7773 dictitem_T *v;
7774 int cc;
7776 cc = name[*lenp];
7777 name[*lenp] = NUL;
7778 v = find_var(name, NULL);
7779 name[*lenp] = cc;
7780 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7782 if (v->di_tv.vval.v_string == NULL)
7784 *lenp = 0;
7785 return (char_u *)""; /* just in case */
7787 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7788 return v->di_tv.vval.v_string;
7791 return name;
7795 * Allocate a variable for the result of a function.
7796 * Return OK or FAIL.
7798 static int
7799 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7800 evaluate, selfdict)
7801 char_u *name; /* name of the function */
7802 int len; /* length of "name" */
7803 typval_T *rettv;
7804 char_u **arg; /* argument, pointing to the '(' */
7805 linenr_T firstline; /* first line of range */
7806 linenr_T lastline; /* last line of range */
7807 int *doesrange; /* return: function handled range */
7808 int evaluate;
7809 dict_T *selfdict; /* Dictionary for "self" */
7811 char_u *argp;
7812 int ret = OK;
7813 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7814 int argcount = 0; /* number of arguments found */
7817 * Get the arguments.
7819 argp = *arg;
7820 while (argcount < MAX_FUNC_ARGS)
7822 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7823 if (*argp == ')' || *argp == ',' || *argp == NUL)
7824 break;
7825 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7827 ret = FAIL;
7828 break;
7830 ++argcount;
7831 if (*argp != ',')
7832 break;
7834 if (*argp == ')')
7835 ++argp;
7836 else
7837 ret = FAIL;
7839 if (ret == OK)
7840 ret = call_func(name, len, rettv, argcount, argvars,
7841 firstline, lastline, doesrange, evaluate, selfdict);
7842 else if (!aborting())
7844 if (argcount == MAX_FUNC_ARGS)
7845 emsg_funcname("E740: Too many arguments for function %s", name);
7846 else
7847 emsg_funcname("E116: Invalid arguments for function %s", name);
7850 while (--argcount >= 0)
7851 clear_tv(&argvars[argcount]);
7853 *arg = skipwhite(argp);
7854 return ret;
7859 * Call a function with its resolved parameters
7860 * Return OK when the function can't be called, FAIL otherwise.
7861 * Also returns OK when an error was encountered while executing the function.
7863 static int
7864 call_func(name, len, rettv, argcount, argvars, firstline, lastline,
7865 doesrange, evaluate, selfdict)
7866 char_u *name; /* name of the function */
7867 int len; /* length of "name" */
7868 typval_T *rettv; /* return value goes here */
7869 int argcount; /* number of "argvars" */
7870 typval_T *argvars; /* vars for arguments, must have "argcount"
7871 PLUS ONE elements! */
7872 linenr_T firstline; /* first line of range */
7873 linenr_T lastline; /* last line of range */
7874 int *doesrange; /* return: function handled range */
7875 int evaluate;
7876 dict_T *selfdict; /* Dictionary for "self" */
7878 int ret = FAIL;
7879 #define ERROR_UNKNOWN 0
7880 #define ERROR_TOOMANY 1
7881 #define ERROR_TOOFEW 2
7882 #define ERROR_SCRIPT 3
7883 #define ERROR_DICT 4
7884 #define ERROR_NONE 5
7885 #define ERROR_OTHER 6
7886 int error = ERROR_NONE;
7887 int i;
7888 int llen;
7889 ufunc_T *fp;
7890 int cc;
7891 #define FLEN_FIXED 40
7892 char_u fname_buf[FLEN_FIXED + 1];
7893 char_u *fname;
7896 * In a script change <SID>name() and s:name() to K_SNR 123_name().
7897 * Change <SNR>123_name() to K_SNR 123_name().
7898 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
7900 cc = name[len];
7901 name[len] = NUL;
7902 llen = eval_fname_script(name);
7903 if (llen > 0)
7905 fname_buf[0] = K_SPECIAL;
7906 fname_buf[1] = KS_EXTRA;
7907 fname_buf[2] = (int)KE_SNR;
7908 i = 3;
7909 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
7911 if (current_SID <= 0)
7912 error = ERROR_SCRIPT;
7913 else
7915 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
7916 i = (int)STRLEN(fname_buf);
7919 if (i + STRLEN(name + llen) < FLEN_FIXED)
7921 STRCPY(fname_buf + i, name + llen);
7922 fname = fname_buf;
7924 else
7926 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
7927 if (fname == NULL)
7928 error = ERROR_OTHER;
7929 else
7931 mch_memmove(fname, fname_buf, (size_t)i);
7932 STRCPY(fname + i, name + llen);
7936 else
7937 fname = name;
7939 *doesrange = FALSE;
7942 /* execute the function if no errors detected and executing */
7943 if (evaluate && error == ERROR_NONE)
7945 rettv->v_type = VAR_NUMBER; /* default is number rettv */
7946 error = ERROR_UNKNOWN;
7948 if (!builtin_function(fname))
7951 * User defined function.
7953 fp = find_func(fname);
7955 #ifdef FEAT_AUTOCMD
7956 /* Trigger FuncUndefined event, may load the function. */
7957 if (fp == NULL
7958 && apply_autocmds(EVENT_FUNCUNDEFINED,
7959 fname, fname, TRUE, NULL)
7960 && !aborting())
7962 /* executed an autocommand, search for the function again */
7963 fp = find_func(fname);
7965 #endif
7966 /* Try loading a package. */
7967 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
7969 /* loaded a package, search for the function again */
7970 fp = find_func(fname);
7973 if (fp != NULL)
7975 if (fp->uf_flags & FC_RANGE)
7976 *doesrange = TRUE;
7977 if (argcount < fp->uf_args.ga_len)
7978 error = ERROR_TOOFEW;
7979 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
7980 error = ERROR_TOOMANY;
7981 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
7982 error = ERROR_DICT;
7983 else
7986 * Call the user function.
7987 * Save and restore search patterns, script variables and
7988 * redo buffer.
7990 save_search_patterns();
7991 saveRedobuff();
7992 ++fp->uf_calls;
7993 call_user_func(fp, argcount, argvars, rettv,
7994 firstline, lastline,
7995 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
7996 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
7997 && fp->uf_refcount <= 0)
7998 /* Function was unreferenced while being used, free it
7999 * now. */
8000 func_free(fp);
8001 restoreRedobuff();
8002 restore_search_patterns();
8003 error = ERROR_NONE;
8007 else
8010 * Find the function name in the table, call its implementation.
8012 i = find_internal_func(fname);
8013 if (i >= 0)
8015 if (argcount < functions[i].f_min_argc)
8016 error = ERROR_TOOFEW;
8017 else if (argcount > functions[i].f_max_argc)
8018 error = ERROR_TOOMANY;
8019 else
8021 argvars[argcount].v_type = VAR_UNKNOWN;
8022 functions[i].f_func(argvars, rettv);
8023 error = ERROR_NONE;
8028 * The function call (or "FuncUndefined" autocommand sequence) might
8029 * have been aborted by an error, an interrupt, or an explicitly thrown
8030 * exception that has not been caught so far. This situation can be
8031 * tested for by calling aborting(). For an error in an internal
8032 * function or for the "E132" error in call_user_func(), however, the
8033 * throw point at which the "force_abort" flag (temporarily reset by
8034 * emsg()) is normally updated has not been reached yet. We need to
8035 * update that flag first to make aborting() reliable.
8037 update_force_abort();
8039 if (error == ERROR_NONE)
8040 ret = OK;
8043 * Report an error unless the argument evaluation or function call has been
8044 * cancelled due to an aborting error, an interrupt, or an exception.
8046 if (!aborting())
8048 switch (error)
8050 case ERROR_UNKNOWN:
8051 emsg_funcname(N_("E117: Unknown function: %s"), name);
8052 break;
8053 case ERROR_TOOMANY:
8054 emsg_funcname(e_toomanyarg, name);
8055 break;
8056 case ERROR_TOOFEW:
8057 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8058 name);
8059 break;
8060 case ERROR_SCRIPT:
8061 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8062 name);
8063 break;
8064 case ERROR_DICT:
8065 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8066 name);
8067 break;
8071 name[len] = cc;
8072 if (fname != name && fname != fname_buf)
8073 vim_free(fname);
8075 return ret;
8079 * Give an error message with a function name. Handle <SNR> things.
8081 static void
8082 emsg_funcname(ermsg, name)
8083 char *ermsg;
8084 char_u *name;
8086 char_u *p;
8088 if (*name == K_SPECIAL)
8089 p = concat_str((char_u *)"<SNR>", name + 3);
8090 else
8091 p = name;
8092 EMSG2(_(ermsg), p);
8093 if (p != name)
8094 vim_free(p);
8097 /*********************************************
8098 * Implementation of the built-in functions
8101 #ifdef FEAT_FLOAT
8103 * "abs(expr)" function
8105 static void
8106 f_abs(argvars, rettv)
8107 typval_T *argvars;
8108 typval_T *rettv;
8110 if (argvars[0].v_type == VAR_FLOAT)
8112 rettv->v_type = VAR_FLOAT;
8113 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8115 else
8117 varnumber_T n;
8118 int error = FALSE;
8120 n = get_tv_number_chk(&argvars[0], &error);
8121 if (error)
8122 rettv->vval.v_number = -1;
8123 else if (n > 0)
8124 rettv->vval.v_number = n;
8125 else
8126 rettv->vval.v_number = -n;
8129 #endif
8132 * "add(list, item)" function
8134 static void
8135 f_add(argvars, rettv)
8136 typval_T *argvars;
8137 typval_T *rettv;
8139 list_T *l;
8141 rettv->vval.v_number = 1; /* Default: Failed */
8142 if (argvars[0].v_type == VAR_LIST)
8144 if ((l = argvars[0].vval.v_list) != NULL
8145 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8146 && list_append_tv(l, &argvars[1]) == OK)
8147 copy_tv(&argvars[0], rettv);
8149 else
8150 EMSG(_(e_listreq));
8154 * "append(lnum, string/list)" function
8156 static void
8157 f_append(argvars, rettv)
8158 typval_T *argvars;
8159 typval_T *rettv;
8161 long lnum;
8162 char_u *line;
8163 list_T *l = NULL;
8164 listitem_T *li = NULL;
8165 typval_T *tv;
8166 long added = 0;
8168 lnum = get_tv_lnum(argvars);
8169 if (lnum >= 0
8170 && lnum <= curbuf->b_ml.ml_line_count
8171 && u_save(lnum, lnum + 1) == OK)
8173 if (argvars[1].v_type == VAR_LIST)
8175 l = argvars[1].vval.v_list;
8176 if (l == NULL)
8177 return;
8178 li = l->lv_first;
8180 rettv->vval.v_number = 0; /* Default: Success */
8181 for (;;)
8183 if (l == NULL)
8184 tv = &argvars[1]; /* append a string */
8185 else if (li == NULL)
8186 break; /* end of list */
8187 else
8188 tv = &li->li_tv; /* append item from list */
8189 line = get_tv_string_chk(tv);
8190 if (line == NULL) /* type error */
8192 rettv->vval.v_number = 1; /* Failed */
8193 break;
8195 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8196 ++added;
8197 if (l == NULL)
8198 break;
8199 li = li->li_next;
8202 appended_lines_mark(lnum, added);
8203 if (curwin->w_cursor.lnum > lnum)
8204 curwin->w_cursor.lnum += added;
8206 else
8207 rettv->vval.v_number = 1; /* Failed */
8211 * "argc()" function
8213 /* ARGSUSED */
8214 static void
8215 f_argc(argvars, rettv)
8216 typval_T *argvars;
8217 typval_T *rettv;
8219 rettv->vval.v_number = ARGCOUNT;
8223 * "argidx()" function
8225 /* ARGSUSED */
8226 static void
8227 f_argidx(argvars, rettv)
8228 typval_T *argvars;
8229 typval_T *rettv;
8231 rettv->vval.v_number = curwin->w_arg_idx;
8235 * "argv(nr)" function
8237 static void
8238 f_argv(argvars, rettv)
8239 typval_T *argvars;
8240 typval_T *rettv;
8242 int idx;
8244 if (argvars[0].v_type != VAR_UNKNOWN)
8246 idx = get_tv_number_chk(&argvars[0], NULL);
8247 if (idx >= 0 && idx < ARGCOUNT)
8248 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8249 else
8250 rettv->vval.v_string = NULL;
8251 rettv->v_type = VAR_STRING;
8253 else if (rettv_list_alloc(rettv) == OK)
8254 for (idx = 0; idx < ARGCOUNT; ++idx)
8255 list_append_string(rettv->vval.v_list,
8256 alist_name(&ARGLIST[idx]), -1);
8259 #ifdef FEAT_FLOAT
8260 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8263 * Get the float value of "argvars[0]" into "f".
8264 * Returns FAIL when the argument is not a Number or Float.
8266 static int
8267 get_float_arg(argvars, f)
8268 typval_T *argvars;
8269 float_T *f;
8271 if (argvars[0].v_type == VAR_FLOAT)
8273 *f = argvars[0].vval.v_float;
8274 return OK;
8276 if (argvars[0].v_type == VAR_NUMBER)
8278 *f = (float_T)argvars[0].vval.v_number;
8279 return OK;
8281 EMSG(_("E808: Number or Float required"));
8282 return FAIL;
8286 * "atan()" function
8288 static void
8289 f_atan(argvars, rettv)
8290 typval_T *argvars;
8291 typval_T *rettv;
8293 float_T f;
8295 rettv->v_type = VAR_FLOAT;
8296 if (get_float_arg(argvars, &f) == OK)
8297 rettv->vval.v_float = atan(f);
8298 else
8299 rettv->vval.v_float = 0.0;
8301 #endif
8304 * "browse(save, title, initdir, default)" function
8306 /* ARGSUSED */
8307 static void
8308 f_browse(argvars, rettv)
8309 typval_T *argvars;
8310 typval_T *rettv;
8312 #ifdef FEAT_BROWSE
8313 int save;
8314 char_u *title;
8315 char_u *initdir;
8316 char_u *defname;
8317 char_u buf[NUMBUFLEN];
8318 char_u buf2[NUMBUFLEN];
8319 int error = FALSE;
8321 save = get_tv_number_chk(&argvars[0], &error);
8322 title = get_tv_string_chk(&argvars[1]);
8323 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8324 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8326 if (error || title == NULL || initdir == NULL || defname == NULL)
8327 rettv->vval.v_string = NULL;
8328 else
8329 rettv->vval.v_string =
8330 do_browse(save ? BROWSE_SAVE : 0,
8331 title, defname, NULL, initdir, NULL, curbuf);
8332 #else
8333 rettv->vval.v_string = NULL;
8334 #endif
8335 rettv->v_type = VAR_STRING;
8339 * "browsedir(title, initdir)" function
8341 /* ARGSUSED */
8342 static void
8343 f_browsedir(argvars, rettv)
8344 typval_T *argvars;
8345 typval_T *rettv;
8347 #ifdef FEAT_BROWSE
8348 char_u *title;
8349 char_u *initdir;
8350 char_u buf[NUMBUFLEN];
8352 title = get_tv_string_chk(&argvars[0]);
8353 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8355 if (title == NULL || initdir == NULL)
8356 rettv->vval.v_string = NULL;
8357 else
8358 rettv->vval.v_string = do_browse(BROWSE_DIR,
8359 title, NULL, NULL, initdir, NULL, curbuf);
8360 #else
8361 rettv->vval.v_string = NULL;
8362 #endif
8363 rettv->v_type = VAR_STRING;
8366 static buf_T *find_buffer __ARGS((typval_T *avar));
8369 * Find a buffer by number or exact name.
8371 static buf_T *
8372 find_buffer(avar)
8373 typval_T *avar;
8375 buf_T *buf = NULL;
8377 if (avar->v_type == VAR_NUMBER)
8378 buf = buflist_findnr((int)avar->vval.v_number);
8379 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8381 buf = buflist_findname_exp(avar->vval.v_string);
8382 if (buf == NULL)
8384 /* No full path name match, try a match with a URL or a "nofile"
8385 * buffer, these don't use the full path. */
8386 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8387 if (buf->b_fname != NULL
8388 && (path_with_url(buf->b_fname)
8389 #ifdef FEAT_QUICKFIX
8390 || bt_nofile(buf)
8391 #endif
8393 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8394 break;
8397 return buf;
8401 * "bufexists(expr)" function
8403 static void
8404 f_bufexists(argvars, rettv)
8405 typval_T *argvars;
8406 typval_T *rettv;
8408 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8412 * "buflisted(expr)" function
8414 static void
8415 f_buflisted(argvars, rettv)
8416 typval_T *argvars;
8417 typval_T *rettv;
8419 buf_T *buf;
8421 buf = find_buffer(&argvars[0]);
8422 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8426 * "bufloaded(expr)" function
8428 static void
8429 f_bufloaded(argvars, rettv)
8430 typval_T *argvars;
8431 typval_T *rettv;
8433 buf_T *buf;
8435 buf = find_buffer(&argvars[0]);
8436 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8439 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8442 * Get buffer by number or pattern.
8444 static buf_T *
8445 get_buf_tv(tv)
8446 typval_T *tv;
8448 char_u *name = tv->vval.v_string;
8449 int save_magic;
8450 char_u *save_cpo;
8451 buf_T *buf;
8453 if (tv->v_type == VAR_NUMBER)
8454 return buflist_findnr((int)tv->vval.v_number);
8455 if (tv->v_type != VAR_STRING)
8456 return NULL;
8457 if (name == NULL || *name == NUL)
8458 return curbuf;
8459 if (name[0] == '$' && name[1] == NUL)
8460 return lastbuf;
8462 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8463 save_magic = p_magic;
8464 p_magic = TRUE;
8465 save_cpo = p_cpo;
8466 p_cpo = (char_u *)"";
8468 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8469 TRUE, FALSE));
8471 p_magic = save_magic;
8472 p_cpo = save_cpo;
8474 /* If not found, try expanding the name, like done for bufexists(). */
8475 if (buf == NULL)
8476 buf = find_buffer(tv);
8478 return buf;
8482 * "bufname(expr)" function
8484 static void
8485 f_bufname(argvars, rettv)
8486 typval_T *argvars;
8487 typval_T *rettv;
8489 buf_T *buf;
8491 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8492 ++emsg_off;
8493 buf = get_buf_tv(&argvars[0]);
8494 rettv->v_type = VAR_STRING;
8495 if (buf != NULL && buf->b_fname != NULL)
8496 rettv->vval.v_string = vim_strsave(buf->b_fname);
8497 else
8498 rettv->vval.v_string = NULL;
8499 --emsg_off;
8503 * "bufnr(expr)" function
8505 static void
8506 f_bufnr(argvars, rettv)
8507 typval_T *argvars;
8508 typval_T *rettv;
8510 buf_T *buf;
8511 int error = FALSE;
8512 char_u *name;
8514 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8515 ++emsg_off;
8516 buf = get_buf_tv(&argvars[0]);
8517 --emsg_off;
8519 /* If the buffer isn't found and the second argument is not zero create a
8520 * new buffer. */
8521 if (buf == NULL
8522 && argvars[1].v_type != VAR_UNKNOWN
8523 && get_tv_number_chk(&argvars[1], &error) != 0
8524 && !error
8525 && (name = get_tv_string_chk(&argvars[0])) != NULL
8526 && !error)
8527 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8529 if (buf != NULL)
8530 rettv->vval.v_number = buf->b_fnum;
8531 else
8532 rettv->vval.v_number = -1;
8536 * "bufwinnr(nr)" function
8538 static void
8539 f_bufwinnr(argvars, rettv)
8540 typval_T *argvars;
8541 typval_T *rettv;
8543 #ifdef FEAT_WINDOWS
8544 win_T *wp;
8545 int winnr = 0;
8546 #endif
8547 buf_T *buf;
8549 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8550 ++emsg_off;
8551 buf = get_buf_tv(&argvars[0]);
8552 #ifdef FEAT_WINDOWS
8553 for (wp = firstwin; wp; wp = wp->w_next)
8555 ++winnr;
8556 if (wp->w_buffer == buf)
8557 break;
8559 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8560 #else
8561 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8562 #endif
8563 --emsg_off;
8567 * "byte2line(byte)" function
8569 /*ARGSUSED*/
8570 static void
8571 f_byte2line(argvars, rettv)
8572 typval_T *argvars;
8573 typval_T *rettv;
8575 #ifndef FEAT_BYTEOFF
8576 rettv->vval.v_number = -1;
8577 #else
8578 long boff = 0;
8580 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8581 if (boff < 0)
8582 rettv->vval.v_number = -1;
8583 else
8584 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8585 (linenr_T)0, &boff);
8586 #endif
8590 * "byteidx()" function
8592 /*ARGSUSED*/
8593 static void
8594 f_byteidx(argvars, rettv)
8595 typval_T *argvars;
8596 typval_T *rettv;
8598 #ifdef FEAT_MBYTE
8599 char_u *t;
8600 #endif
8601 char_u *str;
8602 long idx;
8604 str = get_tv_string_chk(&argvars[0]);
8605 idx = get_tv_number_chk(&argvars[1], NULL);
8606 rettv->vval.v_number = -1;
8607 if (str == NULL || idx < 0)
8608 return;
8610 #ifdef FEAT_MBYTE
8611 t = str;
8612 for ( ; idx > 0; idx--)
8614 if (*t == NUL) /* EOL reached */
8615 return;
8616 t += (*mb_ptr2len)(t);
8618 rettv->vval.v_number = (varnumber_T)(t - str);
8619 #else
8620 if ((size_t)idx <= STRLEN(str))
8621 rettv->vval.v_number = idx;
8622 #endif
8626 * "call(func, arglist)" function
8628 static void
8629 f_call(argvars, rettv)
8630 typval_T *argvars;
8631 typval_T *rettv;
8633 char_u *func;
8634 typval_T argv[MAX_FUNC_ARGS + 1];
8635 int argc = 0;
8636 listitem_T *item;
8637 int dummy;
8638 dict_T *selfdict = NULL;
8640 rettv->vval.v_number = 0;
8641 if (argvars[1].v_type != VAR_LIST)
8643 EMSG(_(e_listreq));
8644 return;
8646 if (argvars[1].vval.v_list == NULL)
8647 return;
8649 if (argvars[0].v_type == VAR_FUNC)
8650 func = argvars[0].vval.v_string;
8651 else
8652 func = get_tv_string(&argvars[0]);
8653 if (*func == NUL)
8654 return; /* type error or empty name */
8656 if (argvars[2].v_type != VAR_UNKNOWN)
8658 if (argvars[2].v_type != VAR_DICT)
8660 EMSG(_(e_dictreq));
8661 return;
8663 selfdict = argvars[2].vval.v_dict;
8666 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
8667 item = item->li_next)
8669 if (argc == MAX_FUNC_ARGS)
8671 EMSG(_("E699: Too many arguments"));
8672 break;
8674 /* Make a copy of each argument. This is needed to be able to set
8675 * v_lock to VAR_FIXED in the copy without changing the original list.
8677 copy_tv(&item->li_tv, &argv[argc++]);
8680 if (item == NULL)
8681 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
8682 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
8683 &dummy, TRUE, selfdict);
8685 /* Free the arguments. */
8686 while (argc > 0)
8687 clear_tv(&argv[--argc]);
8690 #ifdef FEAT_FLOAT
8692 * "ceil({float})" function
8694 static void
8695 f_ceil(argvars, rettv)
8696 typval_T *argvars;
8697 typval_T *rettv;
8699 float_T f;
8701 rettv->v_type = VAR_FLOAT;
8702 if (get_float_arg(argvars, &f) == OK)
8703 rettv->vval.v_float = ceil(f);
8704 else
8705 rettv->vval.v_float = 0.0;
8707 #endif
8710 * "changenr()" function
8712 /*ARGSUSED*/
8713 static void
8714 f_changenr(argvars, rettv)
8715 typval_T *argvars;
8716 typval_T *rettv;
8718 rettv->vval.v_number = curbuf->b_u_seq_cur;
8722 * "char2nr(string)" function
8724 static void
8725 f_char2nr(argvars, rettv)
8726 typval_T *argvars;
8727 typval_T *rettv;
8729 #ifdef FEAT_MBYTE
8730 if (has_mbyte)
8731 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
8732 else
8733 #endif
8734 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
8738 * "cindent(lnum)" function
8740 static void
8741 f_cindent(argvars, rettv)
8742 typval_T *argvars;
8743 typval_T *rettv;
8745 #ifdef FEAT_CINDENT
8746 pos_T pos;
8747 linenr_T lnum;
8749 pos = curwin->w_cursor;
8750 lnum = get_tv_lnum(argvars);
8751 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
8753 curwin->w_cursor.lnum = lnum;
8754 rettv->vval.v_number = get_c_indent();
8755 curwin->w_cursor = pos;
8757 else
8758 #endif
8759 rettv->vval.v_number = -1;
8763 * "clearmatches()" function
8765 /*ARGSUSED*/
8766 static void
8767 f_clearmatches(argvars, rettv)
8768 typval_T *argvars;
8769 typval_T *rettv;
8771 #ifdef FEAT_SEARCH_EXTRA
8772 clear_matches(curwin);
8773 #endif
8777 * "col(string)" function
8779 static void
8780 f_col(argvars, rettv)
8781 typval_T *argvars;
8782 typval_T *rettv;
8784 colnr_T col = 0;
8785 pos_T *fp;
8786 int fnum = curbuf->b_fnum;
8788 fp = var2fpos(&argvars[0], FALSE, &fnum);
8789 if (fp != NULL && fnum == curbuf->b_fnum)
8791 if (fp->col == MAXCOL)
8793 /* '> can be MAXCOL, get the length of the line then */
8794 if (fp->lnum <= curbuf->b_ml.ml_line_count)
8795 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
8796 else
8797 col = MAXCOL;
8799 else
8801 col = fp->col + 1;
8802 #ifdef FEAT_VIRTUALEDIT
8803 /* col(".") when the cursor is on the NUL at the end of the line
8804 * because of "coladd" can be seen as an extra column. */
8805 if (virtual_active() && fp == &curwin->w_cursor)
8807 char_u *p = ml_get_cursor();
8809 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
8810 curwin->w_virtcol - curwin->w_cursor.coladd))
8812 # ifdef FEAT_MBYTE
8813 int l;
8815 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
8816 col += l;
8817 # else
8818 if (*p != NUL && p[1] == NUL)
8819 ++col;
8820 # endif
8823 #endif
8826 rettv->vval.v_number = col;
8829 #if defined(FEAT_INS_EXPAND)
8831 * "complete()" function
8833 /*ARGSUSED*/
8834 static void
8835 f_complete(argvars, rettv)
8836 typval_T *argvars;
8837 typval_T *rettv;
8839 int startcol;
8841 if ((State & INSERT) == 0)
8843 EMSG(_("E785: complete() can only be used in Insert mode"));
8844 return;
8847 /* Check for undo allowed here, because if something was already inserted
8848 * the line was already saved for undo and this check isn't done. */
8849 if (!undo_allowed())
8850 return;
8852 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
8854 EMSG(_(e_invarg));
8855 return;
8858 startcol = get_tv_number_chk(&argvars[0], NULL);
8859 if (startcol <= 0)
8860 return;
8862 set_completion(startcol - 1, argvars[1].vval.v_list);
8866 * "complete_add()" function
8868 /*ARGSUSED*/
8869 static void
8870 f_complete_add(argvars, rettv)
8871 typval_T *argvars;
8872 typval_T *rettv;
8874 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
8878 * "complete_check()" function
8880 /*ARGSUSED*/
8881 static void
8882 f_complete_check(argvars, rettv)
8883 typval_T *argvars;
8884 typval_T *rettv;
8886 int saved = RedrawingDisabled;
8888 RedrawingDisabled = 0;
8889 ins_compl_check_keys(0);
8890 rettv->vval.v_number = compl_interrupted;
8891 RedrawingDisabled = saved;
8893 #endif
8896 * "confirm(message, buttons[, default [, type]])" function
8898 /*ARGSUSED*/
8899 static void
8900 f_confirm(argvars, rettv)
8901 typval_T *argvars;
8902 typval_T *rettv;
8904 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
8905 char_u *message;
8906 char_u *buttons = NULL;
8907 char_u buf[NUMBUFLEN];
8908 char_u buf2[NUMBUFLEN];
8909 int def = 1;
8910 int type = VIM_GENERIC;
8911 char_u *typestr;
8912 int error = FALSE;
8914 message = get_tv_string_chk(&argvars[0]);
8915 if (message == NULL)
8916 error = TRUE;
8917 if (argvars[1].v_type != VAR_UNKNOWN)
8919 buttons = get_tv_string_buf_chk(&argvars[1], buf);
8920 if (buttons == NULL)
8921 error = TRUE;
8922 if (argvars[2].v_type != VAR_UNKNOWN)
8924 def = get_tv_number_chk(&argvars[2], &error);
8925 if (argvars[3].v_type != VAR_UNKNOWN)
8927 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
8928 if (typestr == NULL)
8929 error = TRUE;
8930 else
8932 switch (TOUPPER_ASC(*typestr))
8934 case 'E': type = VIM_ERROR; break;
8935 case 'Q': type = VIM_QUESTION; break;
8936 case 'I': type = VIM_INFO; break;
8937 case 'W': type = VIM_WARNING; break;
8938 case 'G': type = VIM_GENERIC; break;
8945 if (buttons == NULL || *buttons == NUL)
8946 buttons = (char_u *)_("&Ok");
8948 if (error)
8949 rettv->vval.v_number = 0;
8950 else
8951 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
8952 def, NULL);
8953 #else
8954 rettv->vval.v_number = 0;
8955 #endif
8959 * "copy()" function
8961 static void
8962 f_copy(argvars, rettv)
8963 typval_T *argvars;
8964 typval_T *rettv;
8966 item_copy(&argvars[0], rettv, FALSE, 0);
8969 #ifdef FEAT_FLOAT
8971 * "cos()" function
8973 static void
8974 f_cos(argvars, rettv)
8975 typval_T *argvars;
8976 typval_T *rettv;
8978 float_T f;
8980 rettv->v_type = VAR_FLOAT;
8981 if (get_float_arg(argvars, &f) == OK)
8982 rettv->vval.v_float = cos(f);
8983 else
8984 rettv->vval.v_float = 0.0;
8986 #endif
8989 * "count()" function
8991 static void
8992 f_count(argvars, rettv)
8993 typval_T *argvars;
8994 typval_T *rettv;
8996 long n = 0;
8997 int ic = FALSE;
8999 if (argvars[0].v_type == VAR_LIST)
9001 listitem_T *li;
9002 list_T *l;
9003 long idx;
9005 if ((l = argvars[0].vval.v_list) != NULL)
9007 li = l->lv_first;
9008 if (argvars[2].v_type != VAR_UNKNOWN)
9010 int error = FALSE;
9012 ic = get_tv_number_chk(&argvars[2], &error);
9013 if (argvars[3].v_type != VAR_UNKNOWN)
9015 idx = get_tv_number_chk(&argvars[3], &error);
9016 if (!error)
9018 li = list_find(l, idx);
9019 if (li == NULL)
9020 EMSGN(_(e_listidx), idx);
9023 if (error)
9024 li = NULL;
9027 for ( ; li != NULL; li = li->li_next)
9028 if (tv_equal(&li->li_tv, &argvars[1], ic))
9029 ++n;
9032 else if (argvars[0].v_type == VAR_DICT)
9034 int todo;
9035 dict_T *d;
9036 hashitem_T *hi;
9038 if ((d = argvars[0].vval.v_dict) != NULL)
9040 int error = FALSE;
9042 if (argvars[2].v_type != VAR_UNKNOWN)
9044 ic = get_tv_number_chk(&argvars[2], &error);
9045 if (argvars[3].v_type != VAR_UNKNOWN)
9046 EMSG(_(e_invarg));
9049 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9050 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9052 if (!HASHITEM_EMPTY(hi))
9054 --todo;
9055 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9056 ++n;
9061 else
9062 EMSG2(_(e_listdictarg), "count()");
9063 rettv->vval.v_number = n;
9067 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9069 * Checks the existence of a cscope connection.
9071 /*ARGSUSED*/
9072 static void
9073 f_cscope_connection(argvars, rettv)
9074 typval_T *argvars;
9075 typval_T *rettv;
9077 #ifdef FEAT_CSCOPE
9078 int num = 0;
9079 char_u *dbpath = NULL;
9080 char_u *prepend = NULL;
9081 char_u buf[NUMBUFLEN];
9083 if (argvars[0].v_type != VAR_UNKNOWN
9084 && argvars[1].v_type != VAR_UNKNOWN)
9086 num = (int)get_tv_number(&argvars[0]);
9087 dbpath = get_tv_string(&argvars[1]);
9088 if (argvars[2].v_type != VAR_UNKNOWN)
9089 prepend = get_tv_string_buf(&argvars[2], buf);
9092 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9093 #else
9094 rettv->vval.v_number = 0;
9095 #endif
9099 * "cursor(lnum, col)" function
9101 * Moves the cursor to the specified line and column
9103 /*ARGSUSED*/
9104 static void
9105 f_cursor(argvars, rettv)
9106 typval_T *argvars;
9107 typval_T *rettv;
9109 long line, col;
9110 #ifdef FEAT_VIRTUALEDIT
9111 long coladd = 0;
9112 #endif
9114 if (argvars[1].v_type == VAR_UNKNOWN)
9116 pos_T pos;
9118 if (list2fpos(argvars, &pos, NULL) == FAIL)
9119 return;
9120 line = pos.lnum;
9121 col = pos.col;
9122 #ifdef FEAT_VIRTUALEDIT
9123 coladd = pos.coladd;
9124 #endif
9126 else
9128 line = get_tv_lnum(argvars);
9129 col = get_tv_number_chk(&argvars[1], NULL);
9130 #ifdef FEAT_VIRTUALEDIT
9131 if (argvars[2].v_type != VAR_UNKNOWN)
9132 coladd = get_tv_number_chk(&argvars[2], NULL);
9133 #endif
9135 if (line < 0 || col < 0
9136 #ifdef FEAT_VIRTUALEDIT
9137 || coladd < 0
9138 #endif
9140 return; /* type error; errmsg already given */
9141 if (line > 0)
9142 curwin->w_cursor.lnum = line;
9143 if (col > 0)
9144 curwin->w_cursor.col = col - 1;
9145 #ifdef FEAT_VIRTUALEDIT
9146 curwin->w_cursor.coladd = coladd;
9147 #endif
9149 /* Make sure the cursor is in a valid position. */
9150 check_cursor();
9151 #ifdef FEAT_MBYTE
9152 /* Correct cursor for multi-byte character. */
9153 if (has_mbyte)
9154 mb_adjust_cursor();
9155 #endif
9157 curwin->w_set_curswant = TRUE;
9161 * "deepcopy()" function
9163 static void
9164 f_deepcopy(argvars, rettv)
9165 typval_T *argvars;
9166 typval_T *rettv;
9168 int noref = 0;
9170 if (argvars[1].v_type != VAR_UNKNOWN)
9171 noref = get_tv_number_chk(&argvars[1], NULL);
9172 if (noref < 0 || noref > 1)
9173 EMSG(_(e_invarg));
9174 else
9175 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? ++current_copyID : 0);
9179 * "delete()" function
9181 static void
9182 f_delete(argvars, rettv)
9183 typval_T *argvars;
9184 typval_T *rettv;
9186 if (check_restricted() || check_secure())
9187 rettv->vval.v_number = -1;
9188 else
9189 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9193 * "did_filetype()" function
9195 /*ARGSUSED*/
9196 static void
9197 f_did_filetype(argvars, rettv)
9198 typval_T *argvars;
9199 typval_T *rettv;
9201 #ifdef FEAT_AUTOCMD
9202 rettv->vval.v_number = did_filetype;
9203 #else
9204 rettv->vval.v_number = 0;
9205 #endif
9209 * "diff_filler()" function
9211 /*ARGSUSED*/
9212 static void
9213 f_diff_filler(argvars, rettv)
9214 typval_T *argvars;
9215 typval_T *rettv;
9217 #ifdef FEAT_DIFF
9218 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9219 #endif
9223 * "diff_hlID()" function
9225 /*ARGSUSED*/
9226 static void
9227 f_diff_hlID(argvars, rettv)
9228 typval_T *argvars;
9229 typval_T *rettv;
9231 #ifdef FEAT_DIFF
9232 linenr_T lnum = get_tv_lnum(argvars);
9233 static linenr_T prev_lnum = 0;
9234 static int changedtick = 0;
9235 static int fnum = 0;
9236 static int change_start = 0;
9237 static int change_end = 0;
9238 static hlf_T hlID = (hlf_T)0;
9239 int filler_lines;
9240 int col;
9242 if (lnum < 0) /* ignore type error in {lnum} arg */
9243 lnum = 0;
9244 if (lnum != prev_lnum
9245 || changedtick != curbuf->b_changedtick
9246 || fnum != curbuf->b_fnum)
9248 /* New line, buffer, change: need to get the values. */
9249 filler_lines = diff_check(curwin, lnum);
9250 if (filler_lines < 0)
9252 if (filler_lines == -1)
9254 change_start = MAXCOL;
9255 change_end = -1;
9256 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9257 hlID = HLF_ADD; /* added line */
9258 else
9259 hlID = HLF_CHD; /* changed line */
9261 else
9262 hlID = HLF_ADD; /* added line */
9264 else
9265 hlID = (hlf_T)0;
9266 prev_lnum = lnum;
9267 changedtick = curbuf->b_changedtick;
9268 fnum = curbuf->b_fnum;
9271 if (hlID == HLF_CHD || hlID == HLF_TXD)
9273 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9274 if (col >= change_start && col <= change_end)
9275 hlID = HLF_TXD; /* changed text */
9276 else
9277 hlID = HLF_CHD; /* changed line */
9279 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9280 #endif
9284 * "empty({expr})" function
9286 static void
9287 f_empty(argvars, rettv)
9288 typval_T *argvars;
9289 typval_T *rettv;
9291 int n;
9293 switch (argvars[0].v_type)
9295 case VAR_STRING:
9296 case VAR_FUNC:
9297 n = argvars[0].vval.v_string == NULL
9298 || *argvars[0].vval.v_string == NUL;
9299 break;
9300 case VAR_NUMBER:
9301 n = argvars[0].vval.v_number == 0;
9302 break;
9303 #ifdef FEAT_FLOAT
9304 case VAR_FLOAT:
9305 n = argvars[0].vval.v_float == 0.0;
9306 break;
9307 #endif
9308 case VAR_LIST:
9309 n = argvars[0].vval.v_list == NULL
9310 || argvars[0].vval.v_list->lv_first == NULL;
9311 break;
9312 case VAR_DICT:
9313 n = argvars[0].vval.v_dict == NULL
9314 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9315 break;
9316 default:
9317 EMSG2(_(e_intern2), "f_empty()");
9318 n = 0;
9321 rettv->vval.v_number = n;
9325 * "escape({string}, {chars})" function
9327 static void
9328 f_escape(argvars, rettv)
9329 typval_T *argvars;
9330 typval_T *rettv;
9332 char_u buf[NUMBUFLEN];
9334 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9335 get_tv_string_buf(&argvars[1], buf));
9336 rettv->v_type = VAR_STRING;
9340 * "eval()" function
9342 /*ARGSUSED*/
9343 static void
9344 f_eval(argvars, rettv)
9345 typval_T *argvars;
9346 typval_T *rettv;
9348 char_u *s;
9350 s = get_tv_string_chk(&argvars[0]);
9351 if (s != NULL)
9352 s = skipwhite(s);
9354 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9356 rettv->v_type = VAR_NUMBER;
9357 rettv->vval.v_number = 0;
9359 else if (*s != NUL)
9360 EMSG(_(e_trailing));
9364 * "eventhandler()" function
9366 /*ARGSUSED*/
9367 static void
9368 f_eventhandler(argvars, rettv)
9369 typval_T *argvars;
9370 typval_T *rettv;
9372 rettv->vval.v_number = vgetc_busy;
9376 * "executable()" function
9378 static void
9379 f_executable(argvars, rettv)
9380 typval_T *argvars;
9381 typval_T *rettv;
9383 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9387 * "exists()" function
9389 static void
9390 f_exists(argvars, rettv)
9391 typval_T *argvars;
9392 typval_T *rettv;
9394 char_u *p;
9395 char_u *name;
9396 int n = FALSE;
9397 int len = 0;
9399 p = get_tv_string(&argvars[0]);
9400 if (*p == '$') /* environment variable */
9402 /* first try "normal" environment variables (fast) */
9403 if (mch_getenv(p + 1) != NULL)
9404 n = TRUE;
9405 else
9407 /* try expanding things like $VIM and ${HOME} */
9408 p = expand_env_save(p);
9409 if (p != NULL && *p != '$')
9410 n = TRUE;
9411 vim_free(p);
9414 else if (*p == '&' || *p == '+') /* option */
9416 n = (get_option_tv(&p, NULL, TRUE) == OK);
9417 if (*skipwhite(p) != NUL)
9418 n = FALSE; /* trailing garbage */
9420 else if (*p == '*') /* internal or user defined function */
9422 n = function_exists(p + 1);
9424 else if (*p == ':')
9426 n = cmd_exists(p + 1);
9428 else if (*p == '#')
9430 #ifdef FEAT_AUTOCMD
9431 if (p[1] == '#')
9432 n = autocmd_supported(p + 2);
9433 else
9434 n = au_exists(p + 1);
9435 #endif
9437 else /* internal variable */
9439 char_u *tofree;
9440 typval_T tv;
9442 /* get_name_len() takes care of expanding curly braces */
9443 name = p;
9444 len = get_name_len(&p, &tofree, TRUE, FALSE);
9445 if (len > 0)
9447 if (tofree != NULL)
9448 name = tofree;
9449 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9450 if (n)
9452 /* handle d.key, l[idx], f(expr) */
9453 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9454 if (n)
9455 clear_tv(&tv);
9458 if (*p != NUL)
9459 n = FALSE;
9461 vim_free(tofree);
9464 rettv->vval.v_number = n;
9468 * "expand()" function
9470 static void
9471 f_expand(argvars, rettv)
9472 typval_T *argvars;
9473 typval_T *rettv;
9475 char_u *s;
9476 int len;
9477 char_u *errormsg;
9478 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9479 expand_T xpc;
9480 int error = FALSE;
9482 rettv->v_type = VAR_STRING;
9483 s = get_tv_string(&argvars[0]);
9484 if (*s == '%' || *s == '#' || *s == '<')
9486 ++emsg_off;
9487 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9488 --emsg_off;
9490 else
9492 /* When the optional second argument is non-zero, don't remove matches
9493 * for 'suffixes' and 'wildignore' */
9494 if (argvars[1].v_type != VAR_UNKNOWN
9495 && get_tv_number_chk(&argvars[1], &error))
9496 flags |= WILD_KEEP_ALL;
9497 if (!error)
9499 ExpandInit(&xpc);
9500 xpc.xp_context = EXPAND_FILES;
9501 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9503 else
9504 rettv->vval.v_string = NULL;
9509 * "extend(list, list [, idx])" function
9510 * "extend(dict, dict [, action])" function
9512 static void
9513 f_extend(argvars, rettv)
9514 typval_T *argvars;
9515 typval_T *rettv;
9517 rettv->vval.v_number = 0;
9518 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9520 list_T *l1, *l2;
9521 listitem_T *item;
9522 long before;
9523 int error = FALSE;
9525 l1 = argvars[0].vval.v_list;
9526 l2 = argvars[1].vval.v_list;
9527 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9528 && l2 != NULL)
9530 if (argvars[2].v_type != VAR_UNKNOWN)
9532 before = get_tv_number_chk(&argvars[2], &error);
9533 if (error)
9534 return; /* type error; errmsg already given */
9536 if (before == l1->lv_len)
9537 item = NULL;
9538 else
9540 item = list_find(l1, before);
9541 if (item == NULL)
9543 EMSGN(_(e_listidx), before);
9544 return;
9548 else
9549 item = NULL;
9550 list_extend(l1, l2, item);
9552 copy_tv(&argvars[0], rettv);
9555 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9557 dict_T *d1, *d2;
9558 dictitem_T *di1;
9559 char_u *action;
9560 int i;
9561 hashitem_T *hi2;
9562 int todo;
9564 d1 = argvars[0].vval.v_dict;
9565 d2 = argvars[1].vval.v_dict;
9566 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9567 && d2 != NULL)
9569 /* Check the third argument. */
9570 if (argvars[2].v_type != VAR_UNKNOWN)
9572 static char *(av[]) = {"keep", "force", "error"};
9574 action = get_tv_string_chk(&argvars[2]);
9575 if (action == NULL)
9576 return; /* type error; errmsg already given */
9577 for (i = 0; i < 3; ++i)
9578 if (STRCMP(action, av[i]) == 0)
9579 break;
9580 if (i == 3)
9582 EMSG2(_(e_invarg2), action);
9583 return;
9586 else
9587 action = (char_u *)"force";
9589 /* Go over all entries in the second dict and add them to the
9590 * first dict. */
9591 todo = (int)d2->dv_hashtab.ht_used;
9592 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9594 if (!HASHITEM_EMPTY(hi2))
9596 --todo;
9597 di1 = dict_find(d1, hi2->hi_key, -1);
9598 if (di1 == NULL)
9600 di1 = dictitem_copy(HI2DI(hi2));
9601 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9602 dictitem_free(di1);
9604 else if (*action == 'e')
9606 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9607 break;
9609 else if (*action == 'f')
9611 clear_tv(&di1->di_tv);
9612 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9617 copy_tv(&argvars[0], rettv);
9620 else
9621 EMSG2(_(e_listdictarg), "extend()");
9625 * "feedkeys()" function
9627 /*ARGSUSED*/
9628 static void
9629 f_feedkeys(argvars, rettv)
9630 typval_T *argvars;
9631 typval_T *rettv;
9633 int remap = TRUE;
9634 char_u *keys, *flags;
9635 char_u nbuf[NUMBUFLEN];
9636 int typed = FALSE;
9637 char_u *keys_esc;
9639 /* This is not allowed in the sandbox. If the commands would still be
9640 * executed in the sandbox it would be OK, but it probably happens later,
9641 * when "sandbox" is no longer set. */
9642 if (check_secure())
9643 return;
9645 rettv->vval.v_number = 0;
9646 keys = get_tv_string(&argvars[0]);
9647 if (*keys != NUL)
9649 if (argvars[1].v_type != VAR_UNKNOWN)
9651 flags = get_tv_string_buf(&argvars[1], nbuf);
9652 for ( ; *flags != NUL; ++flags)
9654 switch (*flags)
9656 case 'n': remap = FALSE; break;
9657 case 'm': remap = TRUE; break;
9658 case 't': typed = TRUE; break;
9663 /* Need to escape K_SPECIAL and CSI before putting the string in the
9664 * typeahead buffer. */
9665 keys_esc = vim_strsave_escape_csi(keys);
9666 if (keys_esc != NULL)
9668 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
9669 typebuf.tb_len, !typed, FALSE);
9670 vim_free(keys_esc);
9671 if (vgetc_busy)
9672 typebuf_was_filled = TRUE;
9678 * "filereadable()" function
9680 static void
9681 f_filereadable(argvars, rettv)
9682 typval_T *argvars;
9683 typval_T *rettv;
9685 FILE *fd;
9686 char_u *p;
9687 int n;
9689 p = get_tv_string(&argvars[0]);
9690 if (*p && !mch_isdir(p) && (fd = mch_fopen((char *)p, "r")) != NULL)
9692 n = TRUE;
9693 fclose(fd);
9695 else
9696 n = FALSE;
9698 rettv->vval.v_number = n;
9702 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
9703 * rights to write into.
9705 static void
9706 f_filewritable(argvars, rettv)
9707 typval_T *argvars;
9708 typval_T *rettv;
9710 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
9713 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
9715 static void
9716 findfilendir(argvars, rettv, find_what)
9717 typval_T *argvars;
9718 typval_T *rettv;
9719 int find_what;
9721 #ifdef FEAT_SEARCHPATH
9722 char_u *fname;
9723 char_u *fresult = NULL;
9724 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
9725 char_u *p;
9726 char_u pathbuf[NUMBUFLEN];
9727 int count = 1;
9728 int first = TRUE;
9729 int error = FALSE;
9730 #endif
9732 rettv->vval.v_string = NULL;
9733 rettv->v_type = VAR_STRING;
9735 #ifdef FEAT_SEARCHPATH
9736 fname = get_tv_string(&argvars[0]);
9738 if (argvars[1].v_type != VAR_UNKNOWN)
9740 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
9741 if (p == NULL)
9742 error = TRUE;
9743 else
9745 if (*p != NUL)
9746 path = p;
9748 if (argvars[2].v_type != VAR_UNKNOWN)
9749 count = get_tv_number_chk(&argvars[2], &error);
9753 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
9754 error = TRUE;
9756 if (*fname != NUL && !error)
9760 if (rettv->v_type == VAR_STRING)
9761 vim_free(fresult);
9762 fresult = find_file_in_path_option(first ? fname : NULL,
9763 first ? (int)STRLEN(fname) : 0,
9764 0, first, path,
9765 find_what,
9766 curbuf->b_ffname,
9767 find_what == FINDFILE_DIR
9768 ? (char_u *)"" : curbuf->b_p_sua);
9769 first = FALSE;
9771 if (fresult != NULL && rettv->v_type == VAR_LIST)
9772 list_append_string(rettv->vval.v_list, fresult, -1);
9774 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
9777 if (rettv->v_type == VAR_STRING)
9778 rettv->vval.v_string = fresult;
9779 #endif
9782 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
9783 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
9786 * Implementation of map() and filter().
9788 static void
9789 filter_map(argvars, rettv, map)
9790 typval_T *argvars;
9791 typval_T *rettv;
9792 int map;
9794 char_u buf[NUMBUFLEN];
9795 char_u *expr;
9796 listitem_T *li, *nli;
9797 list_T *l = NULL;
9798 dictitem_T *di;
9799 hashtab_T *ht;
9800 hashitem_T *hi;
9801 dict_T *d = NULL;
9802 typval_T save_val;
9803 typval_T save_key;
9804 int rem;
9805 int todo;
9806 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
9807 int save_did_emsg;
9809 rettv->vval.v_number = 0;
9810 if (argvars[0].v_type == VAR_LIST)
9812 if ((l = argvars[0].vval.v_list) == NULL
9813 || (map && tv_check_lock(l->lv_lock, ermsg)))
9814 return;
9816 else if (argvars[0].v_type == VAR_DICT)
9818 if ((d = argvars[0].vval.v_dict) == NULL
9819 || (map && tv_check_lock(d->dv_lock, ermsg)))
9820 return;
9822 else
9824 EMSG2(_(e_listdictarg), ermsg);
9825 return;
9828 expr = get_tv_string_buf_chk(&argvars[1], buf);
9829 /* On type errors, the preceding call has already displayed an error
9830 * message. Avoid a misleading error message for an empty string that
9831 * was not passed as argument. */
9832 if (expr != NULL)
9834 prepare_vimvar(VV_VAL, &save_val);
9835 expr = skipwhite(expr);
9837 /* We reset "did_emsg" to be able to detect whether an error
9838 * occurred during evaluation of the expression. */
9839 save_did_emsg = did_emsg;
9840 did_emsg = FALSE;
9842 if (argvars[0].v_type == VAR_DICT)
9844 prepare_vimvar(VV_KEY, &save_key);
9845 vimvars[VV_KEY].vv_type = VAR_STRING;
9847 ht = &d->dv_hashtab;
9848 hash_lock(ht);
9849 todo = (int)ht->ht_used;
9850 for (hi = ht->ht_array; todo > 0; ++hi)
9852 if (!HASHITEM_EMPTY(hi))
9854 --todo;
9855 di = HI2DI(hi);
9856 if (tv_check_lock(di->di_tv.v_lock, ermsg))
9857 break;
9858 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
9859 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
9860 || did_emsg)
9861 break;
9862 if (!map && rem)
9863 dictitem_remove(d, di);
9864 clear_tv(&vimvars[VV_KEY].vv_tv);
9867 hash_unlock(ht);
9869 restore_vimvar(VV_KEY, &save_key);
9871 else
9873 for (li = l->lv_first; li != NULL; li = nli)
9875 if (tv_check_lock(li->li_tv.v_lock, ermsg))
9876 break;
9877 nli = li->li_next;
9878 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
9879 || did_emsg)
9880 break;
9881 if (!map && rem)
9882 listitem_remove(l, li);
9886 restore_vimvar(VV_VAL, &save_val);
9888 did_emsg |= save_did_emsg;
9891 copy_tv(&argvars[0], rettv);
9894 static int
9895 filter_map_one(tv, expr, map, remp)
9896 typval_T *tv;
9897 char_u *expr;
9898 int map;
9899 int *remp;
9901 typval_T rettv;
9902 char_u *s;
9903 int retval = FAIL;
9905 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
9906 s = expr;
9907 if (eval1(&s, &rettv, TRUE) == FAIL)
9908 goto theend;
9909 if (*s != NUL) /* check for trailing chars after expr */
9911 EMSG2(_(e_invexpr2), s);
9912 goto theend;
9914 if (map)
9916 /* map(): replace the list item value */
9917 clear_tv(tv);
9918 rettv.v_lock = 0;
9919 *tv = rettv;
9921 else
9923 int error = FALSE;
9925 /* filter(): when expr is zero remove the item */
9926 *remp = (get_tv_number_chk(&rettv, &error) == 0);
9927 clear_tv(&rettv);
9928 /* On type error, nothing has been removed; return FAIL to stop the
9929 * loop. The error message was given by get_tv_number_chk(). */
9930 if (error)
9931 goto theend;
9933 retval = OK;
9934 theend:
9935 clear_tv(&vimvars[VV_VAL].vv_tv);
9936 return retval;
9940 * "filter()" function
9942 static void
9943 f_filter(argvars, rettv)
9944 typval_T *argvars;
9945 typval_T *rettv;
9947 filter_map(argvars, rettv, FALSE);
9951 * "finddir({fname}[, {path}[, {count}]])" function
9953 static void
9954 f_finddir(argvars, rettv)
9955 typval_T *argvars;
9956 typval_T *rettv;
9958 findfilendir(argvars, rettv, FINDFILE_DIR);
9962 * "findfile({fname}[, {path}[, {count}]])" function
9964 static void
9965 f_findfile(argvars, rettv)
9966 typval_T *argvars;
9967 typval_T *rettv;
9969 findfilendir(argvars, rettv, FINDFILE_FILE);
9972 #ifdef FEAT_FLOAT
9974 * "float2nr({float})" function
9976 static void
9977 f_float2nr(argvars, rettv)
9978 typval_T *argvars;
9979 typval_T *rettv;
9981 float_T f;
9983 if (get_float_arg(argvars, &f) == OK)
9985 if (f < -0x7fffffff)
9986 rettv->vval.v_number = -0x7fffffff;
9987 else if (f > 0x7fffffff)
9988 rettv->vval.v_number = 0x7fffffff;
9989 else
9990 rettv->vval.v_number = (varnumber_T)f;
9992 else
9993 rettv->vval.v_number = 0;
9997 * "floor({float})" function
9999 static void
10000 f_floor(argvars, rettv)
10001 typval_T *argvars;
10002 typval_T *rettv;
10004 float_T f;
10006 rettv->v_type = VAR_FLOAT;
10007 if (get_float_arg(argvars, &f) == OK)
10008 rettv->vval.v_float = floor(f);
10009 else
10010 rettv->vval.v_float = 0.0;
10012 #endif
10015 * "fnameescape({string})" function
10017 static void
10018 f_fnameescape(argvars, rettv)
10019 typval_T *argvars;
10020 typval_T *rettv;
10022 rettv->vval.v_string = vim_strsave_fnameescape(
10023 get_tv_string(&argvars[0]), FALSE);
10024 rettv->v_type = VAR_STRING;
10028 * "fnamemodify({fname}, {mods})" function
10030 static void
10031 f_fnamemodify(argvars, rettv)
10032 typval_T *argvars;
10033 typval_T *rettv;
10035 char_u *fname;
10036 char_u *mods;
10037 int usedlen = 0;
10038 int len;
10039 char_u *fbuf = NULL;
10040 char_u buf[NUMBUFLEN];
10042 fname = get_tv_string_chk(&argvars[0]);
10043 mods = get_tv_string_buf_chk(&argvars[1], buf);
10044 if (fname == NULL || mods == NULL)
10045 fname = NULL;
10046 else
10048 len = (int)STRLEN(fname);
10049 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10052 rettv->v_type = VAR_STRING;
10053 if (fname == NULL)
10054 rettv->vval.v_string = NULL;
10055 else
10056 rettv->vval.v_string = vim_strnsave(fname, len);
10057 vim_free(fbuf);
10060 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10063 * "foldclosed()" function
10065 static void
10066 foldclosed_both(argvars, rettv, end)
10067 typval_T *argvars;
10068 typval_T *rettv;
10069 int end;
10071 #ifdef FEAT_FOLDING
10072 linenr_T lnum;
10073 linenr_T first, last;
10075 lnum = get_tv_lnum(argvars);
10076 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10078 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10080 if (end)
10081 rettv->vval.v_number = (varnumber_T)last;
10082 else
10083 rettv->vval.v_number = (varnumber_T)first;
10084 return;
10087 #endif
10088 rettv->vval.v_number = -1;
10092 * "foldclosed()" function
10094 static void
10095 f_foldclosed(argvars, rettv)
10096 typval_T *argvars;
10097 typval_T *rettv;
10099 foldclosed_both(argvars, rettv, FALSE);
10103 * "foldclosedend()" function
10105 static void
10106 f_foldclosedend(argvars, rettv)
10107 typval_T *argvars;
10108 typval_T *rettv;
10110 foldclosed_both(argvars, rettv, TRUE);
10114 * "foldlevel()" function
10116 static void
10117 f_foldlevel(argvars, rettv)
10118 typval_T *argvars;
10119 typval_T *rettv;
10121 #ifdef FEAT_FOLDING
10122 linenr_T lnum;
10124 lnum = get_tv_lnum(argvars);
10125 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10126 rettv->vval.v_number = foldLevel(lnum);
10127 else
10128 #endif
10129 rettv->vval.v_number = 0;
10133 * "foldtext()" function
10135 /*ARGSUSED*/
10136 static void
10137 f_foldtext(argvars, rettv)
10138 typval_T *argvars;
10139 typval_T *rettv;
10141 #ifdef FEAT_FOLDING
10142 linenr_T lnum;
10143 char_u *s;
10144 char_u *r;
10145 int len;
10146 char *txt;
10147 #endif
10149 rettv->v_type = VAR_STRING;
10150 rettv->vval.v_string = NULL;
10151 #ifdef FEAT_FOLDING
10152 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10153 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10154 <= curbuf->b_ml.ml_line_count
10155 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10157 /* Find first non-empty line in the fold. */
10158 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10159 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10161 if (!linewhite(lnum))
10162 break;
10163 ++lnum;
10166 /* Find interesting text in this line. */
10167 s = skipwhite(ml_get(lnum));
10168 /* skip C comment-start */
10169 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10171 s = skipwhite(s + 2);
10172 if (*skipwhite(s) == NUL
10173 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10175 s = skipwhite(ml_get(lnum + 1));
10176 if (*s == '*')
10177 s = skipwhite(s + 1);
10180 txt = _("+-%s%3ld lines: ");
10181 r = alloc((unsigned)(STRLEN(txt)
10182 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10183 + 20 /* for %3ld */
10184 + STRLEN(s))); /* concatenated */
10185 if (r != NULL)
10187 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10188 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10189 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10190 len = (int)STRLEN(r);
10191 STRCAT(r, s);
10192 /* remove 'foldmarker' and 'commentstring' */
10193 foldtext_cleanup(r + len);
10194 rettv->vval.v_string = r;
10197 #endif
10201 * "foldtextresult(lnum)" function
10203 /*ARGSUSED*/
10204 static void
10205 f_foldtextresult(argvars, rettv)
10206 typval_T *argvars;
10207 typval_T *rettv;
10209 #ifdef FEAT_FOLDING
10210 linenr_T lnum;
10211 char_u *text;
10212 char_u buf[51];
10213 foldinfo_T foldinfo;
10214 int fold_count;
10215 #endif
10217 rettv->v_type = VAR_STRING;
10218 rettv->vval.v_string = NULL;
10219 #ifdef FEAT_FOLDING
10220 lnum = get_tv_lnum(argvars);
10221 /* treat illegal types and illegal string values for {lnum} the same */
10222 if (lnum < 0)
10223 lnum = 0;
10224 fold_count = foldedCount(curwin, lnum, &foldinfo);
10225 if (fold_count > 0)
10227 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10228 &foldinfo, buf);
10229 if (text == buf)
10230 text = vim_strsave(text);
10231 rettv->vval.v_string = text;
10233 #endif
10237 * "foreground()" function
10239 /*ARGSUSED*/
10240 static void
10241 f_foreground(argvars, rettv)
10242 typval_T *argvars;
10243 typval_T *rettv;
10245 rettv->vval.v_number = 0;
10246 #ifdef FEAT_GUI
10247 if (gui.in_use)
10248 gui_mch_set_foreground();
10249 #else
10250 # ifdef WIN32
10251 win32_set_foreground();
10252 # endif
10253 #endif
10257 * "function()" function
10259 /*ARGSUSED*/
10260 static void
10261 f_function(argvars, rettv)
10262 typval_T *argvars;
10263 typval_T *rettv;
10265 char_u *s;
10267 rettv->vval.v_number = 0;
10268 s = get_tv_string(&argvars[0]);
10269 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10270 EMSG2(_(e_invarg2), s);
10271 else if (!function_exists(s))
10272 EMSG2(_("E700: Unknown function: %s"), s);
10273 else
10275 rettv->vval.v_string = vim_strsave(s);
10276 rettv->v_type = VAR_FUNC;
10281 * "garbagecollect()" function
10283 /*ARGSUSED*/
10284 static void
10285 f_garbagecollect(argvars, rettv)
10286 typval_T *argvars;
10287 typval_T *rettv;
10289 /* This is postponed until we are back at the toplevel, because we may be
10290 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10291 want_garbage_collect = TRUE;
10293 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10294 garbage_collect_at_exit = TRUE;
10298 * "get()" function
10300 static void
10301 f_get(argvars, rettv)
10302 typval_T *argvars;
10303 typval_T *rettv;
10305 listitem_T *li;
10306 list_T *l;
10307 dictitem_T *di;
10308 dict_T *d;
10309 typval_T *tv = NULL;
10311 if (argvars[0].v_type == VAR_LIST)
10313 if ((l = argvars[0].vval.v_list) != NULL)
10315 int error = FALSE;
10317 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10318 if (!error && li != NULL)
10319 tv = &li->li_tv;
10322 else if (argvars[0].v_type == VAR_DICT)
10324 if ((d = argvars[0].vval.v_dict) != NULL)
10326 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10327 if (di != NULL)
10328 tv = &di->di_tv;
10331 else
10332 EMSG2(_(e_listdictarg), "get()");
10334 if (tv == NULL)
10336 if (argvars[2].v_type == VAR_UNKNOWN)
10337 rettv->vval.v_number = 0;
10338 else
10339 copy_tv(&argvars[2], rettv);
10341 else
10342 copy_tv(tv, rettv);
10345 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10348 * Get line or list of lines from buffer "buf" into "rettv".
10349 * Return a range (from start to end) of lines in rettv from the specified
10350 * buffer.
10351 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10353 static void
10354 get_buffer_lines(buf, start, end, retlist, rettv)
10355 buf_T *buf;
10356 linenr_T start;
10357 linenr_T end;
10358 int retlist;
10359 typval_T *rettv;
10361 char_u *p;
10363 if (retlist)
10365 if (rettv_list_alloc(rettv) == FAIL)
10366 return;
10368 else
10369 rettv->vval.v_number = 0;
10371 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10372 return;
10374 if (!retlist)
10376 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10377 p = ml_get_buf(buf, start, FALSE);
10378 else
10379 p = (char_u *)"";
10381 rettv->v_type = VAR_STRING;
10382 rettv->vval.v_string = vim_strsave(p);
10384 else
10386 if (end < start)
10387 return;
10389 if (start < 1)
10390 start = 1;
10391 if (end > buf->b_ml.ml_line_count)
10392 end = buf->b_ml.ml_line_count;
10393 while (start <= end)
10394 if (list_append_string(rettv->vval.v_list,
10395 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10396 break;
10401 * "getbufline()" function
10403 static void
10404 f_getbufline(argvars, rettv)
10405 typval_T *argvars;
10406 typval_T *rettv;
10408 linenr_T lnum;
10409 linenr_T end;
10410 buf_T *buf;
10412 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10413 ++emsg_off;
10414 buf = get_buf_tv(&argvars[0]);
10415 --emsg_off;
10417 lnum = get_tv_lnum_buf(&argvars[1], buf);
10418 if (argvars[2].v_type == VAR_UNKNOWN)
10419 end = lnum;
10420 else
10421 end = get_tv_lnum_buf(&argvars[2], buf);
10423 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10427 * "getbufvar()" function
10429 static void
10430 f_getbufvar(argvars, rettv)
10431 typval_T *argvars;
10432 typval_T *rettv;
10434 buf_T *buf;
10435 buf_T *save_curbuf;
10436 char_u *varname;
10437 dictitem_T *v;
10439 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10440 varname = get_tv_string_chk(&argvars[1]);
10441 ++emsg_off;
10442 buf = get_buf_tv(&argvars[0]);
10444 rettv->v_type = VAR_STRING;
10445 rettv->vval.v_string = NULL;
10447 if (buf != NULL && varname != NULL)
10449 /* set curbuf to be our buf, temporarily */
10450 save_curbuf = curbuf;
10451 curbuf = buf;
10453 if (*varname == '&') /* buffer-local-option */
10454 get_option_tv(&varname, rettv, TRUE);
10455 else
10457 if (*varname == NUL)
10458 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10459 * scope prefix before the NUL byte is required by
10460 * find_var_in_ht(). */
10461 varname = (char_u *)"b:" + 2;
10462 /* look up the variable */
10463 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10464 if (v != NULL)
10465 copy_tv(&v->di_tv, rettv);
10468 /* restore previous notion of curbuf */
10469 curbuf = save_curbuf;
10472 --emsg_off;
10476 * "getchar()" function
10478 static void
10479 f_getchar(argvars, rettv)
10480 typval_T *argvars;
10481 typval_T *rettv;
10483 varnumber_T n;
10484 int error = FALSE;
10486 /* Position the cursor. Needed after a message that ends in a space. */
10487 windgoto(msg_row, msg_col);
10489 ++no_mapping;
10490 ++allow_keys;
10491 for (;;)
10493 if (argvars[0].v_type == VAR_UNKNOWN)
10494 /* getchar(): blocking wait. */
10495 n = safe_vgetc();
10496 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10497 /* getchar(1): only check if char avail */
10498 n = vpeekc();
10499 else if (error || vpeekc() == NUL)
10500 /* illegal argument or getchar(0) and no char avail: return zero */
10501 n = 0;
10502 else
10503 /* getchar(0) and char avail: return char */
10504 n = safe_vgetc();
10505 if (n == K_IGNORE)
10506 continue;
10507 break;
10509 --no_mapping;
10510 --allow_keys;
10512 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10513 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10514 vimvars[VV_MOUSE_COL].vv_nr = 0;
10516 rettv->vval.v_number = n;
10517 if (IS_SPECIAL(n) || mod_mask != 0)
10519 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10520 int i = 0;
10522 /* Turn a special key into three bytes, plus modifier. */
10523 if (mod_mask != 0)
10525 temp[i++] = K_SPECIAL;
10526 temp[i++] = KS_MODIFIER;
10527 temp[i++] = mod_mask;
10529 if (IS_SPECIAL(n))
10531 temp[i++] = K_SPECIAL;
10532 temp[i++] = K_SECOND(n);
10533 temp[i++] = K_THIRD(n);
10535 #ifdef FEAT_MBYTE
10536 else if (has_mbyte)
10537 i += (*mb_char2bytes)(n, temp + i);
10538 #endif
10539 else
10540 temp[i++] = n;
10541 temp[i++] = NUL;
10542 rettv->v_type = VAR_STRING;
10543 rettv->vval.v_string = vim_strsave(temp);
10545 #ifdef FEAT_MOUSE
10546 if (n == K_LEFTMOUSE
10547 || n == K_LEFTMOUSE_NM
10548 || n == K_LEFTDRAG
10549 || n == K_LEFTRELEASE
10550 || n == K_LEFTRELEASE_NM
10551 || n == K_MIDDLEMOUSE
10552 || n == K_MIDDLEDRAG
10553 || n == K_MIDDLERELEASE
10554 || n == K_RIGHTMOUSE
10555 || n == K_RIGHTDRAG
10556 || n == K_RIGHTRELEASE
10557 || n == K_X1MOUSE
10558 || n == K_X1DRAG
10559 || n == K_X1RELEASE
10560 || n == K_X2MOUSE
10561 || n == K_X2DRAG
10562 || n == K_X2RELEASE
10563 || n == K_MOUSEDOWN
10564 || n == K_MOUSEUP)
10566 int row = mouse_row;
10567 int col = mouse_col;
10568 win_T *win;
10569 linenr_T lnum;
10570 # ifdef FEAT_WINDOWS
10571 win_T *wp;
10572 # endif
10573 int n = 1;
10575 if (row >= 0 && col >= 0)
10577 /* Find the window at the mouse coordinates and compute the
10578 * text position. */
10579 win = mouse_find_win(&row, &col);
10580 (void)mouse_comp_pos(win, &row, &col, &lnum);
10581 # ifdef FEAT_WINDOWS
10582 for (wp = firstwin; wp != win; wp = wp->w_next)
10583 ++n;
10584 # endif
10585 vimvars[VV_MOUSE_WIN].vv_nr = n;
10586 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10587 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10590 #endif
10595 * "getcharmod()" function
10597 /*ARGSUSED*/
10598 static void
10599 f_getcharmod(argvars, rettv)
10600 typval_T *argvars;
10601 typval_T *rettv;
10603 rettv->vval.v_number = mod_mask;
10607 * "getcmdline()" function
10609 /*ARGSUSED*/
10610 static void
10611 f_getcmdline(argvars, rettv)
10612 typval_T *argvars;
10613 typval_T *rettv;
10615 rettv->v_type = VAR_STRING;
10616 rettv->vval.v_string = get_cmdline_str();
10620 * "getcmdpos()" function
10622 /*ARGSUSED*/
10623 static void
10624 f_getcmdpos(argvars, rettv)
10625 typval_T *argvars;
10626 typval_T *rettv;
10628 rettv->vval.v_number = get_cmdline_pos() + 1;
10632 * "getcmdtype()" function
10634 /*ARGSUSED*/
10635 static void
10636 f_getcmdtype(argvars, rettv)
10637 typval_T *argvars;
10638 typval_T *rettv;
10640 rettv->v_type = VAR_STRING;
10641 rettv->vval.v_string = alloc(2);
10642 if (rettv->vval.v_string != NULL)
10644 rettv->vval.v_string[0] = get_cmdline_type();
10645 rettv->vval.v_string[1] = NUL;
10650 * "getcwd()" function
10652 /*ARGSUSED*/
10653 static void
10654 f_getcwd(argvars, rettv)
10655 typval_T *argvars;
10656 typval_T *rettv;
10658 char_u cwd[MAXPATHL];
10660 rettv->v_type = VAR_STRING;
10661 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10662 rettv->vval.v_string = NULL;
10663 else
10665 rettv->vval.v_string = vim_strsave(cwd);
10666 #ifdef BACKSLASH_IN_FILENAME
10667 if (rettv->vval.v_string != NULL)
10668 slash_adjust(rettv->vval.v_string);
10669 #endif
10674 * "getfontname()" function
10676 /*ARGSUSED*/
10677 static void
10678 f_getfontname(argvars, rettv)
10679 typval_T *argvars;
10680 typval_T *rettv;
10682 rettv->v_type = VAR_STRING;
10683 rettv->vval.v_string = NULL;
10684 #ifdef FEAT_GUI
10685 if (gui.in_use)
10687 GuiFont font;
10688 char_u *name = NULL;
10690 if (argvars[0].v_type == VAR_UNKNOWN)
10692 /* Get the "Normal" font. Either the name saved by
10693 * hl_set_font_name() or from the font ID. */
10694 font = gui.norm_font;
10695 name = hl_get_font_name();
10697 else
10699 name = get_tv_string(&argvars[0]);
10700 if (STRCMP(name, "*") == 0) /* don't use font dialog */
10701 return;
10702 font = gui_mch_get_font(name, FALSE);
10703 if (font == NOFONT)
10704 return; /* Invalid font name, return empty string. */
10706 rettv->vval.v_string = gui_mch_get_fontname(font, name);
10707 if (argvars[0].v_type != VAR_UNKNOWN)
10708 gui_mch_free_font(font);
10710 #endif
10714 * "getfperm({fname})" function
10716 static void
10717 f_getfperm(argvars, rettv)
10718 typval_T *argvars;
10719 typval_T *rettv;
10721 char_u *fname;
10722 struct stat st;
10723 char_u *perm = NULL;
10724 char_u flags[] = "rwx";
10725 int i;
10727 fname = get_tv_string(&argvars[0]);
10729 rettv->v_type = VAR_STRING;
10730 if (mch_stat((char *)fname, &st) >= 0)
10732 perm = vim_strsave((char_u *)"---------");
10733 if (perm != NULL)
10735 for (i = 0; i < 9; i++)
10737 if (st.st_mode & (1 << (8 - i)))
10738 perm[i] = flags[i % 3];
10742 rettv->vval.v_string = perm;
10746 * "getfsize({fname})" function
10748 static void
10749 f_getfsize(argvars, rettv)
10750 typval_T *argvars;
10751 typval_T *rettv;
10753 char_u *fname;
10754 struct stat st;
10756 fname = get_tv_string(&argvars[0]);
10758 rettv->v_type = VAR_NUMBER;
10760 if (mch_stat((char *)fname, &st) >= 0)
10762 if (mch_isdir(fname))
10763 rettv->vval.v_number = 0;
10764 else
10766 rettv->vval.v_number = (varnumber_T)st.st_size;
10768 /* non-perfect check for overflow */
10769 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
10770 rettv->vval.v_number = -2;
10773 else
10774 rettv->vval.v_number = -1;
10778 * "getftime({fname})" function
10780 static void
10781 f_getftime(argvars, rettv)
10782 typval_T *argvars;
10783 typval_T *rettv;
10785 char_u *fname;
10786 struct stat st;
10788 fname = get_tv_string(&argvars[0]);
10790 if (mch_stat((char *)fname, &st) >= 0)
10791 rettv->vval.v_number = (varnumber_T)st.st_mtime;
10792 else
10793 rettv->vval.v_number = -1;
10797 * "getftype({fname})" function
10799 static void
10800 f_getftype(argvars, rettv)
10801 typval_T *argvars;
10802 typval_T *rettv;
10804 char_u *fname;
10805 struct stat st;
10806 char_u *type = NULL;
10807 char *t;
10809 fname = get_tv_string(&argvars[0]);
10811 rettv->v_type = VAR_STRING;
10812 if (mch_lstat((char *)fname, &st) >= 0)
10814 #ifdef S_ISREG
10815 if (S_ISREG(st.st_mode))
10816 t = "file";
10817 else if (S_ISDIR(st.st_mode))
10818 t = "dir";
10819 # ifdef S_ISLNK
10820 else if (S_ISLNK(st.st_mode))
10821 t = "link";
10822 # endif
10823 # ifdef S_ISBLK
10824 else if (S_ISBLK(st.st_mode))
10825 t = "bdev";
10826 # endif
10827 # ifdef S_ISCHR
10828 else if (S_ISCHR(st.st_mode))
10829 t = "cdev";
10830 # endif
10831 # ifdef S_ISFIFO
10832 else if (S_ISFIFO(st.st_mode))
10833 t = "fifo";
10834 # endif
10835 # ifdef S_ISSOCK
10836 else if (S_ISSOCK(st.st_mode))
10837 t = "fifo";
10838 # endif
10839 else
10840 t = "other";
10841 #else
10842 # ifdef S_IFMT
10843 switch (st.st_mode & S_IFMT)
10845 case S_IFREG: t = "file"; break;
10846 case S_IFDIR: t = "dir"; break;
10847 # ifdef S_IFLNK
10848 case S_IFLNK: t = "link"; break;
10849 # endif
10850 # ifdef S_IFBLK
10851 case S_IFBLK: t = "bdev"; break;
10852 # endif
10853 # ifdef S_IFCHR
10854 case S_IFCHR: t = "cdev"; break;
10855 # endif
10856 # ifdef S_IFIFO
10857 case S_IFIFO: t = "fifo"; break;
10858 # endif
10859 # ifdef S_IFSOCK
10860 case S_IFSOCK: t = "socket"; break;
10861 # endif
10862 default: t = "other";
10864 # else
10865 if (mch_isdir(fname))
10866 t = "dir";
10867 else
10868 t = "file";
10869 # endif
10870 #endif
10871 type = vim_strsave((char_u *)t);
10873 rettv->vval.v_string = type;
10877 * "getline(lnum, [end])" function
10879 static void
10880 f_getline(argvars, rettv)
10881 typval_T *argvars;
10882 typval_T *rettv;
10884 linenr_T lnum;
10885 linenr_T end;
10886 int retlist;
10888 lnum = get_tv_lnum(argvars);
10889 if (argvars[1].v_type == VAR_UNKNOWN)
10891 end = 0;
10892 retlist = FALSE;
10894 else
10896 end = get_tv_lnum(&argvars[1]);
10897 retlist = TRUE;
10900 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
10904 * "getmatches()" function
10906 /*ARGSUSED*/
10907 static void
10908 f_getmatches(argvars, rettv)
10909 typval_T *argvars;
10910 typval_T *rettv;
10912 #ifdef FEAT_SEARCH_EXTRA
10913 dict_T *dict;
10914 matchitem_T *cur = curwin->w_match_head;
10916 rettv->vval.v_number = 0;
10918 if (rettv_list_alloc(rettv) == OK)
10920 while (cur != NULL)
10922 dict = dict_alloc();
10923 if (dict == NULL)
10924 return;
10925 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
10926 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
10927 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
10928 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
10929 list_append_dict(rettv->vval.v_list, dict);
10930 cur = cur->next;
10933 #endif
10937 * "getpid()" function
10939 /*ARGSUSED*/
10940 static void
10941 f_getpid(argvars, rettv)
10942 typval_T *argvars;
10943 typval_T *rettv;
10945 rettv->vval.v_number = mch_get_pid();
10949 * "getpos(string)" function
10951 static void
10952 f_getpos(argvars, rettv)
10953 typval_T *argvars;
10954 typval_T *rettv;
10956 pos_T *fp;
10957 list_T *l;
10958 int fnum = -1;
10960 if (rettv_list_alloc(rettv) == OK)
10962 l = rettv->vval.v_list;
10963 fp = var2fpos(&argvars[0], TRUE, &fnum);
10964 if (fnum != -1)
10965 list_append_number(l, (varnumber_T)fnum);
10966 else
10967 list_append_number(l, (varnumber_T)0);
10968 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
10969 : (varnumber_T)0);
10970 list_append_number(l, (fp != NULL)
10971 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
10972 : (varnumber_T)0);
10973 list_append_number(l,
10974 #ifdef FEAT_VIRTUALEDIT
10975 (fp != NULL) ? (varnumber_T)fp->coladd :
10976 #endif
10977 (varnumber_T)0);
10979 else
10980 rettv->vval.v_number = FALSE;
10984 * "getqflist()" and "getloclist()" functions
10986 /*ARGSUSED*/
10987 static void
10988 f_getqflist(argvars, rettv)
10989 typval_T *argvars;
10990 typval_T *rettv;
10992 #ifdef FEAT_QUICKFIX
10993 win_T *wp;
10994 #endif
10996 rettv->vval.v_number = 0;
10997 #ifdef FEAT_QUICKFIX
10998 if (rettv_list_alloc(rettv) == OK)
11000 wp = NULL;
11001 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11003 wp = find_win_by_nr(&argvars[0], NULL);
11004 if (wp == NULL)
11005 return;
11008 (void)get_errorlist(wp, rettv->vval.v_list);
11010 #endif
11014 * "getreg()" function
11016 static void
11017 f_getreg(argvars, rettv)
11018 typval_T *argvars;
11019 typval_T *rettv;
11021 char_u *strregname;
11022 int regname;
11023 int arg2 = FALSE;
11024 int error = FALSE;
11026 if (argvars[0].v_type != VAR_UNKNOWN)
11028 strregname = get_tv_string_chk(&argvars[0]);
11029 error = strregname == NULL;
11030 if (argvars[1].v_type != VAR_UNKNOWN)
11031 arg2 = get_tv_number_chk(&argvars[1], &error);
11033 else
11034 strregname = vimvars[VV_REG].vv_str;
11035 regname = (strregname == NULL ? '"' : *strregname);
11036 if (regname == 0)
11037 regname = '"';
11039 rettv->v_type = VAR_STRING;
11040 rettv->vval.v_string = error ? NULL :
11041 get_reg_contents(regname, TRUE, arg2);
11045 * "getregtype()" function
11047 static void
11048 f_getregtype(argvars, rettv)
11049 typval_T *argvars;
11050 typval_T *rettv;
11052 char_u *strregname;
11053 int regname;
11054 char_u buf[NUMBUFLEN + 2];
11055 long reglen = 0;
11057 if (argvars[0].v_type != VAR_UNKNOWN)
11059 strregname = get_tv_string_chk(&argvars[0]);
11060 if (strregname == NULL) /* type error; errmsg already given */
11062 rettv->v_type = VAR_STRING;
11063 rettv->vval.v_string = NULL;
11064 return;
11067 else
11068 /* Default to v:register */
11069 strregname = vimvars[VV_REG].vv_str;
11071 regname = (strregname == NULL ? '"' : *strregname);
11072 if (regname == 0)
11073 regname = '"';
11075 buf[0] = NUL;
11076 buf[1] = NUL;
11077 switch (get_reg_type(regname, &reglen))
11079 case MLINE: buf[0] = 'V'; break;
11080 case MCHAR: buf[0] = 'v'; break;
11081 #ifdef FEAT_VISUAL
11082 case MBLOCK:
11083 buf[0] = Ctrl_V;
11084 sprintf((char *)buf + 1, "%ld", reglen + 1);
11085 break;
11086 #endif
11088 rettv->v_type = VAR_STRING;
11089 rettv->vval.v_string = vim_strsave(buf);
11093 * "gettabwinvar()" function
11095 static void
11096 f_gettabwinvar(argvars, rettv)
11097 typval_T *argvars;
11098 typval_T *rettv;
11100 getwinvar(argvars, rettv, 1);
11104 * "getwinposx()" function
11106 /*ARGSUSED*/
11107 static void
11108 f_getwinposx(argvars, rettv)
11109 typval_T *argvars;
11110 typval_T *rettv;
11112 rettv->vval.v_number = -1;
11113 #ifdef FEAT_GUI
11114 if (gui.in_use)
11116 int x, y;
11118 if (gui_mch_get_winpos(&x, &y) == OK)
11119 rettv->vval.v_number = x;
11121 #endif
11125 * "getwinposy()" function
11127 /*ARGSUSED*/
11128 static void
11129 f_getwinposy(argvars, rettv)
11130 typval_T *argvars;
11131 typval_T *rettv;
11133 rettv->vval.v_number = -1;
11134 #ifdef FEAT_GUI
11135 if (gui.in_use)
11137 int x, y;
11139 if (gui_mch_get_winpos(&x, &y) == OK)
11140 rettv->vval.v_number = y;
11142 #endif
11146 * Find window specified by "vp" in tabpage "tp".
11148 static win_T *
11149 find_win_by_nr(vp, tp)
11150 typval_T *vp;
11151 tabpage_T *tp; /* NULL for current tab page */
11153 #ifdef FEAT_WINDOWS
11154 win_T *wp;
11155 #endif
11156 int nr;
11158 nr = get_tv_number_chk(vp, NULL);
11160 #ifdef FEAT_WINDOWS
11161 if (nr < 0)
11162 return NULL;
11163 if (nr == 0)
11164 return curwin;
11166 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11167 wp != NULL; wp = wp->w_next)
11168 if (--nr <= 0)
11169 break;
11170 return wp;
11171 #else
11172 if (nr == 0 || nr == 1)
11173 return curwin;
11174 return NULL;
11175 #endif
11179 * "getwinvar()" function
11181 static void
11182 f_getwinvar(argvars, rettv)
11183 typval_T *argvars;
11184 typval_T *rettv;
11186 getwinvar(argvars, rettv, 0);
11190 * getwinvar() and gettabwinvar()
11192 static void
11193 getwinvar(argvars, rettv, off)
11194 typval_T *argvars;
11195 typval_T *rettv;
11196 int off; /* 1 for gettabwinvar() */
11198 win_T *win, *oldcurwin;
11199 char_u *varname;
11200 dictitem_T *v;
11201 tabpage_T *tp;
11203 #ifdef FEAT_WINDOWS
11204 if (off == 1)
11205 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11206 else
11207 tp = curtab;
11208 #endif
11209 win = find_win_by_nr(&argvars[off], tp);
11210 varname = get_tv_string_chk(&argvars[off + 1]);
11211 ++emsg_off;
11213 rettv->v_type = VAR_STRING;
11214 rettv->vval.v_string = NULL;
11216 if (win != NULL && varname != NULL)
11218 /* Set curwin to be our win, temporarily. Also set curbuf, so
11219 * that we can get buffer-local options. */
11220 oldcurwin = curwin;
11221 curwin = win;
11222 curbuf = win->w_buffer;
11224 if (*varname == '&') /* window-local-option */
11225 get_option_tv(&varname, rettv, 1);
11226 else
11228 if (*varname == NUL)
11229 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11230 * scope prefix before the NUL byte is required by
11231 * find_var_in_ht(). */
11232 varname = (char_u *)"w:" + 2;
11233 /* look up the variable */
11234 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11235 if (v != NULL)
11236 copy_tv(&v->di_tv, rettv);
11239 /* restore previous notion of curwin */
11240 curwin = oldcurwin;
11241 curbuf = curwin->w_buffer;
11244 --emsg_off;
11248 * "glob()" function
11250 static void
11251 f_glob(argvars, rettv)
11252 typval_T *argvars;
11253 typval_T *rettv;
11255 expand_T xpc;
11257 ExpandInit(&xpc);
11258 xpc.xp_context = EXPAND_FILES;
11259 rettv->v_type = VAR_STRING;
11260 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11261 NULL, WILD_USE_NL|WILD_SILENT, WILD_ALL);
11265 * "globpath()" function
11267 static void
11268 f_globpath(argvars, rettv)
11269 typval_T *argvars;
11270 typval_T *rettv;
11272 char_u buf1[NUMBUFLEN];
11273 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11275 rettv->v_type = VAR_STRING;
11276 if (file == NULL)
11277 rettv->vval.v_string = NULL;
11278 else
11279 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file);
11283 * "has()" function
11285 static void
11286 f_has(argvars, rettv)
11287 typval_T *argvars;
11288 typval_T *rettv;
11290 int i;
11291 char_u *name;
11292 int n = FALSE;
11293 static char *(has_list[]) =
11295 #ifdef AMIGA
11296 "amiga",
11297 # ifdef FEAT_ARP
11298 "arp",
11299 # endif
11300 #endif
11301 #ifdef __BEOS__
11302 "beos",
11303 #endif
11304 #ifdef MSDOS
11305 # ifdef DJGPP
11306 "dos32",
11307 # else
11308 "dos16",
11309 # endif
11310 #endif
11311 #ifdef MACOS
11312 "mac",
11313 #endif
11314 #if defined(MACOS_X_UNIX)
11315 "macunix",
11316 #endif
11317 #ifdef OS2
11318 "os2",
11319 #endif
11320 #ifdef __QNX__
11321 "qnx",
11322 #endif
11323 #ifdef RISCOS
11324 "riscos",
11325 #endif
11326 #ifdef UNIX
11327 "unix",
11328 #endif
11329 #ifdef VMS
11330 "vms",
11331 #endif
11332 #ifdef WIN16
11333 "win16",
11334 #endif
11335 #ifdef WIN32
11336 "win32",
11337 #endif
11338 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11339 "win32unix",
11340 #endif
11341 #ifdef WIN64
11342 "win64",
11343 #endif
11344 #ifdef EBCDIC
11345 "ebcdic",
11346 #endif
11347 #ifndef CASE_INSENSITIVE_FILENAME
11348 "fname_case",
11349 #endif
11350 #ifdef FEAT_ARABIC
11351 "arabic",
11352 #endif
11353 #ifdef FEAT_AUTOCMD
11354 "autocmd",
11355 #endif
11356 #ifdef FEAT_BEVAL
11357 "balloon_eval",
11358 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11359 "balloon_multiline",
11360 # endif
11361 #endif
11362 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11363 "builtin_terms",
11364 # ifdef ALL_BUILTIN_TCAPS
11365 "all_builtin_terms",
11366 # endif
11367 #endif
11368 #ifdef FEAT_BYTEOFF
11369 "byte_offset",
11370 #endif
11371 #ifdef FEAT_CINDENT
11372 "cindent",
11373 #endif
11374 #ifdef FEAT_CLIENTSERVER
11375 "clientserver",
11376 #endif
11377 #ifdef FEAT_CLIPBOARD
11378 "clipboard",
11379 #endif
11380 #ifdef FEAT_CMDL_COMPL
11381 "cmdline_compl",
11382 #endif
11383 #ifdef FEAT_CMDHIST
11384 "cmdline_hist",
11385 #endif
11386 #ifdef FEAT_COMMENTS
11387 "comments",
11388 #endif
11389 #ifdef FEAT_CRYPT
11390 "cryptv",
11391 #endif
11392 #ifdef FEAT_CSCOPE
11393 "cscope",
11394 #endif
11395 #ifdef CURSOR_SHAPE
11396 "cursorshape",
11397 #endif
11398 #ifdef DEBUG
11399 "debug",
11400 #endif
11401 #ifdef FEAT_CON_DIALOG
11402 "dialog_con",
11403 #endif
11404 #ifdef FEAT_GUI_DIALOG
11405 "dialog_gui",
11406 #endif
11407 #ifdef FEAT_DIFF
11408 "diff",
11409 #endif
11410 #ifdef FEAT_DIGRAPHS
11411 "digraphs",
11412 #endif
11413 #ifdef FEAT_DND
11414 "dnd",
11415 #endif
11416 #ifdef FEAT_EMACS_TAGS
11417 "emacs_tags",
11418 #endif
11419 "eval", /* always present, of course! */
11420 #ifdef FEAT_EX_EXTRA
11421 "ex_extra",
11422 #endif
11423 #ifdef FEAT_SEARCH_EXTRA
11424 "extra_search",
11425 #endif
11426 #ifdef FEAT_FKMAP
11427 "farsi",
11428 #endif
11429 #ifdef FEAT_SEARCHPATH
11430 "file_in_path",
11431 #endif
11432 #if defined(UNIX) && !defined(USE_SYSTEM)
11433 "filterpipe",
11434 #endif
11435 #ifdef FEAT_FIND_ID
11436 "find_in_path",
11437 #endif
11438 #ifdef FEAT_FLOAT
11439 "float",
11440 #endif
11441 #ifdef FEAT_FOLDING
11442 "folding",
11443 #endif
11444 #ifdef FEAT_FOOTER
11445 "footer",
11446 #endif
11447 #if !defined(USE_SYSTEM) && defined(UNIX)
11448 "fork",
11449 #endif
11450 #ifdef FEAT_GETTEXT
11451 "gettext",
11452 #endif
11453 #ifdef FEAT_GUI
11454 "gui",
11455 #endif
11456 #ifdef FEAT_GUI_ATHENA
11457 # ifdef FEAT_GUI_NEXTAW
11458 "gui_neXtaw",
11459 # else
11460 "gui_athena",
11461 # endif
11462 #endif
11463 #ifdef FEAT_GUI_GTK
11464 "gui_gtk",
11465 # ifdef HAVE_GTK2
11466 "gui_gtk2",
11467 # endif
11468 #endif
11469 #ifdef FEAT_GUI_GNOME
11470 "gui_gnome",
11471 #endif
11472 #ifdef FEAT_GUI_MAC
11473 "gui_mac",
11474 #endif
11475 #ifdef FEAT_GUI_MOTIF
11476 "gui_motif",
11477 #endif
11478 #ifdef FEAT_GUI_PHOTON
11479 "gui_photon",
11480 #endif
11481 #ifdef FEAT_GUI_W16
11482 "gui_win16",
11483 #endif
11484 #ifdef FEAT_GUI_W32
11485 "gui_win32",
11486 #endif
11487 #ifdef FEAT_HANGULIN
11488 "hangul_input",
11489 #endif
11490 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11491 "iconv",
11492 #endif
11493 #ifdef FEAT_INS_EXPAND
11494 "insert_expand",
11495 #endif
11496 #ifdef FEAT_JUMPLIST
11497 "jumplist",
11498 #endif
11499 #ifdef FEAT_KEYMAP
11500 "keymap",
11501 #endif
11502 #ifdef FEAT_LANGMAP
11503 "langmap",
11504 #endif
11505 #ifdef FEAT_LIBCALL
11506 "libcall",
11507 #endif
11508 #ifdef FEAT_LINEBREAK
11509 "linebreak",
11510 #endif
11511 #ifdef FEAT_LISP
11512 "lispindent",
11513 #endif
11514 #ifdef FEAT_LISTCMDS
11515 "listcmds",
11516 #endif
11517 #ifdef FEAT_LOCALMAP
11518 "localmap",
11519 #endif
11520 #ifdef FEAT_MENU
11521 "menu",
11522 #endif
11523 #ifdef FEAT_SESSION
11524 "mksession",
11525 #endif
11526 #ifdef FEAT_MODIFY_FNAME
11527 "modify_fname",
11528 #endif
11529 #ifdef FEAT_MOUSE
11530 "mouse",
11531 #endif
11532 #ifdef FEAT_MOUSESHAPE
11533 "mouseshape",
11534 #endif
11535 #if defined(UNIX) || defined(VMS)
11536 # ifdef FEAT_MOUSE_DEC
11537 "mouse_dec",
11538 # endif
11539 # ifdef FEAT_MOUSE_GPM
11540 "mouse_gpm",
11541 # endif
11542 # ifdef FEAT_MOUSE_JSB
11543 "mouse_jsbterm",
11544 # endif
11545 # ifdef FEAT_MOUSE_NET
11546 "mouse_netterm",
11547 # endif
11548 # ifdef FEAT_MOUSE_PTERM
11549 "mouse_pterm",
11550 # endif
11551 # ifdef FEAT_SYSMOUSE
11552 "mouse_sysmouse",
11553 # endif
11554 # ifdef FEAT_MOUSE_XTERM
11555 "mouse_xterm",
11556 # endif
11557 #endif
11558 #ifdef FEAT_MBYTE
11559 "multi_byte",
11560 #endif
11561 #ifdef FEAT_MBYTE_IME
11562 "multi_byte_ime",
11563 #endif
11564 #ifdef FEAT_MULTI_LANG
11565 "multi_lang",
11566 #endif
11567 #ifdef FEAT_MZSCHEME
11568 #ifndef DYNAMIC_MZSCHEME
11569 "mzscheme",
11570 #endif
11571 #endif
11572 #ifdef FEAT_OLE
11573 "ole",
11574 #endif
11575 #ifdef FEAT_OSFILETYPE
11576 "osfiletype",
11577 #endif
11578 #ifdef FEAT_PATH_EXTRA
11579 "path_extra",
11580 #endif
11581 #ifdef FEAT_PERL
11582 #ifndef DYNAMIC_PERL
11583 "perl",
11584 #endif
11585 #endif
11586 #ifdef FEAT_PYTHON
11587 #ifndef DYNAMIC_PYTHON
11588 "python",
11589 #endif
11590 #endif
11591 #ifdef FEAT_POSTSCRIPT
11592 "postscript",
11593 #endif
11594 #ifdef FEAT_PRINTER
11595 "printer",
11596 #endif
11597 #ifdef FEAT_PROFILE
11598 "profile",
11599 #endif
11600 #ifdef FEAT_RELTIME
11601 "reltime",
11602 #endif
11603 #ifdef FEAT_QUICKFIX
11604 "quickfix",
11605 #endif
11606 #ifdef FEAT_RIGHTLEFT
11607 "rightleft",
11608 #endif
11609 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11610 "ruby",
11611 #endif
11612 #ifdef FEAT_SCROLLBIND
11613 "scrollbind",
11614 #endif
11615 #ifdef FEAT_CMDL_INFO
11616 "showcmd",
11617 "cmdline_info",
11618 #endif
11619 #ifdef FEAT_SIGNS
11620 "signs",
11621 #endif
11622 #ifdef FEAT_SMARTINDENT
11623 "smartindent",
11624 #endif
11625 #ifdef FEAT_SNIFF
11626 "sniff",
11627 #endif
11628 #ifdef FEAT_STL_OPT
11629 "statusline",
11630 #endif
11631 #ifdef FEAT_SUN_WORKSHOP
11632 "sun_workshop",
11633 #endif
11634 #ifdef FEAT_NETBEANS_INTG
11635 "netbeans_intg",
11636 #endif
11637 #ifdef FEAT_SPELL
11638 "spell",
11639 #endif
11640 #ifdef FEAT_SYN_HL
11641 "syntax",
11642 #endif
11643 #if defined(USE_SYSTEM) || !defined(UNIX)
11644 "system",
11645 #endif
11646 #ifdef FEAT_TAG_BINS
11647 "tag_binary",
11648 #endif
11649 #ifdef FEAT_TAG_OLDSTATIC
11650 "tag_old_static",
11651 #endif
11652 #ifdef FEAT_TAG_ANYWHITE
11653 "tag_any_white",
11654 #endif
11655 #ifdef FEAT_TCL
11656 # ifndef DYNAMIC_TCL
11657 "tcl",
11658 # endif
11659 #endif
11660 #ifdef TERMINFO
11661 "terminfo",
11662 #endif
11663 #ifdef FEAT_TERMRESPONSE
11664 "termresponse",
11665 #endif
11666 #ifdef FEAT_TEXTOBJ
11667 "textobjects",
11668 #endif
11669 #ifdef HAVE_TGETENT
11670 "tgetent",
11671 #endif
11672 #ifdef FEAT_TITLE
11673 "title",
11674 #endif
11675 #ifdef FEAT_TOOLBAR
11676 "toolbar",
11677 #endif
11678 #ifdef FEAT_USR_CMDS
11679 "user-commands", /* was accidentally included in 5.4 */
11680 "user_commands",
11681 #endif
11682 #ifdef FEAT_VIMINFO
11683 "viminfo",
11684 #endif
11685 #ifdef FEAT_VERTSPLIT
11686 "vertsplit",
11687 #endif
11688 #ifdef FEAT_VIRTUALEDIT
11689 "virtualedit",
11690 #endif
11691 #ifdef FEAT_VISUAL
11692 "visual",
11693 #endif
11694 #ifdef FEAT_VISUALEXTRA
11695 "visualextra",
11696 #endif
11697 #ifdef FEAT_VREPLACE
11698 "vreplace",
11699 #endif
11700 #ifdef FEAT_WILDIGN
11701 "wildignore",
11702 #endif
11703 #ifdef FEAT_WILDMENU
11704 "wildmenu",
11705 #endif
11706 #ifdef FEAT_WINDOWS
11707 "windows",
11708 #endif
11709 #ifdef FEAT_WAK
11710 "winaltkeys",
11711 #endif
11712 #ifdef FEAT_WRITEBACKUP
11713 "writebackup",
11714 #endif
11715 #ifdef FEAT_XIM
11716 "xim",
11717 #endif
11718 #ifdef FEAT_XFONTSET
11719 "xfontset",
11720 #endif
11721 #ifdef USE_XSMP
11722 "xsmp",
11723 #endif
11724 #ifdef USE_XSMP_INTERACT
11725 "xsmp_interact",
11726 #endif
11727 #ifdef FEAT_XCLIPBOARD
11728 "xterm_clipboard",
11729 #endif
11730 #ifdef FEAT_XTERM_SAVE
11731 "xterm_save",
11732 #endif
11733 #if defined(UNIX) && defined(FEAT_X11)
11734 "X11",
11735 #endif
11736 NULL
11739 name = get_tv_string(&argvars[0]);
11740 for (i = 0; has_list[i] != NULL; ++i)
11741 if (STRICMP(name, has_list[i]) == 0)
11743 n = TRUE;
11744 break;
11747 if (n == FALSE)
11749 if (STRNICMP(name, "patch", 5) == 0)
11750 n = has_patch(atoi((char *)name + 5));
11751 else if (STRICMP(name, "vim_starting") == 0)
11752 n = (starting != 0);
11753 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11754 else if (STRICMP(name, "balloon_multiline") == 0)
11755 n = multiline_balloon_available();
11756 #endif
11757 #ifdef DYNAMIC_TCL
11758 else if (STRICMP(name, "tcl") == 0)
11759 n = tcl_enabled(FALSE);
11760 #endif
11761 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11762 else if (STRICMP(name, "iconv") == 0)
11763 n = iconv_enabled(FALSE);
11764 #endif
11765 #ifdef DYNAMIC_MZSCHEME
11766 else if (STRICMP(name, "mzscheme") == 0)
11767 n = mzscheme_enabled(FALSE);
11768 #endif
11769 #ifdef DYNAMIC_RUBY
11770 else if (STRICMP(name, "ruby") == 0)
11771 n = ruby_enabled(FALSE);
11772 #endif
11773 #ifdef DYNAMIC_PYTHON
11774 else if (STRICMP(name, "python") == 0)
11775 n = python_enabled(FALSE);
11776 #endif
11777 #ifdef DYNAMIC_PERL
11778 else if (STRICMP(name, "perl") == 0)
11779 n = perl_enabled(FALSE);
11780 #endif
11781 #ifdef FEAT_GUI
11782 else if (STRICMP(name, "gui_running") == 0)
11783 n = (gui.in_use || gui.starting);
11784 # ifdef FEAT_GUI_W32
11785 else if (STRICMP(name, "gui_win32s") == 0)
11786 n = gui_is_win32s();
11787 # endif
11788 # ifdef FEAT_BROWSE
11789 else if (STRICMP(name, "browse") == 0)
11790 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11791 # endif
11792 #endif
11793 #ifdef FEAT_SYN_HL
11794 else if (STRICMP(name, "syntax_items") == 0)
11795 n = syntax_present(curbuf);
11796 #endif
11797 #if defined(WIN3264)
11798 else if (STRICMP(name, "win95") == 0)
11799 n = mch_windows95();
11800 #endif
11801 #ifdef FEAT_NETBEANS_INTG
11802 else if (STRICMP(name, "netbeans_enabled") == 0)
11803 n = usingNetbeans;
11804 #endif
11807 rettv->vval.v_number = n;
11811 * "has_key()" function
11813 static void
11814 f_has_key(argvars, rettv)
11815 typval_T *argvars;
11816 typval_T *rettv;
11818 rettv->vval.v_number = 0;
11819 if (argvars[0].v_type != VAR_DICT)
11821 EMSG(_(e_dictreq));
11822 return;
11824 if (argvars[0].vval.v_dict == NULL)
11825 return;
11827 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11828 get_tv_string(&argvars[1]), -1) != NULL;
11832 * "haslocaldir()" function
11834 /*ARGSUSED*/
11835 static void
11836 f_haslocaldir(argvars, rettv)
11837 typval_T *argvars;
11838 typval_T *rettv;
11840 rettv->vval.v_number = (curwin->w_localdir != NULL);
11844 * "hasmapto()" function
11846 static void
11847 f_hasmapto(argvars, rettv)
11848 typval_T *argvars;
11849 typval_T *rettv;
11851 char_u *name;
11852 char_u *mode;
11853 char_u buf[NUMBUFLEN];
11854 int abbr = FALSE;
11856 name = get_tv_string(&argvars[0]);
11857 if (argvars[1].v_type == VAR_UNKNOWN)
11858 mode = (char_u *)"nvo";
11859 else
11861 mode = get_tv_string_buf(&argvars[1], buf);
11862 if (argvars[2].v_type != VAR_UNKNOWN)
11863 abbr = get_tv_number(&argvars[2]);
11866 if (map_to_exists(name, mode, abbr))
11867 rettv->vval.v_number = TRUE;
11868 else
11869 rettv->vval.v_number = FALSE;
11873 * "histadd()" function
11875 /*ARGSUSED*/
11876 static void
11877 f_histadd(argvars, rettv)
11878 typval_T *argvars;
11879 typval_T *rettv;
11881 #ifdef FEAT_CMDHIST
11882 int histype;
11883 char_u *str;
11884 char_u buf[NUMBUFLEN];
11885 #endif
11887 rettv->vval.v_number = FALSE;
11888 if (check_restricted() || check_secure())
11889 return;
11890 #ifdef FEAT_CMDHIST
11891 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11892 histype = str != NULL ? get_histtype(str) : -1;
11893 if (histype >= 0)
11895 str = get_tv_string_buf(&argvars[1], buf);
11896 if (*str != NUL)
11898 add_to_history(histype, str, FALSE, NUL);
11899 rettv->vval.v_number = TRUE;
11900 return;
11903 #endif
11907 * "histdel()" function
11909 /*ARGSUSED*/
11910 static void
11911 f_histdel(argvars, rettv)
11912 typval_T *argvars;
11913 typval_T *rettv;
11915 #ifdef FEAT_CMDHIST
11916 int n;
11917 char_u buf[NUMBUFLEN];
11918 char_u *str;
11920 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11921 if (str == NULL)
11922 n = 0;
11923 else if (argvars[1].v_type == VAR_UNKNOWN)
11924 /* only one argument: clear entire history */
11925 n = clr_history(get_histtype(str));
11926 else if (argvars[1].v_type == VAR_NUMBER)
11927 /* index given: remove that entry */
11928 n = del_history_idx(get_histtype(str),
11929 (int)get_tv_number(&argvars[1]));
11930 else
11931 /* string given: remove all matching entries */
11932 n = del_history_entry(get_histtype(str),
11933 get_tv_string_buf(&argvars[1], buf));
11934 rettv->vval.v_number = n;
11935 #else
11936 rettv->vval.v_number = 0;
11937 #endif
11941 * "histget()" function
11943 /*ARGSUSED*/
11944 static void
11945 f_histget(argvars, rettv)
11946 typval_T *argvars;
11947 typval_T *rettv;
11949 #ifdef FEAT_CMDHIST
11950 int type;
11951 int idx;
11952 char_u *str;
11954 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11955 if (str == NULL)
11956 rettv->vval.v_string = NULL;
11957 else
11959 type = get_histtype(str);
11960 if (argvars[1].v_type == VAR_UNKNOWN)
11961 idx = get_history_idx(type);
11962 else
11963 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11964 /* -1 on type error */
11965 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11967 #else
11968 rettv->vval.v_string = NULL;
11969 #endif
11970 rettv->v_type = VAR_STRING;
11974 * "histnr()" function
11976 /*ARGSUSED*/
11977 static void
11978 f_histnr(argvars, rettv)
11979 typval_T *argvars;
11980 typval_T *rettv;
11982 int i;
11984 #ifdef FEAT_CMDHIST
11985 char_u *history = get_tv_string_chk(&argvars[0]);
11987 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
11988 if (i >= HIST_CMD && i < HIST_COUNT)
11989 i = get_history_idx(i);
11990 else
11991 #endif
11992 i = -1;
11993 rettv->vval.v_number = i;
11997 * "highlightID(name)" function
11999 static void
12000 f_hlID(argvars, rettv)
12001 typval_T *argvars;
12002 typval_T *rettv;
12004 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12008 * "highlight_exists()" function
12010 static void
12011 f_hlexists(argvars, rettv)
12012 typval_T *argvars;
12013 typval_T *rettv;
12015 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12019 * "hostname()" function
12021 /*ARGSUSED*/
12022 static void
12023 f_hostname(argvars, rettv)
12024 typval_T *argvars;
12025 typval_T *rettv;
12027 char_u hostname[256];
12029 mch_get_host_name(hostname, 256);
12030 rettv->v_type = VAR_STRING;
12031 rettv->vval.v_string = vim_strsave(hostname);
12035 * iconv() function
12037 /*ARGSUSED*/
12038 static void
12039 f_iconv(argvars, rettv)
12040 typval_T *argvars;
12041 typval_T *rettv;
12043 #ifdef FEAT_MBYTE
12044 char_u buf1[NUMBUFLEN];
12045 char_u buf2[NUMBUFLEN];
12046 char_u *from, *to, *str;
12047 vimconv_T vimconv;
12048 #endif
12050 rettv->v_type = VAR_STRING;
12051 rettv->vval.v_string = NULL;
12053 #ifdef FEAT_MBYTE
12054 str = get_tv_string(&argvars[0]);
12055 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12056 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12057 vimconv.vc_type = CONV_NONE;
12058 convert_setup(&vimconv, from, to);
12060 /* If the encodings are equal, no conversion needed. */
12061 if (vimconv.vc_type == CONV_NONE)
12062 rettv->vval.v_string = vim_strsave(str);
12063 else
12064 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12066 convert_setup(&vimconv, NULL, NULL);
12067 vim_free(from);
12068 vim_free(to);
12069 #endif
12073 * "indent()" function
12075 static void
12076 f_indent(argvars, rettv)
12077 typval_T *argvars;
12078 typval_T *rettv;
12080 linenr_T lnum;
12082 lnum = get_tv_lnum(argvars);
12083 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12084 rettv->vval.v_number = get_indent_lnum(lnum);
12085 else
12086 rettv->vval.v_number = -1;
12090 * "index()" function
12092 static void
12093 f_index(argvars, rettv)
12094 typval_T *argvars;
12095 typval_T *rettv;
12097 list_T *l;
12098 listitem_T *item;
12099 long idx = 0;
12100 int ic = FALSE;
12102 rettv->vval.v_number = -1;
12103 if (argvars[0].v_type != VAR_LIST)
12105 EMSG(_(e_listreq));
12106 return;
12108 l = argvars[0].vval.v_list;
12109 if (l != NULL)
12111 item = l->lv_first;
12112 if (argvars[2].v_type != VAR_UNKNOWN)
12114 int error = FALSE;
12116 /* Start at specified item. Use the cached index that list_find()
12117 * sets, so that a negative number also works. */
12118 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12119 idx = l->lv_idx;
12120 if (argvars[3].v_type != VAR_UNKNOWN)
12121 ic = get_tv_number_chk(&argvars[3], &error);
12122 if (error)
12123 item = NULL;
12126 for ( ; item != NULL; item = item->li_next, ++idx)
12127 if (tv_equal(&item->li_tv, &argvars[1], ic))
12129 rettv->vval.v_number = idx;
12130 break;
12135 static int inputsecret_flag = 0;
12137 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12140 * This function is used by f_input() and f_inputdialog() functions. The third
12141 * argument to f_input() specifies the type of completion to use at the
12142 * prompt. The third argument to f_inputdialog() specifies the value to return
12143 * when the user cancels the prompt.
12145 static void
12146 get_user_input(argvars, rettv, inputdialog)
12147 typval_T *argvars;
12148 typval_T *rettv;
12149 int inputdialog;
12151 char_u *prompt = get_tv_string_chk(&argvars[0]);
12152 char_u *p = NULL;
12153 int c;
12154 char_u buf[NUMBUFLEN];
12155 int cmd_silent_save = cmd_silent;
12156 char_u *defstr = (char_u *)"";
12157 int xp_type = EXPAND_NOTHING;
12158 char_u *xp_arg = NULL;
12160 rettv->v_type = VAR_STRING;
12161 rettv->vval.v_string = NULL;
12163 #ifdef NO_CONSOLE_INPUT
12164 /* While starting up, there is no place to enter text. */
12165 if (no_console_input())
12166 return;
12167 #endif
12169 cmd_silent = FALSE; /* Want to see the prompt. */
12170 if (prompt != NULL)
12172 /* Only the part of the message after the last NL is considered as
12173 * prompt for the command line */
12174 p = vim_strrchr(prompt, '\n');
12175 if (p == NULL)
12176 p = prompt;
12177 else
12179 ++p;
12180 c = *p;
12181 *p = NUL;
12182 msg_start();
12183 msg_clr_eos();
12184 msg_puts_attr(prompt, echo_attr);
12185 msg_didout = FALSE;
12186 msg_starthere();
12187 *p = c;
12189 cmdline_row = msg_row;
12191 if (argvars[1].v_type != VAR_UNKNOWN)
12193 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12194 if (defstr != NULL)
12195 stuffReadbuffSpec(defstr);
12197 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12199 char_u *xp_name;
12200 int xp_namelen;
12201 long argt;
12203 rettv->vval.v_string = NULL;
12205 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12206 if (xp_name == NULL)
12207 return;
12209 xp_namelen = (int)STRLEN(xp_name);
12211 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12212 &xp_arg) == FAIL)
12213 return;
12217 if (defstr != NULL)
12218 rettv->vval.v_string =
12219 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12220 xp_type, xp_arg);
12222 vim_free(xp_arg);
12224 /* since the user typed this, no need to wait for return */
12225 need_wait_return = FALSE;
12226 msg_didout = FALSE;
12228 cmd_silent = cmd_silent_save;
12232 * "input()" function
12233 * Also handles inputsecret() when inputsecret is set.
12235 static void
12236 f_input(argvars, rettv)
12237 typval_T *argvars;
12238 typval_T *rettv;
12240 get_user_input(argvars, rettv, FALSE);
12244 * "inputdialog()" function
12246 static void
12247 f_inputdialog(argvars, rettv)
12248 typval_T *argvars;
12249 typval_T *rettv;
12251 #if defined(FEAT_GUI_TEXTDIALOG)
12252 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12253 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12255 char_u *message;
12256 char_u buf[NUMBUFLEN];
12257 char_u *defstr = (char_u *)"";
12259 message = get_tv_string_chk(&argvars[0]);
12260 if (argvars[1].v_type != VAR_UNKNOWN
12261 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12262 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12263 else
12264 IObuff[0] = NUL;
12265 if (message != NULL && defstr != NULL
12266 && do_dialog(VIM_QUESTION, NULL, message,
12267 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12268 rettv->vval.v_string = vim_strsave(IObuff);
12269 else
12271 if (message != NULL && defstr != NULL
12272 && argvars[1].v_type != VAR_UNKNOWN
12273 && argvars[2].v_type != VAR_UNKNOWN)
12274 rettv->vval.v_string = vim_strsave(
12275 get_tv_string_buf(&argvars[2], buf));
12276 else
12277 rettv->vval.v_string = NULL;
12279 rettv->v_type = VAR_STRING;
12281 else
12282 #endif
12283 get_user_input(argvars, rettv, TRUE);
12287 * "inputlist()" function
12289 static void
12290 f_inputlist(argvars, rettv)
12291 typval_T *argvars;
12292 typval_T *rettv;
12294 listitem_T *li;
12295 int selected;
12296 int mouse_used;
12298 rettv->vval.v_number = 0;
12299 #ifdef NO_CONSOLE_INPUT
12300 /* While starting up, there is no place to enter text. */
12301 if (no_console_input())
12302 return;
12303 #endif
12304 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12306 EMSG2(_(e_listarg), "inputlist()");
12307 return;
12310 msg_start();
12311 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12312 lines_left = Rows; /* avoid more prompt */
12313 msg_scroll = TRUE;
12314 msg_clr_eos();
12316 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12318 msg_puts(get_tv_string(&li->li_tv));
12319 msg_putchar('\n');
12322 /* Ask for choice. */
12323 selected = prompt_for_number(&mouse_used);
12324 if (mouse_used)
12325 selected -= lines_left;
12327 rettv->vval.v_number = selected;
12331 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12334 * "inputrestore()" function
12336 /*ARGSUSED*/
12337 static void
12338 f_inputrestore(argvars, rettv)
12339 typval_T *argvars;
12340 typval_T *rettv;
12342 if (ga_userinput.ga_len > 0)
12344 --ga_userinput.ga_len;
12345 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12346 + ga_userinput.ga_len);
12347 rettv->vval.v_number = 0; /* OK */
12349 else if (p_verbose > 1)
12351 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12352 rettv->vval.v_number = 1; /* Failed */
12357 * "inputsave()" function
12359 /*ARGSUSED*/
12360 static void
12361 f_inputsave(argvars, rettv)
12362 typval_T *argvars;
12363 typval_T *rettv;
12365 /* Add an entry to the stack of typeahead storage. */
12366 if (ga_grow(&ga_userinput, 1) == OK)
12368 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12369 + ga_userinput.ga_len);
12370 ++ga_userinput.ga_len;
12371 rettv->vval.v_number = 0; /* OK */
12373 else
12374 rettv->vval.v_number = 1; /* Failed */
12378 * "inputsecret()" function
12380 static void
12381 f_inputsecret(argvars, rettv)
12382 typval_T *argvars;
12383 typval_T *rettv;
12385 ++cmdline_star;
12386 ++inputsecret_flag;
12387 f_input(argvars, rettv);
12388 --cmdline_star;
12389 --inputsecret_flag;
12393 * "insert()" function
12395 static void
12396 f_insert(argvars, rettv)
12397 typval_T *argvars;
12398 typval_T *rettv;
12400 long before = 0;
12401 listitem_T *item;
12402 list_T *l;
12403 int error = FALSE;
12405 rettv->vval.v_number = 0;
12406 if (argvars[0].v_type != VAR_LIST)
12407 EMSG2(_(e_listarg), "insert()");
12408 else if ((l = argvars[0].vval.v_list) != NULL
12409 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12411 if (argvars[2].v_type != VAR_UNKNOWN)
12412 before = get_tv_number_chk(&argvars[2], &error);
12413 if (error)
12414 return; /* type error; errmsg already given */
12416 if (before == l->lv_len)
12417 item = NULL;
12418 else
12420 item = list_find(l, before);
12421 if (item == NULL)
12423 EMSGN(_(e_listidx), before);
12424 l = NULL;
12427 if (l != NULL)
12429 list_insert_tv(l, &argvars[1], item);
12430 copy_tv(&argvars[0], rettv);
12436 * "isdirectory()" function
12438 static void
12439 f_isdirectory(argvars, rettv)
12440 typval_T *argvars;
12441 typval_T *rettv;
12443 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12447 * "islocked()" function
12449 static void
12450 f_islocked(argvars, rettv)
12451 typval_T *argvars;
12452 typval_T *rettv;
12454 lval_T lv;
12455 char_u *end;
12456 dictitem_T *di;
12458 rettv->vval.v_number = -1;
12459 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12460 FNE_CHECK_START);
12461 if (end != NULL && lv.ll_name != NULL)
12463 if (*end != NUL)
12464 EMSG(_(e_trailing));
12465 else
12467 if (lv.ll_tv == NULL)
12469 if (check_changedtick(lv.ll_name))
12470 rettv->vval.v_number = 1; /* always locked */
12471 else
12473 di = find_var(lv.ll_name, NULL);
12474 if (di != NULL)
12476 /* Consider a variable locked when:
12477 * 1. the variable itself is locked
12478 * 2. the value of the variable is locked.
12479 * 3. the List or Dict value is locked.
12481 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12482 || tv_islocked(&di->di_tv));
12486 else if (lv.ll_range)
12487 EMSG(_("E786: Range not allowed"));
12488 else if (lv.ll_newkey != NULL)
12489 EMSG2(_(e_dictkey), lv.ll_newkey);
12490 else if (lv.ll_list != NULL)
12491 /* List item. */
12492 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12493 else
12494 /* Dictionary item. */
12495 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12499 clear_lval(&lv);
12502 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12505 * Turn a dict into a list:
12506 * "what" == 0: list of keys
12507 * "what" == 1: list of values
12508 * "what" == 2: list of items
12510 static void
12511 dict_list(argvars, rettv, what)
12512 typval_T *argvars;
12513 typval_T *rettv;
12514 int what;
12516 list_T *l2;
12517 dictitem_T *di;
12518 hashitem_T *hi;
12519 listitem_T *li;
12520 listitem_T *li2;
12521 dict_T *d;
12522 int todo;
12524 rettv->vval.v_number = 0;
12525 if (argvars[0].v_type != VAR_DICT)
12527 EMSG(_(e_dictreq));
12528 return;
12530 if ((d = argvars[0].vval.v_dict) == NULL)
12531 return;
12533 if (rettv_list_alloc(rettv) == FAIL)
12534 return;
12536 todo = (int)d->dv_hashtab.ht_used;
12537 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12539 if (!HASHITEM_EMPTY(hi))
12541 --todo;
12542 di = HI2DI(hi);
12544 li = listitem_alloc();
12545 if (li == NULL)
12546 break;
12547 list_append(rettv->vval.v_list, li);
12549 if (what == 0)
12551 /* keys() */
12552 li->li_tv.v_type = VAR_STRING;
12553 li->li_tv.v_lock = 0;
12554 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12556 else if (what == 1)
12558 /* values() */
12559 copy_tv(&di->di_tv, &li->li_tv);
12561 else
12563 /* items() */
12564 l2 = list_alloc();
12565 li->li_tv.v_type = VAR_LIST;
12566 li->li_tv.v_lock = 0;
12567 li->li_tv.vval.v_list = l2;
12568 if (l2 == NULL)
12569 break;
12570 ++l2->lv_refcount;
12572 li2 = listitem_alloc();
12573 if (li2 == NULL)
12574 break;
12575 list_append(l2, li2);
12576 li2->li_tv.v_type = VAR_STRING;
12577 li2->li_tv.v_lock = 0;
12578 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12580 li2 = listitem_alloc();
12581 if (li2 == NULL)
12582 break;
12583 list_append(l2, li2);
12584 copy_tv(&di->di_tv, &li2->li_tv);
12591 * "items(dict)" function
12593 static void
12594 f_items(argvars, rettv)
12595 typval_T *argvars;
12596 typval_T *rettv;
12598 dict_list(argvars, rettv, 2);
12602 * "join()" function
12604 static void
12605 f_join(argvars, rettv)
12606 typval_T *argvars;
12607 typval_T *rettv;
12609 garray_T ga;
12610 char_u *sep;
12612 rettv->vval.v_number = 0;
12613 if (argvars[0].v_type != VAR_LIST)
12615 EMSG(_(e_listreq));
12616 return;
12618 if (argvars[0].vval.v_list == NULL)
12619 return;
12620 if (argvars[1].v_type == VAR_UNKNOWN)
12621 sep = (char_u *)" ";
12622 else
12623 sep = get_tv_string_chk(&argvars[1]);
12625 rettv->v_type = VAR_STRING;
12627 if (sep != NULL)
12629 ga_init2(&ga, (int)sizeof(char), 80);
12630 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12631 ga_append(&ga, NUL);
12632 rettv->vval.v_string = (char_u *)ga.ga_data;
12634 else
12635 rettv->vval.v_string = NULL;
12639 * "keys()" function
12641 static void
12642 f_keys(argvars, rettv)
12643 typval_T *argvars;
12644 typval_T *rettv;
12646 dict_list(argvars, rettv, 0);
12650 * "last_buffer_nr()" function.
12652 /*ARGSUSED*/
12653 static void
12654 f_last_buffer_nr(argvars, rettv)
12655 typval_T *argvars;
12656 typval_T *rettv;
12658 int n = 0;
12659 buf_T *buf;
12661 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12662 if (n < buf->b_fnum)
12663 n = buf->b_fnum;
12665 rettv->vval.v_number = n;
12669 * "len()" function
12671 static void
12672 f_len(argvars, rettv)
12673 typval_T *argvars;
12674 typval_T *rettv;
12676 switch (argvars[0].v_type)
12678 case VAR_STRING:
12679 case VAR_NUMBER:
12680 rettv->vval.v_number = (varnumber_T)STRLEN(
12681 get_tv_string(&argvars[0]));
12682 break;
12683 case VAR_LIST:
12684 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12685 break;
12686 case VAR_DICT:
12687 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12688 break;
12689 default:
12690 EMSG(_("E701: Invalid type for len()"));
12691 break;
12695 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12697 static void
12698 libcall_common(argvars, rettv, type)
12699 typval_T *argvars;
12700 typval_T *rettv;
12701 int type;
12703 #ifdef FEAT_LIBCALL
12704 char_u *string_in;
12705 char_u **string_result;
12706 int nr_result;
12707 #endif
12709 rettv->v_type = type;
12710 if (type == VAR_NUMBER)
12711 rettv->vval.v_number = 0;
12712 else
12713 rettv->vval.v_string = NULL;
12715 if (check_restricted() || check_secure())
12716 return;
12718 #ifdef FEAT_LIBCALL
12719 /* The first two args must be strings, otherwise its meaningless */
12720 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12722 string_in = NULL;
12723 if (argvars[2].v_type == VAR_STRING)
12724 string_in = argvars[2].vval.v_string;
12725 if (type == VAR_NUMBER)
12726 string_result = NULL;
12727 else
12728 string_result = &rettv->vval.v_string;
12729 if (mch_libcall(argvars[0].vval.v_string,
12730 argvars[1].vval.v_string,
12731 string_in,
12732 argvars[2].vval.v_number,
12733 string_result,
12734 &nr_result) == OK
12735 && type == VAR_NUMBER)
12736 rettv->vval.v_number = nr_result;
12738 #endif
12742 * "libcall()" function
12744 static void
12745 f_libcall(argvars, rettv)
12746 typval_T *argvars;
12747 typval_T *rettv;
12749 libcall_common(argvars, rettv, VAR_STRING);
12753 * "libcallnr()" function
12755 static void
12756 f_libcallnr(argvars, rettv)
12757 typval_T *argvars;
12758 typval_T *rettv;
12760 libcall_common(argvars, rettv, VAR_NUMBER);
12764 * "line(string)" function
12766 static void
12767 f_line(argvars, rettv)
12768 typval_T *argvars;
12769 typval_T *rettv;
12771 linenr_T lnum = 0;
12772 pos_T *fp;
12773 int fnum;
12775 fp = var2fpos(&argvars[0], TRUE, &fnum);
12776 if (fp != NULL)
12777 lnum = fp->lnum;
12778 rettv->vval.v_number = lnum;
12782 * "line2byte(lnum)" function
12784 /*ARGSUSED*/
12785 static void
12786 f_line2byte(argvars, rettv)
12787 typval_T *argvars;
12788 typval_T *rettv;
12790 #ifndef FEAT_BYTEOFF
12791 rettv->vval.v_number = -1;
12792 #else
12793 linenr_T lnum;
12795 lnum = get_tv_lnum(argvars);
12796 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12797 rettv->vval.v_number = -1;
12798 else
12799 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12800 if (rettv->vval.v_number >= 0)
12801 ++rettv->vval.v_number;
12802 #endif
12806 * "lispindent(lnum)" function
12808 static void
12809 f_lispindent(argvars, rettv)
12810 typval_T *argvars;
12811 typval_T *rettv;
12813 #ifdef FEAT_LISP
12814 pos_T pos;
12815 linenr_T lnum;
12817 pos = curwin->w_cursor;
12818 lnum = get_tv_lnum(argvars);
12819 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12821 curwin->w_cursor.lnum = lnum;
12822 rettv->vval.v_number = get_lisp_indent();
12823 curwin->w_cursor = pos;
12825 else
12826 #endif
12827 rettv->vval.v_number = -1;
12831 * "localtime()" function
12833 /*ARGSUSED*/
12834 static void
12835 f_localtime(argvars, rettv)
12836 typval_T *argvars;
12837 typval_T *rettv;
12839 rettv->vval.v_number = (varnumber_T)time(NULL);
12842 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12844 static void
12845 get_maparg(argvars, rettv, exact)
12846 typval_T *argvars;
12847 typval_T *rettv;
12848 int exact;
12850 char_u *keys;
12851 char_u *which;
12852 char_u buf[NUMBUFLEN];
12853 char_u *keys_buf = NULL;
12854 char_u *rhs;
12855 int mode;
12856 garray_T ga;
12857 int abbr = FALSE;
12859 /* return empty string for failure */
12860 rettv->v_type = VAR_STRING;
12861 rettv->vval.v_string = NULL;
12863 keys = get_tv_string(&argvars[0]);
12864 if (*keys == NUL)
12865 return;
12867 if (argvars[1].v_type != VAR_UNKNOWN)
12869 which = get_tv_string_buf_chk(&argvars[1], buf);
12870 if (argvars[2].v_type != VAR_UNKNOWN)
12871 abbr = get_tv_number(&argvars[2]);
12873 else
12874 which = (char_u *)"";
12875 if (which == NULL)
12876 return;
12878 mode = get_map_mode(&which, 0);
12880 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12881 rhs = check_map(keys, mode, exact, FALSE, abbr);
12882 vim_free(keys_buf);
12883 if (rhs != NULL)
12885 ga_init(&ga);
12886 ga.ga_itemsize = 1;
12887 ga.ga_growsize = 40;
12889 while (*rhs != NUL)
12890 ga_concat(&ga, str2special(&rhs, FALSE));
12892 ga_append(&ga, NUL);
12893 rettv->vval.v_string = (char_u *)ga.ga_data;
12897 #ifdef FEAT_FLOAT
12899 * "log10()" function
12901 static void
12902 f_log10(argvars, rettv)
12903 typval_T *argvars;
12904 typval_T *rettv;
12906 float_T f;
12908 rettv->v_type = VAR_FLOAT;
12909 if (get_float_arg(argvars, &f) == OK)
12910 rettv->vval.v_float = log10(f);
12911 else
12912 rettv->vval.v_float = 0.0;
12914 #endif
12917 * "map()" function
12919 static void
12920 f_map(argvars, rettv)
12921 typval_T *argvars;
12922 typval_T *rettv;
12924 filter_map(argvars, rettv, TRUE);
12928 * "maparg()" function
12930 static void
12931 f_maparg(argvars, rettv)
12932 typval_T *argvars;
12933 typval_T *rettv;
12935 get_maparg(argvars, rettv, TRUE);
12939 * "mapcheck()" function
12941 static void
12942 f_mapcheck(argvars, rettv)
12943 typval_T *argvars;
12944 typval_T *rettv;
12946 get_maparg(argvars, rettv, FALSE);
12949 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12951 static void
12952 find_some_match(argvars, rettv, type)
12953 typval_T *argvars;
12954 typval_T *rettv;
12955 int type;
12957 char_u *str = NULL;
12958 char_u *expr = NULL;
12959 char_u *pat;
12960 regmatch_T regmatch;
12961 char_u patbuf[NUMBUFLEN];
12962 char_u strbuf[NUMBUFLEN];
12963 char_u *save_cpo;
12964 long start = 0;
12965 long nth = 1;
12966 colnr_T startcol = 0;
12967 int match = 0;
12968 list_T *l = NULL;
12969 listitem_T *li = NULL;
12970 long idx = 0;
12971 char_u *tofree = NULL;
12973 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12974 save_cpo = p_cpo;
12975 p_cpo = (char_u *)"";
12977 rettv->vval.v_number = -1;
12978 if (type == 3)
12980 /* return empty list when there are no matches */
12981 if (rettv_list_alloc(rettv) == FAIL)
12982 goto theend;
12984 else if (type == 2)
12986 rettv->v_type = VAR_STRING;
12987 rettv->vval.v_string = NULL;
12990 if (argvars[0].v_type == VAR_LIST)
12992 if ((l = argvars[0].vval.v_list) == NULL)
12993 goto theend;
12994 li = l->lv_first;
12996 else
12997 expr = str = get_tv_string(&argvars[0]);
12999 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13000 if (pat == NULL)
13001 goto theend;
13003 if (argvars[2].v_type != VAR_UNKNOWN)
13005 int error = FALSE;
13007 start = get_tv_number_chk(&argvars[2], &error);
13008 if (error)
13009 goto theend;
13010 if (l != NULL)
13012 li = list_find(l, start);
13013 if (li == NULL)
13014 goto theend;
13015 idx = l->lv_idx; /* use the cached index */
13017 else
13019 if (start < 0)
13020 start = 0;
13021 if (start > (long)STRLEN(str))
13022 goto theend;
13023 /* When "count" argument is there ignore matches before "start",
13024 * otherwise skip part of the string. Differs when pattern is "^"
13025 * or "\<". */
13026 if (argvars[3].v_type != VAR_UNKNOWN)
13027 startcol = start;
13028 else
13029 str += start;
13032 if (argvars[3].v_type != VAR_UNKNOWN)
13033 nth = get_tv_number_chk(&argvars[3], &error);
13034 if (error)
13035 goto theend;
13038 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13039 if (regmatch.regprog != NULL)
13041 regmatch.rm_ic = p_ic;
13043 for (;;)
13045 if (l != NULL)
13047 if (li == NULL)
13049 match = FALSE;
13050 break;
13052 vim_free(tofree);
13053 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13054 if (str == NULL)
13055 break;
13058 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13060 if (match && --nth <= 0)
13061 break;
13062 if (l == NULL && !match)
13063 break;
13065 /* Advance to just after the match. */
13066 if (l != NULL)
13068 li = li->li_next;
13069 ++idx;
13071 else
13073 #ifdef FEAT_MBYTE
13074 startcol = (colnr_T)(regmatch.startp[0]
13075 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13076 #else
13077 startcol = regmatch.startp[0] + 1 - str;
13078 #endif
13082 if (match)
13084 if (type == 3)
13086 int i;
13088 /* return list with matched string and submatches */
13089 for (i = 0; i < NSUBEXP; ++i)
13091 if (regmatch.endp[i] == NULL)
13093 if (list_append_string(rettv->vval.v_list,
13094 (char_u *)"", 0) == FAIL)
13095 break;
13097 else if (list_append_string(rettv->vval.v_list,
13098 regmatch.startp[i],
13099 (int)(regmatch.endp[i] - regmatch.startp[i]))
13100 == FAIL)
13101 break;
13104 else if (type == 2)
13106 /* return matched string */
13107 if (l != NULL)
13108 copy_tv(&li->li_tv, rettv);
13109 else
13110 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13111 (int)(regmatch.endp[0] - regmatch.startp[0]));
13113 else if (l != NULL)
13114 rettv->vval.v_number = idx;
13115 else
13117 if (type != 0)
13118 rettv->vval.v_number =
13119 (varnumber_T)(regmatch.startp[0] - str);
13120 else
13121 rettv->vval.v_number =
13122 (varnumber_T)(regmatch.endp[0] - str);
13123 rettv->vval.v_number += (varnumber_T)(str - expr);
13126 vim_free(regmatch.regprog);
13129 theend:
13130 vim_free(tofree);
13131 p_cpo = save_cpo;
13135 * "match()" function
13137 static void
13138 f_match(argvars, rettv)
13139 typval_T *argvars;
13140 typval_T *rettv;
13142 find_some_match(argvars, rettv, 1);
13146 * "matchadd()" function
13148 static void
13149 f_matchadd(argvars, rettv)
13150 typval_T *argvars;
13151 typval_T *rettv;
13153 #ifdef FEAT_SEARCH_EXTRA
13154 char_u buf[NUMBUFLEN];
13155 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13156 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13157 int prio = 10; /* default priority */
13158 int id = -1;
13159 int error = FALSE;
13161 rettv->vval.v_number = -1;
13163 if (grp == NULL || pat == NULL)
13164 return;
13165 if (argvars[2].v_type != VAR_UNKNOWN)
13167 prio = get_tv_number_chk(&argvars[2], &error);
13168 if (argvars[3].v_type != VAR_UNKNOWN)
13169 id = get_tv_number_chk(&argvars[3], &error);
13171 if (error == TRUE)
13172 return;
13173 if (id >= 1 && id <= 3)
13175 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13176 return;
13179 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13180 #endif
13184 * "matcharg()" function
13186 static void
13187 f_matcharg(argvars, rettv)
13188 typval_T *argvars;
13189 typval_T *rettv;
13191 if (rettv_list_alloc(rettv) == OK)
13193 #ifdef FEAT_SEARCH_EXTRA
13194 int id = get_tv_number(&argvars[0]);
13195 matchitem_T *m;
13197 if (id >= 1 && id <= 3)
13199 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13201 list_append_string(rettv->vval.v_list,
13202 syn_id2name(m->hlg_id), -1);
13203 list_append_string(rettv->vval.v_list, m->pattern, -1);
13205 else
13207 list_append_string(rettv->vval.v_list, NUL, -1);
13208 list_append_string(rettv->vval.v_list, NUL, -1);
13211 #endif
13216 * "matchdelete()" function
13218 static void
13219 f_matchdelete(argvars, rettv)
13220 typval_T *argvars;
13221 typval_T *rettv;
13223 #ifdef FEAT_SEARCH_EXTRA
13224 rettv->vval.v_number = match_delete(curwin,
13225 (int)get_tv_number(&argvars[0]), TRUE);
13226 #endif
13230 * "matchend()" function
13232 static void
13233 f_matchend(argvars, rettv)
13234 typval_T *argvars;
13235 typval_T *rettv;
13237 find_some_match(argvars, rettv, 0);
13241 * "matchlist()" function
13243 static void
13244 f_matchlist(argvars, rettv)
13245 typval_T *argvars;
13246 typval_T *rettv;
13248 find_some_match(argvars, rettv, 3);
13252 * "matchstr()" function
13254 static void
13255 f_matchstr(argvars, rettv)
13256 typval_T *argvars;
13257 typval_T *rettv;
13259 find_some_match(argvars, rettv, 2);
13262 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13264 static void
13265 max_min(argvars, rettv, domax)
13266 typval_T *argvars;
13267 typval_T *rettv;
13268 int domax;
13270 long n = 0;
13271 long i;
13272 int error = FALSE;
13274 if (argvars[0].v_type == VAR_LIST)
13276 list_T *l;
13277 listitem_T *li;
13279 l = argvars[0].vval.v_list;
13280 if (l != NULL)
13282 li = l->lv_first;
13283 if (li != NULL)
13285 n = get_tv_number_chk(&li->li_tv, &error);
13286 for (;;)
13288 li = li->li_next;
13289 if (li == NULL)
13290 break;
13291 i = get_tv_number_chk(&li->li_tv, &error);
13292 if (domax ? i > n : i < n)
13293 n = i;
13298 else if (argvars[0].v_type == VAR_DICT)
13300 dict_T *d;
13301 int first = TRUE;
13302 hashitem_T *hi;
13303 int todo;
13305 d = argvars[0].vval.v_dict;
13306 if (d != NULL)
13308 todo = (int)d->dv_hashtab.ht_used;
13309 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13311 if (!HASHITEM_EMPTY(hi))
13313 --todo;
13314 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13315 if (first)
13317 n = i;
13318 first = FALSE;
13320 else if (domax ? i > n : i < n)
13321 n = i;
13326 else
13327 EMSG(_(e_listdictarg));
13328 rettv->vval.v_number = error ? 0 : n;
13332 * "max()" function
13334 static void
13335 f_max(argvars, rettv)
13336 typval_T *argvars;
13337 typval_T *rettv;
13339 max_min(argvars, rettv, TRUE);
13343 * "min()" function
13345 static void
13346 f_min(argvars, rettv)
13347 typval_T *argvars;
13348 typval_T *rettv;
13350 max_min(argvars, rettv, FALSE);
13353 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13356 * Create the directory in which "dir" is located, and higher levels when
13357 * needed.
13359 static int
13360 mkdir_recurse(dir, prot)
13361 char_u *dir;
13362 int prot;
13364 char_u *p;
13365 char_u *updir;
13366 int r = FAIL;
13368 /* Get end of directory name in "dir".
13369 * We're done when it's "/" or "c:/". */
13370 p = gettail_sep(dir);
13371 if (p <= get_past_head(dir))
13372 return OK;
13374 /* If the directory exists we're done. Otherwise: create it.*/
13375 updir = vim_strnsave(dir, (int)(p - dir));
13376 if (updir == NULL)
13377 return FAIL;
13378 if (mch_isdir(updir))
13379 r = OK;
13380 else if (mkdir_recurse(updir, prot) == OK)
13381 r = vim_mkdir_emsg(updir, prot);
13382 vim_free(updir);
13383 return r;
13386 #ifdef vim_mkdir
13388 * "mkdir()" function
13390 static void
13391 f_mkdir(argvars, rettv)
13392 typval_T *argvars;
13393 typval_T *rettv;
13395 char_u *dir;
13396 char_u buf[NUMBUFLEN];
13397 int prot = 0755;
13399 rettv->vval.v_number = FAIL;
13400 if (check_restricted() || check_secure())
13401 return;
13403 dir = get_tv_string_buf(&argvars[0], buf);
13404 if (argvars[1].v_type != VAR_UNKNOWN)
13406 if (argvars[2].v_type != VAR_UNKNOWN)
13407 prot = get_tv_number_chk(&argvars[2], NULL);
13408 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13409 mkdir_recurse(dir, prot);
13411 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13413 #endif
13416 * "mode()" function
13418 /*ARGSUSED*/
13419 static void
13420 f_mode(argvars, rettv)
13421 typval_T *argvars;
13422 typval_T *rettv;
13424 char_u buf[3];
13426 buf[1] = NUL;
13427 buf[2] = NUL;
13429 #ifdef FEAT_VISUAL
13430 if (VIsual_active)
13432 if (VIsual_select)
13433 buf[0] = VIsual_mode + 's' - 'v';
13434 else
13435 buf[0] = VIsual_mode;
13437 else
13438 #endif
13439 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13440 || State == CONFIRM)
13442 buf[0] = 'r';
13443 if (State == ASKMORE)
13444 buf[1] = 'm';
13445 else if (State == CONFIRM)
13446 buf[1] = '?';
13448 else if (State == EXTERNCMD)
13449 buf[0] = '!';
13450 else if (State & INSERT)
13452 #ifdef FEAT_VREPLACE
13453 if (State & VREPLACE_FLAG)
13455 buf[0] = 'R';
13456 buf[1] = 'v';
13458 else
13459 #endif
13460 if (State & REPLACE_FLAG)
13461 buf[0] = 'R';
13462 else
13463 buf[0] = 'i';
13465 else if (State & CMDLINE)
13467 buf[0] = 'c';
13468 if (exmode_active)
13469 buf[1] = 'v';
13471 else if (exmode_active)
13473 buf[0] = 'c';
13474 buf[1] = 'e';
13476 else
13478 buf[0] = 'n';
13479 if (finish_op)
13480 buf[1] = 'o';
13483 /* A zero number or empty string argument: return only major mode. */
13484 if (!(argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number != 0)
13485 && !(argvars[0].v_type == VAR_STRING
13486 && *get_tv_string(&argvars[0]) != NUL))
13487 buf[1] = NUL;
13489 rettv->vval.v_string = vim_strsave(buf);
13490 rettv->v_type = VAR_STRING;
13494 * "nextnonblank()" function
13496 static void
13497 f_nextnonblank(argvars, rettv)
13498 typval_T *argvars;
13499 typval_T *rettv;
13501 linenr_T lnum;
13503 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13505 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13507 lnum = 0;
13508 break;
13510 if (*skipwhite(ml_get(lnum)) != NUL)
13511 break;
13513 rettv->vval.v_number = lnum;
13517 * "nr2char()" function
13519 static void
13520 f_nr2char(argvars, rettv)
13521 typval_T *argvars;
13522 typval_T *rettv;
13524 char_u buf[NUMBUFLEN];
13526 #ifdef FEAT_MBYTE
13527 if (has_mbyte)
13528 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13529 else
13530 #endif
13532 buf[0] = (char_u)get_tv_number(&argvars[0]);
13533 buf[1] = NUL;
13535 rettv->v_type = VAR_STRING;
13536 rettv->vval.v_string = vim_strsave(buf);
13540 * "pathshorten()" function
13542 static void
13543 f_pathshorten(argvars, rettv)
13544 typval_T *argvars;
13545 typval_T *rettv;
13547 char_u *p;
13549 rettv->v_type = VAR_STRING;
13550 p = get_tv_string_chk(&argvars[0]);
13551 if (p == NULL)
13552 rettv->vval.v_string = NULL;
13553 else
13555 p = vim_strsave(p);
13556 rettv->vval.v_string = p;
13557 if (p != NULL)
13558 shorten_dir(p);
13562 #ifdef FEAT_FLOAT
13564 * "pow()" function
13566 static void
13567 f_pow(argvars, rettv)
13568 typval_T *argvars;
13569 typval_T *rettv;
13571 float_T fx, fy;
13573 rettv->v_type = VAR_FLOAT;
13574 if (get_float_arg(argvars, &fx) == OK
13575 && get_float_arg(&argvars[1], &fy) == OK)
13576 rettv->vval.v_float = pow(fx, fy);
13577 else
13578 rettv->vval.v_float = 0.0;
13580 #endif
13583 * "prevnonblank()" function
13585 static void
13586 f_prevnonblank(argvars, rettv)
13587 typval_T *argvars;
13588 typval_T *rettv;
13590 linenr_T lnum;
13592 lnum = get_tv_lnum(argvars);
13593 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13594 lnum = 0;
13595 else
13596 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13597 --lnum;
13598 rettv->vval.v_number = lnum;
13601 #ifdef HAVE_STDARG_H
13602 /* This dummy va_list is here because:
13603 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13604 * - locally in the function results in a "used before set" warning
13605 * - using va_start() to initialize it gives "function with fixed args" error */
13606 static va_list ap;
13607 #endif
13610 * "printf()" function
13612 static void
13613 f_printf(argvars, rettv)
13614 typval_T *argvars;
13615 typval_T *rettv;
13617 rettv->v_type = VAR_STRING;
13618 rettv->vval.v_string = NULL;
13619 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13621 char_u buf[NUMBUFLEN];
13622 int len;
13623 char_u *s;
13624 int saved_did_emsg = did_emsg;
13625 char *fmt;
13627 /* Get the required length, allocate the buffer and do it for real. */
13628 did_emsg = FALSE;
13629 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13630 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13631 if (!did_emsg)
13633 s = alloc(len + 1);
13634 if (s != NULL)
13636 rettv->vval.v_string = s;
13637 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13640 did_emsg |= saved_did_emsg;
13642 #endif
13646 * "pumvisible()" function
13648 /*ARGSUSED*/
13649 static void
13650 f_pumvisible(argvars, rettv)
13651 typval_T *argvars;
13652 typval_T *rettv;
13654 rettv->vval.v_number = 0;
13655 #ifdef FEAT_INS_EXPAND
13656 if (pum_visible())
13657 rettv->vval.v_number = 1;
13658 #endif
13662 * "range()" function
13664 static void
13665 f_range(argvars, rettv)
13666 typval_T *argvars;
13667 typval_T *rettv;
13669 long start;
13670 long end;
13671 long stride = 1;
13672 long i;
13673 int error = FALSE;
13675 start = get_tv_number_chk(&argvars[0], &error);
13676 if (argvars[1].v_type == VAR_UNKNOWN)
13678 end = start - 1;
13679 start = 0;
13681 else
13683 end = get_tv_number_chk(&argvars[1], &error);
13684 if (argvars[2].v_type != VAR_UNKNOWN)
13685 stride = get_tv_number_chk(&argvars[2], &error);
13688 rettv->vval.v_number = 0;
13689 if (error)
13690 return; /* type error; errmsg already given */
13691 if (stride == 0)
13692 EMSG(_("E726: Stride is zero"));
13693 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13694 EMSG(_("E727: Start past end"));
13695 else
13697 if (rettv_list_alloc(rettv) == OK)
13698 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13699 if (list_append_number(rettv->vval.v_list,
13700 (varnumber_T)i) == FAIL)
13701 break;
13706 * "readfile()" function
13708 static void
13709 f_readfile(argvars, rettv)
13710 typval_T *argvars;
13711 typval_T *rettv;
13713 int binary = FALSE;
13714 char_u *fname;
13715 FILE *fd;
13716 listitem_T *li;
13717 #define FREAD_SIZE 200 /* optimized for text lines */
13718 char_u buf[FREAD_SIZE];
13719 int readlen; /* size of last fread() */
13720 int buflen; /* nr of valid chars in buf[] */
13721 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13722 int tolist; /* first byte in buf[] still to be put in list */
13723 int chop; /* how many CR to chop off */
13724 char_u *prev = NULL; /* previously read bytes, if any */
13725 int prevlen = 0; /* length of "prev" if not NULL */
13726 char_u *s;
13727 int len;
13728 long maxline = MAXLNUM;
13729 long cnt = 0;
13731 if (argvars[1].v_type != VAR_UNKNOWN)
13733 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13734 binary = TRUE;
13735 if (argvars[2].v_type != VAR_UNKNOWN)
13736 maxline = get_tv_number(&argvars[2]);
13739 if (rettv_list_alloc(rettv) == FAIL)
13740 return;
13742 /* Always open the file in binary mode, library functions have a mind of
13743 * their own about CR-LF conversion. */
13744 fname = get_tv_string(&argvars[0]);
13745 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13747 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13748 return;
13751 filtd = 0;
13752 while (cnt < maxline || maxline < 0)
13754 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13755 buflen = filtd + readlen;
13756 tolist = 0;
13757 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13759 if (buf[filtd] == '\n' || readlen <= 0)
13761 /* Only when in binary mode add an empty list item when the
13762 * last line ends in a '\n'. */
13763 if (!binary && readlen == 0 && filtd == 0)
13764 break;
13766 /* Found end-of-line or end-of-file: add a text line to the
13767 * list. */
13768 chop = 0;
13769 if (!binary)
13770 while (filtd - chop - 1 >= tolist
13771 && buf[filtd - chop - 1] == '\r')
13772 ++chop;
13773 len = filtd - tolist - chop;
13774 if (prev == NULL)
13775 s = vim_strnsave(buf + tolist, len);
13776 else
13778 s = alloc((unsigned)(prevlen + len + 1));
13779 if (s != NULL)
13781 mch_memmove(s, prev, prevlen);
13782 vim_free(prev);
13783 prev = NULL;
13784 mch_memmove(s + prevlen, buf + tolist, len);
13785 s[prevlen + len] = NUL;
13788 tolist = filtd + 1;
13790 li = listitem_alloc();
13791 if (li == NULL)
13793 vim_free(s);
13794 break;
13796 li->li_tv.v_type = VAR_STRING;
13797 li->li_tv.v_lock = 0;
13798 li->li_tv.vval.v_string = s;
13799 list_append(rettv->vval.v_list, li);
13801 if (++cnt >= maxline && maxline >= 0)
13802 break;
13803 if (readlen <= 0)
13804 break;
13806 else if (buf[filtd] == NUL)
13807 buf[filtd] = '\n';
13809 if (readlen <= 0)
13810 break;
13812 if (tolist == 0)
13814 /* "buf" is full, need to move text to an allocated buffer */
13815 if (prev == NULL)
13817 prev = vim_strnsave(buf, buflen);
13818 prevlen = buflen;
13820 else
13822 s = alloc((unsigned)(prevlen + buflen));
13823 if (s != NULL)
13825 mch_memmove(s, prev, prevlen);
13826 mch_memmove(s + prevlen, buf, buflen);
13827 vim_free(prev);
13828 prev = s;
13829 prevlen += buflen;
13832 filtd = 0;
13834 else
13836 mch_memmove(buf, buf + tolist, buflen - tolist);
13837 filtd -= tolist;
13842 * For a negative line count use only the lines at the end of the file,
13843 * free the rest.
13845 if (maxline < 0)
13846 while (cnt > -maxline)
13848 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13849 --cnt;
13852 vim_free(prev);
13853 fclose(fd);
13856 #if defined(FEAT_RELTIME)
13857 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13860 * Convert a List to proftime_T.
13861 * Return FAIL when there is something wrong.
13863 static int
13864 list2proftime(arg, tm)
13865 typval_T *arg;
13866 proftime_T *tm;
13868 long n1, n2;
13869 int error = FALSE;
13871 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13872 || arg->vval.v_list->lv_len != 2)
13873 return FAIL;
13874 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13875 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13876 # ifdef WIN3264
13877 tm->HighPart = n1;
13878 tm->LowPart = n2;
13879 # else
13880 tm->tv_sec = n1;
13881 tm->tv_usec = n2;
13882 # endif
13883 return error ? FAIL : OK;
13885 #endif /* FEAT_RELTIME */
13888 * "reltime()" function
13890 static void
13891 f_reltime(argvars, rettv)
13892 typval_T *argvars;
13893 typval_T *rettv;
13895 #ifdef FEAT_RELTIME
13896 proftime_T res;
13897 proftime_T start;
13899 if (argvars[0].v_type == VAR_UNKNOWN)
13901 /* No arguments: get current time. */
13902 profile_start(&res);
13904 else if (argvars[1].v_type == VAR_UNKNOWN)
13906 if (list2proftime(&argvars[0], &res) == FAIL)
13907 return;
13908 profile_end(&res);
13910 else
13912 /* Two arguments: compute the difference. */
13913 if (list2proftime(&argvars[0], &start) == FAIL
13914 || list2proftime(&argvars[1], &res) == FAIL)
13915 return;
13916 profile_sub(&res, &start);
13919 if (rettv_list_alloc(rettv) == OK)
13921 long n1, n2;
13923 # ifdef WIN3264
13924 n1 = res.HighPart;
13925 n2 = res.LowPart;
13926 # else
13927 n1 = res.tv_sec;
13928 n2 = res.tv_usec;
13929 # endif
13930 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13931 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13933 #endif
13937 * "reltimestr()" function
13939 static void
13940 f_reltimestr(argvars, rettv)
13941 typval_T *argvars;
13942 typval_T *rettv;
13944 #ifdef FEAT_RELTIME
13945 proftime_T tm;
13946 #endif
13948 rettv->v_type = VAR_STRING;
13949 rettv->vval.v_string = NULL;
13950 #ifdef FEAT_RELTIME
13951 if (list2proftime(&argvars[0], &tm) == OK)
13952 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13953 #endif
13956 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13957 static void make_connection __ARGS((void));
13958 static int check_connection __ARGS((void));
13960 static void
13961 make_connection()
13963 if (X_DISPLAY == NULL
13964 # ifdef FEAT_GUI
13965 && !gui.in_use
13966 # endif
13969 x_force_connect = TRUE;
13970 setup_term_clip();
13971 x_force_connect = FALSE;
13975 static int
13976 check_connection()
13978 make_connection();
13979 if (X_DISPLAY == NULL)
13981 EMSG(_("E240: No connection to Vim server"));
13982 return FAIL;
13984 return OK;
13986 #endif
13988 #ifdef FEAT_CLIENTSERVER
13989 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
13991 static void
13992 remote_common(argvars, rettv, expr)
13993 typval_T *argvars;
13994 typval_T *rettv;
13995 int expr;
13997 char_u *server_name;
13998 char_u *keys;
13999 char_u *r = NULL;
14000 char_u buf[NUMBUFLEN];
14001 # ifdef WIN32
14002 HWND w;
14003 # else
14004 Window w;
14005 # endif
14007 if (check_restricted() || check_secure())
14008 return;
14010 # ifdef FEAT_X11
14011 if (check_connection() == FAIL)
14012 return;
14013 # endif
14015 server_name = get_tv_string_chk(&argvars[0]);
14016 if (server_name == NULL)
14017 return; /* type error; errmsg already given */
14018 keys = get_tv_string_buf(&argvars[1], buf);
14019 # ifdef WIN32
14020 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14021 # else
14022 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14023 < 0)
14024 # endif
14026 if (r != NULL)
14027 EMSG(r); /* sending worked but evaluation failed */
14028 else
14029 EMSG2(_("E241: Unable to send to %s"), server_name);
14030 return;
14033 rettv->vval.v_string = r;
14035 if (argvars[2].v_type != VAR_UNKNOWN)
14037 dictitem_T v;
14038 char_u str[30];
14039 char_u *idvar;
14041 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14042 v.di_tv.v_type = VAR_STRING;
14043 v.di_tv.vval.v_string = vim_strsave(str);
14044 idvar = get_tv_string_chk(&argvars[2]);
14045 if (idvar != NULL)
14046 set_var(idvar, &v.di_tv, FALSE);
14047 vim_free(v.di_tv.vval.v_string);
14050 #endif
14053 * "remote_expr()" function
14055 /*ARGSUSED*/
14056 static void
14057 f_remote_expr(argvars, rettv)
14058 typval_T *argvars;
14059 typval_T *rettv;
14061 rettv->v_type = VAR_STRING;
14062 rettv->vval.v_string = NULL;
14063 #ifdef FEAT_CLIENTSERVER
14064 remote_common(argvars, rettv, TRUE);
14065 #endif
14069 * "remote_foreground()" function
14071 /*ARGSUSED*/
14072 static void
14073 f_remote_foreground(argvars, rettv)
14074 typval_T *argvars;
14075 typval_T *rettv;
14077 rettv->vval.v_number = 0;
14078 #ifdef FEAT_CLIENTSERVER
14079 # ifdef WIN32
14080 /* On Win32 it's done in this application. */
14082 char_u *server_name = get_tv_string_chk(&argvars[0]);
14084 if (server_name != NULL)
14085 serverForeground(server_name);
14087 # else
14088 /* Send a foreground() expression to the server. */
14089 argvars[1].v_type = VAR_STRING;
14090 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14091 argvars[2].v_type = VAR_UNKNOWN;
14092 remote_common(argvars, rettv, TRUE);
14093 vim_free(argvars[1].vval.v_string);
14094 # endif
14095 #endif
14098 /*ARGSUSED*/
14099 static void
14100 f_remote_peek(argvars, rettv)
14101 typval_T *argvars;
14102 typval_T *rettv;
14104 #ifdef FEAT_CLIENTSERVER
14105 dictitem_T v;
14106 char_u *s = NULL;
14107 # ifdef WIN32
14108 long_u n = 0;
14109 # endif
14110 char_u *serverid;
14112 if (check_restricted() || check_secure())
14114 rettv->vval.v_number = -1;
14115 return;
14117 serverid = get_tv_string_chk(&argvars[0]);
14118 if (serverid == NULL)
14120 rettv->vval.v_number = -1;
14121 return; /* type error; errmsg already given */
14123 # ifdef WIN32
14124 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14125 if (n == 0)
14126 rettv->vval.v_number = -1;
14127 else
14129 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14130 rettv->vval.v_number = (s != NULL);
14132 # else
14133 rettv->vval.v_number = 0;
14134 if (check_connection() == FAIL)
14135 return;
14137 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14138 serverStrToWin(serverid), &s);
14139 # endif
14141 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14143 char_u *retvar;
14145 v.di_tv.v_type = VAR_STRING;
14146 v.di_tv.vval.v_string = vim_strsave(s);
14147 retvar = get_tv_string_chk(&argvars[1]);
14148 if (retvar != NULL)
14149 set_var(retvar, &v.di_tv, FALSE);
14150 vim_free(v.di_tv.vval.v_string);
14152 #else
14153 rettv->vval.v_number = -1;
14154 #endif
14157 /*ARGSUSED*/
14158 static void
14159 f_remote_read(argvars, rettv)
14160 typval_T *argvars;
14161 typval_T *rettv;
14163 char_u *r = NULL;
14165 #ifdef FEAT_CLIENTSERVER
14166 char_u *serverid = get_tv_string_chk(&argvars[0]);
14168 if (serverid != NULL && !check_restricted() && !check_secure())
14170 # ifdef WIN32
14171 /* The server's HWND is encoded in the 'id' parameter */
14172 long_u n = 0;
14174 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14175 if (n != 0)
14176 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14177 if (r == NULL)
14178 # else
14179 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14180 serverStrToWin(serverid), &r, FALSE) < 0)
14181 # endif
14182 EMSG(_("E277: Unable to read a server reply"));
14184 #endif
14185 rettv->v_type = VAR_STRING;
14186 rettv->vval.v_string = r;
14190 * "remote_send()" function
14192 /*ARGSUSED*/
14193 static void
14194 f_remote_send(argvars, rettv)
14195 typval_T *argvars;
14196 typval_T *rettv;
14198 rettv->v_type = VAR_STRING;
14199 rettv->vval.v_string = NULL;
14200 #ifdef FEAT_CLIENTSERVER
14201 remote_common(argvars, rettv, FALSE);
14202 #endif
14206 * "remove()" function
14208 static void
14209 f_remove(argvars, rettv)
14210 typval_T *argvars;
14211 typval_T *rettv;
14213 list_T *l;
14214 listitem_T *item, *item2;
14215 listitem_T *li;
14216 long idx;
14217 long end;
14218 char_u *key;
14219 dict_T *d;
14220 dictitem_T *di;
14222 rettv->vval.v_number = 0;
14223 if (argvars[0].v_type == VAR_DICT)
14225 if (argvars[2].v_type != VAR_UNKNOWN)
14226 EMSG2(_(e_toomanyarg), "remove()");
14227 else if ((d = argvars[0].vval.v_dict) != NULL
14228 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14230 key = get_tv_string_chk(&argvars[1]);
14231 if (key != NULL)
14233 di = dict_find(d, key, -1);
14234 if (di == NULL)
14235 EMSG2(_(e_dictkey), key);
14236 else
14238 *rettv = di->di_tv;
14239 init_tv(&di->di_tv);
14240 dictitem_remove(d, di);
14245 else if (argvars[0].v_type != VAR_LIST)
14246 EMSG2(_(e_listdictarg), "remove()");
14247 else if ((l = argvars[0].vval.v_list) != NULL
14248 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14250 int error = FALSE;
14252 idx = get_tv_number_chk(&argvars[1], &error);
14253 if (error)
14254 ; /* type error: do nothing, errmsg already given */
14255 else if ((item = list_find(l, idx)) == NULL)
14256 EMSGN(_(e_listidx), idx);
14257 else
14259 if (argvars[2].v_type == VAR_UNKNOWN)
14261 /* Remove one item, return its value. */
14262 list_remove(l, item, item);
14263 *rettv = item->li_tv;
14264 vim_free(item);
14266 else
14268 /* Remove range of items, return list with values. */
14269 end = get_tv_number_chk(&argvars[2], &error);
14270 if (error)
14271 ; /* type error: do nothing */
14272 else if ((item2 = list_find(l, end)) == NULL)
14273 EMSGN(_(e_listidx), end);
14274 else
14276 int cnt = 0;
14278 for (li = item; li != NULL; li = li->li_next)
14280 ++cnt;
14281 if (li == item2)
14282 break;
14284 if (li == NULL) /* didn't find "item2" after "item" */
14285 EMSG(_(e_invrange));
14286 else
14288 list_remove(l, item, item2);
14289 if (rettv_list_alloc(rettv) == OK)
14291 l = rettv->vval.v_list;
14292 l->lv_first = item;
14293 l->lv_last = item2;
14294 item->li_prev = NULL;
14295 item2->li_next = NULL;
14296 l->lv_len = cnt;
14306 * "rename({from}, {to})" function
14308 static void
14309 f_rename(argvars, rettv)
14310 typval_T *argvars;
14311 typval_T *rettv;
14313 char_u buf[NUMBUFLEN];
14315 if (check_restricted() || check_secure())
14316 rettv->vval.v_number = -1;
14317 else
14318 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14319 get_tv_string_buf(&argvars[1], buf));
14323 * "repeat()" function
14325 /*ARGSUSED*/
14326 static void
14327 f_repeat(argvars, rettv)
14328 typval_T *argvars;
14329 typval_T *rettv;
14331 char_u *p;
14332 int n;
14333 int slen;
14334 int len;
14335 char_u *r;
14336 int i;
14338 n = get_tv_number(&argvars[1]);
14339 if (argvars[0].v_type == VAR_LIST)
14341 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14342 while (n-- > 0)
14343 if (list_extend(rettv->vval.v_list,
14344 argvars[0].vval.v_list, NULL) == FAIL)
14345 break;
14347 else
14349 p = get_tv_string(&argvars[0]);
14350 rettv->v_type = VAR_STRING;
14351 rettv->vval.v_string = NULL;
14353 slen = (int)STRLEN(p);
14354 len = slen * n;
14355 if (len <= 0)
14356 return;
14358 r = alloc(len + 1);
14359 if (r != NULL)
14361 for (i = 0; i < n; i++)
14362 mch_memmove(r + i * slen, p, (size_t)slen);
14363 r[len] = NUL;
14366 rettv->vval.v_string = r;
14371 * "resolve()" function
14373 static void
14374 f_resolve(argvars, rettv)
14375 typval_T *argvars;
14376 typval_T *rettv;
14378 char_u *p;
14380 p = get_tv_string(&argvars[0]);
14381 #ifdef FEAT_SHORTCUT
14383 char_u *v = NULL;
14385 v = mch_resolve_shortcut(p);
14386 if (v != NULL)
14387 rettv->vval.v_string = v;
14388 else
14389 rettv->vval.v_string = vim_strsave(p);
14391 #else
14392 # ifdef HAVE_READLINK
14394 char_u buf[MAXPATHL + 1];
14395 char_u *cpy;
14396 int len;
14397 char_u *remain = NULL;
14398 char_u *q;
14399 int is_relative_to_current = FALSE;
14400 int has_trailing_pathsep = FALSE;
14401 int limit = 100;
14403 p = vim_strsave(p);
14405 if (p[0] == '.' && (vim_ispathsep(p[1])
14406 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14407 is_relative_to_current = TRUE;
14409 len = STRLEN(p);
14410 if (len > 0 && after_pathsep(p, p + len))
14411 has_trailing_pathsep = TRUE;
14413 q = getnextcomp(p);
14414 if (*q != NUL)
14416 /* Separate the first path component in "p", and keep the
14417 * remainder (beginning with the path separator). */
14418 remain = vim_strsave(q - 1);
14419 q[-1] = NUL;
14422 for (;;)
14424 for (;;)
14426 len = readlink((char *)p, (char *)buf, MAXPATHL);
14427 if (len <= 0)
14428 break;
14429 buf[len] = NUL;
14431 if (limit-- == 0)
14433 vim_free(p);
14434 vim_free(remain);
14435 EMSG(_("E655: Too many symbolic links (cycle?)"));
14436 rettv->vval.v_string = NULL;
14437 goto fail;
14440 /* Ensure that the result will have a trailing path separator
14441 * if the argument has one. */
14442 if (remain == NULL && has_trailing_pathsep)
14443 add_pathsep(buf);
14445 /* Separate the first path component in the link value and
14446 * concatenate the remainders. */
14447 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14448 if (*q != NUL)
14450 if (remain == NULL)
14451 remain = vim_strsave(q - 1);
14452 else
14454 cpy = concat_str(q - 1, remain);
14455 if (cpy != NULL)
14457 vim_free(remain);
14458 remain = cpy;
14461 q[-1] = NUL;
14464 q = gettail(p);
14465 if (q > p && *q == NUL)
14467 /* Ignore trailing path separator. */
14468 q[-1] = NUL;
14469 q = gettail(p);
14471 if (q > p && !mch_isFullName(buf))
14473 /* symlink is relative to directory of argument */
14474 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14475 if (cpy != NULL)
14477 STRCPY(cpy, p);
14478 STRCPY(gettail(cpy), buf);
14479 vim_free(p);
14480 p = cpy;
14483 else
14485 vim_free(p);
14486 p = vim_strsave(buf);
14490 if (remain == NULL)
14491 break;
14493 /* Append the first path component of "remain" to "p". */
14494 q = getnextcomp(remain + 1);
14495 len = q - remain - (*q != NUL);
14496 cpy = vim_strnsave(p, STRLEN(p) + len);
14497 if (cpy != NULL)
14499 STRNCAT(cpy, remain, len);
14500 vim_free(p);
14501 p = cpy;
14503 /* Shorten "remain". */
14504 if (*q != NUL)
14505 STRMOVE(remain, q - 1);
14506 else
14508 vim_free(remain);
14509 remain = NULL;
14513 /* If the result is a relative path name, make it explicitly relative to
14514 * the current directory if and only if the argument had this form. */
14515 if (!vim_ispathsep(*p))
14517 if (is_relative_to_current
14518 && *p != NUL
14519 && !(p[0] == '.'
14520 && (p[1] == NUL
14521 || vim_ispathsep(p[1])
14522 || (p[1] == '.'
14523 && (p[2] == NUL
14524 || vim_ispathsep(p[2]))))))
14526 /* Prepend "./". */
14527 cpy = concat_str((char_u *)"./", p);
14528 if (cpy != NULL)
14530 vim_free(p);
14531 p = cpy;
14534 else if (!is_relative_to_current)
14536 /* Strip leading "./". */
14537 q = p;
14538 while (q[0] == '.' && vim_ispathsep(q[1]))
14539 q += 2;
14540 if (q > p)
14541 STRMOVE(p, p + 2);
14545 /* Ensure that the result will have no trailing path separator
14546 * if the argument had none. But keep "/" or "//". */
14547 if (!has_trailing_pathsep)
14549 q = p + STRLEN(p);
14550 if (after_pathsep(p, q))
14551 *gettail_sep(p) = NUL;
14554 rettv->vval.v_string = p;
14556 # else
14557 rettv->vval.v_string = vim_strsave(p);
14558 # endif
14559 #endif
14561 simplify_filename(rettv->vval.v_string);
14563 #ifdef HAVE_READLINK
14564 fail:
14565 #endif
14566 rettv->v_type = VAR_STRING;
14570 * "reverse({list})" function
14572 static void
14573 f_reverse(argvars, rettv)
14574 typval_T *argvars;
14575 typval_T *rettv;
14577 list_T *l;
14578 listitem_T *li, *ni;
14580 rettv->vval.v_number = 0;
14581 if (argvars[0].v_type != VAR_LIST)
14582 EMSG2(_(e_listarg), "reverse()");
14583 else if ((l = argvars[0].vval.v_list) != NULL
14584 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14586 li = l->lv_last;
14587 l->lv_first = l->lv_last = NULL;
14588 l->lv_len = 0;
14589 while (li != NULL)
14591 ni = li->li_prev;
14592 list_append(l, li);
14593 li = ni;
14595 rettv->vval.v_list = l;
14596 rettv->v_type = VAR_LIST;
14597 ++l->lv_refcount;
14598 l->lv_idx = l->lv_len - l->lv_idx - 1;
14602 #define SP_NOMOVE 0x01 /* don't move cursor */
14603 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14604 #define SP_RETCOUNT 0x04 /* return matchcount */
14605 #define SP_SETPCMARK 0x08 /* set previous context mark */
14606 #define SP_START 0x10 /* accept match at start position */
14607 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14608 #define SP_END 0x40 /* leave cursor at end of match */
14610 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14613 * Get flags for a search function.
14614 * Possibly sets "p_ws".
14615 * Returns BACKWARD, FORWARD or zero (for an error).
14617 static int
14618 get_search_arg(varp, flagsp)
14619 typval_T *varp;
14620 int *flagsp;
14622 int dir = FORWARD;
14623 char_u *flags;
14624 char_u nbuf[NUMBUFLEN];
14625 int mask;
14627 if (varp->v_type != VAR_UNKNOWN)
14629 flags = get_tv_string_buf_chk(varp, nbuf);
14630 if (flags == NULL)
14631 return 0; /* type error; errmsg already given */
14632 while (*flags != NUL)
14634 switch (*flags)
14636 case 'b': dir = BACKWARD; break;
14637 case 'w': p_ws = TRUE; break;
14638 case 'W': p_ws = FALSE; break;
14639 default: mask = 0;
14640 if (flagsp != NULL)
14641 switch (*flags)
14643 case 'c': mask = SP_START; break;
14644 case 'e': mask = SP_END; break;
14645 case 'm': mask = SP_RETCOUNT; break;
14646 case 'n': mask = SP_NOMOVE; break;
14647 case 'p': mask = SP_SUBPAT; break;
14648 case 'r': mask = SP_REPEAT; break;
14649 case 's': mask = SP_SETPCMARK; break;
14651 if (mask == 0)
14653 EMSG2(_(e_invarg2), flags);
14654 dir = 0;
14656 else
14657 *flagsp |= mask;
14659 if (dir == 0)
14660 break;
14661 ++flags;
14664 return dir;
14668 * Shared by search() and searchpos() functions
14670 static int
14671 search_cmn(argvars, match_pos, flagsp)
14672 typval_T *argvars;
14673 pos_T *match_pos;
14674 int *flagsp;
14676 int flags;
14677 char_u *pat;
14678 pos_T pos;
14679 pos_T save_cursor;
14680 int save_p_ws = p_ws;
14681 int dir;
14682 int retval = 0; /* default: FAIL */
14683 long lnum_stop = 0;
14684 proftime_T tm;
14685 #ifdef FEAT_RELTIME
14686 long time_limit = 0;
14687 #endif
14688 int options = SEARCH_KEEP;
14689 int subpatnum;
14691 pat = get_tv_string(&argvars[0]);
14692 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14693 if (dir == 0)
14694 goto theend;
14695 flags = *flagsp;
14696 if (flags & SP_START)
14697 options |= SEARCH_START;
14698 if (flags & SP_END)
14699 options |= SEARCH_END;
14701 /* Optional arguments: line number to stop searching and timeout. */
14702 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14704 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14705 if (lnum_stop < 0)
14706 goto theend;
14707 #ifdef FEAT_RELTIME
14708 if (argvars[3].v_type != VAR_UNKNOWN)
14710 time_limit = get_tv_number_chk(&argvars[3], NULL);
14711 if (time_limit < 0)
14712 goto theend;
14714 #endif
14717 #ifdef FEAT_RELTIME
14718 /* Set the time limit, if there is one. */
14719 profile_setlimit(time_limit, &tm);
14720 #endif
14723 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14724 * Check to make sure only those flags are set.
14725 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14726 * flags cannot be set. Check for that condition also.
14728 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14729 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14731 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14732 goto theend;
14735 pos = save_cursor = curwin->w_cursor;
14736 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14737 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14738 if (subpatnum != FAIL)
14740 if (flags & SP_SUBPAT)
14741 retval = subpatnum;
14742 else
14743 retval = pos.lnum;
14744 if (flags & SP_SETPCMARK)
14745 setpcmark();
14746 curwin->w_cursor = pos;
14747 if (match_pos != NULL)
14749 /* Store the match cursor position */
14750 match_pos->lnum = pos.lnum;
14751 match_pos->col = pos.col + 1;
14753 /* "/$" will put the cursor after the end of the line, may need to
14754 * correct that here */
14755 check_cursor();
14758 /* If 'n' flag is used: restore cursor position. */
14759 if (flags & SP_NOMOVE)
14760 curwin->w_cursor = save_cursor;
14761 else
14762 curwin->w_set_curswant = TRUE;
14763 theend:
14764 p_ws = save_p_ws;
14766 return retval;
14769 #ifdef FEAT_FLOAT
14771 * "round({float})" function
14773 static void
14774 f_round(argvars, rettv)
14775 typval_T *argvars;
14776 typval_T *rettv;
14778 float_T f;
14780 rettv->v_type = VAR_FLOAT;
14781 if (get_float_arg(argvars, &f) == OK)
14782 /* round() is not in C90, use ceil() or floor() instead. */
14783 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14784 else
14785 rettv->vval.v_float = 0.0;
14787 #endif
14790 * "search()" function
14792 static void
14793 f_search(argvars, rettv)
14794 typval_T *argvars;
14795 typval_T *rettv;
14797 int flags = 0;
14799 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14803 * "searchdecl()" function
14805 static void
14806 f_searchdecl(argvars, rettv)
14807 typval_T *argvars;
14808 typval_T *rettv;
14810 int locally = 1;
14811 int thisblock = 0;
14812 int error = FALSE;
14813 char_u *name;
14815 rettv->vval.v_number = 1; /* default: FAIL */
14817 name = get_tv_string_chk(&argvars[0]);
14818 if (argvars[1].v_type != VAR_UNKNOWN)
14820 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14821 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14822 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14824 if (!error && name != NULL)
14825 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14826 locally, thisblock, SEARCH_KEEP) == FAIL;
14830 * Used by searchpair() and searchpairpos()
14832 static int
14833 searchpair_cmn(argvars, match_pos)
14834 typval_T *argvars;
14835 pos_T *match_pos;
14837 char_u *spat, *mpat, *epat;
14838 char_u *skip;
14839 int save_p_ws = p_ws;
14840 int dir;
14841 int flags = 0;
14842 char_u nbuf1[NUMBUFLEN];
14843 char_u nbuf2[NUMBUFLEN];
14844 char_u nbuf3[NUMBUFLEN];
14845 int retval = 0; /* default: FAIL */
14846 long lnum_stop = 0;
14847 long time_limit = 0;
14849 /* Get the three pattern arguments: start, middle, end. */
14850 spat = get_tv_string_chk(&argvars[0]);
14851 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14852 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14853 if (spat == NULL || mpat == NULL || epat == NULL)
14854 goto theend; /* type error */
14856 /* Handle the optional fourth argument: flags */
14857 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14858 if (dir == 0)
14859 goto theend;
14861 /* Don't accept SP_END or SP_SUBPAT.
14862 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14864 if ((flags & (SP_END | SP_SUBPAT)) != 0
14865 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14867 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14868 goto theend;
14871 /* Using 'r' implies 'W', otherwise it doesn't work. */
14872 if (flags & SP_REPEAT)
14873 p_ws = FALSE;
14875 /* Optional fifth argument: skip expression */
14876 if (argvars[3].v_type == VAR_UNKNOWN
14877 || argvars[4].v_type == VAR_UNKNOWN)
14878 skip = (char_u *)"";
14879 else
14881 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14882 if (argvars[5].v_type != VAR_UNKNOWN)
14884 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14885 if (lnum_stop < 0)
14886 goto theend;
14887 #ifdef FEAT_RELTIME
14888 if (argvars[6].v_type != VAR_UNKNOWN)
14890 time_limit = get_tv_number_chk(&argvars[6], NULL);
14891 if (time_limit < 0)
14892 goto theend;
14894 #endif
14897 if (skip == NULL)
14898 goto theend; /* type error */
14900 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14901 match_pos, lnum_stop, time_limit);
14903 theend:
14904 p_ws = save_p_ws;
14906 return retval;
14910 * "searchpair()" function
14912 static void
14913 f_searchpair(argvars, rettv)
14914 typval_T *argvars;
14915 typval_T *rettv;
14917 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14921 * "searchpairpos()" function
14923 static void
14924 f_searchpairpos(argvars, rettv)
14925 typval_T *argvars;
14926 typval_T *rettv;
14928 pos_T match_pos;
14929 int lnum = 0;
14930 int col = 0;
14932 rettv->vval.v_number = 0;
14934 if (rettv_list_alloc(rettv) == FAIL)
14935 return;
14937 if (searchpair_cmn(argvars, &match_pos) > 0)
14939 lnum = match_pos.lnum;
14940 col = match_pos.col;
14943 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14944 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14948 * Search for a start/middle/end thing.
14949 * Used by searchpair(), see its documentation for the details.
14950 * Returns 0 or -1 for no match,
14952 long
14953 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
14954 lnum_stop, time_limit)
14955 char_u *spat; /* start pattern */
14956 char_u *mpat; /* middle pattern */
14957 char_u *epat; /* end pattern */
14958 int dir; /* BACKWARD or FORWARD */
14959 char_u *skip; /* skip expression */
14960 int flags; /* SP_SETPCMARK and other SP_ values */
14961 pos_T *match_pos;
14962 linenr_T lnum_stop; /* stop at this line if not zero */
14963 long time_limit; /* stop after this many msec */
14965 char_u *save_cpo;
14966 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14967 long retval = 0;
14968 pos_T pos;
14969 pos_T firstpos;
14970 pos_T foundpos;
14971 pos_T save_cursor;
14972 pos_T save_pos;
14973 int n;
14974 int r;
14975 int nest = 1;
14976 int err;
14977 int options = SEARCH_KEEP;
14978 proftime_T tm;
14980 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
14981 save_cpo = p_cpo;
14982 p_cpo = (char_u *)"";
14984 #ifdef FEAT_RELTIME
14985 /* Set the time limit, if there is one. */
14986 profile_setlimit(time_limit, &tm);
14987 #endif
14989 /* Make two search patterns: start/end (pat2, for in nested pairs) and
14990 * start/middle/end (pat3, for the top pair). */
14991 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
14992 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
14993 if (pat2 == NULL || pat3 == NULL)
14994 goto theend;
14995 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
14996 if (*mpat == NUL)
14997 STRCPY(pat3, pat2);
14998 else
14999 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15000 spat, epat, mpat);
15001 if (flags & SP_START)
15002 options |= SEARCH_START;
15004 save_cursor = curwin->w_cursor;
15005 pos = curwin->w_cursor;
15006 clearpos(&firstpos);
15007 clearpos(&foundpos);
15008 pat = pat3;
15009 for (;;)
15011 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15012 options, RE_SEARCH, lnum_stop, &tm);
15013 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15014 /* didn't find it or found the first match again: FAIL */
15015 break;
15017 if (firstpos.lnum == 0)
15018 firstpos = pos;
15019 if (equalpos(pos, foundpos))
15021 /* Found the same position again. Can happen with a pattern that
15022 * has "\zs" at the end and searching backwards. Advance one
15023 * character and try again. */
15024 if (dir == BACKWARD)
15025 decl(&pos);
15026 else
15027 incl(&pos);
15029 foundpos = pos;
15031 /* clear the start flag to avoid getting stuck here */
15032 options &= ~SEARCH_START;
15034 /* If the skip pattern matches, ignore this match. */
15035 if (*skip != NUL)
15037 save_pos = curwin->w_cursor;
15038 curwin->w_cursor = pos;
15039 r = eval_to_bool(skip, &err, NULL, FALSE);
15040 curwin->w_cursor = save_pos;
15041 if (err)
15043 /* Evaluating {skip} caused an error, break here. */
15044 curwin->w_cursor = save_cursor;
15045 retval = -1;
15046 break;
15048 if (r)
15049 continue;
15052 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15054 /* Found end when searching backwards or start when searching
15055 * forward: nested pair. */
15056 ++nest;
15057 pat = pat2; /* nested, don't search for middle */
15059 else
15061 /* Found end when searching forward or start when searching
15062 * backward: end of (nested) pair; or found middle in outer pair. */
15063 if (--nest == 1)
15064 pat = pat3; /* outer level, search for middle */
15067 if (nest == 0)
15069 /* Found the match: return matchcount or line number. */
15070 if (flags & SP_RETCOUNT)
15071 ++retval;
15072 else
15073 retval = pos.lnum;
15074 if (flags & SP_SETPCMARK)
15075 setpcmark();
15076 curwin->w_cursor = pos;
15077 if (!(flags & SP_REPEAT))
15078 break;
15079 nest = 1; /* search for next unmatched */
15083 if (match_pos != NULL)
15085 /* Store the match cursor position */
15086 match_pos->lnum = curwin->w_cursor.lnum;
15087 match_pos->col = curwin->w_cursor.col + 1;
15090 /* If 'n' flag is used or search failed: restore cursor position. */
15091 if ((flags & SP_NOMOVE) || retval == 0)
15092 curwin->w_cursor = save_cursor;
15094 theend:
15095 vim_free(pat2);
15096 vim_free(pat3);
15097 p_cpo = save_cpo;
15099 return retval;
15103 * "searchpos()" function
15105 static void
15106 f_searchpos(argvars, rettv)
15107 typval_T *argvars;
15108 typval_T *rettv;
15110 pos_T match_pos;
15111 int lnum = 0;
15112 int col = 0;
15113 int n;
15114 int flags = 0;
15116 rettv->vval.v_number = 0;
15118 if (rettv_list_alloc(rettv) == FAIL)
15119 return;
15121 n = search_cmn(argvars, &match_pos, &flags);
15122 if (n > 0)
15124 lnum = match_pos.lnum;
15125 col = match_pos.col;
15128 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15129 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15130 if (flags & SP_SUBPAT)
15131 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15135 /*ARGSUSED*/
15136 static void
15137 f_server2client(argvars, rettv)
15138 typval_T *argvars;
15139 typval_T *rettv;
15141 #ifdef FEAT_CLIENTSERVER
15142 char_u buf[NUMBUFLEN];
15143 char_u *server = get_tv_string_chk(&argvars[0]);
15144 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15146 rettv->vval.v_number = -1;
15147 if (server == NULL || reply == NULL)
15148 return;
15149 if (check_restricted() || check_secure())
15150 return;
15151 # ifdef FEAT_X11
15152 if (check_connection() == FAIL)
15153 return;
15154 # endif
15156 if (serverSendReply(server, reply) < 0)
15158 EMSG(_("E258: Unable to send to client"));
15159 return;
15161 rettv->vval.v_number = 0;
15162 #else
15163 rettv->vval.v_number = -1;
15164 #endif
15167 /*ARGSUSED*/
15168 static void
15169 f_serverlist(argvars, rettv)
15170 typval_T *argvars;
15171 typval_T *rettv;
15173 char_u *r = NULL;
15175 #ifdef FEAT_CLIENTSERVER
15176 # ifdef WIN32
15177 r = serverGetVimNames();
15178 # else
15179 make_connection();
15180 if (X_DISPLAY != NULL)
15181 r = serverGetVimNames(X_DISPLAY);
15182 # endif
15183 #endif
15184 rettv->v_type = VAR_STRING;
15185 rettv->vval.v_string = r;
15189 * "setbufvar()" function
15191 /*ARGSUSED*/
15192 static void
15193 f_setbufvar(argvars, rettv)
15194 typval_T *argvars;
15195 typval_T *rettv;
15197 buf_T *buf;
15198 aco_save_T aco;
15199 char_u *varname, *bufvarname;
15200 typval_T *varp;
15201 char_u nbuf[NUMBUFLEN];
15203 rettv->vval.v_number = 0;
15205 if (check_restricted() || check_secure())
15206 return;
15207 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15208 varname = get_tv_string_chk(&argvars[1]);
15209 buf = get_buf_tv(&argvars[0]);
15210 varp = &argvars[2];
15212 if (buf != NULL && varname != NULL && varp != NULL)
15214 /* set curbuf to be our buf, temporarily */
15215 aucmd_prepbuf(&aco, buf);
15217 if (*varname == '&')
15219 long numval;
15220 char_u *strval;
15221 int error = FALSE;
15223 ++varname;
15224 numval = get_tv_number_chk(varp, &error);
15225 strval = get_tv_string_buf_chk(varp, nbuf);
15226 if (!error && strval != NULL)
15227 set_option_value(varname, numval, strval, OPT_LOCAL);
15229 else
15231 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15232 if (bufvarname != NULL)
15234 STRCPY(bufvarname, "b:");
15235 STRCPY(bufvarname + 2, varname);
15236 set_var(bufvarname, varp, TRUE);
15237 vim_free(bufvarname);
15241 /* reset notion of buffer */
15242 aucmd_restbuf(&aco);
15247 * "setcmdpos()" function
15249 static void
15250 f_setcmdpos(argvars, rettv)
15251 typval_T *argvars;
15252 typval_T *rettv;
15254 int pos = (int)get_tv_number(&argvars[0]) - 1;
15256 if (pos >= 0)
15257 rettv->vval.v_number = set_cmdline_pos(pos);
15261 * "setline()" function
15263 static void
15264 f_setline(argvars, rettv)
15265 typval_T *argvars;
15266 typval_T *rettv;
15268 linenr_T lnum;
15269 char_u *line = NULL;
15270 list_T *l = NULL;
15271 listitem_T *li = NULL;
15272 long added = 0;
15273 linenr_T lcount = curbuf->b_ml.ml_line_count;
15275 lnum = get_tv_lnum(&argvars[0]);
15276 if (argvars[1].v_type == VAR_LIST)
15278 l = argvars[1].vval.v_list;
15279 li = l->lv_first;
15281 else
15282 line = get_tv_string_chk(&argvars[1]);
15284 rettv->vval.v_number = 0; /* OK */
15285 for (;;)
15287 if (l != NULL)
15289 /* list argument, get next string */
15290 if (li == NULL)
15291 break;
15292 line = get_tv_string_chk(&li->li_tv);
15293 li = li->li_next;
15296 rettv->vval.v_number = 1; /* FAIL */
15297 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15298 break;
15299 if (lnum <= curbuf->b_ml.ml_line_count)
15301 /* existing line, replace it */
15302 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15304 changed_bytes(lnum, 0);
15305 if (lnum == curwin->w_cursor.lnum)
15306 check_cursor_col();
15307 rettv->vval.v_number = 0; /* OK */
15310 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15312 /* lnum is one past the last line, append the line */
15313 ++added;
15314 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15315 rettv->vval.v_number = 0; /* OK */
15318 if (l == NULL) /* only one string argument */
15319 break;
15320 ++lnum;
15323 if (added > 0)
15324 appended_lines_mark(lcount, added);
15327 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15330 * Used by "setqflist()" and "setloclist()" functions
15332 /*ARGSUSED*/
15333 static void
15334 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15335 win_T *wp;
15336 typval_T *list_arg;
15337 typval_T *action_arg;
15338 typval_T *rettv;
15340 #ifdef FEAT_QUICKFIX
15341 char_u *act;
15342 int action = ' ';
15343 #endif
15345 rettv->vval.v_number = -1;
15347 #ifdef FEAT_QUICKFIX
15348 if (list_arg->v_type != VAR_LIST)
15349 EMSG(_(e_listreq));
15350 else
15352 list_T *l = list_arg->vval.v_list;
15354 if (action_arg->v_type == VAR_STRING)
15356 act = get_tv_string_chk(action_arg);
15357 if (act == NULL)
15358 return; /* type error; errmsg already given */
15359 if (*act == 'a' || *act == 'r')
15360 action = *act;
15363 if (l != NULL && set_errorlist(wp, l, action) == OK)
15364 rettv->vval.v_number = 0;
15366 #endif
15370 * "setloclist()" function
15372 /*ARGSUSED*/
15373 static void
15374 f_setloclist(argvars, rettv)
15375 typval_T *argvars;
15376 typval_T *rettv;
15378 win_T *win;
15380 rettv->vval.v_number = -1;
15382 win = find_win_by_nr(&argvars[0], NULL);
15383 if (win != NULL)
15384 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15388 * "setmatches()" function
15390 static void
15391 f_setmatches(argvars, rettv)
15392 typval_T *argvars;
15393 typval_T *rettv;
15395 #ifdef FEAT_SEARCH_EXTRA
15396 list_T *l;
15397 listitem_T *li;
15398 dict_T *d;
15400 rettv->vval.v_number = -1;
15401 if (argvars[0].v_type != VAR_LIST)
15403 EMSG(_(e_listreq));
15404 return;
15406 if ((l = argvars[0].vval.v_list) != NULL)
15409 /* To some extent make sure that we are dealing with a list from
15410 * "getmatches()". */
15411 li = l->lv_first;
15412 while (li != NULL)
15414 if (li->li_tv.v_type != VAR_DICT
15415 || (d = li->li_tv.vval.v_dict) == NULL)
15417 EMSG(_(e_invarg));
15418 return;
15420 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15421 && dict_find(d, (char_u *)"pattern", -1) != NULL
15422 && dict_find(d, (char_u *)"priority", -1) != NULL
15423 && dict_find(d, (char_u *)"id", -1) != NULL))
15425 EMSG(_(e_invarg));
15426 return;
15428 li = li->li_next;
15431 clear_matches(curwin);
15432 li = l->lv_first;
15433 while (li != NULL)
15435 d = li->li_tv.vval.v_dict;
15436 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15437 get_dict_string(d, (char_u *)"pattern", FALSE),
15438 (int)get_dict_number(d, (char_u *)"priority"),
15439 (int)get_dict_number(d, (char_u *)"id"));
15440 li = li->li_next;
15442 rettv->vval.v_number = 0;
15444 #endif
15448 * "setpos()" function
15450 /*ARGSUSED*/
15451 static void
15452 f_setpos(argvars, rettv)
15453 typval_T *argvars;
15454 typval_T *rettv;
15456 pos_T pos;
15457 int fnum;
15458 char_u *name;
15460 rettv->vval.v_number = -1;
15461 name = get_tv_string_chk(argvars);
15462 if (name != NULL)
15464 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15466 --pos.col;
15467 if (name[0] == '.' && name[1] == NUL)
15469 /* set cursor */
15470 if (fnum == curbuf->b_fnum)
15472 curwin->w_cursor = pos;
15473 check_cursor();
15474 rettv->vval.v_number = 0;
15476 else
15477 EMSG(_(e_invarg));
15479 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15481 /* set mark */
15482 if (setmark_pos(name[1], &pos, fnum) == OK)
15483 rettv->vval.v_number = 0;
15485 else
15486 EMSG(_(e_invarg));
15492 * "setqflist()" function
15494 /*ARGSUSED*/
15495 static void
15496 f_setqflist(argvars, rettv)
15497 typval_T *argvars;
15498 typval_T *rettv;
15500 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15504 * "setreg()" function
15506 static void
15507 f_setreg(argvars, rettv)
15508 typval_T *argvars;
15509 typval_T *rettv;
15511 int regname;
15512 char_u *strregname;
15513 char_u *stropt;
15514 char_u *strval;
15515 int append;
15516 char_u yank_type;
15517 long block_len;
15519 block_len = -1;
15520 yank_type = MAUTO;
15521 append = FALSE;
15523 strregname = get_tv_string_chk(argvars);
15524 rettv->vval.v_number = 1; /* FAIL is default */
15526 if (strregname == NULL)
15527 return; /* type error; errmsg already given */
15528 regname = *strregname;
15529 if (regname == 0 || regname == '@')
15530 regname = '"';
15531 else if (regname == '=')
15532 return;
15534 if (argvars[2].v_type != VAR_UNKNOWN)
15536 stropt = get_tv_string_chk(&argvars[2]);
15537 if (stropt == NULL)
15538 return; /* type error */
15539 for (; *stropt != NUL; ++stropt)
15540 switch (*stropt)
15542 case 'a': case 'A': /* append */
15543 append = TRUE;
15544 break;
15545 case 'v': case 'c': /* character-wise selection */
15546 yank_type = MCHAR;
15547 break;
15548 case 'V': case 'l': /* line-wise selection */
15549 yank_type = MLINE;
15550 break;
15551 #ifdef FEAT_VISUAL
15552 case 'b': case Ctrl_V: /* block-wise selection */
15553 yank_type = MBLOCK;
15554 if (VIM_ISDIGIT(stropt[1]))
15556 ++stropt;
15557 block_len = getdigits(&stropt) - 1;
15558 --stropt;
15560 break;
15561 #endif
15565 strval = get_tv_string_chk(&argvars[1]);
15566 if (strval != NULL)
15567 write_reg_contents_ex(regname, strval, -1,
15568 append, yank_type, block_len);
15569 rettv->vval.v_number = 0;
15573 * "settabwinvar()" function
15575 static void
15576 f_settabwinvar(argvars, rettv)
15577 typval_T *argvars;
15578 typval_T *rettv;
15580 setwinvar(argvars, rettv, 1);
15584 * "setwinvar()" function
15586 static void
15587 f_setwinvar(argvars, rettv)
15588 typval_T *argvars;
15589 typval_T *rettv;
15591 setwinvar(argvars, rettv, 0);
15595 * "setwinvar()" and "settabwinvar()" functions
15597 static void
15598 setwinvar(argvars, rettv, off)
15599 typval_T *argvars;
15600 typval_T *rettv;
15601 int off;
15603 win_T *win;
15604 #ifdef FEAT_WINDOWS
15605 win_T *save_curwin;
15606 tabpage_T *save_curtab;
15607 #endif
15608 char_u *varname, *winvarname;
15609 typval_T *varp;
15610 char_u nbuf[NUMBUFLEN];
15611 tabpage_T *tp;
15613 rettv->vval.v_number = 0;
15615 if (check_restricted() || check_secure())
15616 return;
15618 #ifdef FEAT_WINDOWS
15619 if (off == 1)
15620 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15621 else
15622 tp = curtab;
15623 #endif
15624 win = find_win_by_nr(&argvars[off], tp);
15625 varname = get_tv_string_chk(&argvars[off + 1]);
15626 varp = &argvars[off + 2];
15628 if (win != NULL && varname != NULL && varp != NULL)
15630 #ifdef FEAT_WINDOWS
15631 /* set curwin to be our win, temporarily */
15632 save_curwin = curwin;
15633 save_curtab = curtab;
15634 goto_tabpage_tp(tp);
15635 if (!win_valid(win))
15636 return;
15637 curwin = win;
15638 curbuf = curwin->w_buffer;
15639 #endif
15641 if (*varname == '&')
15643 long numval;
15644 char_u *strval;
15645 int error = FALSE;
15647 ++varname;
15648 numval = get_tv_number_chk(varp, &error);
15649 strval = get_tv_string_buf_chk(varp, nbuf);
15650 if (!error && strval != NULL)
15651 set_option_value(varname, numval, strval, OPT_LOCAL);
15653 else
15655 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15656 if (winvarname != NULL)
15658 STRCPY(winvarname, "w:");
15659 STRCPY(winvarname + 2, varname);
15660 set_var(winvarname, varp, TRUE);
15661 vim_free(winvarname);
15665 #ifdef FEAT_WINDOWS
15666 /* Restore current tabpage and window, if still valid (autocomands can
15667 * make them invalid). */
15668 if (valid_tabpage(save_curtab))
15669 goto_tabpage_tp(save_curtab);
15670 if (win_valid(save_curwin))
15672 curwin = save_curwin;
15673 curbuf = curwin->w_buffer;
15675 #endif
15680 * "shellescape({string})" function
15682 static void
15683 f_shellescape(argvars, rettv)
15684 typval_T *argvars;
15685 typval_T *rettv;
15687 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
15688 rettv->v_type = VAR_STRING;
15692 * "simplify()" function
15694 static void
15695 f_simplify(argvars, rettv)
15696 typval_T *argvars;
15697 typval_T *rettv;
15699 char_u *p;
15701 p = get_tv_string(&argvars[0]);
15702 rettv->vval.v_string = vim_strsave(p);
15703 simplify_filename(rettv->vval.v_string); /* simplify in place */
15704 rettv->v_type = VAR_STRING;
15707 #ifdef FEAT_FLOAT
15709 * "sin()" function
15711 static void
15712 f_sin(argvars, rettv)
15713 typval_T *argvars;
15714 typval_T *rettv;
15716 float_T f;
15718 rettv->v_type = VAR_FLOAT;
15719 if (get_float_arg(argvars, &f) == OK)
15720 rettv->vval.v_float = sin(f);
15721 else
15722 rettv->vval.v_float = 0.0;
15724 #endif
15726 static int
15727 #ifdef __BORLANDC__
15728 _RTLENTRYF
15729 #endif
15730 item_compare __ARGS((const void *s1, const void *s2));
15731 static int
15732 #ifdef __BORLANDC__
15733 _RTLENTRYF
15734 #endif
15735 item_compare2 __ARGS((const void *s1, const void *s2));
15737 static int item_compare_ic;
15738 static char_u *item_compare_func;
15739 static int item_compare_func_err;
15740 #define ITEM_COMPARE_FAIL 999
15743 * Compare functions for f_sort() below.
15745 static int
15746 #ifdef __BORLANDC__
15747 _RTLENTRYF
15748 #endif
15749 item_compare(s1, s2)
15750 const void *s1;
15751 const void *s2;
15753 char_u *p1, *p2;
15754 char_u *tofree1, *tofree2;
15755 int res;
15756 char_u numbuf1[NUMBUFLEN];
15757 char_u numbuf2[NUMBUFLEN];
15759 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15760 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15761 if (p1 == NULL)
15762 p1 = (char_u *)"";
15763 if (p2 == NULL)
15764 p2 = (char_u *)"";
15765 if (item_compare_ic)
15766 res = STRICMP(p1, p2);
15767 else
15768 res = STRCMP(p1, p2);
15769 vim_free(tofree1);
15770 vim_free(tofree2);
15771 return res;
15774 static int
15775 #ifdef __BORLANDC__
15776 _RTLENTRYF
15777 #endif
15778 item_compare2(s1, s2)
15779 const void *s1;
15780 const void *s2;
15782 int res;
15783 typval_T rettv;
15784 typval_T argv[3];
15785 int dummy;
15787 /* shortcut after failure in previous call; compare all items equal */
15788 if (item_compare_func_err)
15789 return 0;
15791 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15792 * in the copy without changing the original list items. */
15793 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15794 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15796 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15797 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15798 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15799 clear_tv(&argv[0]);
15800 clear_tv(&argv[1]);
15802 if (res == FAIL)
15803 res = ITEM_COMPARE_FAIL;
15804 else
15805 /* return value has wrong type */
15806 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15807 if (item_compare_func_err)
15808 res = ITEM_COMPARE_FAIL;
15809 clear_tv(&rettv);
15810 return res;
15814 * "sort({list})" function
15816 static void
15817 f_sort(argvars, rettv)
15818 typval_T *argvars;
15819 typval_T *rettv;
15821 list_T *l;
15822 listitem_T *li;
15823 listitem_T **ptrs;
15824 long len;
15825 long i;
15827 rettv->vval.v_number = 0;
15828 if (argvars[0].v_type != VAR_LIST)
15829 EMSG2(_(e_listarg), "sort()");
15830 else
15832 l = argvars[0].vval.v_list;
15833 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15834 return;
15835 rettv->vval.v_list = l;
15836 rettv->v_type = VAR_LIST;
15837 ++l->lv_refcount;
15839 len = list_len(l);
15840 if (len <= 1)
15841 return; /* short list sorts pretty quickly */
15843 item_compare_ic = FALSE;
15844 item_compare_func = NULL;
15845 if (argvars[1].v_type != VAR_UNKNOWN)
15847 if (argvars[1].v_type == VAR_FUNC)
15848 item_compare_func = argvars[1].vval.v_string;
15849 else
15851 int error = FALSE;
15853 i = get_tv_number_chk(&argvars[1], &error);
15854 if (error)
15855 return; /* type error; errmsg already given */
15856 if (i == 1)
15857 item_compare_ic = TRUE;
15858 else
15859 item_compare_func = get_tv_string(&argvars[1]);
15863 /* Make an array with each entry pointing to an item in the List. */
15864 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15865 if (ptrs == NULL)
15866 return;
15867 i = 0;
15868 for (li = l->lv_first; li != NULL; li = li->li_next)
15869 ptrs[i++] = li;
15871 item_compare_func_err = FALSE;
15872 /* test the compare function */
15873 if (item_compare_func != NULL
15874 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15875 == ITEM_COMPARE_FAIL)
15876 EMSG(_("E702: Sort compare function failed"));
15877 else
15879 /* Sort the array with item pointers. */
15880 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15881 item_compare_func == NULL ? item_compare : item_compare2);
15883 if (!item_compare_func_err)
15885 /* Clear the List and append the items in the sorted order. */
15886 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15887 l->lv_len = 0;
15888 for (i = 0; i < len; ++i)
15889 list_append(l, ptrs[i]);
15893 vim_free(ptrs);
15898 * "soundfold({word})" function
15900 static void
15901 f_soundfold(argvars, rettv)
15902 typval_T *argvars;
15903 typval_T *rettv;
15905 char_u *s;
15907 rettv->v_type = VAR_STRING;
15908 s = get_tv_string(&argvars[0]);
15909 #ifdef FEAT_SPELL
15910 rettv->vval.v_string = eval_soundfold(s);
15911 #else
15912 rettv->vval.v_string = vim_strsave(s);
15913 #endif
15917 * "spellbadword()" function
15919 /* ARGSUSED */
15920 static void
15921 f_spellbadword(argvars, rettv)
15922 typval_T *argvars;
15923 typval_T *rettv;
15925 char_u *word = (char_u *)"";
15926 hlf_T attr = HLF_COUNT;
15927 int len = 0;
15929 if (rettv_list_alloc(rettv) == FAIL)
15930 return;
15932 #ifdef FEAT_SPELL
15933 if (argvars[0].v_type == VAR_UNKNOWN)
15935 /* Find the start and length of the badly spelled word. */
15936 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15937 if (len != 0)
15938 word = ml_get_cursor();
15940 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15942 char_u *str = get_tv_string_chk(&argvars[0]);
15943 int capcol = -1;
15945 if (str != NULL)
15947 /* Check the argument for spelling. */
15948 while (*str != NUL)
15950 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15951 if (attr != HLF_COUNT)
15953 word = str;
15954 break;
15956 str += len;
15960 #endif
15962 list_append_string(rettv->vval.v_list, word, len);
15963 list_append_string(rettv->vval.v_list, (char_u *)(
15964 attr == HLF_SPB ? "bad" :
15965 attr == HLF_SPR ? "rare" :
15966 attr == HLF_SPL ? "local" :
15967 attr == HLF_SPC ? "caps" :
15968 ""), -1);
15972 * "spellsuggest()" function
15974 /*ARGSUSED*/
15975 static void
15976 f_spellsuggest(argvars, rettv)
15977 typval_T *argvars;
15978 typval_T *rettv;
15980 #ifdef FEAT_SPELL
15981 char_u *str;
15982 int typeerr = FALSE;
15983 int maxcount;
15984 garray_T ga;
15985 int i;
15986 listitem_T *li;
15987 int need_capital = FALSE;
15988 #endif
15990 if (rettv_list_alloc(rettv) == FAIL)
15991 return;
15993 #ifdef FEAT_SPELL
15994 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15996 str = get_tv_string(&argvars[0]);
15997 if (argvars[1].v_type != VAR_UNKNOWN)
15999 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16000 if (maxcount <= 0)
16001 return;
16002 if (argvars[2].v_type != VAR_UNKNOWN)
16004 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16005 if (typeerr)
16006 return;
16009 else
16010 maxcount = 25;
16012 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16014 for (i = 0; i < ga.ga_len; ++i)
16016 str = ((char_u **)ga.ga_data)[i];
16018 li = listitem_alloc();
16019 if (li == NULL)
16020 vim_free(str);
16021 else
16023 li->li_tv.v_type = VAR_STRING;
16024 li->li_tv.v_lock = 0;
16025 li->li_tv.vval.v_string = str;
16026 list_append(rettv->vval.v_list, li);
16029 ga_clear(&ga);
16031 #endif
16034 static void
16035 f_split(argvars, rettv)
16036 typval_T *argvars;
16037 typval_T *rettv;
16039 char_u *str;
16040 char_u *end;
16041 char_u *pat = NULL;
16042 regmatch_T regmatch;
16043 char_u patbuf[NUMBUFLEN];
16044 char_u *save_cpo;
16045 int match;
16046 colnr_T col = 0;
16047 int keepempty = FALSE;
16048 int typeerr = FALSE;
16050 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16051 save_cpo = p_cpo;
16052 p_cpo = (char_u *)"";
16054 str = get_tv_string(&argvars[0]);
16055 if (argvars[1].v_type != VAR_UNKNOWN)
16057 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16058 if (pat == NULL)
16059 typeerr = TRUE;
16060 if (argvars[2].v_type != VAR_UNKNOWN)
16061 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16063 if (pat == NULL || *pat == NUL)
16064 pat = (char_u *)"[\\x01- ]\\+";
16066 if (rettv_list_alloc(rettv) == FAIL)
16067 return;
16068 if (typeerr)
16069 return;
16071 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16072 if (regmatch.regprog != NULL)
16074 regmatch.rm_ic = FALSE;
16075 while (*str != NUL || keepempty)
16077 if (*str == NUL)
16078 match = FALSE; /* empty item at the end */
16079 else
16080 match = vim_regexec_nl(&regmatch, str, col);
16081 if (match)
16082 end = regmatch.startp[0];
16083 else
16084 end = str + STRLEN(str);
16085 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16086 && *str != NUL && match && end < regmatch.endp[0]))
16088 if (list_append_string(rettv->vval.v_list, str,
16089 (int)(end - str)) == FAIL)
16090 break;
16092 if (!match)
16093 break;
16094 /* Advance to just after the match. */
16095 if (regmatch.endp[0] > str)
16096 col = 0;
16097 else
16099 /* Don't get stuck at the same match. */
16100 #ifdef FEAT_MBYTE
16101 col = (*mb_ptr2len)(regmatch.endp[0]);
16102 #else
16103 col = 1;
16104 #endif
16106 str = regmatch.endp[0];
16109 vim_free(regmatch.regprog);
16112 p_cpo = save_cpo;
16115 #ifdef FEAT_FLOAT
16117 * "sqrt()" function
16119 static void
16120 f_sqrt(argvars, rettv)
16121 typval_T *argvars;
16122 typval_T *rettv;
16124 float_T f;
16126 rettv->v_type = VAR_FLOAT;
16127 if (get_float_arg(argvars, &f) == OK)
16128 rettv->vval.v_float = sqrt(f);
16129 else
16130 rettv->vval.v_float = 0.0;
16134 * "str2float()" function
16136 static void
16137 f_str2float(argvars, rettv)
16138 typval_T *argvars;
16139 typval_T *rettv;
16141 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16143 if (*p == '+')
16144 p = skipwhite(p + 1);
16145 (void)string2float(p, &rettv->vval.v_float);
16146 rettv->v_type = VAR_FLOAT;
16148 #endif
16151 * "str2nr()" function
16153 static void
16154 f_str2nr(argvars, rettv)
16155 typval_T *argvars;
16156 typval_T *rettv;
16158 int base = 10;
16159 char_u *p;
16160 long n;
16162 if (argvars[1].v_type != VAR_UNKNOWN)
16164 base = get_tv_number(&argvars[1]);
16165 if (base != 8 && base != 10 && base != 16)
16167 EMSG(_(e_invarg));
16168 return;
16172 p = skipwhite(get_tv_string(&argvars[0]));
16173 if (*p == '+')
16174 p = skipwhite(p + 1);
16175 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16176 rettv->vval.v_number = n;
16179 #ifdef HAVE_STRFTIME
16181 * "strftime({format}[, {time}])" function
16183 static void
16184 f_strftime(argvars, rettv)
16185 typval_T *argvars;
16186 typval_T *rettv;
16188 char_u result_buf[256];
16189 struct tm *curtime;
16190 time_t seconds;
16191 char_u *p;
16193 rettv->v_type = VAR_STRING;
16195 p = get_tv_string(&argvars[0]);
16196 if (argvars[1].v_type == VAR_UNKNOWN)
16197 seconds = time(NULL);
16198 else
16199 seconds = (time_t)get_tv_number(&argvars[1]);
16200 curtime = localtime(&seconds);
16201 /* MSVC returns NULL for an invalid value of seconds. */
16202 if (curtime == NULL)
16203 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16204 else
16206 # ifdef FEAT_MBYTE
16207 vimconv_T conv;
16208 char_u *enc;
16210 conv.vc_type = CONV_NONE;
16211 enc = enc_locale();
16212 convert_setup(&conv, p_enc, enc);
16213 if (conv.vc_type != CONV_NONE)
16214 p = string_convert(&conv, p, NULL);
16215 # endif
16216 if (p != NULL)
16217 (void)strftime((char *)result_buf, sizeof(result_buf),
16218 (char *)p, curtime);
16219 else
16220 result_buf[0] = NUL;
16222 # ifdef FEAT_MBYTE
16223 if (conv.vc_type != CONV_NONE)
16224 vim_free(p);
16225 convert_setup(&conv, enc, p_enc);
16226 if (conv.vc_type != CONV_NONE)
16227 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16228 else
16229 # endif
16230 rettv->vval.v_string = vim_strsave(result_buf);
16232 # ifdef FEAT_MBYTE
16233 /* Release conversion descriptors */
16234 convert_setup(&conv, NULL, NULL);
16235 vim_free(enc);
16236 # endif
16239 #endif
16242 * "stridx()" function
16244 static void
16245 f_stridx(argvars, rettv)
16246 typval_T *argvars;
16247 typval_T *rettv;
16249 char_u buf[NUMBUFLEN];
16250 char_u *needle;
16251 char_u *haystack;
16252 char_u *save_haystack;
16253 char_u *pos;
16254 int start_idx;
16256 needle = get_tv_string_chk(&argvars[1]);
16257 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16258 rettv->vval.v_number = -1;
16259 if (needle == NULL || haystack == NULL)
16260 return; /* type error; errmsg already given */
16262 if (argvars[2].v_type != VAR_UNKNOWN)
16264 int error = FALSE;
16266 start_idx = get_tv_number_chk(&argvars[2], &error);
16267 if (error || start_idx >= (int)STRLEN(haystack))
16268 return;
16269 if (start_idx >= 0)
16270 haystack += start_idx;
16273 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16274 if (pos != NULL)
16275 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16279 * "string()" function
16281 static void
16282 f_string(argvars, rettv)
16283 typval_T *argvars;
16284 typval_T *rettv;
16286 char_u *tofree;
16287 char_u numbuf[NUMBUFLEN];
16289 rettv->v_type = VAR_STRING;
16290 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16291 /* Make a copy if we have a value but it's not in allocated memory. */
16292 if (rettv->vval.v_string != NULL && tofree == NULL)
16293 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16297 * "strlen()" function
16299 static void
16300 f_strlen(argvars, rettv)
16301 typval_T *argvars;
16302 typval_T *rettv;
16304 rettv->vval.v_number = (varnumber_T)(STRLEN(
16305 get_tv_string(&argvars[0])));
16309 * "strpart()" function
16311 static void
16312 f_strpart(argvars, rettv)
16313 typval_T *argvars;
16314 typval_T *rettv;
16316 char_u *p;
16317 int n;
16318 int len;
16319 int slen;
16320 int error = FALSE;
16322 p = get_tv_string(&argvars[0]);
16323 slen = (int)STRLEN(p);
16325 n = get_tv_number_chk(&argvars[1], &error);
16326 if (error)
16327 len = 0;
16328 else if (argvars[2].v_type != VAR_UNKNOWN)
16329 len = get_tv_number(&argvars[2]);
16330 else
16331 len = slen - n; /* default len: all bytes that are available. */
16334 * Only return the overlap between the specified part and the actual
16335 * string.
16337 if (n < 0)
16339 len += n;
16340 n = 0;
16342 else if (n > slen)
16343 n = slen;
16344 if (len < 0)
16345 len = 0;
16346 else if (n + len > slen)
16347 len = slen - n;
16349 rettv->v_type = VAR_STRING;
16350 rettv->vval.v_string = vim_strnsave(p + n, len);
16354 * "strridx()" function
16356 static void
16357 f_strridx(argvars, rettv)
16358 typval_T *argvars;
16359 typval_T *rettv;
16361 char_u buf[NUMBUFLEN];
16362 char_u *needle;
16363 char_u *haystack;
16364 char_u *rest;
16365 char_u *lastmatch = NULL;
16366 int haystack_len, end_idx;
16368 needle = get_tv_string_chk(&argvars[1]);
16369 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16371 rettv->vval.v_number = -1;
16372 if (needle == NULL || haystack == NULL)
16373 return; /* type error; errmsg already given */
16375 haystack_len = (int)STRLEN(haystack);
16376 if (argvars[2].v_type != VAR_UNKNOWN)
16378 /* Third argument: upper limit for index */
16379 end_idx = get_tv_number_chk(&argvars[2], NULL);
16380 if (end_idx < 0)
16381 return; /* can never find a match */
16383 else
16384 end_idx = haystack_len;
16386 if (*needle == NUL)
16388 /* Empty string matches past the end. */
16389 lastmatch = haystack + end_idx;
16391 else
16393 for (rest = haystack; *rest != '\0'; ++rest)
16395 rest = (char_u *)strstr((char *)rest, (char *)needle);
16396 if (rest == NULL || rest > haystack + end_idx)
16397 break;
16398 lastmatch = rest;
16402 if (lastmatch == NULL)
16403 rettv->vval.v_number = -1;
16404 else
16405 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16409 * "strtrans()" function
16411 static void
16412 f_strtrans(argvars, rettv)
16413 typval_T *argvars;
16414 typval_T *rettv;
16416 rettv->v_type = VAR_STRING;
16417 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16421 * "submatch()" function
16423 static void
16424 f_submatch(argvars, rettv)
16425 typval_T *argvars;
16426 typval_T *rettv;
16428 rettv->v_type = VAR_STRING;
16429 rettv->vval.v_string =
16430 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16434 * "substitute()" function
16436 static void
16437 f_substitute(argvars, rettv)
16438 typval_T *argvars;
16439 typval_T *rettv;
16441 char_u patbuf[NUMBUFLEN];
16442 char_u subbuf[NUMBUFLEN];
16443 char_u flagsbuf[NUMBUFLEN];
16445 char_u *str = get_tv_string_chk(&argvars[0]);
16446 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16447 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16448 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16450 rettv->v_type = VAR_STRING;
16451 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16452 rettv->vval.v_string = NULL;
16453 else
16454 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16458 * "synID(lnum, col, trans)" function
16460 /*ARGSUSED*/
16461 static void
16462 f_synID(argvars, rettv)
16463 typval_T *argvars;
16464 typval_T *rettv;
16466 int id = 0;
16467 #ifdef FEAT_SYN_HL
16468 long lnum;
16469 long col;
16470 int trans;
16471 int transerr = FALSE;
16473 lnum = get_tv_lnum(argvars); /* -1 on type error */
16474 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16475 trans = get_tv_number_chk(&argvars[2], &transerr);
16477 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16478 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16479 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16480 #endif
16482 rettv->vval.v_number = id;
16486 * "synIDattr(id, what [, mode])" function
16488 /*ARGSUSED*/
16489 static void
16490 f_synIDattr(argvars, rettv)
16491 typval_T *argvars;
16492 typval_T *rettv;
16494 char_u *p = NULL;
16495 #ifdef FEAT_SYN_HL
16496 int id;
16497 char_u *what;
16498 char_u *mode;
16499 char_u modebuf[NUMBUFLEN];
16500 int modec;
16502 id = get_tv_number(&argvars[0]);
16503 what = get_tv_string(&argvars[1]);
16504 if (argvars[2].v_type != VAR_UNKNOWN)
16506 mode = get_tv_string_buf(&argvars[2], modebuf);
16507 modec = TOLOWER_ASC(mode[0]);
16508 if (modec != 't' && modec != 'c'
16509 #ifdef FEAT_GUI
16510 && modec != 'g'
16511 #endif
16513 modec = 0; /* replace invalid with current */
16515 else
16517 #ifdef FEAT_GUI
16518 if (gui.in_use)
16519 modec = 'g';
16520 else
16521 #endif
16522 if (t_colors > 1)
16523 modec = 'c';
16524 else
16525 modec = 't';
16529 switch (TOLOWER_ASC(what[0]))
16531 case 'b':
16532 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16533 p = highlight_color(id, what, modec);
16534 else /* bold */
16535 p = highlight_has_attr(id, HL_BOLD, modec);
16536 break;
16538 case 'f': /* fg[#] */
16539 p = highlight_color(id, what, modec);
16540 break;
16542 case 'i':
16543 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16544 p = highlight_has_attr(id, HL_INVERSE, modec);
16545 else /* italic */
16546 p = highlight_has_attr(id, HL_ITALIC, modec);
16547 break;
16549 case 'n': /* name */
16550 p = get_highlight_name(NULL, id - 1);
16551 break;
16553 case 'r': /* reverse */
16554 p = highlight_has_attr(id, HL_INVERSE, modec);
16555 break;
16557 case 's': /* standout */
16558 p = highlight_has_attr(id, HL_STANDOUT, modec);
16559 break;
16561 case 'u':
16562 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16563 /* underline */
16564 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16565 else
16566 /* undercurl */
16567 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16568 break;
16571 if (p != NULL)
16572 p = vim_strsave(p);
16573 #endif
16574 rettv->v_type = VAR_STRING;
16575 rettv->vval.v_string = p;
16579 * "synIDtrans(id)" function
16581 /*ARGSUSED*/
16582 static void
16583 f_synIDtrans(argvars, rettv)
16584 typval_T *argvars;
16585 typval_T *rettv;
16587 int id;
16589 #ifdef FEAT_SYN_HL
16590 id = get_tv_number(&argvars[0]);
16592 if (id > 0)
16593 id = syn_get_final_id(id);
16594 else
16595 #endif
16596 id = 0;
16598 rettv->vval.v_number = id;
16602 * "synstack(lnum, col)" function
16604 /*ARGSUSED*/
16605 static void
16606 f_synstack(argvars, rettv)
16607 typval_T *argvars;
16608 typval_T *rettv;
16610 #ifdef FEAT_SYN_HL
16611 long lnum;
16612 long col;
16613 int i;
16614 int id;
16615 #endif
16617 rettv->v_type = VAR_LIST;
16618 rettv->vval.v_list = NULL;
16620 #ifdef FEAT_SYN_HL
16621 lnum = get_tv_lnum(argvars); /* -1 on type error */
16622 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16624 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16625 && col >= 0 && col < (long)STRLEN(ml_get(lnum))
16626 && rettv_list_alloc(rettv) != FAIL)
16628 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16629 for (i = 0; ; ++i)
16631 id = syn_get_stack_item(i);
16632 if (id < 0)
16633 break;
16634 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16635 break;
16638 #endif
16642 * "system()" function
16644 static void
16645 f_system(argvars, rettv)
16646 typval_T *argvars;
16647 typval_T *rettv;
16649 char_u *res = NULL;
16650 char_u *p;
16651 char_u *infile = NULL;
16652 char_u buf[NUMBUFLEN];
16653 int err = FALSE;
16654 FILE *fd;
16656 if (check_restricted() || check_secure())
16657 goto done;
16659 if (argvars[1].v_type != VAR_UNKNOWN)
16662 * Write the string to a temp file, to be used for input of the shell
16663 * command.
16665 if ((infile = vim_tempname('i')) == NULL)
16667 EMSG(_(e_notmp));
16668 goto done;
16671 fd = mch_fopen((char *)infile, WRITEBIN);
16672 if (fd == NULL)
16674 EMSG2(_(e_notopen), infile);
16675 goto done;
16677 p = get_tv_string_buf_chk(&argvars[1], buf);
16678 if (p == NULL)
16680 fclose(fd);
16681 goto done; /* type error; errmsg already given */
16683 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16684 err = TRUE;
16685 if (fclose(fd) != 0)
16686 err = TRUE;
16687 if (err)
16689 EMSG(_("E677: Error writing temp file"));
16690 goto done;
16694 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16695 SHELL_SILENT | SHELL_COOKED);
16697 #ifdef USE_CR
16698 /* translate <CR> into <NL> */
16699 if (res != NULL)
16701 char_u *s;
16703 for (s = res; *s; ++s)
16705 if (*s == CAR)
16706 *s = NL;
16709 #else
16710 # ifdef USE_CRNL
16711 /* translate <CR><NL> into <NL> */
16712 if (res != NULL)
16714 char_u *s, *d;
16716 d = res;
16717 for (s = res; *s; ++s)
16719 if (s[0] == CAR && s[1] == NL)
16720 ++s;
16721 *d++ = *s;
16723 *d = NUL;
16725 # endif
16726 #endif
16728 done:
16729 if (infile != NULL)
16731 mch_remove(infile);
16732 vim_free(infile);
16734 rettv->v_type = VAR_STRING;
16735 rettv->vval.v_string = res;
16739 * "tabpagebuflist()" function
16741 /* ARGSUSED */
16742 static void
16743 f_tabpagebuflist(argvars, rettv)
16744 typval_T *argvars;
16745 typval_T *rettv;
16747 #ifndef FEAT_WINDOWS
16748 rettv->vval.v_number = 0;
16749 #else
16750 tabpage_T *tp;
16751 win_T *wp = NULL;
16753 if (argvars[0].v_type == VAR_UNKNOWN)
16754 wp = firstwin;
16755 else
16757 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16758 if (tp != NULL)
16759 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16761 if (wp == NULL)
16762 rettv->vval.v_number = 0;
16763 else
16765 if (rettv_list_alloc(rettv) == FAIL)
16766 rettv->vval.v_number = 0;
16767 else
16769 for (; wp != NULL; wp = wp->w_next)
16770 if (list_append_number(rettv->vval.v_list,
16771 wp->w_buffer->b_fnum) == FAIL)
16772 break;
16775 #endif
16780 * "tabpagenr()" function
16782 /* ARGSUSED */
16783 static void
16784 f_tabpagenr(argvars, rettv)
16785 typval_T *argvars;
16786 typval_T *rettv;
16788 int nr = 1;
16789 #ifdef FEAT_WINDOWS
16790 char_u *arg;
16792 if (argvars[0].v_type != VAR_UNKNOWN)
16794 arg = get_tv_string_chk(&argvars[0]);
16795 nr = 0;
16796 if (arg != NULL)
16798 if (STRCMP(arg, "$") == 0)
16799 nr = tabpage_index(NULL) - 1;
16800 else
16801 EMSG2(_(e_invexpr2), arg);
16804 else
16805 nr = tabpage_index(curtab);
16806 #endif
16807 rettv->vval.v_number = nr;
16811 #ifdef FEAT_WINDOWS
16812 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16815 * Common code for tabpagewinnr() and winnr().
16817 static int
16818 get_winnr(tp, argvar)
16819 tabpage_T *tp;
16820 typval_T *argvar;
16822 win_T *twin;
16823 int nr = 1;
16824 win_T *wp;
16825 char_u *arg;
16827 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16828 if (argvar->v_type != VAR_UNKNOWN)
16830 arg = get_tv_string_chk(argvar);
16831 if (arg == NULL)
16832 nr = 0; /* type error; errmsg already given */
16833 else if (STRCMP(arg, "$") == 0)
16834 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16835 else if (STRCMP(arg, "#") == 0)
16837 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16838 if (twin == NULL)
16839 nr = 0;
16841 else
16843 EMSG2(_(e_invexpr2), arg);
16844 nr = 0;
16848 if (nr > 0)
16849 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16850 wp != twin; wp = wp->w_next)
16852 if (wp == NULL)
16854 /* didn't find it in this tabpage */
16855 nr = 0;
16856 break;
16858 ++nr;
16860 return nr;
16862 #endif
16865 * "tabpagewinnr()" function
16867 /* ARGSUSED */
16868 static void
16869 f_tabpagewinnr(argvars, rettv)
16870 typval_T *argvars;
16871 typval_T *rettv;
16873 int nr = 1;
16874 #ifdef FEAT_WINDOWS
16875 tabpage_T *tp;
16877 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16878 if (tp == NULL)
16879 nr = 0;
16880 else
16881 nr = get_winnr(tp, &argvars[1]);
16882 #endif
16883 rettv->vval.v_number = nr;
16888 * "tagfiles()" function
16890 /*ARGSUSED*/
16891 static void
16892 f_tagfiles(argvars, rettv)
16893 typval_T *argvars;
16894 typval_T *rettv;
16896 char_u fname[MAXPATHL + 1];
16897 tagname_T tn;
16898 int first;
16900 if (rettv_list_alloc(rettv) == FAIL)
16902 rettv->vval.v_number = 0;
16903 return;
16906 for (first = TRUE; ; first = FALSE)
16907 if (get_tagfname(&tn, first, fname) == FAIL
16908 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16909 break;
16910 tagname_free(&tn);
16914 * "taglist()" function
16916 static void
16917 f_taglist(argvars, rettv)
16918 typval_T *argvars;
16919 typval_T *rettv;
16921 char_u *tag_pattern;
16923 tag_pattern = get_tv_string(&argvars[0]);
16925 rettv->vval.v_number = FALSE;
16926 if (*tag_pattern == NUL)
16927 return;
16929 if (rettv_list_alloc(rettv) == OK)
16930 (void)get_tags(rettv->vval.v_list, tag_pattern);
16934 * "tempname()" function
16936 /*ARGSUSED*/
16937 static void
16938 f_tempname(argvars, rettv)
16939 typval_T *argvars;
16940 typval_T *rettv;
16942 static int x = 'A';
16944 rettv->v_type = VAR_STRING;
16945 rettv->vval.v_string = vim_tempname(x);
16947 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16948 * names. Skip 'I' and 'O', they are used for shell redirection. */
16951 if (x == 'Z')
16952 x = '0';
16953 else if (x == '9')
16954 x = 'A';
16955 else
16957 #ifdef EBCDIC
16958 if (x == 'I')
16959 x = 'J';
16960 else if (x == 'R')
16961 x = 'S';
16962 else
16963 #endif
16964 ++x;
16966 } while (x == 'I' || x == 'O');
16970 * "test(list)" function: Just checking the walls...
16972 /*ARGSUSED*/
16973 static void
16974 f_test(argvars, rettv)
16975 typval_T *argvars;
16976 typval_T *rettv;
16978 /* Used for unit testing. Change the code below to your liking. */
16979 #if 0
16980 listitem_T *li;
16981 list_T *l;
16982 char_u *bad, *good;
16984 if (argvars[0].v_type != VAR_LIST)
16985 return;
16986 l = argvars[0].vval.v_list;
16987 if (l == NULL)
16988 return;
16989 li = l->lv_first;
16990 if (li == NULL)
16991 return;
16992 bad = get_tv_string(&li->li_tv);
16993 li = li->li_next;
16994 if (li == NULL)
16995 return;
16996 good = get_tv_string(&li->li_tv);
16997 rettv->vval.v_number = test_edit_score(bad, good);
16998 #endif
17002 * "tolower(string)" function
17004 static void
17005 f_tolower(argvars, rettv)
17006 typval_T *argvars;
17007 typval_T *rettv;
17009 char_u *p;
17011 p = vim_strsave(get_tv_string(&argvars[0]));
17012 rettv->v_type = VAR_STRING;
17013 rettv->vval.v_string = p;
17015 if (p != NULL)
17016 while (*p != NUL)
17018 #ifdef FEAT_MBYTE
17019 int l;
17021 if (enc_utf8)
17023 int c, lc;
17025 c = utf_ptr2char(p);
17026 lc = utf_tolower(c);
17027 l = utf_ptr2len(p);
17028 /* TODO: reallocate string when byte count changes. */
17029 if (utf_char2len(lc) == l)
17030 utf_char2bytes(lc, p);
17031 p += l;
17033 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17034 p += l; /* skip multi-byte character */
17035 else
17036 #endif
17038 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17039 ++p;
17045 * "toupper(string)" function
17047 static void
17048 f_toupper(argvars, rettv)
17049 typval_T *argvars;
17050 typval_T *rettv;
17052 rettv->v_type = VAR_STRING;
17053 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17057 * "tr(string, fromstr, tostr)" function
17059 static void
17060 f_tr(argvars, rettv)
17061 typval_T *argvars;
17062 typval_T *rettv;
17064 char_u *instr;
17065 char_u *fromstr;
17066 char_u *tostr;
17067 char_u *p;
17068 #ifdef FEAT_MBYTE
17069 int inlen;
17070 int fromlen;
17071 int tolen;
17072 int idx;
17073 char_u *cpstr;
17074 int cplen;
17075 int first = TRUE;
17076 #endif
17077 char_u buf[NUMBUFLEN];
17078 char_u buf2[NUMBUFLEN];
17079 garray_T ga;
17081 instr = get_tv_string(&argvars[0]);
17082 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17083 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17085 /* Default return value: empty string. */
17086 rettv->v_type = VAR_STRING;
17087 rettv->vval.v_string = NULL;
17088 if (fromstr == NULL || tostr == NULL)
17089 return; /* type error; errmsg already given */
17090 ga_init2(&ga, (int)sizeof(char), 80);
17092 #ifdef FEAT_MBYTE
17093 if (!has_mbyte)
17094 #endif
17095 /* not multi-byte: fromstr and tostr must be the same length */
17096 if (STRLEN(fromstr) != STRLEN(tostr))
17098 #ifdef FEAT_MBYTE
17099 error:
17100 #endif
17101 EMSG2(_(e_invarg2), fromstr);
17102 ga_clear(&ga);
17103 return;
17106 /* fromstr and tostr have to contain the same number of chars */
17107 while (*instr != NUL)
17109 #ifdef FEAT_MBYTE
17110 if (has_mbyte)
17112 inlen = (*mb_ptr2len)(instr);
17113 cpstr = instr;
17114 cplen = inlen;
17115 idx = 0;
17116 for (p = fromstr; *p != NUL; p += fromlen)
17118 fromlen = (*mb_ptr2len)(p);
17119 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17121 for (p = tostr; *p != NUL; p += tolen)
17123 tolen = (*mb_ptr2len)(p);
17124 if (idx-- == 0)
17126 cplen = tolen;
17127 cpstr = p;
17128 break;
17131 if (*p == NUL) /* tostr is shorter than fromstr */
17132 goto error;
17133 break;
17135 ++idx;
17138 if (first && cpstr == instr)
17140 /* Check that fromstr and tostr have the same number of
17141 * (multi-byte) characters. Done only once when a character
17142 * of instr doesn't appear in fromstr. */
17143 first = FALSE;
17144 for (p = tostr; *p != NUL; p += tolen)
17146 tolen = (*mb_ptr2len)(p);
17147 --idx;
17149 if (idx != 0)
17150 goto error;
17153 ga_grow(&ga, cplen);
17154 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17155 ga.ga_len += cplen;
17157 instr += inlen;
17159 else
17160 #endif
17162 /* When not using multi-byte chars we can do it faster. */
17163 p = vim_strchr(fromstr, *instr);
17164 if (p != NULL)
17165 ga_append(&ga, tostr[p - fromstr]);
17166 else
17167 ga_append(&ga, *instr);
17168 ++instr;
17172 /* add a terminating NUL */
17173 ga_grow(&ga, 1);
17174 ga_append(&ga, NUL);
17176 rettv->vval.v_string = ga.ga_data;
17179 #ifdef FEAT_FLOAT
17181 * "trunc({float})" function
17183 static void
17184 f_trunc(argvars, rettv)
17185 typval_T *argvars;
17186 typval_T *rettv;
17188 float_T f;
17190 rettv->v_type = VAR_FLOAT;
17191 if (get_float_arg(argvars, &f) == OK)
17192 /* trunc() is not in C90, use floor() or ceil() instead. */
17193 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17194 else
17195 rettv->vval.v_float = 0.0;
17197 #endif
17200 * "type(expr)" function
17202 static void
17203 f_type(argvars, rettv)
17204 typval_T *argvars;
17205 typval_T *rettv;
17207 int n;
17209 switch (argvars[0].v_type)
17211 case VAR_NUMBER: n = 0; break;
17212 case VAR_STRING: n = 1; break;
17213 case VAR_FUNC: n = 2; break;
17214 case VAR_LIST: n = 3; break;
17215 case VAR_DICT: n = 4; break;
17216 #ifdef FEAT_FLOAT
17217 case VAR_FLOAT: n = 5; break;
17218 #endif
17219 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17221 rettv->vval.v_number = n;
17225 * "values(dict)" function
17227 static void
17228 f_values(argvars, rettv)
17229 typval_T *argvars;
17230 typval_T *rettv;
17232 dict_list(argvars, rettv, 1);
17236 * "virtcol(string)" function
17238 static void
17239 f_virtcol(argvars, rettv)
17240 typval_T *argvars;
17241 typval_T *rettv;
17243 colnr_T vcol = 0;
17244 pos_T *fp;
17245 int fnum = curbuf->b_fnum;
17247 fp = var2fpos(&argvars[0], FALSE, &fnum);
17248 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17249 && fnum == curbuf->b_fnum)
17251 getvvcol(curwin, fp, NULL, NULL, &vcol);
17252 ++vcol;
17255 rettv->vval.v_number = vcol;
17259 * "visualmode()" function
17261 /*ARGSUSED*/
17262 static void
17263 f_visualmode(argvars, rettv)
17264 typval_T *argvars;
17265 typval_T *rettv;
17267 #ifdef FEAT_VISUAL
17268 char_u str[2];
17270 rettv->v_type = VAR_STRING;
17271 str[0] = curbuf->b_visual_mode_eval;
17272 str[1] = NUL;
17273 rettv->vval.v_string = vim_strsave(str);
17275 /* A non-zero number or non-empty string argument: reset mode. */
17276 if ((argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number != 0)
17277 || (argvars[0].v_type == VAR_STRING
17278 && *get_tv_string(&argvars[0]) != NUL))
17279 curbuf->b_visual_mode_eval = NUL;
17280 #else
17281 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
17282 #endif
17286 * "winbufnr(nr)" function
17288 static void
17289 f_winbufnr(argvars, rettv)
17290 typval_T *argvars;
17291 typval_T *rettv;
17293 win_T *wp;
17295 wp = find_win_by_nr(&argvars[0], NULL);
17296 if (wp == NULL)
17297 rettv->vval.v_number = -1;
17298 else
17299 rettv->vval.v_number = wp->w_buffer->b_fnum;
17303 * "wincol()" function
17305 /*ARGSUSED*/
17306 static void
17307 f_wincol(argvars, rettv)
17308 typval_T *argvars;
17309 typval_T *rettv;
17311 validate_cursor();
17312 rettv->vval.v_number = curwin->w_wcol + 1;
17316 * "winheight(nr)" function
17318 static void
17319 f_winheight(argvars, rettv)
17320 typval_T *argvars;
17321 typval_T *rettv;
17323 win_T *wp;
17325 wp = find_win_by_nr(&argvars[0], NULL);
17326 if (wp == NULL)
17327 rettv->vval.v_number = -1;
17328 else
17329 rettv->vval.v_number = wp->w_height;
17333 * "winline()" function
17335 /*ARGSUSED*/
17336 static void
17337 f_winline(argvars, rettv)
17338 typval_T *argvars;
17339 typval_T *rettv;
17341 validate_cursor();
17342 rettv->vval.v_number = curwin->w_wrow + 1;
17346 * "winnr()" function
17348 /* ARGSUSED */
17349 static void
17350 f_winnr(argvars, rettv)
17351 typval_T *argvars;
17352 typval_T *rettv;
17354 int nr = 1;
17356 #ifdef FEAT_WINDOWS
17357 nr = get_winnr(curtab, &argvars[0]);
17358 #endif
17359 rettv->vval.v_number = nr;
17363 * "winrestcmd()" function
17365 /* ARGSUSED */
17366 static void
17367 f_winrestcmd(argvars, rettv)
17368 typval_T *argvars;
17369 typval_T *rettv;
17371 #ifdef FEAT_WINDOWS
17372 win_T *wp;
17373 int winnr = 1;
17374 garray_T ga;
17375 char_u buf[50];
17377 ga_init2(&ga, (int)sizeof(char), 70);
17378 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17380 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17381 ga_concat(&ga, buf);
17382 # ifdef FEAT_VERTSPLIT
17383 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17384 ga_concat(&ga, buf);
17385 # endif
17386 ++winnr;
17388 ga_append(&ga, NUL);
17390 rettv->vval.v_string = ga.ga_data;
17391 #else
17392 rettv->vval.v_string = NULL;
17393 #endif
17394 rettv->v_type = VAR_STRING;
17398 * "winrestview()" function
17400 /* ARGSUSED */
17401 static void
17402 f_winrestview(argvars, rettv)
17403 typval_T *argvars;
17404 typval_T *rettv;
17406 dict_T *dict;
17408 if (argvars[0].v_type != VAR_DICT
17409 || (dict = argvars[0].vval.v_dict) == NULL)
17410 EMSG(_(e_invarg));
17411 else
17413 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17414 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17415 #ifdef FEAT_VIRTUALEDIT
17416 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17417 #endif
17418 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17419 curwin->w_set_curswant = FALSE;
17421 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17422 #ifdef FEAT_DIFF
17423 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17424 #endif
17425 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17426 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17428 check_cursor();
17429 changed_cline_bef_curs();
17430 invalidate_botline();
17431 redraw_later(VALID);
17433 if (curwin->w_topline == 0)
17434 curwin->w_topline = 1;
17435 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17436 curwin->w_topline = curbuf->b_ml.ml_line_count;
17437 #ifdef FEAT_DIFF
17438 check_topfill(curwin, TRUE);
17439 #endif
17444 * "winsaveview()" function
17446 /* ARGSUSED */
17447 static void
17448 f_winsaveview(argvars, rettv)
17449 typval_T *argvars;
17450 typval_T *rettv;
17452 dict_T *dict;
17454 dict = dict_alloc();
17455 if (dict == NULL)
17456 return;
17457 rettv->v_type = VAR_DICT;
17458 rettv->vval.v_dict = dict;
17459 ++dict->dv_refcount;
17461 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17462 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17463 #ifdef FEAT_VIRTUALEDIT
17464 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17465 #endif
17466 update_curswant();
17467 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17469 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17470 #ifdef FEAT_DIFF
17471 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17472 #endif
17473 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17474 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17478 * "winwidth(nr)" function
17480 static void
17481 f_winwidth(argvars, rettv)
17482 typval_T *argvars;
17483 typval_T *rettv;
17485 win_T *wp;
17487 wp = find_win_by_nr(&argvars[0], NULL);
17488 if (wp == NULL)
17489 rettv->vval.v_number = -1;
17490 else
17491 #ifdef FEAT_VERTSPLIT
17492 rettv->vval.v_number = wp->w_width;
17493 #else
17494 rettv->vval.v_number = Columns;
17495 #endif
17499 * "writefile()" function
17501 static void
17502 f_writefile(argvars, rettv)
17503 typval_T *argvars;
17504 typval_T *rettv;
17506 int binary = FALSE;
17507 char_u *fname;
17508 FILE *fd;
17509 listitem_T *li;
17510 char_u *s;
17511 int ret = 0;
17512 int c;
17514 if (check_restricted() || check_secure())
17515 return;
17517 if (argvars[0].v_type != VAR_LIST)
17519 EMSG2(_(e_listarg), "writefile()");
17520 return;
17522 if (argvars[0].vval.v_list == NULL)
17523 return;
17525 if (argvars[2].v_type != VAR_UNKNOWN
17526 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17527 binary = TRUE;
17529 /* Always open the file in binary mode, library functions have a mind of
17530 * their own about CR-LF conversion. */
17531 fname = get_tv_string(&argvars[1]);
17532 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17534 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17535 ret = -1;
17537 else
17539 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17540 li = li->li_next)
17542 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17544 if (*s == '\n')
17545 c = putc(NUL, fd);
17546 else
17547 c = putc(*s, fd);
17548 if (c == EOF)
17550 ret = -1;
17551 break;
17554 if (!binary || li->li_next != NULL)
17555 if (putc('\n', fd) == EOF)
17557 ret = -1;
17558 break;
17560 if (ret < 0)
17562 EMSG(_(e_write));
17563 break;
17566 fclose(fd);
17569 rettv->vval.v_number = ret;
17573 * Translate a String variable into a position.
17574 * Returns NULL when there is an error.
17576 static pos_T *
17577 var2fpos(varp, dollar_lnum, fnum)
17578 typval_T *varp;
17579 int dollar_lnum; /* TRUE when $ is last line */
17580 int *fnum; /* set to fnum for '0, 'A, etc. */
17582 char_u *name;
17583 static pos_T pos;
17584 pos_T *pp;
17586 /* Argument can be [lnum, col, coladd]. */
17587 if (varp->v_type == VAR_LIST)
17589 list_T *l;
17590 int len;
17591 int error = FALSE;
17592 listitem_T *li;
17594 l = varp->vval.v_list;
17595 if (l == NULL)
17596 return NULL;
17598 /* Get the line number */
17599 pos.lnum = list_find_nr(l, 0L, &error);
17600 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17601 return NULL; /* invalid line number */
17603 /* Get the column number */
17604 pos.col = list_find_nr(l, 1L, &error);
17605 if (error)
17606 return NULL;
17607 len = (long)STRLEN(ml_get(pos.lnum));
17609 /* We accept "$" for the column number: last column. */
17610 li = list_find(l, 1L);
17611 if (li != NULL && li->li_tv.v_type == VAR_STRING
17612 && li->li_tv.vval.v_string != NULL
17613 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17614 pos.col = len + 1;
17616 /* Accept a position up to the NUL after the line. */
17617 if (pos.col == 0 || (int)pos.col > len + 1)
17618 return NULL; /* invalid column number */
17619 --pos.col;
17621 #ifdef FEAT_VIRTUALEDIT
17622 /* Get the virtual offset. Defaults to zero. */
17623 pos.coladd = list_find_nr(l, 2L, &error);
17624 if (error)
17625 pos.coladd = 0;
17626 #endif
17628 return &pos;
17631 name = get_tv_string_chk(varp);
17632 if (name == NULL)
17633 return NULL;
17634 if (name[0] == '.') /* cursor */
17635 return &curwin->w_cursor;
17636 #ifdef FEAT_VISUAL
17637 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17639 if (VIsual_active)
17640 return &VIsual;
17641 return &curwin->w_cursor;
17643 #endif
17644 if (name[0] == '\'') /* mark */
17646 pp = getmark_fnum(name[1], FALSE, fnum);
17647 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17648 return NULL;
17649 return pp;
17652 #ifdef FEAT_VIRTUALEDIT
17653 pos.coladd = 0;
17654 #endif
17656 if (name[0] == 'w' && dollar_lnum)
17658 pos.col = 0;
17659 if (name[1] == '0') /* "w0": first visible line */
17661 update_topline();
17662 pos.lnum = curwin->w_topline;
17663 return &pos;
17665 else if (name[1] == '$') /* "w$": last visible line */
17667 validate_botline();
17668 pos.lnum = curwin->w_botline - 1;
17669 return &pos;
17672 else if (name[0] == '$') /* last column or line */
17674 if (dollar_lnum)
17676 pos.lnum = curbuf->b_ml.ml_line_count;
17677 pos.col = 0;
17679 else
17681 pos.lnum = curwin->w_cursor.lnum;
17682 pos.col = (colnr_T)STRLEN(ml_get_curline());
17684 return &pos;
17686 return NULL;
17690 * Convert list in "arg" into a position and optional file number.
17691 * When "fnump" is NULL there is no file number, only 3 items.
17692 * Note that the column is passed on as-is, the caller may want to decrement
17693 * it to use 1 for the first column.
17694 * Return FAIL when conversion is not possible, doesn't check the position for
17695 * validity.
17697 static int
17698 list2fpos(arg, posp, fnump)
17699 typval_T *arg;
17700 pos_T *posp;
17701 int *fnump;
17703 list_T *l = arg->vval.v_list;
17704 long i = 0;
17705 long n;
17707 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17708 * when "fnump" isn't NULL and "coladd" is optional. */
17709 if (arg->v_type != VAR_LIST
17710 || l == NULL
17711 || l->lv_len < (fnump == NULL ? 2 : 3)
17712 || l->lv_len > (fnump == NULL ? 3 : 4))
17713 return FAIL;
17715 if (fnump != NULL)
17717 n = list_find_nr(l, i++, NULL); /* fnum */
17718 if (n < 0)
17719 return FAIL;
17720 if (n == 0)
17721 n = curbuf->b_fnum; /* current buffer */
17722 *fnump = n;
17725 n = list_find_nr(l, i++, NULL); /* lnum */
17726 if (n < 0)
17727 return FAIL;
17728 posp->lnum = n;
17730 n = list_find_nr(l, i++, NULL); /* col */
17731 if (n < 0)
17732 return FAIL;
17733 posp->col = n;
17735 #ifdef FEAT_VIRTUALEDIT
17736 n = list_find_nr(l, i, NULL);
17737 if (n < 0)
17738 posp->coladd = 0;
17739 else
17740 posp->coladd = n;
17741 #endif
17743 return OK;
17747 * Get the length of an environment variable name.
17748 * Advance "arg" to the first character after the name.
17749 * Return 0 for error.
17751 static int
17752 get_env_len(arg)
17753 char_u **arg;
17755 char_u *p;
17756 int len;
17758 for (p = *arg; vim_isIDc(*p); ++p)
17760 if (p == *arg) /* no name found */
17761 return 0;
17763 len = (int)(p - *arg);
17764 *arg = p;
17765 return len;
17769 * Get the length of the name of a function or internal variable.
17770 * "arg" is advanced to the first non-white character after the name.
17771 * Return 0 if something is wrong.
17773 static int
17774 get_id_len(arg)
17775 char_u **arg;
17777 char_u *p;
17778 int len;
17780 /* Find the end of the name. */
17781 for (p = *arg; eval_isnamec(*p); ++p)
17783 if (p == *arg) /* no name found */
17784 return 0;
17786 len = (int)(p - *arg);
17787 *arg = skipwhite(p);
17789 return len;
17793 * Get the length of the name of a variable or function.
17794 * Only the name is recognized, does not handle ".key" or "[idx]".
17795 * "arg" is advanced to the first non-white character after the name.
17796 * Return -1 if curly braces expansion failed.
17797 * Return 0 if something else is wrong.
17798 * If the name contains 'magic' {}'s, expand them and return the
17799 * expanded name in an allocated string via 'alias' - caller must free.
17801 static int
17802 get_name_len(arg, alias, evaluate, verbose)
17803 char_u **arg;
17804 char_u **alias;
17805 int evaluate;
17806 int verbose;
17808 int len;
17809 char_u *p;
17810 char_u *expr_start;
17811 char_u *expr_end;
17813 *alias = NULL; /* default to no alias */
17815 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17816 && (*arg)[2] == (int)KE_SNR)
17818 /* hard coded <SNR>, already translated */
17819 *arg += 3;
17820 return get_id_len(arg) + 3;
17822 len = eval_fname_script(*arg);
17823 if (len > 0)
17825 /* literal "<SID>", "s:" or "<SNR>" */
17826 *arg += len;
17830 * Find the end of the name; check for {} construction.
17832 p = find_name_end(*arg, &expr_start, &expr_end,
17833 len > 0 ? 0 : FNE_CHECK_START);
17834 if (expr_start != NULL)
17836 char_u *temp_string;
17838 if (!evaluate)
17840 len += (int)(p - *arg);
17841 *arg = skipwhite(p);
17842 return len;
17846 * Include any <SID> etc in the expanded string:
17847 * Thus the -len here.
17849 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17850 if (temp_string == NULL)
17851 return -1;
17852 *alias = temp_string;
17853 *arg = skipwhite(p);
17854 return (int)STRLEN(temp_string);
17857 len += get_id_len(arg);
17858 if (len == 0 && verbose)
17859 EMSG2(_(e_invexpr2), *arg);
17861 return len;
17865 * Find the end of a variable or function name, taking care of magic braces.
17866 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17867 * start and end of the first magic braces item.
17868 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17869 * Return a pointer to just after the name. Equal to "arg" if there is no
17870 * valid name.
17872 static char_u *
17873 find_name_end(arg, expr_start, expr_end, flags)
17874 char_u *arg;
17875 char_u **expr_start;
17876 char_u **expr_end;
17877 int flags;
17879 int mb_nest = 0;
17880 int br_nest = 0;
17881 char_u *p;
17883 if (expr_start != NULL)
17885 *expr_start = NULL;
17886 *expr_end = NULL;
17889 /* Quick check for valid starting character. */
17890 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17891 return arg;
17893 for (p = arg; *p != NUL
17894 && (eval_isnamec(*p)
17895 || *p == '{'
17896 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17897 || mb_nest != 0
17898 || br_nest != 0); mb_ptr_adv(p))
17900 if (*p == '\'')
17902 /* skip over 'string' to avoid counting [ and ] inside it. */
17903 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17905 if (*p == NUL)
17906 break;
17908 else if (*p == '"')
17910 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17911 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17912 if (*p == '\\' && p[1] != NUL)
17913 ++p;
17914 if (*p == NUL)
17915 break;
17918 if (mb_nest == 0)
17920 if (*p == '[')
17921 ++br_nest;
17922 else if (*p == ']')
17923 --br_nest;
17926 if (br_nest == 0)
17928 if (*p == '{')
17930 mb_nest++;
17931 if (expr_start != NULL && *expr_start == NULL)
17932 *expr_start = p;
17934 else if (*p == '}')
17936 mb_nest--;
17937 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17938 *expr_end = p;
17943 return p;
17947 * Expands out the 'magic' {}'s in a variable/function name.
17948 * Note that this can call itself recursively, to deal with
17949 * constructs like foo{bar}{baz}{bam}
17950 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17951 * "in_start" ^
17952 * "expr_start" ^
17953 * "expr_end" ^
17954 * "in_end" ^
17956 * Returns a new allocated string, which the caller must free.
17957 * Returns NULL for failure.
17959 static char_u *
17960 make_expanded_name(in_start, expr_start, expr_end, in_end)
17961 char_u *in_start;
17962 char_u *expr_start;
17963 char_u *expr_end;
17964 char_u *in_end;
17966 char_u c1;
17967 char_u *retval = NULL;
17968 char_u *temp_result;
17969 char_u *nextcmd = NULL;
17971 if (expr_end == NULL || in_end == NULL)
17972 return NULL;
17973 *expr_start = NUL;
17974 *expr_end = NUL;
17975 c1 = *in_end;
17976 *in_end = NUL;
17978 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17979 if (temp_result != NULL && nextcmd == NULL)
17981 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
17982 + (in_end - expr_end) + 1));
17983 if (retval != NULL)
17985 STRCPY(retval, in_start);
17986 STRCAT(retval, temp_result);
17987 STRCAT(retval, expr_end + 1);
17990 vim_free(temp_result);
17992 *in_end = c1; /* put char back for error messages */
17993 *expr_start = '{';
17994 *expr_end = '}';
17996 if (retval != NULL)
17998 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
17999 if (expr_start != NULL)
18001 /* Further expansion! */
18002 temp_result = make_expanded_name(retval, expr_start,
18003 expr_end, temp_result);
18004 vim_free(retval);
18005 retval = temp_result;
18009 return retval;
18013 * Return TRUE if character "c" can be used in a variable or function name.
18014 * Does not include '{' or '}' for magic braces.
18016 static int
18017 eval_isnamec(c)
18018 int c;
18020 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18024 * Return TRUE if character "c" can be used as the first character in a
18025 * variable or function name (excluding '{' and '}').
18027 static int
18028 eval_isnamec1(c)
18029 int c;
18031 return (ASCII_ISALPHA(c) || c == '_');
18035 * Set number v: variable to "val".
18037 void
18038 set_vim_var_nr(idx, val)
18039 int idx;
18040 long val;
18042 vimvars[idx].vv_nr = val;
18046 * Get number v: variable value.
18048 long
18049 get_vim_var_nr(idx)
18050 int idx;
18052 return vimvars[idx].vv_nr;
18055 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18057 * Get string v: variable value. Uses a static buffer, can only be used once.
18059 char_u *
18060 get_vim_var_str(idx)
18061 int idx;
18063 return get_tv_string(&vimvars[idx].vv_tv);
18065 #endif
18068 * Set v:count, v:count1 and v:prevcount.
18070 void
18071 set_vcount(count, count1)
18072 long count;
18073 long count1;
18075 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18076 vimvars[VV_COUNT].vv_nr = count;
18077 vimvars[VV_COUNT1].vv_nr = count1;
18081 * Set string v: variable to a copy of "val".
18083 void
18084 set_vim_var_string(idx, val, len)
18085 int idx;
18086 char_u *val;
18087 int len; /* length of "val" to use or -1 (whole string) */
18089 /* Need to do this (at least) once, since we can't initialize a union.
18090 * Will always be invoked when "v:progname" is set. */
18091 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18093 vim_free(vimvars[idx].vv_str);
18094 if (val == NULL)
18095 vimvars[idx].vv_str = NULL;
18096 else if (len == -1)
18097 vimvars[idx].vv_str = vim_strsave(val);
18098 else
18099 vimvars[idx].vv_str = vim_strnsave(val, len);
18103 * Set v:register if needed.
18105 void
18106 set_reg_var(c)
18107 int c;
18109 char_u regname;
18111 if (c == 0 || c == ' ')
18112 regname = '"';
18113 else
18114 regname = c;
18115 /* Avoid free/alloc when the value is already right. */
18116 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18117 set_vim_var_string(VV_REG, &regname, 1);
18121 * Get or set v:exception. If "oldval" == NULL, return the current value.
18122 * Otherwise, restore the value to "oldval" and return NULL.
18123 * Must always be called in pairs to save and restore v:exception! Does not
18124 * take care of memory allocations.
18126 char_u *
18127 v_exception(oldval)
18128 char_u *oldval;
18130 if (oldval == NULL)
18131 return vimvars[VV_EXCEPTION].vv_str;
18133 vimvars[VV_EXCEPTION].vv_str = oldval;
18134 return NULL;
18138 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18139 * Otherwise, restore the value to "oldval" and return NULL.
18140 * Must always be called in pairs to save and restore v:throwpoint! Does not
18141 * take care of memory allocations.
18143 char_u *
18144 v_throwpoint(oldval)
18145 char_u *oldval;
18147 if (oldval == NULL)
18148 return vimvars[VV_THROWPOINT].vv_str;
18150 vimvars[VV_THROWPOINT].vv_str = oldval;
18151 return NULL;
18154 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18156 * Set v:cmdarg.
18157 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18158 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18159 * Must always be called in pairs!
18161 char_u *
18162 set_cmdarg(eap, oldarg)
18163 exarg_T *eap;
18164 char_u *oldarg;
18166 char_u *oldval;
18167 char_u *newval;
18168 unsigned len;
18170 oldval = vimvars[VV_CMDARG].vv_str;
18171 if (eap == NULL)
18173 vim_free(oldval);
18174 vimvars[VV_CMDARG].vv_str = oldarg;
18175 return NULL;
18178 if (eap->force_bin == FORCE_BIN)
18179 len = 6;
18180 else if (eap->force_bin == FORCE_NOBIN)
18181 len = 8;
18182 else
18183 len = 0;
18185 if (eap->read_edit)
18186 len += 7;
18188 if (eap->force_ff != 0)
18189 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18190 # ifdef FEAT_MBYTE
18191 if (eap->force_enc != 0)
18192 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18193 if (eap->bad_char != 0)
18194 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18195 # endif
18197 newval = alloc(len + 1);
18198 if (newval == NULL)
18199 return NULL;
18201 if (eap->force_bin == FORCE_BIN)
18202 sprintf((char *)newval, " ++bin");
18203 else if (eap->force_bin == FORCE_NOBIN)
18204 sprintf((char *)newval, " ++nobin");
18205 else
18206 *newval = NUL;
18208 if (eap->read_edit)
18209 STRCAT(newval, " ++edit");
18211 if (eap->force_ff != 0)
18212 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18213 eap->cmd + eap->force_ff);
18214 # ifdef FEAT_MBYTE
18215 if (eap->force_enc != 0)
18216 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18217 eap->cmd + eap->force_enc);
18218 if (eap->bad_char != 0)
18219 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18220 eap->cmd + eap->bad_char);
18221 # endif
18222 vimvars[VV_CMDARG].vv_str = newval;
18223 return oldval;
18225 #endif
18228 * Get the value of internal variable "name".
18229 * Return OK or FAIL.
18231 static int
18232 get_var_tv(name, len, rettv, verbose)
18233 char_u *name;
18234 int len; /* length of "name" */
18235 typval_T *rettv; /* NULL when only checking existence */
18236 int verbose; /* may give error message */
18238 int ret = OK;
18239 typval_T *tv = NULL;
18240 typval_T atv;
18241 dictitem_T *v;
18242 int cc;
18244 /* truncate the name, so that we can use strcmp() */
18245 cc = name[len];
18246 name[len] = NUL;
18249 * Check for "b:changedtick".
18251 if (STRCMP(name, "b:changedtick") == 0)
18253 atv.v_type = VAR_NUMBER;
18254 atv.vval.v_number = curbuf->b_changedtick;
18255 tv = &atv;
18259 * Check for user-defined variables.
18261 else
18263 v = find_var(name, NULL);
18264 if (v != NULL)
18265 tv = &v->di_tv;
18268 if (tv == NULL)
18270 if (rettv != NULL && verbose)
18271 EMSG2(_(e_undefvar), name);
18272 ret = FAIL;
18274 else if (rettv != NULL)
18275 copy_tv(tv, rettv);
18277 name[len] = cc;
18279 return ret;
18283 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18284 * Also handle function call with Funcref variable: func(expr)
18285 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18287 static int
18288 handle_subscript(arg, rettv, evaluate, verbose)
18289 char_u **arg;
18290 typval_T *rettv;
18291 int evaluate; /* do more than finding the end */
18292 int verbose; /* give error messages */
18294 int ret = OK;
18295 dict_T *selfdict = NULL;
18296 char_u *s;
18297 int len;
18298 typval_T functv;
18300 while (ret == OK
18301 && (**arg == '['
18302 || (**arg == '.' && rettv->v_type == VAR_DICT)
18303 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18304 && !vim_iswhite(*(*arg - 1)))
18306 if (**arg == '(')
18308 /* need to copy the funcref so that we can clear rettv */
18309 functv = *rettv;
18310 rettv->v_type = VAR_UNKNOWN;
18312 /* Invoke the function. Recursive! */
18313 s = functv.vval.v_string;
18314 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18315 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18316 &len, evaluate, selfdict);
18318 /* Clear the funcref afterwards, so that deleting it while
18319 * evaluating the arguments is possible (see test55). */
18320 clear_tv(&functv);
18322 /* Stop the expression evaluation when immediately aborting on
18323 * error, or when an interrupt occurred or an exception was thrown
18324 * but not caught. */
18325 if (aborting())
18327 if (ret == OK)
18328 clear_tv(rettv);
18329 ret = FAIL;
18331 dict_unref(selfdict);
18332 selfdict = NULL;
18334 else /* **arg == '[' || **arg == '.' */
18336 dict_unref(selfdict);
18337 if (rettv->v_type == VAR_DICT)
18339 selfdict = rettv->vval.v_dict;
18340 if (selfdict != NULL)
18341 ++selfdict->dv_refcount;
18343 else
18344 selfdict = NULL;
18345 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18347 clear_tv(rettv);
18348 ret = FAIL;
18352 dict_unref(selfdict);
18353 return ret;
18357 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18358 * value).
18360 static typval_T *
18361 alloc_tv()
18363 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18367 * Allocate memory for a variable type-value, and assign a string to it.
18368 * The string "s" must have been allocated, it is consumed.
18369 * Return NULL for out of memory, the variable otherwise.
18371 static typval_T *
18372 alloc_string_tv(s)
18373 char_u *s;
18375 typval_T *rettv;
18377 rettv = alloc_tv();
18378 if (rettv != NULL)
18380 rettv->v_type = VAR_STRING;
18381 rettv->vval.v_string = s;
18383 else
18384 vim_free(s);
18385 return rettv;
18389 * Free the memory for a variable type-value.
18391 void
18392 free_tv(varp)
18393 typval_T *varp;
18395 if (varp != NULL)
18397 switch (varp->v_type)
18399 case VAR_FUNC:
18400 func_unref(varp->vval.v_string);
18401 /*FALLTHROUGH*/
18402 case VAR_STRING:
18403 vim_free(varp->vval.v_string);
18404 break;
18405 case VAR_LIST:
18406 list_unref(varp->vval.v_list);
18407 break;
18408 case VAR_DICT:
18409 dict_unref(varp->vval.v_dict);
18410 break;
18411 case VAR_NUMBER:
18412 #ifdef FEAT_FLOAT
18413 case VAR_FLOAT:
18414 #endif
18415 case VAR_UNKNOWN:
18416 break;
18417 default:
18418 EMSG2(_(e_intern2), "free_tv()");
18419 break;
18421 vim_free(varp);
18426 * Free the memory for a variable value and set the value to NULL or 0.
18428 void
18429 clear_tv(varp)
18430 typval_T *varp;
18432 if (varp != NULL)
18434 switch (varp->v_type)
18436 case VAR_FUNC:
18437 func_unref(varp->vval.v_string);
18438 /*FALLTHROUGH*/
18439 case VAR_STRING:
18440 vim_free(varp->vval.v_string);
18441 varp->vval.v_string = NULL;
18442 break;
18443 case VAR_LIST:
18444 list_unref(varp->vval.v_list);
18445 varp->vval.v_list = NULL;
18446 break;
18447 case VAR_DICT:
18448 dict_unref(varp->vval.v_dict);
18449 varp->vval.v_dict = NULL;
18450 break;
18451 case VAR_NUMBER:
18452 varp->vval.v_number = 0;
18453 break;
18454 #ifdef FEAT_FLOAT
18455 case VAR_FLOAT:
18456 varp->vval.v_float = 0.0;
18457 break;
18458 #endif
18459 case VAR_UNKNOWN:
18460 break;
18461 default:
18462 EMSG2(_(e_intern2), "clear_tv()");
18464 varp->v_lock = 0;
18469 * Set the value of a variable to NULL without freeing items.
18471 static void
18472 init_tv(varp)
18473 typval_T *varp;
18475 if (varp != NULL)
18476 vim_memset(varp, 0, sizeof(typval_T));
18480 * Get the number value of a variable.
18481 * If it is a String variable, uses vim_str2nr().
18482 * For incompatible types, return 0.
18483 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18484 * caller of incompatible types: it sets *denote to TRUE if "denote"
18485 * is not NULL or returns -1 otherwise.
18487 static long
18488 get_tv_number(varp)
18489 typval_T *varp;
18491 int error = FALSE;
18493 return get_tv_number_chk(varp, &error); /* return 0L on error */
18496 long
18497 get_tv_number_chk(varp, denote)
18498 typval_T *varp;
18499 int *denote;
18501 long n = 0L;
18503 switch (varp->v_type)
18505 case VAR_NUMBER:
18506 return (long)(varp->vval.v_number);
18507 #ifdef FEAT_FLOAT
18508 case VAR_FLOAT:
18509 EMSG(_("E805: Using a Float as a Number"));
18510 break;
18511 #endif
18512 case VAR_FUNC:
18513 EMSG(_("E703: Using a Funcref as a Number"));
18514 break;
18515 case VAR_STRING:
18516 if (varp->vval.v_string != NULL)
18517 vim_str2nr(varp->vval.v_string, NULL, NULL,
18518 TRUE, TRUE, &n, NULL);
18519 return n;
18520 case VAR_LIST:
18521 EMSG(_("E745: Using a List as a Number"));
18522 break;
18523 case VAR_DICT:
18524 EMSG(_("E728: Using a Dictionary as a Number"));
18525 break;
18526 default:
18527 EMSG2(_(e_intern2), "get_tv_number()");
18528 break;
18530 if (denote == NULL) /* useful for values that must be unsigned */
18531 n = -1;
18532 else
18533 *denote = TRUE;
18534 return n;
18538 * Get the lnum from the first argument.
18539 * Also accepts ".", "$", etc., but that only works for the current buffer.
18540 * Returns -1 on error.
18542 static linenr_T
18543 get_tv_lnum(argvars)
18544 typval_T *argvars;
18546 typval_T rettv;
18547 linenr_T lnum;
18549 lnum = get_tv_number_chk(&argvars[0], NULL);
18550 if (lnum == 0) /* no valid number, try using line() */
18552 rettv.v_type = VAR_NUMBER;
18553 f_line(argvars, &rettv);
18554 lnum = rettv.vval.v_number;
18555 clear_tv(&rettv);
18557 return lnum;
18561 * Get the lnum from the first argument.
18562 * Also accepts "$", then "buf" is used.
18563 * Returns 0 on error.
18565 static linenr_T
18566 get_tv_lnum_buf(argvars, buf)
18567 typval_T *argvars;
18568 buf_T *buf;
18570 if (argvars[0].v_type == VAR_STRING
18571 && argvars[0].vval.v_string != NULL
18572 && argvars[0].vval.v_string[0] == '$'
18573 && buf != NULL)
18574 return buf->b_ml.ml_line_count;
18575 return get_tv_number_chk(&argvars[0], NULL);
18579 * Get the string value of a variable.
18580 * If it is a Number variable, the number is converted into a string.
18581 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18582 * get_tv_string_buf() uses a given buffer.
18583 * If the String variable has never been set, return an empty string.
18584 * Never returns NULL;
18585 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18586 * NULL on error.
18588 static char_u *
18589 get_tv_string(varp)
18590 typval_T *varp;
18592 static char_u mybuf[NUMBUFLEN];
18594 return get_tv_string_buf(varp, mybuf);
18597 static char_u *
18598 get_tv_string_buf(varp, buf)
18599 typval_T *varp;
18600 char_u *buf;
18602 char_u *res = get_tv_string_buf_chk(varp, buf);
18604 return res != NULL ? res : (char_u *)"";
18607 char_u *
18608 get_tv_string_chk(varp)
18609 typval_T *varp;
18611 static char_u mybuf[NUMBUFLEN];
18613 return get_tv_string_buf_chk(varp, mybuf);
18616 static char_u *
18617 get_tv_string_buf_chk(varp, buf)
18618 typval_T *varp;
18619 char_u *buf;
18621 switch (varp->v_type)
18623 case VAR_NUMBER:
18624 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18625 return buf;
18626 case VAR_FUNC:
18627 EMSG(_("E729: using Funcref as a String"));
18628 break;
18629 case VAR_LIST:
18630 EMSG(_("E730: using List as a String"));
18631 break;
18632 case VAR_DICT:
18633 EMSG(_("E731: using Dictionary as a String"));
18634 break;
18635 #ifdef FEAT_FLOAT
18636 case VAR_FLOAT:
18637 EMSG(_("E806: using Float as a String"));
18638 break;
18639 #endif
18640 case VAR_STRING:
18641 if (varp->vval.v_string != NULL)
18642 return varp->vval.v_string;
18643 return (char_u *)"";
18644 default:
18645 EMSG2(_(e_intern2), "get_tv_string_buf()");
18646 break;
18648 return NULL;
18652 * Find variable "name" in the list of variables.
18653 * Return a pointer to it if found, NULL if not found.
18654 * Careful: "a:0" variables don't have a name.
18655 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18656 * hashtab_T used.
18658 static dictitem_T *
18659 find_var(name, htp)
18660 char_u *name;
18661 hashtab_T **htp;
18663 char_u *varname;
18664 hashtab_T *ht;
18666 ht = find_var_ht(name, &varname);
18667 if (htp != NULL)
18668 *htp = ht;
18669 if (ht == NULL)
18670 return NULL;
18671 return find_var_in_ht(ht, varname, htp != NULL);
18675 * Find variable "varname" in hashtab "ht".
18676 * Returns NULL if not found.
18678 static dictitem_T *
18679 find_var_in_ht(ht, varname, writing)
18680 hashtab_T *ht;
18681 char_u *varname;
18682 int writing;
18684 hashitem_T *hi;
18686 if (*varname == NUL)
18688 /* Must be something like "s:", otherwise "ht" would be NULL. */
18689 switch (varname[-2])
18691 case 's': return &SCRIPT_SV(current_SID).sv_var;
18692 case 'g': return &globvars_var;
18693 case 'v': return &vimvars_var;
18694 case 'b': return &curbuf->b_bufvar;
18695 case 'w': return &curwin->w_winvar;
18696 #ifdef FEAT_WINDOWS
18697 case 't': return &curtab->tp_winvar;
18698 #endif
18699 case 'l': return current_funccal == NULL
18700 ? NULL : &current_funccal->l_vars_var;
18701 case 'a': return current_funccal == NULL
18702 ? NULL : &current_funccal->l_avars_var;
18704 return NULL;
18707 hi = hash_find(ht, varname);
18708 if (HASHITEM_EMPTY(hi))
18710 /* For global variables we may try auto-loading the script. If it
18711 * worked find the variable again. Don't auto-load a script if it was
18712 * loaded already, otherwise it would be loaded every time when
18713 * checking if a function name is a Funcref variable. */
18714 if (ht == &globvarht && !writing
18715 && script_autoload(varname, FALSE) && !aborting())
18716 hi = hash_find(ht, varname);
18717 if (HASHITEM_EMPTY(hi))
18718 return NULL;
18720 return HI2DI(hi);
18724 * Find the hashtab used for a variable name.
18725 * Set "varname" to the start of name without ':'.
18727 static hashtab_T *
18728 find_var_ht(name, varname)
18729 char_u *name;
18730 char_u **varname;
18732 hashitem_T *hi;
18734 if (name[1] != ':')
18736 /* The name must not start with a colon or #. */
18737 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18738 return NULL;
18739 *varname = name;
18741 /* "version" is "v:version" in all scopes */
18742 hi = hash_find(&compat_hashtab, name);
18743 if (!HASHITEM_EMPTY(hi))
18744 return &compat_hashtab;
18746 if (current_funccal == NULL)
18747 return &globvarht; /* global variable */
18748 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18750 *varname = name + 2;
18751 if (*name == 'g') /* global variable */
18752 return &globvarht;
18753 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18755 if (vim_strchr(name + 2, ':') != NULL
18756 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18757 return NULL;
18758 if (*name == 'b') /* buffer variable */
18759 return &curbuf->b_vars.dv_hashtab;
18760 if (*name == 'w') /* window variable */
18761 return &curwin->w_vars.dv_hashtab;
18762 #ifdef FEAT_WINDOWS
18763 if (*name == 't') /* tab page variable */
18764 return &curtab->tp_vars.dv_hashtab;
18765 #endif
18766 if (*name == 'v') /* v: variable */
18767 return &vimvarht;
18768 if (*name == 'a' && current_funccal != NULL) /* function argument */
18769 return &current_funccal->l_avars.dv_hashtab;
18770 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18771 return &current_funccal->l_vars.dv_hashtab;
18772 if (*name == 's' /* script variable */
18773 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18774 return &SCRIPT_VARS(current_SID);
18775 return NULL;
18779 * Get the string value of a (global/local) variable.
18780 * Returns NULL when it doesn't exist.
18782 char_u *
18783 get_var_value(name)
18784 char_u *name;
18786 dictitem_T *v;
18788 v = find_var(name, NULL);
18789 if (v == NULL)
18790 return NULL;
18791 return get_tv_string(&v->di_tv);
18795 * Allocate a new hashtab for a sourced script. It will be used while
18796 * sourcing this script and when executing functions defined in the script.
18798 void
18799 new_script_vars(id)
18800 scid_T id;
18802 int i;
18803 hashtab_T *ht;
18804 scriptvar_T *sv;
18806 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18808 /* Re-allocating ga_data means that an ht_array pointing to
18809 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18810 * at its init value. Also reset "v_dict", it's always the same. */
18811 for (i = 1; i <= ga_scripts.ga_len; ++i)
18813 ht = &SCRIPT_VARS(i);
18814 if (ht->ht_mask == HT_INIT_SIZE - 1)
18815 ht->ht_array = ht->ht_smallarray;
18816 sv = &SCRIPT_SV(i);
18817 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18820 while (ga_scripts.ga_len < id)
18822 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18823 init_var_dict(&sv->sv_dict, &sv->sv_var);
18824 ++ga_scripts.ga_len;
18830 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18831 * point to it.
18833 void
18834 init_var_dict(dict, dict_var)
18835 dict_T *dict;
18836 dictitem_T *dict_var;
18838 hash_init(&dict->dv_hashtab);
18839 dict->dv_refcount = 99999;
18840 dict_var->di_tv.vval.v_dict = dict;
18841 dict_var->di_tv.v_type = VAR_DICT;
18842 dict_var->di_tv.v_lock = VAR_FIXED;
18843 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18844 dict_var->di_key[0] = NUL;
18848 * Clean up a list of internal variables.
18849 * Frees all allocated variables and the value they contain.
18850 * Clears hashtab "ht", does not free it.
18852 void
18853 vars_clear(ht)
18854 hashtab_T *ht;
18856 vars_clear_ext(ht, TRUE);
18860 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18862 static void
18863 vars_clear_ext(ht, free_val)
18864 hashtab_T *ht;
18865 int free_val;
18867 int todo;
18868 hashitem_T *hi;
18869 dictitem_T *v;
18871 hash_lock(ht);
18872 todo = (int)ht->ht_used;
18873 for (hi = ht->ht_array; todo > 0; ++hi)
18875 if (!HASHITEM_EMPTY(hi))
18877 --todo;
18879 /* Free the variable. Don't remove it from the hashtab,
18880 * ht_array might change then. hash_clear() takes care of it
18881 * later. */
18882 v = HI2DI(hi);
18883 if (free_val)
18884 clear_tv(&v->di_tv);
18885 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18886 vim_free(v);
18889 hash_clear(ht);
18890 ht->ht_used = 0;
18894 * Delete a variable from hashtab "ht" at item "hi".
18895 * Clear the variable value and free the dictitem.
18897 static void
18898 delete_var(ht, hi)
18899 hashtab_T *ht;
18900 hashitem_T *hi;
18902 dictitem_T *di = HI2DI(hi);
18904 hash_remove(ht, hi);
18905 clear_tv(&di->di_tv);
18906 vim_free(di);
18910 * List the value of one internal variable.
18912 static void
18913 list_one_var(v, prefix, first)
18914 dictitem_T *v;
18915 char_u *prefix;
18916 int *first;
18918 char_u *tofree;
18919 char_u *s;
18920 char_u numbuf[NUMBUFLEN];
18922 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18923 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18924 s == NULL ? (char_u *)"" : s, first);
18925 vim_free(tofree);
18928 static void
18929 list_one_var_a(prefix, name, type, string, first)
18930 char_u *prefix;
18931 char_u *name;
18932 int type;
18933 char_u *string;
18934 int *first; /* when TRUE clear rest of screen and set to FALSE */
18936 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18937 msg_start();
18938 msg_puts(prefix);
18939 if (name != NULL) /* "a:" vars don't have a name stored */
18940 msg_puts(name);
18941 msg_putchar(' ');
18942 msg_advance(22);
18943 if (type == VAR_NUMBER)
18944 msg_putchar('#');
18945 else if (type == VAR_FUNC)
18946 msg_putchar('*');
18947 else if (type == VAR_LIST)
18949 msg_putchar('[');
18950 if (*string == '[')
18951 ++string;
18953 else if (type == VAR_DICT)
18955 msg_putchar('{');
18956 if (*string == '{')
18957 ++string;
18959 else
18960 msg_putchar(' ');
18962 msg_outtrans(string);
18964 if (type == VAR_FUNC)
18965 msg_puts((char_u *)"()");
18966 if (*first)
18968 msg_clr_eos();
18969 *first = FALSE;
18974 * Set variable "name" to value in "tv".
18975 * If the variable already exists, the value is updated.
18976 * Otherwise the variable is created.
18978 static void
18979 set_var(name, tv, copy)
18980 char_u *name;
18981 typval_T *tv;
18982 int copy; /* make copy of value in "tv" */
18984 dictitem_T *v;
18985 char_u *varname;
18986 hashtab_T *ht;
18987 char_u *p;
18989 if (tv->v_type == VAR_FUNC)
18991 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
18992 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
18993 ? name[2] : name[0]))
18995 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
18996 return;
18998 if (function_exists(name))
19000 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19001 name);
19002 return;
19006 ht = find_var_ht(name, &varname);
19007 if (ht == NULL || *varname == NUL)
19009 EMSG2(_(e_illvar), name);
19010 return;
19013 v = find_var_in_ht(ht, varname, TRUE);
19014 if (v != NULL)
19016 /* existing variable, need to clear the value */
19017 if (var_check_ro(v->di_flags, name)
19018 || tv_check_lock(v->di_tv.v_lock, name))
19019 return;
19020 if (v->di_tv.v_type != tv->v_type
19021 && !((v->di_tv.v_type == VAR_STRING
19022 || v->di_tv.v_type == VAR_NUMBER)
19023 && (tv->v_type == VAR_STRING
19024 || tv->v_type == VAR_NUMBER))
19025 #ifdef FEAT_FLOAT
19026 && !((v->di_tv.v_type == VAR_NUMBER
19027 || v->di_tv.v_type == VAR_FLOAT)
19028 && (tv->v_type == VAR_NUMBER
19029 || tv->v_type == VAR_FLOAT))
19030 #endif
19033 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19034 return;
19038 * Handle setting internal v: variables separately: we don't change
19039 * the type.
19041 if (ht == &vimvarht)
19043 if (v->di_tv.v_type == VAR_STRING)
19045 vim_free(v->di_tv.vval.v_string);
19046 if (copy || tv->v_type != VAR_STRING)
19047 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19048 else
19050 /* Take over the string to avoid an extra alloc/free. */
19051 v->di_tv.vval.v_string = tv->vval.v_string;
19052 tv->vval.v_string = NULL;
19055 else if (v->di_tv.v_type != VAR_NUMBER)
19056 EMSG2(_(e_intern2), "set_var()");
19057 else
19059 v->di_tv.vval.v_number = get_tv_number(tv);
19060 if (STRCMP(varname, "searchforward") == 0)
19061 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19063 return;
19066 clear_tv(&v->di_tv);
19068 else /* add a new variable */
19070 /* Can't add "v:" variable. */
19071 if (ht == &vimvarht)
19073 EMSG2(_(e_illvar), name);
19074 return;
19077 /* Make sure the variable name is valid. */
19078 for (p = varname; *p != NUL; ++p)
19079 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19080 && *p != AUTOLOAD_CHAR)
19082 EMSG2(_(e_illvar), varname);
19083 return;
19086 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19087 + STRLEN(varname)));
19088 if (v == NULL)
19089 return;
19090 STRCPY(v->di_key, varname);
19091 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19093 vim_free(v);
19094 return;
19096 v->di_flags = 0;
19099 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19100 copy_tv(tv, &v->di_tv);
19101 else
19103 v->di_tv = *tv;
19104 v->di_tv.v_lock = 0;
19105 init_tv(tv);
19110 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19111 * Also give an error message.
19113 static int
19114 var_check_ro(flags, name)
19115 int flags;
19116 char_u *name;
19118 if (flags & DI_FLAGS_RO)
19120 EMSG2(_(e_readonlyvar), name);
19121 return TRUE;
19123 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19125 EMSG2(_(e_readonlysbx), name);
19126 return TRUE;
19128 return FALSE;
19132 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19133 * Also give an error message.
19135 static int
19136 var_check_fixed(flags, name)
19137 int flags;
19138 char_u *name;
19140 if (flags & DI_FLAGS_FIX)
19142 EMSG2(_("E795: Cannot delete variable %s"), name);
19143 return TRUE;
19145 return FALSE;
19149 * Return TRUE if typeval "tv" is set to be locked (immutable).
19150 * Also give an error message, using "name".
19152 static int
19153 tv_check_lock(lock, name)
19154 int lock;
19155 char_u *name;
19157 if (lock & VAR_LOCKED)
19159 EMSG2(_("E741: Value is locked: %s"),
19160 name == NULL ? (char_u *)_("Unknown") : name);
19161 return TRUE;
19163 if (lock & VAR_FIXED)
19165 EMSG2(_("E742: Cannot change value of %s"),
19166 name == NULL ? (char_u *)_("Unknown") : name);
19167 return TRUE;
19169 return FALSE;
19173 * Copy the values from typval_T "from" to typval_T "to".
19174 * When needed allocates string or increases reference count.
19175 * Does not make a copy of a list or dict but copies the reference!
19177 static void
19178 copy_tv(from, to)
19179 typval_T *from;
19180 typval_T *to;
19182 to->v_type = from->v_type;
19183 to->v_lock = 0;
19184 switch (from->v_type)
19186 case VAR_NUMBER:
19187 to->vval.v_number = from->vval.v_number;
19188 break;
19189 #ifdef FEAT_FLOAT
19190 case VAR_FLOAT:
19191 to->vval.v_float = from->vval.v_float;
19192 break;
19193 #endif
19194 case VAR_STRING:
19195 case VAR_FUNC:
19196 if (from->vval.v_string == NULL)
19197 to->vval.v_string = NULL;
19198 else
19200 to->vval.v_string = vim_strsave(from->vval.v_string);
19201 if (from->v_type == VAR_FUNC)
19202 func_ref(to->vval.v_string);
19204 break;
19205 case VAR_LIST:
19206 if (from->vval.v_list == NULL)
19207 to->vval.v_list = NULL;
19208 else
19210 to->vval.v_list = from->vval.v_list;
19211 ++to->vval.v_list->lv_refcount;
19213 break;
19214 case VAR_DICT:
19215 if (from->vval.v_dict == NULL)
19216 to->vval.v_dict = NULL;
19217 else
19219 to->vval.v_dict = from->vval.v_dict;
19220 ++to->vval.v_dict->dv_refcount;
19222 break;
19223 default:
19224 EMSG2(_(e_intern2), "copy_tv()");
19225 break;
19230 * Make a copy of an item.
19231 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19232 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19233 * reference to an already copied list/dict can be used.
19234 * Returns FAIL or OK.
19236 static int
19237 item_copy(from, to, deep, copyID)
19238 typval_T *from;
19239 typval_T *to;
19240 int deep;
19241 int copyID;
19243 static int recurse = 0;
19244 int ret = OK;
19246 if (recurse >= DICT_MAXNEST)
19248 EMSG(_("E698: variable nested too deep for making a copy"));
19249 return FAIL;
19251 ++recurse;
19253 switch (from->v_type)
19255 case VAR_NUMBER:
19256 #ifdef FEAT_FLOAT
19257 case VAR_FLOAT:
19258 #endif
19259 case VAR_STRING:
19260 case VAR_FUNC:
19261 copy_tv(from, to);
19262 break;
19263 case VAR_LIST:
19264 to->v_type = VAR_LIST;
19265 to->v_lock = 0;
19266 if (from->vval.v_list == NULL)
19267 to->vval.v_list = NULL;
19268 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19270 /* use the copy made earlier */
19271 to->vval.v_list = from->vval.v_list->lv_copylist;
19272 ++to->vval.v_list->lv_refcount;
19274 else
19275 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19276 if (to->vval.v_list == NULL)
19277 ret = FAIL;
19278 break;
19279 case VAR_DICT:
19280 to->v_type = VAR_DICT;
19281 to->v_lock = 0;
19282 if (from->vval.v_dict == NULL)
19283 to->vval.v_dict = NULL;
19284 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19286 /* use the copy made earlier */
19287 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19288 ++to->vval.v_dict->dv_refcount;
19290 else
19291 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19292 if (to->vval.v_dict == NULL)
19293 ret = FAIL;
19294 break;
19295 default:
19296 EMSG2(_(e_intern2), "item_copy()");
19297 ret = FAIL;
19299 --recurse;
19300 return ret;
19304 * ":echo expr1 ..." print each argument separated with a space, add a
19305 * newline at the end.
19306 * ":echon expr1 ..." print each argument plain.
19308 void
19309 ex_echo(eap)
19310 exarg_T *eap;
19312 char_u *arg = eap->arg;
19313 typval_T rettv;
19314 char_u *tofree;
19315 char_u *p;
19316 int needclr = TRUE;
19317 int atstart = TRUE;
19318 char_u numbuf[NUMBUFLEN];
19320 if (eap->skip)
19321 ++emsg_skip;
19322 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19324 /* If eval1() causes an error message the text from the command may
19325 * still need to be cleared. E.g., "echo 22,44". */
19326 need_clr_eos = needclr;
19328 p = arg;
19329 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19332 * Report the invalid expression unless the expression evaluation
19333 * has been cancelled due to an aborting error, an interrupt, or an
19334 * exception.
19336 if (!aborting())
19337 EMSG2(_(e_invexpr2), p);
19338 need_clr_eos = FALSE;
19339 break;
19341 need_clr_eos = FALSE;
19343 if (!eap->skip)
19345 if (atstart)
19347 atstart = FALSE;
19348 /* Call msg_start() after eval1(), evaluating the expression
19349 * may cause a message to appear. */
19350 if (eap->cmdidx == CMD_echo)
19351 msg_start();
19353 else if (eap->cmdidx == CMD_echo)
19354 msg_puts_attr((char_u *)" ", echo_attr);
19355 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
19356 if (p != NULL)
19357 for ( ; *p != NUL && !got_int; ++p)
19359 if (*p == '\n' || *p == '\r' || *p == TAB)
19361 if (*p != TAB && needclr)
19363 /* remove any text still there from the command */
19364 msg_clr_eos();
19365 needclr = FALSE;
19367 msg_putchar_attr(*p, echo_attr);
19369 else
19371 #ifdef FEAT_MBYTE
19372 if (has_mbyte)
19374 int i = (*mb_ptr2len)(p);
19376 (void)msg_outtrans_len_attr(p, i, echo_attr);
19377 p += i - 1;
19379 else
19380 #endif
19381 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19384 vim_free(tofree);
19386 clear_tv(&rettv);
19387 arg = skipwhite(arg);
19389 eap->nextcmd = check_nextcmd(arg);
19391 if (eap->skip)
19392 --emsg_skip;
19393 else
19395 /* remove text that may still be there from the command */
19396 if (needclr)
19397 msg_clr_eos();
19398 if (eap->cmdidx == CMD_echo)
19399 msg_end();
19404 * ":echohl {name}".
19406 void
19407 ex_echohl(eap)
19408 exarg_T *eap;
19410 int id;
19412 id = syn_name2id(eap->arg);
19413 if (id == 0)
19414 echo_attr = 0;
19415 else
19416 echo_attr = syn_id2attr(id);
19420 * ":execute expr1 ..." execute the result of an expression.
19421 * ":echomsg expr1 ..." Print a message
19422 * ":echoerr expr1 ..." Print an error
19423 * Each gets spaces around each argument and a newline at the end for
19424 * echo commands
19426 void
19427 ex_execute(eap)
19428 exarg_T *eap;
19430 char_u *arg = eap->arg;
19431 typval_T rettv;
19432 int ret = OK;
19433 char_u *p;
19434 garray_T ga;
19435 int len;
19436 int save_did_emsg;
19438 ga_init2(&ga, 1, 80);
19440 if (eap->skip)
19441 ++emsg_skip;
19442 while (*arg != NUL && *arg != '|' && *arg != '\n')
19444 p = arg;
19445 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19448 * Report the invalid expression unless the expression evaluation
19449 * has been cancelled due to an aborting error, an interrupt, or an
19450 * exception.
19452 if (!aborting())
19453 EMSG2(_(e_invexpr2), p);
19454 ret = FAIL;
19455 break;
19458 if (!eap->skip)
19460 p = get_tv_string(&rettv);
19461 len = (int)STRLEN(p);
19462 if (ga_grow(&ga, len + 2) == FAIL)
19464 clear_tv(&rettv);
19465 ret = FAIL;
19466 break;
19468 if (ga.ga_len)
19469 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19470 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19471 ga.ga_len += len;
19474 clear_tv(&rettv);
19475 arg = skipwhite(arg);
19478 if (ret != FAIL && ga.ga_data != NULL)
19480 if (eap->cmdidx == CMD_echomsg)
19482 MSG_ATTR(ga.ga_data, echo_attr);
19483 out_flush();
19485 else if (eap->cmdidx == CMD_echoerr)
19487 /* We don't want to abort following commands, restore did_emsg. */
19488 save_did_emsg = did_emsg;
19489 EMSG((char_u *)ga.ga_data);
19490 if (!force_abort)
19491 did_emsg = save_did_emsg;
19493 else if (eap->cmdidx == CMD_execute)
19494 do_cmdline((char_u *)ga.ga_data,
19495 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19498 ga_clear(&ga);
19500 if (eap->skip)
19501 --emsg_skip;
19503 eap->nextcmd = check_nextcmd(arg);
19507 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19508 * "arg" points to the "&" or '+' when called, to "option" when returning.
19509 * Returns NULL when no option name found. Otherwise pointer to the char
19510 * after the option name.
19512 static char_u *
19513 find_option_end(arg, opt_flags)
19514 char_u **arg;
19515 int *opt_flags;
19517 char_u *p = *arg;
19519 ++p;
19520 if (*p == 'g' && p[1] == ':')
19522 *opt_flags = OPT_GLOBAL;
19523 p += 2;
19525 else if (*p == 'l' && p[1] == ':')
19527 *opt_flags = OPT_LOCAL;
19528 p += 2;
19530 else
19531 *opt_flags = 0;
19533 if (!ASCII_ISALPHA(*p))
19534 return NULL;
19535 *arg = p;
19537 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19538 p += 4; /* termcap option */
19539 else
19540 while (ASCII_ISALPHA(*p))
19541 ++p;
19542 return p;
19546 * ":function"
19548 void
19549 ex_function(eap)
19550 exarg_T *eap;
19552 char_u *theline;
19553 int j;
19554 int c;
19555 int saved_did_emsg;
19556 char_u *name = NULL;
19557 char_u *p;
19558 char_u *arg;
19559 char_u *line_arg = NULL;
19560 garray_T newargs;
19561 garray_T newlines;
19562 int varargs = FALSE;
19563 int mustend = FALSE;
19564 int flags = 0;
19565 ufunc_T *fp;
19566 int indent;
19567 int nesting;
19568 char_u *skip_until = NULL;
19569 dictitem_T *v;
19570 funcdict_T fudi;
19571 static int func_nr = 0; /* number for nameless function */
19572 int paren;
19573 hashtab_T *ht;
19574 int todo;
19575 hashitem_T *hi;
19576 int sourcing_lnum_off;
19579 * ":function" without argument: list functions.
19581 if (ends_excmd(*eap->arg))
19583 if (!eap->skip)
19585 todo = (int)func_hashtab.ht_used;
19586 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19588 if (!HASHITEM_EMPTY(hi))
19590 --todo;
19591 fp = HI2UF(hi);
19592 if (!isdigit(*fp->uf_name))
19593 list_func_head(fp, FALSE);
19597 eap->nextcmd = check_nextcmd(eap->arg);
19598 return;
19602 * ":function /pat": list functions matching pattern.
19604 if (*eap->arg == '/')
19606 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19607 if (!eap->skip)
19609 regmatch_T regmatch;
19611 c = *p;
19612 *p = NUL;
19613 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19614 *p = c;
19615 if (regmatch.regprog != NULL)
19617 regmatch.rm_ic = p_ic;
19619 todo = (int)func_hashtab.ht_used;
19620 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19622 if (!HASHITEM_EMPTY(hi))
19624 --todo;
19625 fp = HI2UF(hi);
19626 if (!isdigit(*fp->uf_name)
19627 && vim_regexec(&regmatch, fp->uf_name, 0))
19628 list_func_head(fp, FALSE);
19633 if (*p == '/')
19634 ++p;
19635 eap->nextcmd = check_nextcmd(p);
19636 return;
19640 * Get the function name. There are these situations:
19641 * func normal function name
19642 * "name" == func, "fudi.fd_dict" == NULL
19643 * dict.func new dictionary entry
19644 * "name" == NULL, "fudi.fd_dict" set,
19645 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19646 * dict.func existing dict entry with a Funcref
19647 * "name" == func, "fudi.fd_dict" set,
19648 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19649 * dict.func existing dict entry that's not a Funcref
19650 * "name" == NULL, "fudi.fd_dict" set,
19651 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19653 p = eap->arg;
19654 name = trans_function_name(&p, eap->skip, 0, &fudi);
19655 paren = (vim_strchr(p, '(') != NULL);
19656 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19659 * Return on an invalid expression in braces, unless the expression
19660 * evaluation has been cancelled due to an aborting error, an
19661 * interrupt, or an exception.
19663 if (!aborting())
19665 if (!eap->skip && fudi.fd_newkey != NULL)
19666 EMSG2(_(e_dictkey), fudi.fd_newkey);
19667 vim_free(fudi.fd_newkey);
19668 return;
19670 else
19671 eap->skip = TRUE;
19674 /* An error in a function call during evaluation of an expression in magic
19675 * braces should not cause the function not to be defined. */
19676 saved_did_emsg = did_emsg;
19677 did_emsg = FALSE;
19680 * ":function func" with only function name: list function.
19682 if (!paren)
19684 if (!ends_excmd(*skipwhite(p)))
19686 EMSG(_(e_trailing));
19687 goto ret_free;
19689 eap->nextcmd = check_nextcmd(p);
19690 if (eap->nextcmd != NULL)
19691 *p = NUL;
19692 if (!eap->skip && !got_int)
19694 fp = find_func(name);
19695 if (fp != NULL)
19697 list_func_head(fp, TRUE);
19698 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19700 if (FUNCLINE(fp, j) == NULL)
19701 continue;
19702 msg_putchar('\n');
19703 msg_outnum((long)(j + 1));
19704 if (j < 9)
19705 msg_putchar(' ');
19706 if (j < 99)
19707 msg_putchar(' ');
19708 msg_prt_line(FUNCLINE(fp, j), FALSE);
19709 out_flush(); /* show a line at a time */
19710 ui_breakcheck();
19712 if (!got_int)
19714 msg_putchar('\n');
19715 msg_puts((char_u *)" endfunction");
19718 else
19719 emsg_funcname("E123: Undefined function: %s", name);
19721 goto ret_free;
19725 * ":function name(arg1, arg2)" Define function.
19727 p = skipwhite(p);
19728 if (*p != '(')
19730 if (!eap->skip)
19732 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19733 goto ret_free;
19735 /* attempt to continue by skipping some text */
19736 if (vim_strchr(p, '(') != NULL)
19737 p = vim_strchr(p, '(');
19739 p = skipwhite(p + 1);
19741 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19742 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19744 if (!eap->skip)
19746 /* Check the name of the function. Unless it's a dictionary function
19747 * (that we are overwriting). */
19748 if (name != NULL)
19749 arg = name;
19750 else
19751 arg = fudi.fd_newkey;
19752 if (arg != NULL && (fudi.fd_di == NULL
19753 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19755 if (*arg == K_SPECIAL)
19756 j = 3;
19757 else
19758 j = 0;
19759 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19760 : eval_isnamec(arg[j])))
19761 ++j;
19762 if (arg[j] != NUL)
19763 emsg_funcname(_(e_invarg2), arg);
19768 * Isolate the arguments: "arg1, arg2, ...)"
19770 while (*p != ')')
19772 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19774 varargs = TRUE;
19775 p += 3;
19776 mustend = TRUE;
19778 else
19780 arg = p;
19781 while (ASCII_ISALNUM(*p) || *p == '_')
19782 ++p;
19783 if (arg == p || isdigit(*arg)
19784 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19785 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19787 if (!eap->skip)
19788 EMSG2(_("E125: Illegal argument: %s"), arg);
19789 break;
19791 if (ga_grow(&newargs, 1) == FAIL)
19792 goto erret;
19793 c = *p;
19794 *p = NUL;
19795 arg = vim_strsave(arg);
19796 if (arg == NULL)
19797 goto erret;
19798 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19799 *p = c;
19800 newargs.ga_len++;
19801 if (*p == ',')
19802 ++p;
19803 else
19804 mustend = TRUE;
19806 p = skipwhite(p);
19807 if (mustend && *p != ')')
19809 if (!eap->skip)
19810 EMSG2(_(e_invarg2), eap->arg);
19811 break;
19814 ++p; /* skip the ')' */
19816 /* find extra arguments "range", "dict" and "abort" */
19817 for (;;)
19819 p = skipwhite(p);
19820 if (STRNCMP(p, "range", 5) == 0)
19822 flags |= FC_RANGE;
19823 p += 5;
19825 else if (STRNCMP(p, "dict", 4) == 0)
19827 flags |= FC_DICT;
19828 p += 4;
19830 else if (STRNCMP(p, "abort", 5) == 0)
19832 flags |= FC_ABORT;
19833 p += 5;
19835 else
19836 break;
19839 /* When there is a line break use what follows for the function body.
19840 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19841 if (*p == '\n')
19842 line_arg = p + 1;
19843 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19844 EMSG(_(e_trailing));
19847 * Read the body of the function, until ":endfunction" is found.
19849 if (KeyTyped)
19851 /* Check if the function already exists, don't let the user type the
19852 * whole function before telling him it doesn't work! For a script we
19853 * need to skip the body to be able to find what follows. */
19854 if (!eap->skip && !eap->forceit)
19856 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19857 EMSG(_(e_funcdict));
19858 else if (name != NULL && find_func(name) != NULL)
19859 emsg_funcname(e_funcexts, name);
19862 if (!eap->skip && did_emsg)
19863 goto erret;
19865 msg_putchar('\n'); /* don't overwrite the function name */
19866 cmdline_row = msg_row;
19869 indent = 2;
19870 nesting = 0;
19871 for (;;)
19873 msg_scroll = TRUE;
19874 need_wait_return = FALSE;
19875 sourcing_lnum_off = sourcing_lnum;
19877 if (line_arg != NULL)
19879 /* Use eap->arg, split up in parts by line breaks. */
19880 theline = line_arg;
19881 p = vim_strchr(theline, '\n');
19882 if (p == NULL)
19883 line_arg += STRLEN(line_arg);
19884 else
19886 *p = NUL;
19887 line_arg = p + 1;
19890 else if (eap->getline == NULL)
19891 theline = getcmdline(':', 0L, indent);
19892 else
19893 theline = eap->getline(':', eap->cookie, indent);
19894 if (KeyTyped)
19895 lines_left = Rows - 1;
19896 if (theline == NULL)
19898 EMSG(_("E126: Missing :endfunction"));
19899 goto erret;
19902 /* Detect line continuation: sourcing_lnum increased more than one. */
19903 if (sourcing_lnum > sourcing_lnum_off + 1)
19904 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19905 else
19906 sourcing_lnum_off = 0;
19908 if (skip_until != NULL)
19910 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19911 * don't check for ":endfunc". */
19912 if (STRCMP(theline, skip_until) == 0)
19914 vim_free(skip_until);
19915 skip_until = NULL;
19918 else
19920 /* skip ':' and blanks*/
19921 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19924 /* Check for "endfunction". */
19925 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19927 if (line_arg == NULL)
19928 vim_free(theline);
19929 break;
19932 /* Increase indent inside "if", "while", "for" and "try", decrease
19933 * at "end". */
19934 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19935 indent -= 2;
19936 else if (STRNCMP(p, "if", 2) == 0
19937 || STRNCMP(p, "wh", 2) == 0
19938 || STRNCMP(p, "for", 3) == 0
19939 || STRNCMP(p, "try", 3) == 0)
19940 indent += 2;
19942 /* Check for defining a function inside this function. */
19943 if (checkforcmd(&p, "function", 2))
19945 if (*p == '!')
19946 p = skipwhite(p + 1);
19947 p += eval_fname_script(p);
19948 if (ASCII_ISALPHA(*p))
19950 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19951 if (*skipwhite(p) == '(')
19953 ++nesting;
19954 indent += 2;
19959 /* Check for ":append" or ":insert". */
19960 p = skip_range(p, NULL);
19961 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19962 || (p[0] == 'i'
19963 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19964 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19965 skip_until = vim_strsave((char_u *)".");
19967 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19968 arg = skipwhite(skiptowhite(p));
19969 if (arg[0] == '<' && arg[1] =='<'
19970 && ((p[0] == 'p' && p[1] == 'y'
19971 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19972 || (p[0] == 'p' && p[1] == 'e'
19973 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19974 || (p[0] == 't' && p[1] == 'c'
19975 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19976 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19977 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19978 || (p[0] == 'm' && p[1] == 'z'
19979 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
19982 /* ":python <<" continues until a dot, like ":append" */
19983 p = skipwhite(arg + 2);
19984 if (*p == NUL)
19985 skip_until = vim_strsave((char_u *)".");
19986 else
19987 skip_until = vim_strsave(p);
19991 /* Add the line to the function. */
19992 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
19994 if (line_arg == NULL)
19995 vim_free(theline);
19996 goto erret;
19999 /* Copy the line to newly allocated memory. get_one_sourceline()
20000 * allocates 250 bytes per line, this saves 80% on average. The cost
20001 * is an extra alloc/free. */
20002 p = vim_strsave(theline);
20003 if (p != NULL)
20005 if (line_arg == NULL)
20006 vim_free(theline);
20007 theline = p;
20010 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20012 /* Add NULL lines for continuation lines, so that the line count is
20013 * equal to the index in the growarray. */
20014 while (sourcing_lnum_off-- > 0)
20015 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20017 /* Check for end of eap->arg. */
20018 if (line_arg != NULL && *line_arg == NUL)
20019 line_arg = NULL;
20022 /* Don't define the function when skipping commands or when an error was
20023 * detected. */
20024 if (eap->skip || did_emsg)
20025 goto erret;
20028 * If there are no errors, add the function
20030 if (fudi.fd_dict == NULL)
20032 v = find_var(name, &ht);
20033 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20035 emsg_funcname("E707: Function name conflicts with variable: %s",
20036 name);
20037 goto erret;
20040 fp = find_func(name);
20041 if (fp != NULL)
20043 if (!eap->forceit)
20045 emsg_funcname(e_funcexts, name);
20046 goto erret;
20048 if (fp->uf_calls > 0)
20050 emsg_funcname("E127: Cannot redefine function %s: It is in use",
20051 name);
20052 goto erret;
20054 /* redefine existing function */
20055 ga_clear_strings(&(fp->uf_args));
20056 ga_clear_strings(&(fp->uf_lines));
20057 vim_free(name);
20058 name = NULL;
20061 else
20063 char numbuf[20];
20065 fp = NULL;
20066 if (fudi.fd_newkey == NULL && !eap->forceit)
20068 EMSG(_(e_funcdict));
20069 goto erret;
20071 if (fudi.fd_di == NULL)
20073 /* Can't add a function to a locked dictionary */
20074 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20075 goto erret;
20077 /* Can't change an existing function if it is locked */
20078 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20079 goto erret;
20081 /* Give the function a sequential number. Can only be used with a
20082 * Funcref! */
20083 vim_free(name);
20084 sprintf(numbuf, "%d", ++func_nr);
20085 name = vim_strsave((char_u *)numbuf);
20086 if (name == NULL)
20087 goto erret;
20090 if (fp == NULL)
20092 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20094 int slen, plen;
20095 char_u *scriptname;
20097 /* Check that the autoload name matches the script name. */
20098 j = FAIL;
20099 if (sourcing_name != NULL)
20101 scriptname = autoload_name(name);
20102 if (scriptname != NULL)
20104 p = vim_strchr(scriptname, '/');
20105 plen = (int)STRLEN(p);
20106 slen = (int)STRLEN(sourcing_name);
20107 if (slen > plen && fnamecmp(p,
20108 sourcing_name + slen - plen) == 0)
20109 j = OK;
20110 vim_free(scriptname);
20113 if (j == FAIL)
20115 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20116 goto erret;
20120 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20121 if (fp == NULL)
20122 goto erret;
20124 if (fudi.fd_dict != NULL)
20126 if (fudi.fd_di == NULL)
20128 /* add new dict entry */
20129 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20130 if (fudi.fd_di == NULL)
20132 vim_free(fp);
20133 goto erret;
20135 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20137 vim_free(fudi.fd_di);
20138 vim_free(fp);
20139 goto erret;
20142 else
20143 /* overwrite existing dict entry */
20144 clear_tv(&fudi.fd_di->di_tv);
20145 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20146 fudi.fd_di->di_tv.v_lock = 0;
20147 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20148 fp->uf_refcount = 1;
20150 /* behave like "dict" was used */
20151 flags |= FC_DICT;
20154 /* insert the new function in the function list */
20155 STRCPY(fp->uf_name, name);
20156 hash_add(&func_hashtab, UF2HIKEY(fp));
20158 fp->uf_args = newargs;
20159 fp->uf_lines = newlines;
20160 #ifdef FEAT_PROFILE
20161 fp->uf_tml_count = NULL;
20162 fp->uf_tml_total = NULL;
20163 fp->uf_tml_self = NULL;
20164 fp->uf_profiling = FALSE;
20165 if (prof_def_func())
20166 func_do_profile(fp);
20167 #endif
20168 fp->uf_varargs = varargs;
20169 fp->uf_flags = flags;
20170 fp->uf_calls = 0;
20171 fp->uf_script_ID = current_SID;
20172 goto ret_free;
20174 erret:
20175 ga_clear_strings(&newargs);
20176 ga_clear_strings(&newlines);
20177 ret_free:
20178 vim_free(skip_until);
20179 vim_free(fudi.fd_newkey);
20180 vim_free(name);
20181 did_emsg |= saved_did_emsg;
20185 * Get a function name, translating "<SID>" and "<SNR>".
20186 * Also handles a Funcref in a List or Dictionary.
20187 * Returns the function name in allocated memory, or NULL for failure.
20188 * flags:
20189 * TFN_INT: internal function name OK
20190 * TFN_QUIET: be quiet
20191 * Advances "pp" to just after the function name (if no error).
20193 static char_u *
20194 trans_function_name(pp, skip, flags, fdp)
20195 char_u **pp;
20196 int skip; /* only find the end, don't evaluate */
20197 int flags;
20198 funcdict_T *fdp; /* return: info about dictionary used */
20200 char_u *name = NULL;
20201 char_u *start;
20202 char_u *end;
20203 int lead;
20204 char_u sid_buf[20];
20205 int len;
20206 lval_T lv;
20208 if (fdp != NULL)
20209 vim_memset(fdp, 0, sizeof(funcdict_T));
20210 start = *pp;
20212 /* Check for hard coded <SNR>: already translated function ID (from a user
20213 * command). */
20214 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20215 && (*pp)[2] == (int)KE_SNR)
20217 *pp += 3;
20218 len = get_id_len(pp) + 3;
20219 return vim_strnsave(start, len);
20222 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20223 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20224 lead = eval_fname_script(start);
20225 if (lead > 2)
20226 start += lead;
20228 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20229 lead > 2 ? 0 : FNE_CHECK_START);
20230 if (end == start)
20232 if (!skip)
20233 EMSG(_("E129: Function name required"));
20234 goto theend;
20236 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20239 * Report an invalid expression in braces, unless the expression
20240 * evaluation has been cancelled due to an aborting error, an
20241 * interrupt, or an exception.
20243 if (!aborting())
20245 if (end != NULL)
20246 EMSG2(_(e_invarg2), start);
20248 else
20249 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20250 goto theend;
20253 if (lv.ll_tv != NULL)
20255 if (fdp != NULL)
20257 fdp->fd_dict = lv.ll_dict;
20258 fdp->fd_newkey = lv.ll_newkey;
20259 lv.ll_newkey = NULL;
20260 fdp->fd_di = lv.ll_di;
20262 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20264 name = vim_strsave(lv.ll_tv->vval.v_string);
20265 *pp = end;
20267 else
20269 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20270 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20271 EMSG(_(e_funcref));
20272 else
20273 *pp = end;
20274 name = NULL;
20276 goto theend;
20279 if (lv.ll_name == NULL)
20281 /* Error found, but continue after the function name. */
20282 *pp = end;
20283 goto theend;
20286 /* Check if the name is a Funcref. If so, use the value. */
20287 if (lv.ll_exp_name != NULL)
20289 len = (int)STRLEN(lv.ll_exp_name);
20290 name = deref_func_name(lv.ll_exp_name, &len);
20291 if (name == lv.ll_exp_name)
20292 name = NULL;
20294 else
20296 len = (int)(end - *pp);
20297 name = deref_func_name(*pp, &len);
20298 if (name == *pp)
20299 name = NULL;
20301 if (name != NULL)
20303 name = vim_strsave(name);
20304 *pp = end;
20305 goto theend;
20308 if (lv.ll_exp_name != NULL)
20310 len = (int)STRLEN(lv.ll_exp_name);
20311 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20312 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20314 /* When there was "s:" already or the name expanded to get a
20315 * leading "s:" then remove it. */
20316 lv.ll_name += 2;
20317 len -= 2;
20318 lead = 2;
20321 else
20323 if (lead == 2) /* skip over "s:" */
20324 lv.ll_name += 2;
20325 len = (int)(end - lv.ll_name);
20329 * Copy the function name to allocated memory.
20330 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20331 * Accept <SNR>123_name() outside a script.
20333 if (skip)
20334 lead = 0; /* do nothing */
20335 else if (lead > 0)
20337 lead = 3;
20338 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20339 || eval_fname_sid(*pp))
20341 /* It's "s:" or "<SID>" */
20342 if (current_SID <= 0)
20344 EMSG(_(e_usingsid));
20345 goto theend;
20347 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20348 lead += (int)STRLEN(sid_buf);
20351 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20353 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20354 goto theend;
20356 name = alloc((unsigned)(len + lead + 1));
20357 if (name != NULL)
20359 if (lead > 0)
20361 name[0] = K_SPECIAL;
20362 name[1] = KS_EXTRA;
20363 name[2] = (int)KE_SNR;
20364 if (lead > 3) /* If it's "<SID>" */
20365 STRCPY(name + 3, sid_buf);
20367 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20368 name[len + lead] = NUL;
20370 *pp = end;
20372 theend:
20373 clear_lval(&lv);
20374 return name;
20378 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20379 * Return 2 if "p" starts with "s:".
20380 * Return 0 otherwise.
20382 static int
20383 eval_fname_script(p)
20384 char_u *p;
20386 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20387 || STRNICMP(p + 1, "SNR>", 4) == 0))
20388 return 5;
20389 if (p[0] == 's' && p[1] == ':')
20390 return 2;
20391 return 0;
20395 * Return TRUE if "p" starts with "<SID>" or "s:".
20396 * Only works if eval_fname_script() returned non-zero for "p"!
20398 static int
20399 eval_fname_sid(p)
20400 char_u *p;
20402 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20406 * List the head of the function: "name(arg1, arg2)".
20408 static void
20409 list_func_head(fp, indent)
20410 ufunc_T *fp;
20411 int indent;
20413 int j;
20415 msg_start();
20416 if (indent)
20417 MSG_PUTS(" ");
20418 MSG_PUTS("function ");
20419 if (fp->uf_name[0] == K_SPECIAL)
20421 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20422 msg_puts(fp->uf_name + 3);
20424 else
20425 msg_puts(fp->uf_name);
20426 msg_putchar('(');
20427 for (j = 0; j < fp->uf_args.ga_len; ++j)
20429 if (j)
20430 MSG_PUTS(", ");
20431 msg_puts(FUNCARG(fp, j));
20433 if (fp->uf_varargs)
20435 if (j)
20436 MSG_PUTS(", ");
20437 MSG_PUTS("...");
20439 msg_putchar(')');
20440 msg_clr_eos();
20441 if (p_verbose > 0)
20442 last_set_msg(fp->uf_script_ID);
20446 * Find a function by name, return pointer to it in ufuncs.
20447 * Return NULL for unknown function.
20449 static ufunc_T *
20450 find_func(name)
20451 char_u *name;
20453 hashitem_T *hi;
20455 hi = hash_find(&func_hashtab, name);
20456 if (!HASHITEM_EMPTY(hi))
20457 return HI2UF(hi);
20458 return NULL;
20461 #if defined(EXITFREE) || defined(PROTO)
20462 void
20463 free_all_functions()
20465 hashitem_T *hi;
20467 /* Need to start all over every time, because func_free() may change the
20468 * hash table. */
20469 while (func_hashtab.ht_used > 0)
20470 for (hi = func_hashtab.ht_array; ; ++hi)
20471 if (!HASHITEM_EMPTY(hi))
20473 func_free(HI2UF(hi));
20474 break;
20477 #endif
20480 * Return TRUE if a function "name" exists.
20482 static int
20483 function_exists(name)
20484 char_u *name;
20486 char_u *nm = name;
20487 char_u *p;
20488 int n = FALSE;
20490 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20491 nm = skipwhite(nm);
20493 /* Only accept "funcname", "funcname ", "funcname (..." and
20494 * "funcname(...", not "funcname!...". */
20495 if (p != NULL && (*nm == NUL || *nm == '('))
20497 if (builtin_function(p))
20498 n = (find_internal_func(p) >= 0);
20499 else
20500 n = (find_func(p) != NULL);
20502 vim_free(p);
20503 return n;
20507 * Return TRUE if "name" looks like a builtin function name: starts with a
20508 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20510 static int
20511 builtin_function(name)
20512 char_u *name;
20514 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20515 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20518 #if defined(FEAT_PROFILE) || defined(PROTO)
20520 * Start profiling function "fp".
20522 static void
20523 func_do_profile(fp)
20524 ufunc_T *fp;
20526 fp->uf_tm_count = 0;
20527 profile_zero(&fp->uf_tm_self);
20528 profile_zero(&fp->uf_tm_total);
20529 if (fp->uf_tml_count == NULL)
20530 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20531 (sizeof(int) * fp->uf_lines.ga_len));
20532 if (fp->uf_tml_total == NULL)
20533 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20534 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20535 if (fp->uf_tml_self == NULL)
20536 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20537 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20538 fp->uf_tml_idx = -1;
20539 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20540 || fp->uf_tml_self == NULL)
20541 return; /* out of memory */
20543 fp->uf_profiling = TRUE;
20547 * Dump the profiling results for all functions in file "fd".
20549 void
20550 func_dump_profile(fd)
20551 FILE *fd;
20553 hashitem_T *hi;
20554 int todo;
20555 ufunc_T *fp;
20556 int i;
20557 ufunc_T **sorttab;
20558 int st_len = 0;
20560 todo = (int)func_hashtab.ht_used;
20561 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20563 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20565 if (!HASHITEM_EMPTY(hi))
20567 --todo;
20568 fp = HI2UF(hi);
20569 if (fp->uf_profiling)
20571 if (sorttab != NULL)
20572 sorttab[st_len++] = fp;
20574 if (fp->uf_name[0] == K_SPECIAL)
20575 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20576 else
20577 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20578 if (fp->uf_tm_count == 1)
20579 fprintf(fd, "Called 1 time\n");
20580 else
20581 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20582 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20583 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20584 fprintf(fd, "\n");
20585 fprintf(fd, "count total (s) self (s)\n");
20587 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20589 if (FUNCLINE(fp, i) == NULL)
20590 continue;
20591 prof_func_line(fd, fp->uf_tml_count[i],
20592 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20593 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20595 fprintf(fd, "\n");
20600 if (sorttab != NULL && st_len > 0)
20602 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20603 prof_total_cmp);
20604 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20605 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20606 prof_self_cmp);
20607 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20611 static void
20612 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20613 FILE *fd;
20614 ufunc_T **sorttab;
20615 int st_len;
20616 char *title;
20617 int prefer_self; /* when equal print only self time */
20619 int i;
20620 ufunc_T *fp;
20622 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20623 fprintf(fd, "count total (s) self (s) function\n");
20624 for (i = 0; i < 20 && i < st_len; ++i)
20626 fp = sorttab[i];
20627 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20628 prefer_self);
20629 if (fp->uf_name[0] == K_SPECIAL)
20630 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20631 else
20632 fprintf(fd, " %s()\n", fp->uf_name);
20634 fprintf(fd, "\n");
20638 * Print the count and times for one function or function line.
20640 static void
20641 prof_func_line(fd, count, total, self, prefer_self)
20642 FILE *fd;
20643 int count;
20644 proftime_T *total;
20645 proftime_T *self;
20646 int prefer_self; /* when equal print only self time */
20648 if (count > 0)
20650 fprintf(fd, "%5d ", count);
20651 if (prefer_self && profile_equal(total, self))
20652 fprintf(fd, " ");
20653 else
20654 fprintf(fd, "%s ", profile_msg(total));
20655 if (!prefer_self && profile_equal(total, self))
20656 fprintf(fd, " ");
20657 else
20658 fprintf(fd, "%s ", profile_msg(self));
20660 else
20661 fprintf(fd, " ");
20665 * Compare function for total time sorting.
20667 static int
20668 #ifdef __BORLANDC__
20669 _RTLENTRYF
20670 #endif
20671 prof_total_cmp(s1, s2)
20672 const void *s1;
20673 const void *s2;
20675 ufunc_T *p1, *p2;
20677 p1 = *(ufunc_T **)s1;
20678 p2 = *(ufunc_T **)s2;
20679 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20683 * Compare function for self time sorting.
20685 static int
20686 #ifdef __BORLANDC__
20687 _RTLENTRYF
20688 #endif
20689 prof_self_cmp(s1, s2)
20690 const void *s1;
20691 const void *s2;
20693 ufunc_T *p1, *p2;
20695 p1 = *(ufunc_T **)s1;
20696 p2 = *(ufunc_T **)s2;
20697 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20700 #endif
20703 * If "name" has a package name try autoloading the script for it.
20704 * Return TRUE if a package was loaded.
20706 static int
20707 script_autoload(name, reload)
20708 char_u *name;
20709 int reload; /* load script again when already loaded */
20711 char_u *p;
20712 char_u *scriptname, *tofree;
20713 int ret = FALSE;
20714 int i;
20716 /* If there is no '#' after name[0] there is no package name. */
20717 p = vim_strchr(name, AUTOLOAD_CHAR);
20718 if (p == NULL || p == name)
20719 return FALSE;
20721 tofree = scriptname = autoload_name(name);
20723 /* Find the name in the list of previously loaded package names. Skip
20724 * "autoload/", it's always the same. */
20725 for (i = 0; i < ga_loaded.ga_len; ++i)
20726 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20727 break;
20728 if (!reload && i < ga_loaded.ga_len)
20729 ret = FALSE; /* was loaded already */
20730 else
20732 /* Remember the name if it wasn't loaded already. */
20733 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20735 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20736 tofree = NULL;
20739 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20740 if (source_runtime(scriptname, FALSE) == OK)
20741 ret = TRUE;
20744 vim_free(tofree);
20745 return ret;
20749 * Return the autoload script name for a function or variable name.
20750 * Returns NULL when out of memory.
20752 static char_u *
20753 autoload_name(name)
20754 char_u *name;
20756 char_u *p;
20757 char_u *scriptname;
20759 /* Get the script file name: replace '#' with '/', append ".vim". */
20760 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20761 if (scriptname == NULL)
20762 return FALSE;
20763 STRCPY(scriptname, "autoload/");
20764 STRCAT(scriptname, name);
20765 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20766 STRCAT(scriptname, ".vim");
20767 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20768 *p = '/';
20769 return scriptname;
20772 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20775 * Function given to ExpandGeneric() to obtain the list of user defined
20776 * function names.
20778 char_u *
20779 get_user_func_name(xp, idx)
20780 expand_T *xp;
20781 int idx;
20783 static long_u done;
20784 static hashitem_T *hi;
20785 ufunc_T *fp;
20787 if (idx == 0)
20789 done = 0;
20790 hi = func_hashtab.ht_array;
20792 if (done < func_hashtab.ht_used)
20794 if (done++ > 0)
20795 ++hi;
20796 while (HASHITEM_EMPTY(hi))
20797 ++hi;
20798 fp = HI2UF(hi);
20800 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20801 return fp->uf_name; /* prevents overflow */
20803 cat_func_name(IObuff, fp);
20804 if (xp->xp_context != EXPAND_USER_FUNC)
20806 STRCAT(IObuff, "(");
20807 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20808 STRCAT(IObuff, ")");
20810 return IObuff;
20812 return NULL;
20815 #endif /* FEAT_CMDL_COMPL */
20818 * Copy the function name of "fp" to buffer "buf".
20819 * "buf" must be able to hold the function name plus three bytes.
20820 * Takes care of script-local function names.
20822 static void
20823 cat_func_name(buf, fp)
20824 char_u *buf;
20825 ufunc_T *fp;
20827 if (fp->uf_name[0] == K_SPECIAL)
20829 STRCPY(buf, "<SNR>");
20830 STRCAT(buf, fp->uf_name + 3);
20832 else
20833 STRCPY(buf, fp->uf_name);
20837 * ":delfunction {name}"
20839 void
20840 ex_delfunction(eap)
20841 exarg_T *eap;
20843 ufunc_T *fp = NULL;
20844 char_u *p;
20845 char_u *name;
20846 funcdict_T fudi;
20848 p = eap->arg;
20849 name = trans_function_name(&p, eap->skip, 0, &fudi);
20850 vim_free(fudi.fd_newkey);
20851 if (name == NULL)
20853 if (fudi.fd_dict != NULL && !eap->skip)
20854 EMSG(_(e_funcref));
20855 return;
20857 if (!ends_excmd(*skipwhite(p)))
20859 vim_free(name);
20860 EMSG(_(e_trailing));
20861 return;
20863 eap->nextcmd = check_nextcmd(p);
20864 if (eap->nextcmd != NULL)
20865 *p = NUL;
20867 if (!eap->skip)
20868 fp = find_func(name);
20869 vim_free(name);
20871 if (!eap->skip)
20873 if (fp == NULL)
20875 EMSG2(_(e_nofunc), eap->arg);
20876 return;
20878 if (fp->uf_calls > 0)
20880 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20881 return;
20884 if (fudi.fd_dict != NULL)
20886 /* Delete the dict item that refers to the function, it will
20887 * invoke func_unref() and possibly delete the function. */
20888 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20890 else
20891 func_free(fp);
20896 * Free a function and remove it from the list of functions.
20898 static void
20899 func_free(fp)
20900 ufunc_T *fp;
20902 hashitem_T *hi;
20904 /* clear this function */
20905 ga_clear_strings(&(fp->uf_args));
20906 ga_clear_strings(&(fp->uf_lines));
20907 #ifdef FEAT_PROFILE
20908 vim_free(fp->uf_tml_count);
20909 vim_free(fp->uf_tml_total);
20910 vim_free(fp->uf_tml_self);
20911 #endif
20913 /* remove the function from the function hashtable */
20914 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20915 if (HASHITEM_EMPTY(hi))
20916 EMSG2(_(e_intern2), "func_free()");
20917 else
20918 hash_remove(&func_hashtab, hi);
20920 vim_free(fp);
20924 * Unreference a Function: decrement the reference count and free it when it
20925 * becomes zero. Only for numbered functions.
20927 static void
20928 func_unref(name)
20929 char_u *name;
20931 ufunc_T *fp;
20933 if (name != NULL && isdigit(*name))
20935 fp = find_func(name);
20936 if (fp == NULL)
20937 EMSG2(_(e_intern2), "func_unref()");
20938 else if (--fp->uf_refcount <= 0)
20940 /* Only delete it when it's not being used. Otherwise it's done
20941 * when "uf_calls" becomes zero. */
20942 if (fp->uf_calls == 0)
20943 func_free(fp);
20949 * Count a reference to a Function.
20951 static void
20952 func_ref(name)
20953 char_u *name;
20955 ufunc_T *fp;
20957 if (name != NULL && isdigit(*name))
20959 fp = find_func(name);
20960 if (fp == NULL)
20961 EMSG2(_(e_intern2), "func_ref()");
20962 else
20963 ++fp->uf_refcount;
20968 * Call a user function.
20970 static void
20971 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20972 ufunc_T *fp; /* pointer to function */
20973 int argcount; /* nr of args */
20974 typval_T *argvars; /* arguments */
20975 typval_T *rettv; /* return value */
20976 linenr_T firstline; /* first line of range */
20977 linenr_T lastline; /* last line of range */
20978 dict_T *selfdict; /* Dictionary for "self" */
20980 char_u *save_sourcing_name;
20981 linenr_T save_sourcing_lnum;
20982 scid_T save_current_SID;
20983 funccall_T fc;
20984 int save_did_emsg;
20985 static int depth = 0;
20986 dictitem_T *v;
20987 int fixvar_idx = 0; /* index in fixvar[] */
20988 int i;
20989 int ai;
20990 char_u numbuf[NUMBUFLEN];
20991 char_u *name;
20992 #ifdef FEAT_PROFILE
20993 proftime_T wait_start;
20994 proftime_T call_start;
20995 #endif
20997 /* If depth of calling is getting too high, don't execute the function */
20998 if (depth >= p_mfd)
21000 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21001 rettv->v_type = VAR_NUMBER;
21002 rettv->vval.v_number = -1;
21003 return;
21005 ++depth;
21007 line_breakcheck(); /* check for CTRL-C hit */
21009 fc.caller = current_funccal;
21010 current_funccal = &fc;
21011 fc.func = fp;
21012 fc.rettv = rettv;
21013 rettv->vval.v_number = 0;
21014 fc.linenr = 0;
21015 fc.returned = FALSE;
21016 fc.level = ex_nesting_level;
21017 /* Check if this function has a breakpoint. */
21018 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21019 fc.dbg_tick = debug_tick;
21022 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
21023 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21024 * each argument variable and saves a lot of time.
21027 * Init l: variables.
21029 init_var_dict(&fc.l_vars, &fc.l_vars_var);
21030 if (selfdict != NULL)
21032 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21033 * some compiler that checks the destination size. */
21034 v = &fc.fixvar[fixvar_idx++].var;
21035 name = v->di_key;
21036 STRCPY(name, "self");
21037 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21038 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
21039 v->di_tv.v_type = VAR_DICT;
21040 v->di_tv.v_lock = 0;
21041 v->di_tv.vval.v_dict = selfdict;
21042 ++selfdict->dv_refcount;
21046 * Init a: variables.
21047 * Set a:0 to "argcount".
21048 * Set a:000 to a list with room for the "..." arguments.
21050 init_var_dict(&fc.l_avars, &fc.l_avars_var);
21051 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
21052 (varnumber_T)(argcount - fp->uf_args.ga_len));
21053 v = &fc.fixvar[fixvar_idx++].var;
21054 STRCPY(v->di_key, "000");
21055 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21056 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
21057 v->di_tv.v_type = VAR_LIST;
21058 v->di_tv.v_lock = VAR_FIXED;
21059 v->di_tv.vval.v_list = &fc.l_varlist;
21060 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
21061 fc.l_varlist.lv_refcount = 99999;
21062 fc.l_varlist.lv_lock = VAR_FIXED;
21065 * Set a:firstline to "firstline" and a:lastline to "lastline".
21066 * Set a:name to named arguments.
21067 * Set a:N to the "..." arguments.
21069 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
21070 (varnumber_T)firstline);
21071 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
21072 (varnumber_T)lastline);
21073 for (i = 0; i < argcount; ++i)
21075 ai = i - fp->uf_args.ga_len;
21076 if (ai < 0)
21077 /* named argument a:name */
21078 name = FUNCARG(fp, i);
21079 else
21081 /* "..." argument a:1, a:2, etc. */
21082 sprintf((char *)numbuf, "%d", ai + 1);
21083 name = numbuf;
21085 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21087 v = &fc.fixvar[fixvar_idx++].var;
21088 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21090 else
21092 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21093 + STRLEN(name)));
21094 if (v == NULL)
21095 break;
21096 v->di_flags = DI_FLAGS_RO;
21098 STRCPY(v->di_key, name);
21099 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
21101 /* Note: the values are copied directly to avoid alloc/free.
21102 * "argvars" must have VAR_FIXED for v_lock. */
21103 v->di_tv = argvars[i];
21104 v->di_tv.v_lock = VAR_FIXED;
21106 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21108 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
21109 fc.l_listitems[ai].li_tv = argvars[i];
21110 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21114 /* Don't redraw while executing the function. */
21115 ++RedrawingDisabled;
21116 save_sourcing_name = sourcing_name;
21117 save_sourcing_lnum = sourcing_lnum;
21118 sourcing_lnum = 1;
21119 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21120 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21121 if (sourcing_name != NULL)
21123 if (save_sourcing_name != NULL
21124 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21125 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21126 else
21127 STRCPY(sourcing_name, "function ");
21128 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21130 if (p_verbose >= 12)
21132 ++no_wait_return;
21133 verbose_enter_scroll();
21135 smsg((char_u *)_("calling %s"), sourcing_name);
21136 if (p_verbose >= 14)
21138 char_u buf[MSG_BUF_LEN];
21139 char_u numbuf2[NUMBUFLEN];
21140 char_u *tofree;
21141 char_u *s;
21143 msg_puts((char_u *)"(");
21144 for (i = 0; i < argcount; ++i)
21146 if (i > 0)
21147 msg_puts((char_u *)", ");
21148 if (argvars[i].v_type == VAR_NUMBER)
21149 msg_outnum((long)argvars[i].vval.v_number);
21150 else
21152 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21153 if (s != NULL)
21155 trunc_string(s, buf, MSG_BUF_CLEN);
21156 msg_puts(buf);
21157 vim_free(tofree);
21161 msg_puts((char_u *)")");
21163 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21165 verbose_leave_scroll();
21166 --no_wait_return;
21169 #ifdef FEAT_PROFILE
21170 if (do_profiling == PROF_YES)
21172 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21173 func_do_profile(fp);
21174 if (fp->uf_profiling
21175 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
21177 ++fp->uf_tm_count;
21178 profile_start(&call_start);
21179 profile_zero(&fp->uf_tm_children);
21181 script_prof_save(&wait_start);
21183 #endif
21185 save_current_SID = current_SID;
21186 current_SID = fp->uf_script_ID;
21187 save_did_emsg = did_emsg;
21188 did_emsg = FALSE;
21190 /* call do_cmdline() to execute the lines */
21191 do_cmdline(NULL, get_func_line, (void *)&fc,
21192 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21194 --RedrawingDisabled;
21196 /* when the function was aborted because of an error, return -1 */
21197 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21199 clear_tv(rettv);
21200 rettv->v_type = VAR_NUMBER;
21201 rettv->vval.v_number = -1;
21204 #ifdef FEAT_PROFILE
21205 if (do_profiling == PROF_YES && (fp->uf_profiling
21206 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
21208 profile_end(&call_start);
21209 profile_sub_wait(&wait_start, &call_start);
21210 profile_add(&fp->uf_tm_total, &call_start);
21211 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21212 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
21214 profile_add(&fc.caller->func->uf_tm_children, &call_start);
21215 profile_add(&fc.caller->func->uf_tml_children, &call_start);
21218 #endif
21220 /* when being verbose, mention the return value */
21221 if (p_verbose >= 12)
21223 ++no_wait_return;
21224 verbose_enter_scroll();
21226 if (aborting())
21227 smsg((char_u *)_("%s aborted"), sourcing_name);
21228 else if (fc.rettv->v_type == VAR_NUMBER)
21229 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21230 (long)fc.rettv->vval.v_number);
21231 else
21233 char_u buf[MSG_BUF_LEN];
21234 char_u numbuf2[NUMBUFLEN];
21235 char_u *tofree;
21236 char_u *s;
21238 /* The value may be very long. Skip the middle part, so that we
21239 * have some idea how it starts and ends. smsg() would always
21240 * truncate it at the end. */
21241 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
21242 if (s != NULL)
21244 trunc_string(s, buf, MSG_BUF_CLEN);
21245 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21246 vim_free(tofree);
21249 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21251 verbose_leave_scroll();
21252 --no_wait_return;
21255 vim_free(sourcing_name);
21256 sourcing_name = save_sourcing_name;
21257 sourcing_lnum = save_sourcing_lnum;
21258 current_SID = save_current_SID;
21259 #ifdef FEAT_PROFILE
21260 if (do_profiling == PROF_YES)
21261 script_prof_restore(&wait_start);
21262 #endif
21264 if (p_verbose >= 12 && sourcing_name != NULL)
21266 ++no_wait_return;
21267 verbose_enter_scroll();
21269 smsg((char_u *)_("continuing in %s"), sourcing_name);
21270 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21272 verbose_leave_scroll();
21273 --no_wait_return;
21276 did_emsg |= save_did_emsg;
21277 current_funccal = fc.caller;
21279 /* The a: variables typevals were not allocated, only free the allocated
21280 * variables. */
21281 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
21283 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
21284 --depth;
21288 * Add a number variable "name" to dict "dp" with value "nr".
21290 static void
21291 add_nr_var(dp, v, name, nr)
21292 dict_T *dp;
21293 dictitem_T *v;
21294 char *name;
21295 varnumber_T nr;
21297 STRCPY(v->di_key, name);
21298 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21299 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21300 v->di_tv.v_type = VAR_NUMBER;
21301 v->di_tv.v_lock = VAR_FIXED;
21302 v->di_tv.vval.v_number = nr;
21306 * ":return [expr]"
21308 void
21309 ex_return(eap)
21310 exarg_T *eap;
21312 char_u *arg = eap->arg;
21313 typval_T rettv;
21314 int returning = FALSE;
21316 if (current_funccal == NULL)
21318 EMSG(_("E133: :return not inside a function"));
21319 return;
21322 if (eap->skip)
21323 ++emsg_skip;
21325 eap->nextcmd = NULL;
21326 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21327 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21329 if (!eap->skip)
21330 returning = do_return(eap, FALSE, TRUE, &rettv);
21331 else
21332 clear_tv(&rettv);
21334 /* It's safer to return also on error. */
21335 else if (!eap->skip)
21338 * Return unless the expression evaluation has been cancelled due to an
21339 * aborting error, an interrupt, or an exception.
21341 if (!aborting())
21342 returning = do_return(eap, FALSE, TRUE, NULL);
21345 /* When skipping or the return gets pending, advance to the next command
21346 * in this line (!returning). Otherwise, ignore the rest of the line.
21347 * Following lines will be ignored by get_func_line(). */
21348 if (returning)
21349 eap->nextcmd = NULL;
21350 else if (eap->nextcmd == NULL) /* no argument */
21351 eap->nextcmd = check_nextcmd(arg);
21353 if (eap->skip)
21354 --emsg_skip;
21358 * Return from a function. Possibly makes the return pending. Also called
21359 * for a pending return at the ":endtry" or after returning from an extra
21360 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21361 * when called due to a ":return" command. "rettv" may point to a typval_T
21362 * with the return rettv. Returns TRUE when the return can be carried out,
21363 * FALSE when the return gets pending.
21366 do_return(eap, reanimate, is_cmd, rettv)
21367 exarg_T *eap;
21368 int reanimate;
21369 int is_cmd;
21370 void *rettv;
21372 int idx;
21373 struct condstack *cstack = eap->cstack;
21375 if (reanimate)
21376 /* Undo the return. */
21377 current_funccal->returned = FALSE;
21380 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21381 * not in its finally clause (which then is to be executed next) is found.
21382 * In this case, make the ":return" pending for execution at the ":endtry".
21383 * Otherwise, return normally.
21385 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21386 if (idx >= 0)
21388 cstack->cs_pending[idx] = CSTP_RETURN;
21390 if (!is_cmd && !reanimate)
21391 /* A pending return again gets pending. "rettv" points to an
21392 * allocated variable with the rettv of the original ":return"'s
21393 * argument if present or is NULL else. */
21394 cstack->cs_rettv[idx] = rettv;
21395 else
21397 /* When undoing a return in order to make it pending, get the stored
21398 * return rettv. */
21399 if (reanimate)
21400 rettv = current_funccal->rettv;
21402 if (rettv != NULL)
21404 /* Store the value of the pending return. */
21405 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21406 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21407 else
21408 EMSG(_(e_outofmem));
21410 else
21411 cstack->cs_rettv[idx] = NULL;
21413 if (reanimate)
21415 /* The pending return value could be overwritten by a ":return"
21416 * without argument in a finally clause; reset the default
21417 * return value. */
21418 current_funccal->rettv->v_type = VAR_NUMBER;
21419 current_funccal->rettv->vval.v_number = 0;
21422 report_make_pending(CSTP_RETURN, rettv);
21424 else
21426 current_funccal->returned = TRUE;
21428 /* If the return is carried out now, store the return value. For
21429 * a return immediately after reanimation, the value is already
21430 * there. */
21431 if (!reanimate && rettv != NULL)
21433 clear_tv(current_funccal->rettv);
21434 *current_funccal->rettv = *(typval_T *)rettv;
21435 if (!is_cmd)
21436 vim_free(rettv);
21440 return idx < 0;
21444 * Free the variable with a pending return value.
21446 void
21447 discard_pending_return(rettv)
21448 void *rettv;
21450 free_tv((typval_T *)rettv);
21454 * Generate a return command for producing the value of "rettv". The result
21455 * is an allocated string. Used by report_pending() for verbose messages.
21457 char_u *
21458 get_return_cmd(rettv)
21459 void *rettv;
21461 char_u *s = NULL;
21462 char_u *tofree = NULL;
21463 char_u numbuf[NUMBUFLEN];
21465 if (rettv != NULL)
21466 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21467 if (s == NULL)
21468 s = (char_u *)"";
21470 STRCPY(IObuff, ":return ");
21471 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21472 if (STRLEN(s) + 8 >= IOSIZE)
21473 STRCPY(IObuff + IOSIZE - 4, "...");
21474 vim_free(tofree);
21475 return vim_strsave(IObuff);
21479 * Get next function line.
21480 * Called by do_cmdline() to get the next line.
21481 * Returns allocated string, or NULL for end of function.
21483 /* ARGSUSED */
21484 char_u *
21485 get_func_line(c, cookie, indent)
21486 int c; /* not used */
21487 void *cookie;
21488 int indent; /* not used */
21490 funccall_T *fcp = (funccall_T *)cookie;
21491 ufunc_T *fp = fcp->func;
21492 char_u *retval;
21493 garray_T *gap; /* growarray with function lines */
21495 /* If breakpoints have been added/deleted need to check for it. */
21496 if (fcp->dbg_tick != debug_tick)
21498 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21499 sourcing_lnum);
21500 fcp->dbg_tick = debug_tick;
21502 #ifdef FEAT_PROFILE
21503 if (do_profiling == PROF_YES)
21504 func_line_end(cookie);
21505 #endif
21507 gap = &fp->uf_lines;
21508 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21509 || fcp->returned)
21510 retval = NULL;
21511 else
21513 /* Skip NULL lines (continuation lines). */
21514 while (fcp->linenr < gap->ga_len
21515 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21516 ++fcp->linenr;
21517 if (fcp->linenr >= gap->ga_len)
21518 retval = NULL;
21519 else
21521 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21522 sourcing_lnum = fcp->linenr;
21523 #ifdef FEAT_PROFILE
21524 if (do_profiling == PROF_YES)
21525 func_line_start(cookie);
21526 #endif
21530 /* Did we encounter a breakpoint? */
21531 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21533 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21534 /* Find next breakpoint. */
21535 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21536 sourcing_lnum);
21537 fcp->dbg_tick = debug_tick;
21540 return retval;
21543 #if defined(FEAT_PROFILE) || defined(PROTO)
21545 * Called when starting to read a function line.
21546 * "sourcing_lnum" must be correct!
21547 * When skipping lines it may not actually be executed, but we won't find out
21548 * until later and we need to store the time now.
21550 void
21551 func_line_start(cookie)
21552 void *cookie;
21554 funccall_T *fcp = (funccall_T *)cookie;
21555 ufunc_T *fp = fcp->func;
21557 if (fp->uf_profiling && sourcing_lnum >= 1
21558 && sourcing_lnum <= fp->uf_lines.ga_len)
21560 fp->uf_tml_idx = sourcing_lnum - 1;
21561 /* Skip continuation lines. */
21562 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21563 --fp->uf_tml_idx;
21564 fp->uf_tml_execed = FALSE;
21565 profile_start(&fp->uf_tml_start);
21566 profile_zero(&fp->uf_tml_children);
21567 profile_get_wait(&fp->uf_tml_wait);
21572 * Called when actually executing a function line.
21574 void
21575 func_line_exec(cookie)
21576 void *cookie;
21578 funccall_T *fcp = (funccall_T *)cookie;
21579 ufunc_T *fp = fcp->func;
21581 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21582 fp->uf_tml_execed = TRUE;
21586 * Called when done with a function line.
21588 void
21589 func_line_end(cookie)
21590 void *cookie;
21592 funccall_T *fcp = (funccall_T *)cookie;
21593 ufunc_T *fp = fcp->func;
21595 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21597 if (fp->uf_tml_execed)
21599 ++fp->uf_tml_count[fp->uf_tml_idx];
21600 profile_end(&fp->uf_tml_start);
21601 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21602 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21603 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21604 &fp->uf_tml_children);
21606 fp->uf_tml_idx = -1;
21609 #endif
21612 * Return TRUE if the currently active function should be ended, because a
21613 * return was encountered or an error occurred. Used inside a ":while".
21616 func_has_ended(cookie)
21617 void *cookie;
21619 funccall_T *fcp = (funccall_T *)cookie;
21621 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21622 * an error inside a try conditional. */
21623 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21624 || fcp->returned);
21628 * return TRUE if cookie indicates a function which "abort"s on errors.
21631 func_has_abort(cookie)
21632 void *cookie;
21634 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21637 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21638 typedef enum
21640 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21641 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21642 VAR_FLAVOUR_VIMINFO /* all uppercase */
21643 } var_flavour_T;
21645 static var_flavour_T var_flavour __ARGS((char_u *varname));
21647 static var_flavour_T
21648 var_flavour(varname)
21649 char_u *varname;
21651 char_u *p = varname;
21653 if (ASCII_ISUPPER(*p))
21655 while (*(++p))
21656 if (ASCII_ISLOWER(*p))
21657 return VAR_FLAVOUR_SESSION;
21658 return VAR_FLAVOUR_VIMINFO;
21660 else
21661 return VAR_FLAVOUR_DEFAULT;
21663 #endif
21665 #if defined(FEAT_VIMINFO) || defined(PROTO)
21667 * Restore global vars that start with a capital from the viminfo file
21670 read_viminfo_varlist(virp, writing)
21671 vir_T *virp;
21672 int writing;
21674 char_u *tab;
21675 int type = VAR_NUMBER;
21676 typval_T tv;
21678 if (!writing && (find_viminfo_parameter('!') != NULL))
21680 tab = vim_strchr(virp->vir_line + 1, '\t');
21681 if (tab != NULL)
21683 *tab++ = '\0'; /* isolate the variable name */
21684 if (*tab == 'S') /* string var */
21685 type = VAR_STRING;
21686 #ifdef FEAT_FLOAT
21687 else if (*tab == 'F')
21688 type = VAR_FLOAT;
21689 #endif
21691 tab = vim_strchr(tab, '\t');
21692 if (tab != NULL)
21694 tv.v_type = type;
21695 if (type == VAR_STRING)
21696 tv.vval.v_string = viminfo_readstring(virp,
21697 (int)(tab - virp->vir_line + 1), TRUE);
21698 #ifdef FEAT_FLOAT
21699 else if (type == VAR_FLOAT)
21700 (void)string2float(tab + 1, &tv.vval.v_float);
21701 #endif
21702 else
21703 tv.vval.v_number = atol((char *)tab + 1);
21704 set_var(virp->vir_line + 1, &tv, FALSE);
21705 if (type == VAR_STRING)
21706 vim_free(tv.vval.v_string);
21711 return viminfo_readline(virp);
21715 * Write global vars that start with a capital to the viminfo file
21717 void
21718 write_viminfo_varlist(fp)
21719 FILE *fp;
21721 hashitem_T *hi;
21722 dictitem_T *this_var;
21723 int todo;
21724 char *s;
21725 char_u *p;
21726 char_u *tofree;
21727 char_u numbuf[NUMBUFLEN];
21729 if (find_viminfo_parameter('!') == NULL)
21730 return;
21732 fprintf(fp, _("\n# global variables:\n"));
21734 todo = (int)globvarht.ht_used;
21735 for (hi = globvarht.ht_array; todo > 0; ++hi)
21737 if (!HASHITEM_EMPTY(hi))
21739 --todo;
21740 this_var = HI2DI(hi);
21741 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21743 switch (this_var->di_tv.v_type)
21745 case VAR_STRING: s = "STR"; break;
21746 case VAR_NUMBER: s = "NUM"; break;
21747 #ifdef FEAT_FLOAT
21748 case VAR_FLOAT: s = "FLO"; break;
21749 #endif
21750 default: continue;
21752 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21753 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21754 if (p != NULL)
21755 viminfo_writestring(fp, p);
21756 vim_free(tofree);
21761 #endif
21763 #if defined(FEAT_SESSION) || defined(PROTO)
21765 store_session_globals(fd)
21766 FILE *fd;
21768 hashitem_T *hi;
21769 dictitem_T *this_var;
21770 int todo;
21771 char_u *p, *t;
21773 todo = (int)globvarht.ht_used;
21774 for (hi = globvarht.ht_array; todo > 0; ++hi)
21776 if (!HASHITEM_EMPTY(hi))
21778 --todo;
21779 this_var = HI2DI(hi);
21780 if ((this_var->di_tv.v_type == VAR_NUMBER
21781 || this_var->di_tv.v_type == VAR_STRING)
21782 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21784 /* Escape special characters with a backslash. Turn a LF and
21785 * CR into \n and \r. */
21786 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
21787 (char_u *)"\\\"\n\r");
21788 if (p == NULL) /* out of memory */
21789 break;
21790 for (t = p; *t != NUL; ++t)
21791 if (*t == '\n')
21792 *t = 'n';
21793 else if (*t == '\r')
21794 *t = 'r';
21795 if ((fprintf(fd, "let %s = %c%s%c",
21796 this_var->di_key,
21797 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21798 : ' ',
21800 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21801 : ' ') < 0)
21802 || put_eol(fd) == FAIL)
21804 vim_free(p);
21805 return FAIL;
21807 vim_free(p);
21809 #ifdef FEAT_FLOAT
21810 else if (this_var->di_tv.v_type == VAR_FLOAT
21811 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21813 float_T f = this_var->di_tv.vval.v_float;
21814 int sign = ' ';
21816 if (f < 0)
21818 f = -f;
21819 sign = '-';
21821 if ((fprintf(fd, "let %s = %c&%f",
21822 this_var->di_key, sign, f) < 0)
21823 || put_eol(fd) == FAIL)
21824 return FAIL;
21826 #endif
21829 return OK;
21831 #endif
21834 * Display script name where an item was last set.
21835 * Should only be invoked when 'verbose' is non-zero.
21837 void
21838 last_set_msg(scriptID)
21839 scid_T scriptID;
21841 char_u *p;
21843 if (scriptID != 0)
21845 p = home_replace_save(NULL, get_scriptname(scriptID));
21846 if (p != NULL)
21848 verbose_enter();
21849 MSG_PUTS(_("\n\tLast set from "));
21850 MSG_PUTS(p);
21851 vim_free(p);
21852 verbose_leave();
21857 #endif /* FEAT_EVAL */
21860 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
21862 #ifdef WIN3264
21864 * Functions for ":8" filename modifier: get 8.3 version of a filename.
21866 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21867 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
21868 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21871 * Get the short path (8.3) for the filename in "fnamep".
21872 * Only works for a valid file name.
21873 * When the path gets longer "fnamep" is changed and the allocated buffer
21874 * is put in "bufp".
21875 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
21876 * Returns OK on success, FAIL on failure.
21878 static int
21879 get_short_pathname(fnamep, bufp, fnamelen)
21880 char_u **fnamep;
21881 char_u **bufp;
21882 int *fnamelen;
21884 int l, len;
21885 char_u *newbuf;
21887 len = *fnamelen;
21888 l = GetShortPathName(*fnamep, *fnamep, len);
21889 if (l > len - 1)
21891 /* If that doesn't work (not enough space), then save the string
21892 * and try again with a new buffer big enough. */
21893 newbuf = vim_strnsave(*fnamep, l);
21894 if (newbuf == NULL)
21895 return FAIL;
21897 vim_free(*bufp);
21898 *fnamep = *bufp = newbuf;
21900 /* Really should always succeed, as the buffer is big enough. */
21901 l = GetShortPathName(*fnamep, *fnamep, l+1);
21904 *fnamelen = l;
21905 return OK;
21909 * Get the short path (8.3) for the filename in "fname". The converted
21910 * path is returned in "bufp".
21912 * Some of the directories specified in "fname" may not exist. This function
21913 * will shorten the existing directories at the beginning of the path and then
21914 * append the remaining non-existing path.
21916 * fname - Pointer to the filename to shorten. On return, contains the
21917 * pointer to the shortened pathname
21918 * bufp - Pointer to an allocated buffer for the filename.
21919 * fnamelen - Length of the filename pointed to by fname
21921 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
21923 static int
21924 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21925 char_u **fname;
21926 char_u **bufp;
21927 int *fnamelen;
21929 char_u *short_fname, *save_fname, *pbuf_unused;
21930 char_u *endp, *save_endp;
21931 char_u ch;
21932 int old_len, len;
21933 int new_len, sfx_len;
21934 int retval = OK;
21936 /* Make a copy */
21937 old_len = *fnamelen;
21938 save_fname = vim_strnsave(*fname, old_len);
21939 pbuf_unused = NULL;
21940 short_fname = NULL;
21942 endp = save_fname + old_len - 1; /* Find the end of the copy */
21943 save_endp = endp;
21946 * Try shortening the supplied path till it succeeds by removing one
21947 * directory at a time from the tail of the path.
21949 len = 0;
21950 for (;;)
21952 /* go back one path-separator */
21953 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
21954 --endp;
21955 if (endp <= save_fname)
21956 break; /* processed the complete path */
21959 * Replace the path separator with a NUL and try to shorten the
21960 * resulting path.
21962 ch = *endp;
21963 *endp = 0;
21964 short_fname = save_fname;
21965 len = STRLEN(short_fname) + 1;
21966 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
21968 retval = FAIL;
21969 goto theend;
21971 *endp = ch; /* preserve the string */
21973 if (len > 0)
21974 break; /* successfully shortened the path */
21976 /* failed to shorten the path. Skip the path separator */
21977 --endp;
21980 if (len > 0)
21983 * Succeeded in shortening the path. Now concatenate the shortened
21984 * path with the remaining path at the tail.
21987 /* Compute the length of the new path. */
21988 sfx_len = (int)(save_endp - endp) + 1;
21989 new_len = len + sfx_len;
21991 *fnamelen = new_len;
21992 vim_free(*bufp);
21993 if (new_len > old_len)
21995 /* There is not enough space in the currently allocated string,
21996 * copy it to a buffer big enough. */
21997 *fname = *bufp = vim_strnsave(short_fname, new_len);
21998 if (*fname == NULL)
22000 retval = FAIL;
22001 goto theend;
22004 else
22006 /* Transfer short_fname to the main buffer (it's big enough),
22007 * unless get_short_pathname() did its work in-place. */
22008 *fname = *bufp = save_fname;
22009 if (short_fname != save_fname)
22010 vim_strncpy(save_fname, short_fname, len);
22011 save_fname = NULL;
22014 /* concat the not-shortened part of the path */
22015 vim_strncpy(*fname + len, endp, sfx_len);
22016 (*fname)[new_len] = NUL;
22019 theend:
22020 vim_free(pbuf_unused);
22021 vim_free(save_fname);
22023 return retval;
22027 * Get a pathname for a partial path.
22028 * Returns OK for success, FAIL for failure.
22030 static int
22031 shortpath_for_partial(fnamep, bufp, fnamelen)
22032 char_u **fnamep;
22033 char_u **bufp;
22034 int *fnamelen;
22036 int sepcount, len, tflen;
22037 char_u *p;
22038 char_u *pbuf, *tfname;
22039 int hasTilde;
22041 /* Count up the path separators from the RHS.. so we know which part
22042 * of the path to return. */
22043 sepcount = 0;
22044 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22045 if (vim_ispathsep(*p))
22046 ++sepcount;
22048 /* Need full path first (use expand_env() to remove a "~/") */
22049 hasTilde = (**fnamep == '~');
22050 if (hasTilde)
22051 pbuf = tfname = expand_env_save(*fnamep);
22052 else
22053 pbuf = tfname = FullName_save(*fnamep, FALSE);
22055 len = tflen = (int)STRLEN(tfname);
22057 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22058 return FAIL;
22060 if (len == 0)
22062 /* Don't have a valid filename, so shorten the rest of the
22063 * path if we can. This CAN give us invalid 8.3 filenames, but
22064 * there's not a lot of point in guessing what it might be.
22066 len = tflen;
22067 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22068 return FAIL;
22071 /* Count the paths backward to find the beginning of the desired string. */
22072 for (p = tfname + len - 1; p >= tfname; --p)
22074 #ifdef FEAT_MBYTE
22075 if (has_mbyte)
22076 p -= mb_head_off(tfname, p);
22077 #endif
22078 if (vim_ispathsep(*p))
22080 if (sepcount == 0 || (hasTilde && sepcount == 1))
22081 break;
22082 else
22083 sepcount --;
22086 if (hasTilde)
22088 --p;
22089 if (p >= tfname)
22090 *p = '~';
22091 else
22092 return FAIL;
22094 else
22095 ++p;
22097 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22098 vim_free(*bufp);
22099 *fnamelen = (int)STRLEN(p);
22100 *bufp = pbuf;
22101 *fnamep = p;
22103 return OK;
22105 #endif /* WIN3264 */
22108 * Adjust a filename, according to a string of modifiers.
22109 * *fnamep must be NUL terminated when called. When returning, the length is
22110 * determined by *fnamelen.
22111 * Returns VALID_ flags or -1 for failure.
22112 * When there is an error, *fnamep is set to NULL.
22115 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22116 char_u *src; /* string with modifiers */
22117 int *usedlen; /* characters after src that are used */
22118 char_u **fnamep; /* file name so far */
22119 char_u **bufp; /* buffer for allocated file name or NULL */
22120 int *fnamelen; /* length of fnamep */
22122 int valid = 0;
22123 char_u *tail;
22124 char_u *s, *p, *pbuf;
22125 char_u dirname[MAXPATHL];
22126 int c;
22127 int has_fullname = 0;
22128 #ifdef WIN3264
22129 int has_shortname = 0;
22130 #endif
22132 repeat:
22133 /* ":p" - full path/file_name */
22134 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22136 has_fullname = 1;
22138 valid |= VALID_PATH;
22139 *usedlen += 2;
22141 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22142 if ((*fnamep)[0] == '~'
22143 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22144 && ((*fnamep)[1] == '/'
22145 # ifdef BACKSLASH_IN_FILENAME
22146 || (*fnamep)[1] == '\\'
22147 # endif
22148 || (*fnamep)[1] == NUL)
22150 #endif
22153 *fnamep = expand_env_save(*fnamep);
22154 vim_free(*bufp); /* free any allocated file name */
22155 *bufp = *fnamep;
22156 if (*fnamep == NULL)
22157 return -1;
22160 /* When "/." or "/.." is used: force expansion to get rid of it. */
22161 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22163 if (vim_ispathsep(*p)
22164 && p[1] == '.'
22165 && (p[2] == NUL
22166 || vim_ispathsep(p[2])
22167 || (p[2] == '.'
22168 && (p[3] == NUL || vim_ispathsep(p[3])))))
22169 break;
22172 /* FullName_save() is slow, don't use it when not needed. */
22173 if (*p != NUL || !vim_isAbsName(*fnamep))
22175 *fnamep = FullName_save(*fnamep, *p != NUL);
22176 vim_free(*bufp); /* free any allocated file name */
22177 *bufp = *fnamep;
22178 if (*fnamep == NULL)
22179 return -1;
22182 /* Append a path separator to a directory. */
22183 if (mch_isdir(*fnamep))
22185 /* Make room for one or two extra characters. */
22186 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22187 vim_free(*bufp); /* free any allocated file name */
22188 *bufp = *fnamep;
22189 if (*fnamep == NULL)
22190 return -1;
22191 add_pathsep(*fnamep);
22195 /* ":." - path relative to the current directory */
22196 /* ":~" - path relative to the home directory */
22197 /* ":8" - shortname path - postponed till after */
22198 while (src[*usedlen] == ':'
22199 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22201 *usedlen += 2;
22202 if (c == '8')
22204 #ifdef WIN3264
22205 has_shortname = 1; /* Postpone this. */
22206 #endif
22207 continue;
22209 pbuf = NULL;
22210 /* Need full path first (use expand_env() to remove a "~/") */
22211 if (!has_fullname)
22213 if (c == '.' && **fnamep == '~')
22214 p = pbuf = expand_env_save(*fnamep);
22215 else
22216 p = pbuf = FullName_save(*fnamep, FALSE);
22218 else
22219 p = *fnamep;
22221 has_fullname = 0;
22223 if (p != NULL)
22225 if (c == '.')
22227 mch_dirname(dirname, MAXPATHL);
22228 s = shorten_fname(p, dirname);
22229 if (s != NULL)
22231 *fnamep = s;
22232 if (pbuf != NULL)
22234 vim_free(*bufp); /* free any allocated file name */
22235 *bufp = pbuf;
22236 pbuf = NULL;
22240 else
22242 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22243 /* Only replace it when it starts with '~' */
22244 if (*dirname == '~')
22246 s = vim_strsave(dirname);
22247 if (s != NULL)
22249 *fnamep = s;
22250 vim_free(*bufp);
22251 *bufp = s;
22255 vim_free(pbuf);
22259 tail = gettail(*fnamep);
22260 *fnamelen = (int)STRLEN(*fnamep);
22262 /* ":h" - head, remove "/file_name", can be repeated */
22263 /* Don't remove the first "/" or "c:\" */
22264 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22266 valid |= VALID_HEAD;
22267 *usedlen += 2;
22268 s = get_past_head(*fnamep);
22269 while (tail > s && after_pathsep(s, tail))
22270 mb_ptr_back(*fnamep, tail);
22271 *fnamelen = (int)(tail - *fnamep);
22272 #ifdef VMS
22273 if (*fnamelen > 0)
22274 *fnamelen += 1; /* the path separator is part of the path */
22275 #endif
22276 if (*fnamelen == 0)
22278 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22279 p = vim_strsave((char_u *)".");
22280 if (p == NULL)
22281 return -1;
22282 vim_free(*bufp);
22283 *bufp = *fnamep = tail = p;
22284 *fnamelen = 1;
22286 else
22288 while (tail > s && !after_pathsep(s, tail))
22289 mb_ptr_back(*fnamep, tail);
22293 /* ":8" - shortname */
22294 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22296 *usedlen += 2;
22297 #ifdef WIN3264
22298 has_shortname = 1;
22299 #endif
22302 #ifdef WIN3264
22303 /* Check shortname after we have done 'heads' and before we do 'tails'
22305 if (has_shortname)
22307 pbuf = NULL;
22308 /* Copy the string if it is shortened by :h */
22309 if (*fnamelen < (int)STRLEN(*fnamep))
22311 p = vim_strnsave(*fnamep, *fnamelen);
22312 if (p == 0)
22313 return -1;
22314 vim_free(*bufp);
22315 *bufp = *fnamep = p;
22318 /* Split into two implementations - makes it easier. First is where
22319 * there isn't a full name already, second is where there is.
22321 if (!has_fullname && !vim_isAbsName(*fnamep))
22323 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22324 return -1;
22326 else
22328 int l;
22330 /* Simple case, already have the full-name
22331 * Nearly always shorter, so try first time. */
22332 l = *fnamelen;
22333 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22334 return -1;
22336 if (l == 0)
22338 /* Couldn't find the filename.. search the paths.
22340 l = *fnamelen;
22341 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22342 return -1;
22344 *fnamelen = l;
22347 #endif /* WIN3264 */
22349 /* ":t" - tail, just the basename */
22350 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22352 *usedlen += 2;
22353 *fnamelen -= (int)(tail - *fnamep);
22354 *fnamep = tail;
22357 /* ":e" - extension, can be repeated */
22358 /* ":r" - root, without extension, can be repeated */
22359 while (src[*usedlen] == ':'
22360 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22362 /* find a '.' in the tail:
22363 * - for second :e: before the current fname
22364 * - otherwise: The last '.'
22366 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22367 s = *fnamep - 2;
22368 else
22369 s = *fnamep + *fnamelen - 1;
22370 for ( ; s > tail; --s)
22371 if (s[0] == '.')
22372 break;
22373 if (src[*usedlen + 1] == 'e') /* :e */
22375 if (s > tail)
22377 *fnamelen += (int)(*fnamep - (s + 1));
22378 *fnamep = s + 1;
22379 #ifdef VMS
22380 /* cut version from the extension */
22381 s = *fnamep + *fnamelen - 1;
22382 for ( ; s > *fnamep; --s)
22383 if (s[0] == ';')
22384 break;
22385 if (s > *fnamep)
22386 *fnamelen = s - *fnamep;
22387 #endif
22389 else if (*fnamep <= tail)
22390 *fnamelen = 0;
22392 else /* :r */
22394 if (s > tail) /* remove one extension */
22395 *fnamelen = (int)(s - *fnamep);
22397 *usedlen += 2;
22400 /* ":s?pat?foo?" - substitute */
22401 /* ":gs?pat?foo?" - global substitute */
22402 if (src[*usedlen] == ':'
22403 && (src[*usedlen + 1] == 's'
22404 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22406 char_u *str;
22407 char_u *pat;
22408 char_u *sub;
22409 int sep;
22410 char_u *flags;
22411 int didit = FALSE;
22413 flags = (char_u *)"";
22414 s = src + *usedlen + 2;
22415 if (src[*usedlen + 1] == 'g')
22417 flags = (char_u *)"g";
22418 ++s;
22421 sep = *s++;
22422 if (sep)
22424 /* find end of pattern */
22425 p = vim_strchr(s, sep);
22426 if (p != NULL)
22428 pat = vim_strnsave(s, (int)(p - s));
22429 if (pat != NULL)
22431 s = p + 1;
22432 /* find end of substitution */
22433 p = vim_strchr(s, sep);
22434 if (p != NULL)
22436 sub = vim_strnsave(s, (int)(p - s));
22437 str = vim_strnsave(*fnamep, *fnamelen);
22438 if (sub != NULL && str != NULL)
22440 *usedlen = (int)(p + 1 - src);
22441 s = do_string_sub(str, pat, sub, flags);
22442 if (s != NULL)
22444 *fnamep = s;
22445 *fnamelen = (int)STRLEN(s);
22446 vim_free(*bufp);
22447 *bufp = s;
22448 didit = TRUE;
22451 vim_free(sub);
22452 vim_free(str);
22454 vim_free(pat);
22457 /* after using ":s", repeat all the modifiers */
22458 if (didit)
22459 goto repeat;
22463 return valid;
22467 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22468 * "flags" can be "g" to do a global substitute.
22469 * Returns an allocated string, NULL for error.
22471 char_u *
22472 do_string_sub(str, pat, sub, flags)
22473 char_u *str;
22474 char_u *pat;
22475 char_u *sub;
22476 char_u *flags;
22478 int sublen;
22479 regmatch_T regmatch;
22480 int i;
22481 int do_all;
22482 char_u *tail;
22483 garray_T ga;
22484 char_u *ret;
22485 char_u *save_cpo;
22487 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22488 save_cpo = p_cpo;
22489 p_cpo = (char_u *)"";
22491 ga_init2(&ga, 1, 200);
22493 do_all = (flags[0] == 'g');
22495 regmatch.rm_ic = p_ic;
22496 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22497 if (regmatch.regprog != NULL)
22499 tail = str;
22500 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22503 * Get some space for a temporary buffer to do the substitution
22504 * into. It will contain:
22505 * - The text up to where the match is.
22506 * - The substituted text.
22507 * - The text after the match.
22509 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22510 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22511 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22513 ga_clear(&ga);
22514 break;
22517 /* copy the text up to where the match is */
22518 i = (int)(regmatch.startp[0] - tail);
22519 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22520 /* add the substituted text */
22521 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22522 + ga.ga_len + i, TRUE, TRUE, FALSE);
22523 ga.ga_len += i + sublen - 1;
22524 /* avoid getting stuck on a match with an empty string */
22525 if (tail == regmatch.endp[0])
22527 if (*tail == NUL)
22528 break;
22529 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22530 ++ga.ga_len;
22532 else
22534 tail = regmatch.endp[0];
22535 if (*tail == NUL)
22536 break;
22538 if (!do_all)
22539 break;
22542 if (ga.ga_data != NULL)
22543 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22545 vim_free(regmatch.regprog);
22548 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22549 ga_clear(&ga);
22550 p_cpo = save_cpo;
22552 return ret;
22555 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */