Marked text baseline adjusts for 'linespace' and font baseline
[MacVim.git] / src / eval.c
blob3cb64c0063d1eb1b246914f0a8f389544834bf6f
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) || defined(FEAT_GUI_MACVIM)
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_FULLSCREEN
11451 "fullscreen",
11452 #endif
11453 #ifdef FEAT_GETTEXT
11454 "gettext",
11455 #endif
11456 #ifdef FEAT_GUI
11457 "gui",
11458 #endif
11459 #ifdef FEAT_GUI_ATHENA
11460 # ifdef FEAT_GUI_NEXTAW
11461 "gui_neXtaw",
11462 # else
11463 "gui_athena",
11464 # endif
11465 #endif
11466 #ifdef FEAT_GUI_GTK
11467 "gui_gtk",
11468 # ifdef HAVE_GTK2
11469 "gui_gtk2",
11470 # endif
11471 #endif
11472 #ifdef FEAT_GUI_GNOME
11473 "gui_gnome",
11474 #endif
11475 #ifdef FEAT_GUI_MAC
11476 "gui_mac",
11477 #endif
11478 #ifdef FEAT_GUI_MACVIM
11479 "gui_macvim",
11480 #endif
11481 #ifdef FEAT_GUI_MOTIF
11482 "gui_motif",
11483 #endif
11484 #ifdef FEAT_GUI_PHOTON
11485 "gui_photon",
11486 #endif
11487 #ifdef FEAT_GUI_W16
11488 "gui_win16",
11489 #endif
11490 #ifdef FEAT_GUI_W32
11491 "gui_win32",
11492 #endif
11493 #ifdef FEAT_HANGULIN
11494 "hangul_input",
11495 #endif
11496 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11497 "iconv",
11498 #endif
11499 #ifdef FEAT_INS_EXPAND
11500 "insert_expand",
11501 #endif
11502 #ifdef FEAT_JUMPLIST
11503 "jumplist",
11504 #endif
11505 #ifdef FEAT_KEYMAP
11506 "keymap",
11507 #endif
11508 #ifdef FEAT_LANGMAP
11509 "langmap",
11510 #endif
11511 #ifdef FEAT_LIBCALL
11512 "libcall",
11513 #endif
11514 #ifdef FEAT_LINEBREAK
11515 "linebreak",
11516 #endif
11517 #ifdef FEAT_LISP
11518 "lispindent",
11519 #endif
11520 #ifdef FEAT_LISTCMDS
11521 "listcmds",
11522 #endif
11523 #ifdef FEAT_LOCALMAP
11524 "localmap",
11525 #endif
11526 #ifdef FEAT_MENU
11527 "menu",
11528 #endif
11529 #ifdef FEAT_SESSION
11530 "mksession",
11531 #endif
11532 #ifdef FEAT_MODIFY_FNAME
11533 "modify_fname",
11534 #endif
11535 #ifdef FEAT_MOUSE
11536 "mouse",
11537 #endif
11538 #ifdef FEAT_MOUSESHAPE
11539 "mouseshape",
11540 #endif
11541 #if defined(UNIX) || defined(VMS)
11542 # ifdef FEAT_MOUSE_DEC
11543 "mouse_dec",
11544 # endif
11545 # ifdef FEAT_MOUSE_GPM
11546 "mouse_gpm",
11547 # endif
11548 # ifdef FEAT_MOUSE_JSB
11549 "mouse_jsbterm",
11550 # endif
11551 # ifdef FEAT_MOUSE_NET
11552 "mouse_netterm",
11553 # endif
11554 # ifdef FEAT_MOUSE_PTERM
11555 "mouse_pterm",
11556 # endif
11557 # ifdef FEAT_SYSMOUSE
11558 "mouse_sysmouse",
11559 # endif
11560 # ifdef FEAT_MOUSE_XTERM
11561 "mouse_xterm",
11562 # endif
11563 #endif
11564 #ifdef FEAT_MBYTE
11565 "multi_byte",
11566 #endif
11567 #ifdef FEAT_MBYTE_IME
11568 "multi_byte_ime",
11569 #endif
11570 #ifdef FEAT_MULTI_LANG
11571 "multi_lang",
11572 #endif
11573 #ifdef FEAT_MZSCHEME
11574 #ifndef DYNAMIC_MZSCHEME
11575 "mzscheme",
11576 #endif
11577 #endif
11578 #ifdef FEAT_OLE
11579 "ole",
11580 #endif
11581 #ifdef FEAT_OSFILETYPE
11582 "osfiletype",
11583 #endif
11584 #ifdef FEAT_PATH_EXTRA
11585 "path_extra",
11586 #endif
11587 #ifdef FEAT_PERL
11588 #ifndef DYNAMIC_PERL
11589 "perl",
11590 #endif
11591 #endif
11592 #ifdef FEAT_PYTHON
11593 #ifndef DYNAMIC_PYTHON
11594 "python",
11595 #endif
11596 #endif
11597 #ifdef FEAT_POSTSCRIPT
11598 "postscript",
11599 #endif
11600 #ifdef FEAT_PRINTER
11601 "printer",
11602 #endif
11603 #ifdef FEAT_PROFILE
11604 "profile",
11605 #endif
11606 #ifdef FEAT_RELTIME
11607 "reltime",
11608 #endif
11609 #ifdef FEAT_QUICKFIX
11610 "quickfix",
11611 #endif
11612 #ifdef FEAT_RIGHTLEFT
11613 "rightleft",
11614 #endif
11615 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11616 "ruby",
11617 #endif
11618 #ifdef FEAT_SCROLLBIND
11619 "scrollbind",
11620 #endif
11621 #ifdef FEAT_CMDL_INFO
11622 "showcmd",
11623 "cmdline_info",
11624 #endif
11625 #ifdef FEAT_SIGNS
11626 "signs",
11627 #endif
11628 #ifdef FEAT_SMARTINDENT
11629 "smartindent",
11630 #endif
11631 #ifdef FEAT_SNIFF
11632 "sniff",
11633 #endif
11634 #ifdef FEAT_STL_OPT
11635 "statusline",
11636 #endif
11637 #ifdef FEAT_SUN_WORKSHOP
11638 "sun_workshop",
11639 #endif
11640 #ifdef FEAT_NETBEANS_INTG
11641 "netbeans_intg",
11642 #endif
11643 #ifdef FEAT_ODB_EDITOR
11644 "odbeditor",
11645 #endif
11646 #ifdef FEAT_SPELL
11647 "spell",
11648 #endif
11649 #ifdef FEAT_SYN_HL
11650 "syntax",
11651 #endif
11652 #if defined(USE_SYSTEM) || !defined(UNIX)
11653 "system",
11654 #endif
11655 #ifdef FEAT_TAG_BINS
11656 "tag_binary",
11657 #endif
11658 #ifdef FEAT_TAG_OLDSTATIC
11659 "tag_old_static",
11660 #endif
11661 #ifdef FEAT_TAG_ANYWHITE
11662 "tag_any_white",
11663 #endif
11664 #ifdef FEAT_TCL
11665 # ifndef DYNAMIC_TCL
11666 "tcl",
11667 # endif
11668 #endif
11669 #ifdef TERMINFO
11670 "terminfo",
11671 #endif
11672 #ifdef FEAT_TERMRESPONSE
11673 "termresponse",
11674 #endif
11675 #ifdef FEAT_TEXTOBJ
11676 "textobjects",
11677 #endif
11678 #ifdef HAVE_TGETENT
11679 "tgetent",
11680 #endif
11681 #ifdef FEAT_TITLE
11682 "title",
11683 #endif
11684 #ifdef FEAT_TOOLBAR
11685 "toolbar",
11686 #endif
11687 #ifdef FEAT_TRANSPARENCY
11688 "transparency",
11689 #endif
11690 #ifdef FEAT_USR_CMDS
11691 "user-commands", /* was accidentally included in 5.4 */
11692 "user_commands",
11693 #endif
11694 #ifdef FEAT_VIMINFO
11695 "viminfo",
11696 #endif
11697 #ifdef FEAT_VERTSPLIT
11698 "vertsplit",
11699 #endif
11700 #ifdef FEAT_VIRTUALEDIT
11701 "virtualedit",
11702 #endif
11703 #ifdef FEAT_VISUAL
11704 "visual",
11705 #endif
11706 #ifdef FEAT_VISUALEXTRA
11707 "visualextra",
11708 #endif
11709 #ifdef FEAT_VREPLACE
11710 "vreplace",
11711 #endif
11712 #ifdef FEAT_WILDIGN
11713 "wildignore",
11714 #endif
11715 #ifdef FEAT_WILDMENU
11716 "wildmenu",
11717 #endif
11718 #ifdef FEAT_WINDOWS
11719 "windows",
11720 #endif
11721 #ifdef FEAT_WAK
11722 "winaltkeys",
11723 #endif
11724 #ifdef FEAT_WRITEBACKUP
11725 "writebackup",
11726 #endif
11727 #ifdef FEAT_XIM
11728 "xim",
11729 #endif
11730 #ifdef FEAT_XFONTSET
11731 "xfontset",
11732 #endif
11733 #ifdef USE_XSMP
11734 "xsmp",
11735 #endif
11736 #ifdef USE_XSMP_INTERACT
11737 "xsmp_interact",
11738 #endif
11739 #ifdef FEAT_XCLIPBOARD
11740 "xterm_clipboard",
11741 #endif
11742 #ifdef FEAT_XTERM_SAVE
11743 "xterm_save",
11744 #endif
11745 #if defined(UNIX) && defined(FEAT_X11)
11746 "X11",
11747 #endif
11748 NULL
11751 name = get_tv_string(&argvars[0]);
11752 for (i = 0; has_list[i] != NULL; ++i)
11753 if (STRICMP(name, has_list[i]) == 0)
11755 n = TRUE;
11756 break;
11759 if (n == FALSE)
11761 if (STRNICMP(name, "patch", 5) == 0)
11762 n = has_patch(atoi((char *)name + 5));
11763 else if (STRICMP(name, "vim_starting") == 0)
11764 n = (starting != 0);
11765 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
11766 else if (STRICMP(name, "balloon_multiline") == 0)
11767 n = multiline_balloon_available();
11768 #endif
11769 #ifdef DYNAMIC_TCL
11770 else if (STRICMP(name, "tcl") == 0)
11771 n = tcl_enabled(FALSE);
11772 #endif
11773 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
11774 else if (STRICMP(name, "iconv") == 0)
11775 n = iconv_enabled(FALSE);
11776 #endif
11777 #ifdef DYNAMIC_MZSCHEME
11778 else if (STRICMP(name, "mzscheme") == 0)
11779 n = mzscheme_enabled(FALSE);
11780 #endif
11781 #ifdef DYNAMIC_RUBY
11782 else if (STRICMP(name, "ruby") == 0)
11783 n = ruby_enabled(FALSE);
11784 #endif
11785 #ifdef DYNAMIC_PYTHON
11786 else if (STRICMP(name, "python") == 0)
11787 n = python_enabled(FALSE);
11788 #endif
11789 #ifdef DYNAMIC_PERL
11790 else if (STRICMP(name, "perl") == 0)
11791 n = perl_enabled(FALSE);
11792 #endif
11793 #ifdef FEAT_GUI
11794 else if (STRICMP(name, "gui_running") == 0)
11795 n = (gui.in_use || gui.starting);
11796 # ifdef FEAT_GUI_W32
11797 else if (STRICMP(name, "gui_win32s") == 0)
11798 n = gui_is_win32s();
11799 # endif
11800 # ifdef FEAT_BROWSE
11801 else if (STRICMP(name, "browse") == 0)
11802 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
11803 # endif
11804 #endif
11805 #ifdef FEAT_SYN_HL
11806 else if (STRICMP(name, "syntax_items") == 0)
11807 n = syntax_present(curbuf);
11808 #endif
11809 #if defined(WIN3264)
11810 else if (STRICMP(name, "win95") == 0)
11811 n = mch_windows95();
11812 #endif
11813 #ifdef FEAT_NETBEANS_INTG
11814 else if (STRICMP(name, "netbeans_enabled") == 0)
11815 n = usingNetbeans;
11816 #endif
11819 rettv->vval.v_number = n;
11823 * "has_key()" function
11825 static void
11826 f_has_key(argvars, rettv)
11827 typval_T *argvars;
11828 typval_T *rettv;
11830 rettv->vval.v_number = 0;
11831 if (argvars[0].v_type != VAR_DICT)
11833 EMSG(_(e_dictreq));
11834 return;
11836 if (argvars[0].vval.v_dict == NULL)
11837 return;
11839 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
11840 get_tv_string(&argvars[1]), -1) != NULL;
11844 * "haslocaldir()" function
11846 /*ARGSUSED*/
11847 static void
11848 f_haslocaldir(argvars, rettv)
11849 typval_T *argvars;
11850 typval_T *rettv;
11852 rettv->vval.v_number = (curwin->w_localdir != NULL);
11856 * "hasmapto()" function
11858 static void
11859 f_hasmapto(argvars, rettv)
11860 typval_T *argvars;
11861 typval_T *rettv;
11863 char_u *name;
11864 char_u *mode;
11865 char_u buf[NUMBUFLEN];
11866 int abbr = FALSE;
11868 name = get_tv_string(&argvars[0]);
11869 if (argvars[1].v_type == VAR_UNKNOWN)
11870 mode = (char_u *)"nvo";
11871 else
11873 mode = get_tv_string_buf(&argvars[1], buf);
11874 if (argvars[2].v_type != VAR_UNKNOWN)
11875 abbr = get_tv_number(&argvars[2]);
11878 if (map_to_exists(name, mode, abbr))
11879 rettv->vval.v_number = TRUE;
11880 else
11881 rettv->vval.v_number = FALSE;
11885 * "histadd()" function
11887 /*ARGSUSED*/
11888 static void
11889 f_histadd(argvars, rettv)
11890 typval_T *argvars;
11891 typval_T *rettv;
11893 #ifdef FEAT_CMDHIST
11894 int histype;
11895 char_u *str;
11896 char_u buf[NUMBUFLEN];
11897 #endif
11899 rettv->vval.v_number = FALSE;
11900 if (check_restricted() || check_secure())
11901 return;
11902 #ifdef FEAT_CMDHIST
11903 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11904 histype = str != NULL ? get_histtype(str) : -1;
11905 if (histype >= 0)
11907 str = get_tv_string_buf(&argvars[1], buf);
11908 if (*str != NUL)
11910 add_to_history(histype, str, FALSE, NUL);
11911 rettv->vval.v_number = TRUE;
11912 return;
11915 #endif
11919 * "histdel()" function
11921 /*ARGSUSED*/
11922 static void
11923 f_histdel(argvars, rettv)
11924 typval_T *argvars;
11925 typval_T *rettv;
11927 #ifdef FEAT_CMDHIST
11928 int n;
11929 char_u buf[NUMBUFLEN];
11930 char_u *str;
11932 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11933 if (str == NULL)
11934 n = 0;
11935 else if (argvars[1].v_type == VAR_UNKNOWN)
11936 /* only one argument: clear entire history */
11937 n = clr_history(get_histtype(str));
11938 else if (argvars[1].v_type == VAR_NUMBER)
11939 /* index given: remove that entry */
11940 n = del_history_idx(get_histtype(str),
11941 (int)get_tv_number(&argvars[1]));
11942 else
11943 /* string given: remove all matching entries */
11944 n = del_history_entry(get_histtype(str),
11945 get_tv_string_buf(&argvars[1], buf));
11946 rettv->vval.v_number = n;
11947 #else
11948 rettv->vval.v_number = 0;
11949 #endif
11953 * "histget()" function
11955 /*ARGSUSED*/
11956 static void
11957 f_histget(argvars, rettv)
11958 typval_T *argvars;
11959 typval_T *rettv;
11961 #ifdef FEAT_CMDHIST
11962 int type;
11963 int idx;
11964 char_u *str;
11966 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
11967 if (str == NULL)
11968 rettv->vval.v_string = NULL;
11969 else
11971 type = get_histtype(str);
11972 if (argvars[1].v_type == VAR_UNKNOWN)
11973 idx = get_history_idx(type);
11974 else
11975 idx = (int)get_tv_number_chk(&argvars[1], NULL);
11976 /* -1 on type error */
11977 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
11979 #else
11980 rettv->vval.v_string = NULL;
11981 #endif
11982 rettv->v_type = VAR_STRING;
11986 * "histnr()" function
11988 /*ARGSUSED*/
11989 static void
11990 f_histnr(argvars, rettv)
11991 typval_T *argvars;
11992 typval_T *rettv;
11994 int i;
11996 #ifdef FEAT_CMDHIST
11997 char_u *history = get_tv_string_chk(&argvars[0]);
11999 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12000 if (i >= HIST_CMD && i < HIST_COUNT)
12001 i = get_history_idx(i);
12002 else
12003 #endif
12004 i = -1;
12005 rettv->vval.v_number = i;
12009 * "highlightID(name)" function
12011 static void
12012 f_hlID(argvars, rettv)
12013 typval_T *argvars;
12014 typval_T *rettv;
12016 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12020 * "highlight_exists()" function
12022 static void
12023 f_hlexists(argvars, rettv)
12024 typval_T *argvars;
12025 typval_T *rettv;
12027 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12031 * "hostname()" function
12033 /*ARGSUSED*/
12034 static void
12035 f_hostname(argvars, rettv)
12036 typval_T *argvars;
12037 typval_T *rettv;
12039 char_u hostname[256];
12041 mch_get_host_name(hostname, 256);
12042 rettv->v_type = VAR_STRING;
12043 rettv->vval.v_string = vim_strsave(hostname);
12047 * iconv() function
12049 /*ARGSUSED*/
12050 static void
12051 f_iconv(argvars, rettv)
12052 typval_T *argvars;
12053 typval_T *rettv;
12055 #ifdef FEAT_MBYTE
12056 char_u buf1[NUMBUFLEN];
12057 char_u buf2[NUMBUFLEN];
12058 char_u *from, *to, *str;
12059 vimconv_T vimconv;
12060 #endif
12062 rettv->v_type = VAR_STRING;
12063 rettv->vval.v_string = NULL;
12065 #ifdef FEAT_MBYTE
12066 str = get_tv_string(&argvars[0]);
12067 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12068 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12069 vimconv.vc_type = CONV_NONE;
12070 convert_setup(&vimconv, from, to);
12072 /* If the encodings are equal, no conversion needed. */
12073 if (vimconv.vc_type == CONV_NONE)
12074 rettv->vval.v_string = vim_strsave(str);
12075 else
12076 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12078 convert_setup(&vimconv, NULL, NULL);
12079 vim_free(from);
12080 vim_free(to);
12081 #endif
12085 * "indent()" function
12087 static void
12088 f_indent(argvars, rettv)
12089 typval_T *argvars;
12090 typval_T *rettv;
12092 linenr_T lnum;
12094 lnum = get_tv_lnum(argvars);
12095 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12096 rettv->vval.v_number = get_indent_lnum(lnum);
12097 else
12098 rettv->vval.v_number = -1;
12102 * "index()" function
12104 static void
12105 f_index(argvars, rettv)
12106 typval_T *argvars;
12107 typval_T *rettv;
12109 list_T *l;
12110 listitem_T *item;
12111 long idx = 0;
12112 int ic = FALSE;
12114 rettv->vval.v_number = -1;
12115 if (argvars[0].v_type != VAR_LIST)
12117 EMSG(_(e_listreq));
12118 return;
12120 l = argvars[0].vval.v_list;
12121 if (l != NULL)
12123 item = l->lv_first;
12124 if (argvars[2].v_type != VAR_UNKNOWN)
12126 int error = FALSE;
12128 /* Start at specified item. Use the cached index that list_find()
12129 * sets, so that a negative number also works. */
12130 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12131 idx = l->lv_idx;
12132 if (argvars[3].v_type != VAR_UNKNOWN)
12133 ic = get_tv_number_chk(&argvars[3], &error);
12134 if (error)
12135 item = NULL;
12138 for ( ; item != NULL; item = item->li_next, ++idx)
12139 if (tv_equal(&item->li_tv, &argvars[1], ic))
12141 rettv->vval.v_number = idx;
12142 break;
12147 static int inputsecret_flag = 0;
12149 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12152 * This function is used by f_input() and f_inputdialog() functions. The third
12153 * argument to f_input() specifies the type of completion to use at the
12154 * prompt. The third argument to f_inputdialog() specifies the value to return
12155 * when the user cancels the prompt.
12157 static void
12158 get_user_input(argvars, rettv, inputdialog)
12159 typval_T *argvars;
12160 typval_T *rettv;
12161 int inputdialog;
12163 char_u *prompt = get_tv_string_chk(&argvars[0]);
12164 char_u *p = NULL;
12165 int c;
12166 char_u buf[NUMBUFLEN];
12167 int cmd_silent_save = cmd_silent;
12168 char_u *defstr = (char_u *)"";
12169 int xp_type = EXPAND_NOTHING;
12170 char_u *xp_arg = NULL;
12172 rettv->v_type = VAR_STRING;
12173 rettv->vval.v_string = NULL;
12175 #ifdef NO_CONSOLE_INPUT
12176 /* While starting up, there is no place to enter text. */
12177 if (no_console_input())
12178 return;
12179 #endif
12181 cmd_silent = FALSE; /* Want to see the prompt. */
12182 if (prompt != NULL)
12184 /* Only the part of the message after the last NL is considered as
12185 * prompt for the command line */
12186 p = vim_strrchr(prompt, '\n');
12187 if (p == NULL)
12188 p = prompt;
12189 else
12191 ++p;
12192 c = *p;
12193 *p = NUL;
12194 msg_start();
12195 msg_clr_eos();
12196 msg_puts_attr(prompt, echo_attr);
12197 msg_didout = FALSE;
12198 msg_starthere();
12199 *p = c;
12201 cmdline_row = msg_row;
12203 if (argvars[1].v_type != VAR_UNKNOWN)
12205 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12206 if (defstr != NULL)
12207 stuffReadbuffSpec(defstr);
12209 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12211 char_u *xp_name;
12212 int xp_namelen;
12213 long argt;
12215 rettv->vval.v_string = NULL;
12217 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12218 if (xp_name == NULL)
12219 return;
12221 xp_namelen = (int)STRLEN(xp_name);
12223 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12224 &xp_arg) == FAIL)
12225 return;
12229 if (defstr != NULL)
12230 rettv->vval.v_string =
12231 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12232 xp_type, xp_arg);
12234 vim_free(xp_arg);
12236 /* since the user typed this, no need to wait for return */
12237 need_wait_return = FALSE;
12238 msg_didout = FALSE;
12240 cmd_silent = cmd_silent_save;
12244 * "input()" function
12245 * Also handles inputsecret() when inputsecret is set.
12247 static void
12248 f_input(argvars, rettv)
12249 typval_T *argvars;
12250 typval_T *rettv;
12252 get_user_input(argvars, rettv, FALSE);
12256 * "inputdialog()" function
12258 static void
12259 f_inputdialog(argvars, rettv)
12260 typval_T *argvars;
12261 typval_T *rettv;
12263 #if defined(FEAT_GUI_TEXTDIALOG)
12264 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12265 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12267 char_u *message;
12268 char_u buf[NUMBUFLEN];
12269 char_u *defstr = (char_u *)"";
12271 message = get_tv_string_chk(&argvars[0]);
12272 if (argvars[1].v_type != VAR_UNKNOWN
12273 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12274 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12275 else
12276 IObuff[0] = NUL;
12277 if (message != NULL && defstr != NULL
12278 && do_dialog(VIM_QUESTION, NULL, message,
12279 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12280 rettv->vval.v_string = vim_strsave(IObuff);
12281 else
12283 if (message != NULL && defstr != NULL
12284 && argvars[1].v_type != VAR_UNKNOWN
12285 && argvars[2].v_type != VAR_UNKNOWN)
12286 rettv->vval.v_string = vim_strsave(
12287 get_tv_string_buf(&argvars[2], buf));
12288 else
12289 rettv->vval.v_string = NULL;
12291 rettv->v_type = VAR_STRING;
12293 else
12294 #endif
12295 get_user_input(argvars, rettv, TRUE);
12299 * "inputlist()" function
12301 static void
12302 f_inputlist(argvars, rettv)
12303 typval_T *argvars;
12304 typval_T *rettv;
12306 listitem_T *li;
12307 int selected;
12308 int mouse_used;
12310 rettv->vval.v_number = 0;
12311 #ifdef NO_CONSOLE_INPUT
12312 /* While starting up, there is no place to enter text. */
12313 if (no_console_input())
12314 return;
12315 #endif
12316 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12318 EMSG2(_(e_listarg), "inputlist()");
12319 return;
12322 msg_start();
12323 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12324 lines_left = Rows; /* avoid more prompt */
12325 msg_scroll = TRUE;
12326 msg_clr_eos();
12328 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12330 msg_puts(get_tv_string(&li->li_tv));
12331 msg_putchar('\n');
12334 /* Ask for choice. */
12335 selected = prompt_for_number(&mouse_used);
12336 if (mouse_used)
12337 selected -= lines_left;
12339 rettv->vval.v_number = selected;
12343 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12346 * "inputrestore()" function
12348 /*ARGSUSED*/
12349 static void
12350 f_inputrestore(argvars, rettv)
12351 typval_T *argvars;
12352 typval_T *rettv;
12354 if (ga_userinput.ga_len > 0)
12356 --ga_userinput.ga_len;
12357 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12358 + ga_userinput.ga_len);
12359 rettv->vval.v_number = 0; /* OK */
12361 else if (p_verbose > 1)
12363 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12364 rettv->vval.v_number = 1; /* Failed */
12369 * "inputsave()" function
12371 /*ARGSUSED*/
12372 static void
12373 f_inputsave(argvars, rettv)
12374 typval_T *argvars;
12375 typval_T *rettv;
12377 /* Add an entry to the stack of typeahead storage. */
12378 if (ga_grow(&ga_userinput, 1) == OK)
12380 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12381 + ga_userinput.ga_len);
12382 ++ga_userinput.ga_len;
12383 rettv->vval.v_number = 0; /* OK */
12385 else
12386 rettv->vval.v_number = 1; /* Failed */
12390 * "inputsecret()" function
12392 static void
12393 f_inputsecret(argvars, rettv)
12394 typval_T *argvars;
12395 typval_T *rettv;
12397 ++cmdline_star;
12398 ++inputsecret_flag;
12399 f_input(argvars, rettv);
12400 --cmdline_star;
12401 --inputsecret_flag;
12405 * "insert()" function
12407 static void
12408 f_insert(argvars, rettv)
12409 typval_T *argvars;
12410 typval_T *rettv;
12412 long before = 0;
12413 listitem_T *item;
12414 list_T *l;
12415 int error = FALSE;
12417 rettv->vval.v_number = 0;
12418 if (argvars[0].v_type != VAR_LIST)
12419 EMSG2(_(e_listarg), "insert()");
12420 else if ((l = argvars[0].vval.v_list) != NULL
12421 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12423 if (argvars[2].v_type != VAR_UNKNOWN)
12424 before = get_tv_number_chk(&argvars[2], &error);
12425 if (error)
12426 return; /* type error; errmsg already given */
12428 if (before == l->lv_len)
12429 item = NULL;
12430 else
12432 item = list_find(l, before);
12433 if (item == NULL)
12435 EMSGN(_(e_listidx), before);
12436 l = NULL;
12439 if (l != NULL)
12441 list_insert_tv(l, &argvars[1], item);
12442 copy_tv(&argvars[0], rettv);
12448 * "isdirectory()" function
12450 static void
12451 f_isdirectory(argvars, rettv)
12452 typval_T *argvars;
12453 typval_T *rettv;
12455 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12459 * "islocked()" function
12461 static void
12462 f_islocked(argvars, rettv)
12463 typval_T *argvars;
12464 typval_T *rettv;
12466 lval_T lv;
12467 char_u *end;
12468 dictitem_T *di;
12470 rettv->vval.v_number = -1;
12471 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12472 FNE_CHECK_START);
12473 if (end != NULL && lv.ll_name != NULL)
12475 if (*end != NUL)
12476 EMSG(_(e_trailing));
12477 else
12479 if (lv.ll_tv == NULL)
12481 if (check_changedtick(lv.ll_name))
12482 rettv->vval.v_number = 1; /* always locked */
12483 else
12485 di = find_var(lv.ll_name, NULL);
12486 if (di != NULL)
12488 /* Consider a variable locked when:
12489 * 1. the variable itself is locked
12490 * 2. the value of the variable is locked.
12491 * 3. the List or Dict value is locked.
12493 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12494 || tv_islocked(&di->di_tv));
12498 else if (lv.ll_range)
12499 EMSG(_("E786: Range not allowed"));
12500 else if (lv.ll_newkey != NULL)
12501 EMSG2(_(e_dictkey), lv.ll_newkey);
12502 else if (lv.ll_list != NULL)
12503 /* List item. */
12504 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12505 else
12506 /* Dictionary item. */
12507 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12511 clear_lval(&lv);
12514 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12517 * Turn a dict into a list:
12518 * "what" == 0: list of keys
12519 * "what" == 1: list of values
12520 * "what" == 2: list of items
12522 static void
12523 dict_list(argvars, rettv, what)
12524 typval_T *argvars;
12525 typval_T *rettv;
12526 int what;
12528 list_T *l2;
12529 dictitem_T *di;
12530 hashitem_T *hi;
12531 listitem_T *li;
12532 listitem_T *li2;
12533 dict_T *d;
12534 int todo;
12536 rettv->vval.v_number = 0;
12537 if (argvars[0].v_type != VAR_DICT)
12539 EMSG(_(e_dictreq));
12540 return;
12542 if ((d = argvars[0].vval.v_dict) == NULL)
12543 return;
12545 if (rettv_list_alloc(rettv) == FAIL)
12546 return;
12548 todo = (int)d->dv_hashtab.ht_used;
12549 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12551 if (!HASHITEM_EMPTY(hi))
12553 --todo;
12554 di = HI2DI(hi);
12556 li = listitem_alloc();
12557 if (li == NULL)
12558 break;
12559 list_append(rettv->vval.v_list, li);
12561 if (what == 0)
12563 /* keys() */
12564 li->li_tv.v_type = VAR_STRING;
12565 li->li_tv.v_lock = 0;
12566 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12568 else if (what == 1)
12570 /* values() */
12571 copy_tv(&di->di_tv, &li->li_tv);
12573 else
12575 /* items() */
12576 l2 = list_alloc();
12577 li->li_tv.v_type = VAR_LIST;
12578 li->li_tv.v_lock = 0;
12579 li->li_tv.vval.v_list = l2;
12580 if (l2 == NULL)
12581 break;
12582 ++l2->lv_refcount;
12584 li2 = listitem_alloc();
12585 if (li2 == NULL)
12586 break;
12587 list_append(l2, li2);
12588 li2->li_tv.v_type = VAR_STRING;
12589 li2->li_tv.v_lock = 0;
12590 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12592 li2 = listitem_alloc();
12593 if (li2 == NULL)
12594 break;
12595 list_append(l2, li2);
12596 copy_tv(&di->di_tv, &li2->li_tv);
12603 * "items(dict)" function
12605 static void
12606 f_items(argvars, rettv)
12607 typval_T *argvars;
12608 typval_T *rettv;
12610 dict_list(argvars, rettv, 2);
12614 * "join()" function
12616 static void
12617 f_join(argvars, rettv)
12618 typval_T *argvars;
12619 typval_T *rettv;
12621 garray_T ga;
12622 char_u *sep;
12624 rettv->vval.v_number = 0;
12625 if (argvars[0].v_type != VAR_LIST)
12627 EMSG(_(e_listreq));
12628 return;
12630 if (argvars[0].vval.v_list == NULL)
12631 return;
12632 if (argvars[1].v_type == VAR_UNKNOWN)
12633 sep = (char_u *)" ";
12634 else
12635 sep = get_tv_string_chk(&argvars[1]);
12637 rettv->v_type = VAR_STRING;
12639 if (sep != NULL)
12641 ga_init2(&ga, (int)sizeof(char), 80);
12642 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12643 ga_append(&ga, NUL);
12644 rettv->vval.v_string = (char_u *)ga.ga_data;
12646 else
12647 rettv->vval.v_string = NULL;
12651 * "keys()" function
12653 static void
12654 f_keys(argvars, rettv)
12655 typval_T *argvars;
12656 typval_T *rettv;
12658 dict_list(argvars, rettv, 0);
12662 * "last_buffer_nr()" function.
12664 /*ARGSUSED*/
12665 static void
12666 f_last_buffer_nr(argvars, rettv)
12667 typval_T *argvars;
12668 typval_T *rettv;
12670 int n = 0;
12671 buf_T *buf;
12673 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12674 if (n < buf->b_fnum)
12675 n = buf->b_fnum;
12677 rettv->vval.v_number = n;
12681 * "len()" function
12683 static void
12684 f_len(argvars, rettv)
12685 typval_T *argvars;
12686 typval_T *rettv;
12688 switch (argvars[0].v_type)
12690 case VAR_STRING:
12691 case VAR_NUMBER:
12692 rettv->vval.v_number = (varnumber_T)STRLEN(
12693 get_tv_string(&argvars[0]));
12694 break;
12695 case VAR_LIST:
12696 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
12697 break;
12698 case VAR_DICT:
12699 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
12700 break;
12701 default:
12702 EMSG(_("E701: Invalid type for len()"));
12703 break;
12707 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
12709 static void
12710 libcall_common(argvars, rettv, type)
12711 typval_T *argvars;
12712 typval_T *rettv;
12713 int type;
12715 #ifdef FEAT_LIBCALL
12716 char_u *string_in;
12717 char_u **string_result;
12718 int nr_result;
12719 #endif
12721 rettv->v_type = type;
12722 if (type == VAR_NUMBER)
12723 rettv->vval.v_number = 0;
12724 else
12725 rettv->vval.v_string = NULL;
12727 if (check_restricted() || check_secure())
12728 return;
12730 #ifdef FEAT_LIBCALL
12731 /* The first two args must be strings, otherwise its meaningless */
12732 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
12734 string_in = NULL;
12735 if (argvars[2].v_type == VAR_STRING)
12736 string_in = argvars[2].vval.v_string;
12737 if (type == VAR_NUMBER)
12738 string_result = NULL;
12739 else
12740 string_result = &rettv->vval.v_string;
12741 if (mch_libcall(argvars[0].vval.v_string,
12742 argvars[1].vval.v_string,
12743 string_in,
12744 argvars[2].vval.v_number,
12745 string_result,
12746 &nr_result) == OK
12747 && type == VAR_NUMBER)
12748 rettv->vval.v_number = nr_result;
12750 #endif
12754 * "libcall()" function
12756 static void
12757 f_libcall(argvars, rettv)
12758 typval_T *argvars;
12759 typval_T *rettv;
12761 libcall_common(argvars, rettv, VAR_STRING);
12765 * "libcallnr()" function
12767 static void
12768 f_libcallnr(argvars, rettv)
12769 typval_T *argvars;
12770 typval_T *rettv;
12772 libcall_common(argvars, rettv, VAR_NUMBER);
12776 * "line(string)" function
12778 static void
12779 f_line(argvars, rettv)
12780 typval_T *argvars;
12781 typval_T *rettv;
12783 linenr_T lnum = 0;
12784 pos_T *fp;
12785 int fnum;
12787 fp = var2fpos(&argvars[0], TRUE, &fnum);
12788 if (fp != NULL)
12789 lnum = fp->lnum;
12790 rettv->vval.v_number = lnum;
12794 * "line2byte(lnum)" function
12796 /*ARGSUSED*/
12797 static void
12798 f_line2byte(argvars, rettv)
12799 typval_T *argvars;
12800 typval_T *rettv;
12802 #ifndef FEAT_BYTEOFF
12803 rettv->vval.v_number = -1;
12804 #else
12805 linenr_T lnum;
12807 lnum = get_tv_lnum(argvars);
12808 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
12809 rettv->vval.v_number = -1;
12810 else
12811 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
12812 if (rettv->vval.v_number >= 0)
12813 ++rettv->vval.v_number;
12814 #endif
12818 * "lispindent(lnum)" function
12820 static void
12821 f_lispindent(argvars, rettv)
12822 typval_T *argvars;
12823 typval_T *rettv;
12825 #ifdef FEAT_LISP
12826 pos_T pos;
12827 linenr_T lnum;
12829 pos = curwin->w_cursor;
12830 lnum = get_tv_lnum(argvars);
12831 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12833 curwin->w_cursor.lnum = lnum;
12834 rettv->vval.v_number = get_lisp_indent();
12835 curwin->w_cursor = pos;
12837 else
12838 #endif
12839 rettv->vval.v_number = -1;
12843 * "localtime()" function
12845 /*ARGSUSED*/
12846 static void
12847 f_localtime(argvars, rettv)
12848 typval_T *argvars;
12849 typval_T *rettv;
12851 rettv->vval.v_number = (varnumber_T)time(NULL);
12854 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
12856 static void
12857 get_maparg(argvars, rettv, exact)
12858 typval_T *argvars;
12859 typval_T *rettv;
12860 int exact;
12862 char_u *keys;
12863 char_u *which;
12864 char_u buf[NUMBUFLEN];
12865 char_u *keys_buf = NULL;
12866 char_u *rhs;
12867 int mode;
12868 garray_T ga;
12869 int abbr = FALSE;
12871 /* return empty string for failure */
12872 rettv->v_type = VAR_STRING;
12873 rettv->vval.v_string = NULL;
12875 keys = get_tv_string(&argvars[0]);
12876 if (*keys == NUL)
12877 return;
12879 if (argvars[1].v_type != VAR_UNKNOWN)
12881 which = get_tv_string_buf_chk(&argvars[1], buf);
12882 if (argvars[2].v_type != VAR_UNKNOWN)
12883 abbr = get_tv_number(&argvars[2]);
12885 else
12886 which = (char_u *)"";
12887 if (which == NULL)
12888 return;
12890 mode = get_map_mode(&which, 0);
12892 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
12893 rhs = check_map(keys, mode, exact, FALSE, abbr);
12894 vim_free(keys_buf);
12895 if (rhs != NULL)
12897 ga_init(&ga);
12898 ga.ga_itemsize = 1;
12899 ga.ga_growsize = 40;
12901 while (*rhs != NUL)
12902 ga_concat(&ga, str2special(&rhs, FALSE));
12904 ga_append(&ga, NUL);
12905 rettv->vval.v_string = (char_u *)ga.ga_data;
12909 #ifdef FEAT_FLOAT
12911 * "log10()" function
12913 static void
12914 f_log10(argvars, rettv)
12915 typval_T *argvars;
12916 typval_T *rettv;
12918 float_T f;
12920 rettv->v_type = VAR_FLOAT;
12921 if (get_float_arg(argvars, &f) == OK)
12922 rettv->vval.v_float = log10(f);
12923 else
12924 rettv->vval.v_float = 0.0;
12926 #endif
12929 * "map()" function
12931 static void
12932 f_map(argvars, rettv)
12933 typval_T *argvars;
12934 typval_T *rettv;
12936 filter_map(argvars, rettv, TRUE);
12940 * "maparg()" function
12942 static void
12943 f_maparg(argvars, rettv)
12944 typval_T *argvars;
12945 typval_T *rettv;
12947 get_maparg(argvars, rettv, TRUE);
12951 * "mapcheck()" function
12953 static void
12954 f_mapcheck(argvars, rettv)
12955 typval_T *argvars;
12956 typval_T *rettv;
12958 get_maparg(argvars, rettv, FALSE);
12961 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
12963 static void
12964 find_some_match(argvars, rettv, type)
12965 typval_T *argvars;
12966 typval_T *rettv;
12967 int type;
12969 char_u *str = NULL;
12970 char_u *expr = NULL;
12971 char_u *pat;
12972 regmatch_T regmatch;
12973 char_u patbuf[NUMBUFLEN];
12974 char_u strbuf[NUMBUFLEN];
12975 char_u *save_cpo;
12976 long start = 0;
12977 long nth = 1;
12978 colnr_T startcol = 0;
12979 int match = 0;
12980 list_T *l = NULL;
12981 listitem_T *li = NULL;
12982 long idx = 0;
12983 char_u *tofree = NULL;
12985 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
12986 save_cpo = p_cpo;
12987 p_cpo = (char_u *)"";
12989 rettv->vval.v_number = -1;
12990 if (type == 3)
12992 /* return empty list when there are no matches */
12993 if (rettv_list_alloc(rettv) == FAIL)
12994 goto theend;
12996 else if (type == 2)
12998 rettv->v_type = VAR_STRING;
12999 rettv->vval.v_string = NULL;
13002 if (argvars[0].v_type == VAR_LIST)
13004 if ((l = argvars[0].vval.v_list) == NULL)
13005 goto theend;
13006 li = l->lv_first;
13008 else
13009 expr = str = get_tv_string(&argvars[0]);
13011 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13012 if (pat == NULL)
13013 goto theend;
13015 if (argvars[2].v_type != VAR_UNKNOWN)
13017 int error = FALSE;
13019 start = get_tv_number_chk(&argvars[2], &error);
13020 if (error)
13021 goto theend;
13022 if (l != NULL)
13024 li = list_find(l, start);
13025 if (li == NULL)
13026 goto theend;
13027 idx = l->lv_idx; /* use the cached index */
13029 else
13031 if (start < 0)
13032 start = 0;
13033 if (start > (long)STRLEN(str))
13034 goto theend;
13035 /* When "count" argument is there ignore matches before "start",
13036 * otherwise skip part of the string. Differs when pattern is "^"
13037 * or "\<". */
13038 if (argvars[3].v_type != VAR_UNKNOWN)
13039 startcol = start;
13040 else
13041 str += start;
13044 if (argvars[3].v_type != VAR_UNKNOWN)
13045 nth = get_tv_number_chk(&argvars[3], &error);
13046 if (error)
13047 goto theend;
13050 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13051 if (regmatch.regprog != NULL)
13053 regmatch.rm_ic = p_ic;
13055 for (;;)
13057 if (l != NULL)
13059 if (li == NULL)
13061 match = FALSE;
13062 break;
13064 vim_free(tofree);
13065 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13066 if (str == NULL)
13067 break;
13070 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13072 if (match && --nth <= 0)
13073 break;
13074 if (l == NULL && !match)
13075 break;
13077 /* Advance to just after the match. */
13078 if (l != NULL)
13080 li = li->li_next;
13081 ++idx;
13083 else
13085 #ifdef FEAT_MBYTE
13086 startcol = (colnr_T)(regmatch.startp[0]
13087 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13088 #else
13089 startcol = regmatch.startp[0] + 1 - str;
13090 #endif
13094 if (match)
13096 if (type == 3)
13098 int i;
13100 /* return list with matched string and submatches */
13101 for (i = 0; i < NSUBEXP; ++i)
13103 if (regmatch.endp[i] == NULL)
13105 if (list_append_string(rettv->vval.v_list,
13106 (char_u *)"", 0) == FAIL)
13107 break;
13109 else if (list_append_string(rettv->vval.v_list,
13110 regmatch.startp[i],
13111 (int)(regmatch.endp[i] - regmatch.startp[i]))
13112 == FAIL)
13113 break;
13116 else if (type == 2)
13118 /* return matched string */
13119 if (l != NULL)
13120 copy_tv(&li->li_tv, rettv);
13121 else
13122 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13123 (int)(regmatch.endp[0] - regmatch.startp[0]));
13125 else if (l != NULL)
13126 rettv->vval.v_number = idx;
13127 else
13129 if (type != 0)
13130 rettv->vval.v_number =
13131 (varnumber_T)(regmatch.startp[0] - str);
13132 else
13133 rettv->vval.v_number =
13134 (varnumber_T)(regmatch.endp[0] - str);
13135 rettv->vval.v_number += (varnumber_T)(str - expr);
13138 vim_free(regmatch.regprog);
13141 theend:
13142 vim_free(tofree);
13143 p_cpo = save_cpo;
13147 * "match()" function
13149 static void
13150 f_match(argvars, rettv)
13151 typval_T *argvars;
13152 typval_T *rettv;
13154 find_some_match(argvars, rettv, 1);
13158 * "matchadd()" function
13160 static void
13161 f_matchadd(argvars, rettv)
13162 typval_T *argvars;
13163 typval_T *rettv;
13165 #ifdef FEAT_SEARCH_EXTRA
13166 char_u buf[NUMBUFLEN];
13167 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13168 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13169 int prio = 10; /* default priority */
13170 int id = -1;
13171 int error = FALSE;
13173 rettv->vval.v_number = -1;
13175 if (grp == NULL || pat == NULL)
13176 return;
13177 if (argvars[2].v_type != VAR_UNKNOWN)
13179 prio = get_tv_number_chk(&argvars[2], &error);
13180 if (argvars[3].v_type != VAR_UNKNOWN)
13181 id = get_tv_number_chk(&argvars[3], &error);
13183 if (error == TRUE)
13184 return;
13185 if (id >= 1 && id <= 3)
13187 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13188 return;
13191 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13192 #endif
13196 * "matcharg()" function
13198 static void
13199 f_matcharg(argvars, rettv)
13200 typval_T *argvars;
13201 typval_T *rettv;
13203 if (rettv_list_alloc(rettv) == OK)
13205 #ifdef FEAT_SEARCH_EXTRA
13206 int id = get_tv_number(&argvars[0]);
13207 matchitem_T *m;
13209 if (id >= 1 && id <= 3)
13211 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13213 list_append_string(rettv->vval.v_list,
13214 syn_id2name(m->hlg_id), -1);
13215 list_append_string(rettv->vval.v_list, m->pattern, -1);
13217 else
13219 list_append_string(rettv->vval.v_list, NUL, -1);
13220 list_append_string(rettv->vval.v_list, NUL, -1);
13223 #endif
13228 * "matchdelete()" function
13230 static void
13231 f_matchdelete(argvars, rettv)
13232 typval_T *argvars;
13233 typval_T *rettv;
13235 #ifdef FEAT_SEARCH_EXTRA
13236 rettv->vval.v_number = match_delete(curwin,
13237 (int)get_tv_number(&argvars[0]), TRUE);
13238 #endif
13242 * "matchend()" function
13244 static void
13245 f_matchend(argvars, rettv)
13246 typval_T *argvars;
13247 typval_T *rettv;
13249 find_some_match(argvars, rettv, 0);
13253 * "matchlist()" function
13255 static void
13256 f_matchlist(argvars, rettv)
13257 typval_T *argvars;
13258 typval_T *rettv;
13260 find_some_match(argvars, rettv, 3);
13264 * "matchstr()" function
13266 static void
13267 f_matchstr(argvars, rettv)
13268 typval_T *argvars;
13269 typval_T *rettv;
13271 find_some_match(argvars, rettv, 2);
13274 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13276 static void
13277 max_min(argvars, rettv, domax)
13278 typval_T *argvars;
13279 typval_T *rettv;
13280 int domax;
13282 long n = 0;
13283 long i;
13284 int error = FALSE;
13286 if (argvars[0].v_type == VAR_LIST)
13288 list_T *l;
13289 listitem_T *li;
13291 l = argvars[0].vval.v_list;
13292 if (l != NULL)
13294 li = l->lv_first;
13295 if (li != NULL)
13297 n = get_tv_number_chk(&li->li_tv, &error);
13298 for (;;)
13300 li = li->li_next;
13301 if (li == NULL)
13302 break;
13303 i = get_tv_number_chk(&li->li_tv, &error);
13304 if (domax ? i > n : i < n)
13305 n = i;
13310 else if (argvars[0].v_type == VAR_DICT)
13312 dict_T *d;
13313 int first = TRUE;
13314 hashitem_T *hi;
13315 int todo;
13317 d = argvars[0].vval.v_dict;
13318 if (d != NULL)
13320 todo = (int)d->dv_hashtab.ht_used;
13321 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13323 if (!HASHITEM_EMPTY(hi))
13325 --todo;
13326 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13327 if (first)
13329 n = i;
13330 first = FALSE;
13332 else if (domax ? i > n : i < n)
13333 n = i;
13338 else
13339 EMSG(_(e_listdictarg));
13340 rettv->vval.v_number = error ? 0 : n;
13344 * "max()" function
13346 static void
13347 f_max(argvars, rettv)
13348 typval_T *argvars;
13349 typval_T *rettv;
13351 max_min(argvars, rettv, TRUE);
13355 * "min()" function
13357 static void
13358 f_min(argvars, rettv)
13359 typval_T *argvars;
13360 typval_T *rettv;
13362 max_min(argvars, rettv, FALSE);
13365 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13368 * Create the directory in which "dir" is located, and higher levels when
13369 * needed.
13371 static int
13372 mkdir_recurse(dir, prot)
13373 char_u *dir;
13374 int prot;
13376 char_u *p;
13377 char_u *updir;
13378 int r = FAIL;
13380 /* Get end of directory name in "dir".
13381 * We're done when it's "/" or "c:/". */
13382 p = gettail_sep(dir);
13383 if (p <= get_past_head(dir))
13384 return OK;
13386 /* If the directory exists we're done. Otherwise: create it.*/
13387 updir = vim_strnsave(dir, (int)(p - dir));
13388 if (updir == NULL)
13389 return FAIL;
13390 if (mch_isdir(updir))
13391 r = OK;
13392 else if (mkdir_recurse(updir, prot) == OK)
13393 r = vim_mkdir_emsg(updir, prot);
13394 vim_free(updir);
13395 return r;
13398 #ifdef vim_mkdir
13400 * "mkdir()" function
13402 static void
13403 f_mkdir(argvars, rettv)
13404 typval_T *argvars;
13405 typval_T *rettv;
13407 char_u *dir;
13408 char_u buf[NUMBUFLEN];
13409 int prot = 0755;
13411 rettv->vval.v_number = FAIL;
13412 if (check_restricted() || check_secure())
13413 return;
13415 dir = get_tv_string_buf(&argvars[0], buf);
13416 if (argvars[1].v_type != VAR_UNKNOWN)
13418 if (argvars[2].v_type != VAR_UNKNOWN)
13419 prot = get_tv_number_chk(&argvars[2], NULL);
13420 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13421 mkdir_recurse(dir, prot);
13423 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13425 #endif
13428 * "mode()" function
13430 /*ARGSUSED*/
13431 static void
13432 f_mode(argvars, rettv)
13433 typval_T *argvars;
13434 typval_T *rettv;
13436 char_u buf[3];
13438 buf[1] = NUL;
13439 buf[2] = NUL;
13441 #ifdef FEAT_VISUAL
13442 if (VIsual_active)
13444 if (VIsual_select)
13445 buf[0] = VIsual_mode + 's' - 'v';
13446 else
13447 buf[0] = VIsual_mode;
13449 else
13450 #endif
13451 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13452 || State == CONFIRM)
13454 buf[0] = 'r';
13455 if (State == ASKMORE)
13456 buf[1] = 'm';
13457 else if (State == CONFIRM)
13458 buf[1] = '?';
13460 else if (State == EXTERNCMD)
13461 buf[0] = '!';
13462 else if (State & INSERT)
13464 #ifdef FEAT_VREPLACE
13465 if (State & VREPLACE_FLAG)
13467 buf[0] = 'R';
13468 buf[1] = 'v';
13470 else
13471 #endif
13472 if (State & REPLACE_FLAG)
13473 buf[0] = 'R';
13474 else
13475 buf[0] = 'i';
13477 else if (State & CMDLINE)
13479 buf[0] = 'c';
13480 if (exmode_active)
13481 buf[1] = 'v';
13483 else if (exmode_active)
13485 buf[0] = 'c';
13486 buf[1] = 'e';
13488 else
13490 buf[0] = 'n';
13491 if (finish_op)
13492 buf[1] = 'o';
13495 /* A zero number or empty string argument: return only major mode. */
13496 if (!(argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number != 0)
13497 && !(argvars[0].v_type == VAR_STRING
13498 && *get_tv_string(&argvars[0]) != NUL))
13499 buf[1] = NUL;
13501 rettv->vval.v_string = vim_strsave(buf);
13502 rettv->v_type = VAR_STRING;
13506 * "nextnonblank()" function
13508 static void
13509 f_nextnonblank(argvars, rettv)
13510 typval_T *argvars;
13511 typval_T *rettv;
13513 linenr_T lnum;
13515 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13517 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13519 lnum = 0;
13520 break;
13522 if (*skipwhite(ml_get(lnum)) != NUL)
13523 break;
13525 rettv->vval.v_number = lnum;
13529 * "nr2char()" function
13531 static void
13532 f_nr2char(argvars, rettv)
13533 typval_T *argvars;
13534 typval_T *rettv;
13536 char_u buf[NUMBUFLEN];
13538 #ifdef FEAT_MBYTE
13539 if (has_mbyte)
13540 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13541 else
13542 #endif
13544 buf[0] = (char_u)get_tv_number(&argvars[0]);
13545 buf[1] = NUL;
13547 rettv->v_type = VAR_STRING;
13548 rettv->vval.v_string = vim_strsave(buf);
13552 * "pathshorten()" function
13554 static void
13555 f_pathshorten(argvars, rettv)
13556 typval_T *argvars;
13557 typval_T *rettv;
13559 char_u *p;
13561 rettv->v_type = VAR_STRING;
13562 p = get_tv_string_chk(&argvars[0]);
13563 if (p == NULL)
13564 rettv->vval.v_string = NULL;
13565 else
13567 p = vim_strsave(p);
13568 rettv->vval.v_string = p;
13569 if (p != NULL)
13570 shorten_dir(p);
13574 #ifdef FEAT_FLOAT
13576 * "pow()" function
13578 static void
13579 f_pow(argvars, rettv)
13580 typval_T *argvars;
13581 typval_T *rettv;
13583 float_T fx, fy;
13585 rettv->v_type = VAR_FLOAT;
13586 if (get_float_arg(argvars, &fx) == OK
13587 && get_float_arg(&argvars[1], &fy) == OK)
13588 rettv->vval.v_float = pow(fx, fy);
13589 else
13590 rettv->vval.v_float = 0.0;
13592 #endif
13595 * "prevnonblank()" function
13597 static void
13598 f_prevnonblank(argvars, rettv)
13599 typval_T *argvars;
13600 typval_T *rettv;
13602 linenr_T lnum;
13604 lnum = get_tv_lnum(argvars);
13605 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13606 lnum = 0;
13607 else
13608 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13609 --lnum;
13610 rettv->vval.v_number = lnum;
13613 #ifdef HAVE_STDARG_H
13614 /* This dummy va_list is here because:
13615 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13616 * - locally in the function results in a "used before set" warning
13617 * - using va_start() to initialize it gives "function with fixed args" error */
13618 static va_list ap;
13619 #endif
13622 * "printf()" function
13624 static void
13625 f_printf(argvars, rettv)
13626 typval_T *argvars;
13627 typval_T *rettv;
13629 rettv->v_type = VAR_STRING;
13630 rettv->vval.v_string = NULL;
13631 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13633 char_u buf[NUMBUFLEN];
13634 int len;
13635 char_u *s;
13636 int saved_did_emsg = did_emsg;
13637 char *fmt;
13639 /* Get the required length, allocate the buffer and do it for real. */
13640 did_emsg = FALSE;
13641 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13642 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13643 if (!did_emsg)
13645 s = alloc(len + 1);
13646 if (s != NULL)
13648 rettv->vval.v_string = s;
13649 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13652 did_emsg |= saved_did_emsg;
13654 #endif
13658 * "pumvisible()" function
13660 /*ARGSUSED*/
13661 static void
13662 f_pumvisible(argvars, rettv)
13663 typval_T *argvars;
13664 typval_T *rettv;
13666 rettv->vval.v_number = 0;
13667 #ifdef FEAT_INS_EXPAND
13668 if (pum_visible())
13669 rettv->vval.v_number = 1;
13670 #endif
13674 * "range()" function
13676 static void
13677 f_range(argvars, rettv)
13678 typval_T *argvars;
13679 typval_T *rettv;
13681 long start;
13682 long end;
13683 long stride = 1;
13684 long i;
13685 int error = FALSE;
13687 start = get_tv_number_chk(&argvars[0], &error);
13688 if (argvars[1].v_type == VAR_UNKNOWN)
13690 end = start - 1;
13691 start = 0;
13693 else
13695 end = get_tv_number_chk(&argvars[1], &error);
13696 if (argvars[2].v_type != VAR_UNKNOWN)
13697 stride = get_tv_number_chk(&argvars[2], &error);
13700 rettv->vval.v_number = 0;
13701 if (error)
13702 return; /* type error; errmsg already given */
13703 if (stride == 0)
13704 EMSG(_("E726: Stride is zero"));
13705 else if (stride > 0 ? end + 1 < start : end - 1 > start)
13706 EMSG(_("E727: Start past end"));
13707 else
13709 if (rettv_list_alloc(rettv) == OK)
13710 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
13711 if (list_append_number(rettv->vval.v_list,
13712 (varnumber_T)i) == FAIL)
13713 break;
13718 * "readfile()" function
13720 static void
13721 f_readfile(argvars, rettv)
13722 typval_T *argvars;
13723 typval_T *rettv;
13725 int binary = FALSE;
13726 char_u *fname;
13727 FILE *fd;
13728 listitem_T *li;
13729 #define FREAD_SIZE 200 /* optimized for text lines */
13730 char_u buf[FREAD_SIZE];
13731 int readlen; /* size of last fread() */
13732 int buflen; /* nr of valid chars in buf[] */
13733 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
13734 int tolist; /* first byte in buf[] still to be put in list */
13735 int chop; /* how many CR to chop off */
13736 char_u *prev = NULL; /* previously read bytes, if any */
13737 int prevlen = 0; /* length of "prev" if not NULL */
13738 char_u *s;
13739 int len;
13740 long maxline = MAXLNUM;
13741 long cnt = 0;
13743 if (argvars[1].v_type != VAR_UNKNOWN)
13745 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
13746 binary = TRUE;
13747 if (argvars[2].v_type != VAR_UNKNOWN)
13748 maxline = get_tv_number(&argvars[2]);
13751 if (rettv_list_alloc(rettv) == FAIL)
13752 return;
13754 /* Always open the file in binary mode, library functions have a mind of
13755 * their own about CR-LF conversion. */
13756 fname = get_tv_string(&argvars[0]);
13757 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
13759 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
13760 return;
13763 filtd = 0;
13764 while (cnt < maxline || maxline < 0)
13766 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
13767 buflen = filtd + readlen;
13768 tolist = 0;
13769 for ( ; filtd < buflen || readlen <= 0; ++filtd)
13771 if (buf[filtd] == '\n' || readlen <= 0)
13773 /* Only when in binary mode add an empty list item when the
13774 * last line ends in a '\n'. */
13775 if (!binary && readlen == 0 && filtd == 0)
13776 break;
13778 /* Found end-of-line or end-of-file: add a text line to the
13779 * list. */
13780 chop = 0;
13781 if (!binary)
13782 while (filtd - chop - 1 >= tolist
13783 && buf[filtd - chop - 1] == '\r')
13784 ++chop;
13785 len = filtd - tolist - chop;
13786 if (prev == NULL)
13787 s = vim_strnsave(buf + tolist, len);
13788 else
13790 s = alloc((unsigned)(prevlen + len + 1));
13791 if (s != NULL)
13793 mch_memmove(s, prev, prevlen);
13794 vim_free(prev);
13795 prev = NULL;
13796 mch_memmove(s + prevlen, buf + tolist, len);
13797 s[prevlen + len] = NUL;
13800 tolist = filtd + 1;
13802 li = listitem_alloc();
13803 if (li == NULL)
13805 vim_free(s);
13806 break;
13808 li->li_tv.v_type = VAR_STRING;
13809 li->li_tv.v_lock = 0;
13810 li->li_tv.vval.v_string = s;
13811 list_append(rettv->vval.v_list, li);
13813 if (++cnt >= maxline && maxline >= 0)
13814 break;
13815 if (readlen <= 0)
13816 break;
13818 else if (buf[filtd] == NUL)
13819 buf[filtd] = '\n';
13821 if (readlen <= 0)
13822 break;
13824 if (tolist == 0)
13826 /* "buf" is full, need to move text to an allocated buffer */
13827 if (prev == NULL)
13829 prev = vim_strnsave(buf, buflen);
13830 prevlen = buflen;
13832 else
13834 s = alloc((unsigned)(prevlen + buflen));
13835 if (s != NULL)
13837 mch_memmove(s, prev, prevlen);
13838 mch_memmove(s + prevlen, buf, buflen);
13839 vim_free(prev);
13840 prev = s;
13841 prevlen += buflen;
13844 filtd = 0;
13846 else
13848 mch_memmove(buf, buf + tolist, buflen - tolist);
13849 filtd -= tolist;
13854 * For a negative line count use only the lines at the end of the file,
13855 * free the rest.
13857 if (maxline < 0)
13858 while (cnt > -maxline)
13860 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
13861 --cnt;
13864 vim_free(prev);
13865 fclose(fd);
13868 #if defined(FEAT_RELTIME)
13869 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
13872 * Convert a List to proftime_T.
13873 * Return FAIL when there is something wrong.
13875 static int
13876 list2proftime(arg, tm)
13877 typval_T *arg;
13878 proftime_T *tm;
13880 long n1, n2;
13881 int error = FALSE;
13883 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
13884 || arg->vval.v_list->lv_len != 2)
13885 return FAIL;
13886 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
13887 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
13888 # ifdef WIN3264
13889 tm->HighPart = n1;
13890 tm->LowPart = n2;
13891 # else
13892 tm->tv_sec = n1;
13893 tm->tv_usec = n2;
13894 # endif
13895 return error ? FAIL : OK;
13897 #endif /* FEAT_RELTIME */
13900 * "reltime()" function
13902 static void
13903 f_reltime(argvars, rettv)
13904 typval_T *argvars;
13905 typval_T *rettv;
13907 #ifdef FEAT_RELTIME
13908 proftime_T res;
13909 proftime_T start;
13911 if (argvars[0].v_type == VAR_UNKNOWN)
13913 /* No arguments: get current time. */
13914 profile_start(&res);
13916 else if (argvars[1].v_type == VAR_UNKNOWN)
13918 if (list2proftime(&argvars[0], &res) == FAIL)
13919 return;
13920 profile_end(&res);
13922 else
13924 /* Two arguments: compute the difference. */
13925 if (list2proftime(&argvars[0], &start) == FAIL
13926 || list2proftime(&argvars[1], &res) == FAIL)
13927 return;
13928 profile_sub(&res, &start);
13931 if (rettv_list_alloc(rettv) == OK)
13933 long n1, n2;
13935 # ifdef WIN3264
13936 n1 = res.HighPart;
13937 n2 = res.LowPart;
13938 # else
13939 n1 = res.tv_sec;
13940 n2 = res.tv_usec;
13941 # endif
13942 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
13943 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
13945 #endif
13949 * "reltimestr()" function
13951 static void
13952 f_reltimestr(argvars, rettv)
13953 typval_T *argvars;
13954 typval_T *rettv;
13956 #ifdef FEAT_RELTIME
13957 proftime_T tm;
13958 #endif
13960 rettv->v_type = VAR_STRING;
13961 rettv->vval.v_string = NULL;
13962 #ifdef FEAT_RELTIME
13963 if (list2proftime(&argvars[0], &tm) == OK)
13964 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
13965 #endif
13968 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
13969 static void make_connection __ARGS((void));
13970 static int check_connection __ARGS((void));
13972 static void
13973 make_connection()
13975 if (X_DISPLAY == NULL
13976 # ifdef FEAT_GUI
13977 && !gui.in_use
13978 # endif
13981 x_force_connect = TRUE;
13982 setup_term_clip();
13983 x_force_connect = FALSE;
13987 static int
13988 check_connection()
13990 make_connection();
13991 if (X_DISPLAY == NULL)
13993 EMSG(_("E240: No connection to Vim server"));
13994 return FAIL;
13996 return OK;
13998 #endif
14000 #ifdef FEAT_CLIENTSERVER
14001 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14003 static void
14004 remote_common(argvars, rettv, expr)
14005 typval_T *argvars;
14006 typval_T *rettv;
14007 int expr;
14009 char_u *server_name;
14010 char_u *keys;
14011 char_u *r = NULL;
14012 char_u buf[NUMBUFLEN];
14013 # ifdef WIN32
14014 HWND w;
14015 # elif defined(FEAT_X11)
14016 Window w;
14017 # elif defined(MAC_CLIENTSERVER)
14018 int w; // This is the port number ('w' is a bit confusing)
14019 # endif
14021 if (check_restricted() || check_secure())
14022 return;
14024 # ifdef FEAT_X11
14025 if (check_connection() == FAIL)
14026 return;
14027 # endif
14029 server_name = get_tv_string_chk(&argvars[0]);
14030 if (server_name == NULL)
14031 return; /* type error; errmsg already given */
14032 keys = get_tv_string_buf(&argvars[1], buf);
14033 # ifdef WIN32
14034 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14035 # elif defined(FEAT_X11)
14036 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14037 < 0)
14038 # elif defined(MAC_CLIENTSERVER)
14039 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14040 # endif
14042 if (r != NULL)
14043 EMSG(r); /* sending worked but evaluation failed */
14044 else
14045 EMSG2(_("E241: Unable to send to %s"), server_name);
14046 return;
14049 rettv->vval.v_string = r;
14051 if (argvars[2].v_type != VAR_UNKNOWN)
14053 dictitem_T v;
14054 char_u str[30];
14055 char_u *idvar;
14057 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14058 v.di_tv.v_type = VAR_STRING;
14059 v.di_tv.vval.v_string = vim_strsave(str);
14060 idvar = get_tv_string_chk(&argvars[2]);
14061 if (idvar != NULL)
14062 set_var(idvar, &v.di_tv, FALSE);
14063 vim_free(v.di_tv.vval.v_string);
14066 #endif
14069 * "remote_expr()" function
14071 /*ARGSUSED*/
14072 static void
14073 f_remote_expr(argvars, rettv)
14074 typval_T *argvars;
14075 typval_T *rettv;
14077 rettv->v_type = VAR_STRING;
14078 rettv->vval.v_string = NULL;
14079 #ifdef FEAT_CLIENTSERVER
14080 remote_common(argvars, rettv, TRUE);
14081 #endif
14085 * "remote_foreground()" function
14087 /*ARGSUSED*/
14088 static void
14089 f_remote_foreground(argvars, rettv)
14090 typval_T *argvars;
14091 typval_T *rettv;
14093 rettv->vval.v_number = 0;
14094 #ifdef FEAT_CLIENTSERVER
14095 # ifdef WIN32
14096 /* On Win32 it's done in this application. */
14098 char_u *server_name = get_tv_string_chk(&argvars[0]);
14100 if (server_name != NULL)
14101 serverForeground(server_name);
14103 # elif defined(FEAT_X11) || defined(MAC_CLIENTSERVER)
14104 /* Send a foreground() expression to the server. */
14105 argvars[1].v_type = VAR_STRING;
14106 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14107 argvars[2].v_type = VAR_UNKNOWN;
14108 remote_common(argvars, rettv, TRUE);
14109 vim_free(argvars[1].vval.v_string);
14110 # endif
14111 #endif
14114 /*ARGSUSED*/
14115 static void
14116 f_remote_peek(argvars, rettv)
14117 typval_T *argvars;
14118 typval_T *rettv;
14120 #ifdef FEAT_CLIENTSERVER
14121 dictitem_T v;
14122 char_u *s = NULL;
14123 # ifdef WIN32
14124 long_u n = 0;
14125 # endif
14126 char_u *serverid;
14128 if (check_restricted() || check_secure())
14130 rettv->vval.v_number = -1;
14131 return;
14133 serverid = get_tv_string_chk(&argvars[0]);
14134 if (serverid == NULL)
14136 rettv->vval.v_number = -1;
14137 return; /* type error; errmsg already given */
14139 # ifdef WIN32
14140 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14141 if (n == 0)
14142 rettv->vval.v_number = -1;
14143 else
14145 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14146 rettv->vval.v_number = (s != NULL);
14148 # elif defined(FEAT_X11)
14149 rettv->vval.v_number = 0;
14150 if (check_connection() == FAIL)
14151 return;
14153 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14154 serverStrToWin(serverid), &s);
14155 # elif defined(MAC_CLIENTSERVER)
14156 rettv->vval.v_number = serverPeekReply(serverStrToPort(serverid), &s);
14157 # endif
14159 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14161 char_u *retvar;
14163 v.di_tv.v_type = VAR_STRING;
14164 v.di_tv.vval.v_string = vim_strsave(s);
14165 retvar = get_tv_string_chk(&argvars[1]);
14166 if (retvar != NULL)
14167 set_var(retvar, &v.di_tv, FALSE);
14168 vim_free(v.di_tv.vval.v_string);
14170 #else
14171 rettv->vval.v_number = -1;
14172 #endif
14175 /*ARGSUSED*/
14176 static void
14177 f_remote_read(argvars, rettv)
14178 typval_T *argvars;
14179 typval_T *rettv;
14181 char_u *r = NULL;
14183 #ifdef FEAT_CLIENTSERVER
14184 char_u *serverid = get_tv_string_chk(&argvars[0]);
14186 if (serverid != NULL && !check_restricted() && !check_secure())
14188 # ifdef WIN32
14189 /* The server's HWND is encoded in the 'id' parameter */
14190 long_u n = 0;
14192 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14193 if (n != 0)
14194 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14195 if (r == NULL)
14196 # elif defined(FEAT_X11)
14197 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14198 serverStrToWin(serverid), &r, FALSE) < 0)
14199 # elif defined(MAC_CLIENTSERVER)
14200 if (serverReadReply(serverStrToPort(serverid), &r) < 0)
14201 # endif
14202 EMSG(_("E277: Unable to read a server reply"));
14204 #endif
14205 rettv->v_type = VAR_STRING;
14206 rettv->vval.v_string = r;
14210 * "remote_send()" function
14212 /*ARGSUSED*/
14213 static void
14214 f_remote_send(argvars, rettv)
14215 typval_T *argvars;
14216 typval_T *rettv;
14218 rettv->v_type = VAR_STRING;
14219 rettv->vval.v_string = NULL;
14220 #ifdef FEAT_CLIENTSERVER
14221 remote_common(argvars, rettv, FALSE);
14222 #endif
14226 * "remove()" function
14228 static void
14229 f_remove(argvars, rettv)
14230 typval_T *argvars;
14231 typval_T *rettv;
14233 list_T *l;
14234 listitem_T *item, *item2;
14235 listitem_T *li;
14236 long idx;
14237 long end;
14238 char_u *key;
14239 dict_T *d;
14240 dictitem_T *di;
14242 rettv->vval.v_number = 0;
14243 if (argvars[0].v_type == VAR_DICT)
14245 if (argvars[2].v_type != VAR_UNKNOWN)
14246 EMSG2(_(e_toomanyarg), "remove()");
14247 else if ((d = argvars[0].vval.v_dict) != NULL
14248 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14250 key = get_tv_string_chk(&argvars[1]);
14251 if (key != NULL)
14253 di = dict_find(d, key, -1);
14254 if (di == NULL)
14255 EMSG2(_(e_dictkey), key);
14256 else
14258 *rettv = di->di_tv;
14259 init_tv(&di->di_tv);
14260 dictitem_remove(d, di);
14265 else if (argvars[0].v_type != VAR_LIST)
14266 EMSG2(_(e_listdictarg), "remove()");
14267 else if ((l = argvars[0].vval.v_list) != NULL
14268 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14270 int error = FALSE;
14272 idx = get_tv_number_chk(&argvars[1], &error);
14273 if (error)
14274 ; /* type error: do nothing, errmsg already given */
14275 else if ((item = list_find(l, idx)) == NULL)
14276 EMSGN(_(e_listidx), idx);
14277 else
14279 if (argvars[2].v_type == VAR_UNKNOWN)
14281 /* Remove one item, return its value. */
14282 list_remove(l, item, item);
14283 *rettv = item->li_tv;
14284 vim_free(item);
14286 else
14288 /* Remove range of items, return list with values. */
14289 end = get_tv_number_chk(&argvars[2], &error);
14290 if (error)
14291 ; /* type error: do nothing */
14292 else if ((item2 = list_find(l, end)) == NULL)
14293 EMSGN(_(e_listidx), end);
14294 else
14296 int cnt = 0;
14298 for (li = item; li != NULL; li = li->li_next)
14300 ++cnt;
14301 if (li == item2)
14302 break;
14304 if (li == NULL) /* didn't find "item2" after "item" */
14305 EMSG(_(e_invrange));
14306 else
14308 list_remove(l, item, item2);
14309 if (rettv_list_alloc(rettv) == OK)
14311 l = rettv->vval.v_list;
14312 l->lv_first = item;
14313 l->lv_last = item2;
14314 item->li_prev = NULL;
14315 item2->li_next = NULL;
14316 l->lv_len = cnt;
14326 * "rename({from}, {to})" function
14328 static void
14329 f_rename(argvars, rettv)
14330 typval_T *argvars;
14331 typval_T *rettv;
14333 char_u buf[NUMBUFLEN];
14335 if (check_restricted() || check_secure())
14336 rettv->vval.v_number = -1;
14337 else
14338 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14339 get_tv_string_buf(&argvars[1], buf));
14343 * "repeat()" function
14345 /*ARGSUSED*/
14346 static void
14347 f_repeat(argvars, rettv)
14348 typval_T *argvars;
14349 typval_T *rettv;
14351 char_u *p;
14352 int n;
14353 int slen;
14354 int len;
14355 char_u *r;
14356 int i;
14358 n = get_tv_number(&argvars[1]);
14359 if (argvars[0].v_type == VAR_LIST)
14361 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14362 while (n-- > 0)
14363 if (list_extend(rettv->vval.v_list,
14364 argvars[0].vval.v_list, NULL) == FAIL)
14365 break;
14367 else
14369 p = get_tv_string(&argvars[0]);
14370 rettv->v_type = VAR_STRING;
14371 rettv->vval.v_string = NULL;
14373 slen = (int)STRLEN(p);
14374 len = slen * n;
14375 if (len <= 0)
14376 return;
14378 r = alloc(len + 1);
14379 if (r != NULL)
14381 for (i = 0; i < n; i++)
14382 mch_memmove(r + i * slen, p, (size_t)slen);
14383 r[len] = NUL;
14386 rettv->vval.v_string = r;
14391 * "resolve()" function
14393 static void
14394 f_resolve(argvars, rettv)
14395 typval_T *argvars;
14396 typval_T *rettv;
14398 char_u *p;
14400 p = get_tv_string(&argvars[0]);
14401 #ifdef FEAT_SHORTCUT
14403 char_u *v = NULL;
14405 v = mch_resolve_shortcut(p);
14406 if (v != NULL)
14407 rettv->vval.v_string = v;
14408 else
14409 rettv->vval.v_string = vim_strsave(p);
14411 #else
14412 # ifdef HAVE_READLINK
14414 char_u buf[MAXPATHL + 1];
14415 char_u *cpy;
14416 int len;
14417 char_u *remain = NULL;
14418 char_u *q;
14419 int is_relative_to_current = FALSE;
14420 int has_trailing_pathsep = FALSE;
14421 int limit = 100;
14423 p = vim_strsave(p);
14425 if (p[0] == '.' && (vim_ispathsep(p[1])
14426 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14427 is_relative_to_current = TRUE;
14429 len = STRLEN(p);
14430 if (len > 0 && after_pathsep(p, p + len))
14431 has_trailing_pathsep = TRUE;
14433 q = getnextcomp(p);
14434 if (*q != NUL)
14436 /* Separate the first path component in "p", and keep the
14437 * remainder (beginning with the path separator). */
14438 remain = vim_strsave(q - 1);
14439 q[-1] = NUL;
14442 for (;;)
14444 for (;;)
14446 len = readlink((char *)p, (char *)buf, MAXPATHL);
14447 if (len <= 0)
14448 break;
14449 buf[len] = NUL;
14451 if (limit-- == 0)
14453 vim_free(p);
14454 vim_free(remain);
14455 EMSG(_("E655: Too many symbolic links (cycle?)"));
14456 rettv->vval.v_string = NULL;
14457 goto fail;
14460 /* Ensure that the result will have a trailing path separator
14461 * if the argument has one. */
14462 if (remain == NULL && has_trailing_pathsep)
14463 add_pathsep(buf);
14465 /* Separate the first path component in the link value and
14466 * concatenate the remainders. */
14467 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14468 if (*q != NUL)
14470 if (remain == NULL)
14471 remain = vim_strsave(q - 1);
14472 else
14474 cpy = concat_str(q - 1, remain);
14475 if (cpy != NULL)
14477 vim_free(remain);
14478 remain = cpy;
14481 q[-1] = NUL;
14484 q = gettail(p);
14485 if (q > p && *q == NUL)
14487 /* Ignore trailing path separator. */
14488 q[-1] = NUL;
14489 q = gettail(p);
14491 if (q > p && !mch_isFullName(buf))
14493 /* symlink is relative to directory of argument */
14494 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14495 if (cpy != NULL)
14497 STRCPY(cpy, p);
14498 STRCPY(gettail(cpy), buf);
14499 vim_free(p);
14500 p = cpy;
14503 else
14505 vim_free(p);
14506 p = vim_strsave(buf);
14510 if (remain == NULL)
14511 break;
14513 /* Append the first path component of "remain" to "p". */
14514 q = getnextcomp(remain + 1);
14515 len = q - remain - (*q != NUL);
14516 cpy = vim_strnsave(p, STRLEN(p) + len);
14517 if (cpy != NULL)
14519 STRNCAT(cpy, remain, len);
14520 vim_free(p);
14521 p = cpy;
14523 /* Shorten "remain". */
14524 if (*q != NUL)
14525 STRMOVE(remain, q - 1);
14526 else
14528 vim_free(remain);
14529 remain = NULL;
14533 /* If the result is a relative path name, make it explicitly relative to
14534 * the current directory if and only if the argument had this form. */
14535 if (!vim_ispathsep(*p))
14537 if (is_relative_to_current
14538 && *p != NUL
14539 && !(p[0] == '.'
14540 && (p[1] == NUL
14541 || vim_ispathsep(p[1])
14542 || (p[1] == '.'
14543 && (p[2] == NUL
14544 || vim_ispathsep(p[2]))))))
14546 /* Prepend "./". */
14547 cpy = concat_str((char_u *)"./", p);
14548 if (cpy != NULL)
14550 vim_free(p);
14551 p = cpy;
14554 else if (!is_relative_to_current)
14556 /* Strip leading "./". */
14557 q = p;
14558 while (q[0] == '.' && vim_ispathsep(q[1]))
14559 q += 2;
14560 if (q > p)
14561 STRMOVE(p, p + 2);
14565 /* Ensure that the result will have no trailing path separator
14566 * if the argument had none. But keep "/" or "//". */
14567 if (!has_trailing_pathsep)
14569 q = p + STRLEN(p);
14570 if (after_pathsep(p, q))
14571 *gettail_sep(p) = NUL;
14574 rettv->vval.v_string = p;
14576 # else
14577 rettv->vval.v_string = vim_strsave(p);
14578 # endif
14579 #endif
14581 simplify_filename(rettv->vval.v_string);
14583 #ifdef HAVE_READLINK
14584 fail:
14585 #endif
14586 rettv->v_type = VAR_STRING;
14590 * "reverse({list})" function
14592 static void
14593 f_reverse(argvars, rettv)
14594 typval_T *argvars;
14595 typval_T *rettv;
14597 list_T *l;
14598 listitem_T *li, *ni;
14600 rettv->vval.v_number = 0;
14601 if (argvars[0].v_type != VAR_LIST)
14602 EMSG2(_(e_listarg), "reverse()");
14603 else if ((l = argvars[0].vval.v_list) != NULL
14604 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14606 li = l->lv_last;
14607 l->lv_first = l->lv_last = NULL;
14608 l->lv_len = 0;
14609 while (li != NULL)
14611 ni = li->li_prev;
14612 list_append(l, li);
14613 li = ni;
14615 rettv->vval.v_list = l;
14616 rettv->v_type = VAR_LIST;
14617 ++l->lv_refcount;
14618 l->lv_idx = l->lv_len - l->lv_idx - 1;
14622 #define SP_NOMOVE 0x01 /* don't move cursor */
14623 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14624 #define SP_RETCOUNT 0x04 /* return matchcount */
14625 #define SP_SETPCMARK 0x08 /* set previous context mark */
14626 #define SP_START 0x10 /* accept match at start position */
14627 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14628 #define SP_END 0x40 /* leave cursor at end of match */
14630 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14633 * Get flags for a search function.
14634 * Possibly sets "p_ws".
14635 * Returns BACKWARD, FORWARD or zero (for an error).
14637 static int
14638 get_search_arg(varp, flagsp)
14639 typval_T *varp;
14640 int *flagsp;
14642 int dir = FORWARD;
14643 char_u *flags;
14644 char_u nbuf[NUMBUFLEN];
14645 int mask;
14647 if (varp->v_type != VAR_UNKNOWN)
14649 flags = get_tv_string_buf_chk(varp, nbuf);
14650 if (flags == NULL)
14651 return 0; /* type error; errmsg already given */
14652 while (*flags != NUL)
14654 switch (*flags)
14656 case 'b': dir = BACKWARD; break;
14657 case 'w': p_ws = TRUE; break;
14658 case 'W': p_ws = FALSE; break;
14659 default: mask = 0;
14660 if (flagsp != NULL)
14661 switch (*flags)
14663 case 'c': mask = SP_START; break;
14664 case 'e': mask = SP_END; break;
14665 case 'm': mask = SP_RETCOUNT; break;
14666 case 'n': mask = SP_NOMOVE; break;
14667 case 'p': mask = SP_SUBPAT; break;
14668 case 'r': mask = SP_REPEAT; break;
14669 case 's': mask = SP_SETPCMARK; break;
14671 if (mask == 0)
14673 EMSG2(_(e_invarg2), flags);
14674 dir = 0;
14676 else
14677 *flagsp |= mask;
14679 if (dir == 0)
14680 break;
14681 ++flags;
14684 return dir;
14688 * Shared by search() and searchpos() functions
14690 static int
14691 search_cmn(argvars, match_pos, flagsp)
14692 typval_T *argvars;
14693 pos_T *match_pos;
14694 int *flagsp;
14696 int flags;
14697 char_u *pat;
14698 pos_T pos;
14699 pos_T save_cursor;
14700 int save_p_ws = p_ws;
14701 int dir;
14702 int retval = 0; /* default: FAIL */
14703 long lnum_stop = 0;
14704 proftime_T tm;
14705 #ifdef FEAT_RELTIME
14706 long time_limit = 0;
14707 #endif
14708 int options = SEARCH_KEEP;
14709 int subpatnum;
14711 pat = get_tv_string(&argvars[0]);
14712 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
14713 if (dir == 0)
14714 goto theend;
14715 flags = *flagsp;
14716 if (flags & SP_START)
14717 options |= SEARCH_START;
14718 if (flags & SP_END)
14719 options |= SEARCH_END;
14721 /* Optional arguments: line number to stop searching and timeout. */
14722 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
14724 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
14725 if (lnum_stop < 0)
14726 goto theend;
14727 #ifdef FEAT_RELTIME
14728 if (argvars[3].v_type != VAR_UNKNOWN)
14730 time_limit = get_tv_number_chk(&argvars[3], NULL);
14731 if (time_limit < 0)
14732 goto theend;
14734 #endif
14737 #ifdef FEAT_RELTIME
14738 /* Set the time limit, if there is one. */
14739 profile_setlimit(time_limit, &tm);
14740 #endif
14743 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
14744 * Check to make sure only those flags are set.
14745 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
14746 * flags cannot be set. Check for that condition also.
14748 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
14749 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14751 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
14752 goto theend;
14755 pos = save_cursor = curwin->w_cursor;
14756 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
14757 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
14758 if (subpatnum != FAIL)
14760 if (flags & SP_SUBPAT)
14761 retval = subpatnum;
14762 else
14763 retval = pos.lnum;
14764 if (flags & SP_SETPCMARK)
14765 setpcmark();
14766 curwin->w_cursor = pos;
14767 if (match_pos != NULL)
14769 /* Store the match cursor position */
14770 match_pos->lnum = pos.lnum;
14771 match_pos->col = pos.col + 1;
14773 /* "/$" will put the cursor after the end of the line, may need to
14774 * correct that here */
14775 check_cursor();
14778 /* If 'n' flag is used: restore cursor position. */
14779 if (flags & SP_NOMOVE)
14780 curwin->w_cursor = save_cursor;
14781 else
14782 curwin->w_set_curswant = TRUE;
14783 theend:
14784 p_ws = save_p_ws;
14786 return retval;
14789 #ifdef FEAT_FLOAT
14791 * "round({float})" function
14793 static void
14794 f_round(argvars, rettv)
14795 typval_T *argvars;
14796 typval_T *rettv;
14798 float_T f;
14800 rettv->v_type = VAR_FLOAT;
14801 if (get_float_arg(argvars, &f) == OK)
14802 /* round() is not in C90, use ceil() or floor() instead. */
14803 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
14804 else
14805 rettv->vval.v_float = 0.0;
14807 #endif
14810 * "search()" function
14812 static void
14813 f_search(argvars, rettv)
14814 typval_T *argvars;
14815 typval_T *rettv;
14817 int flags = 0;
14819 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
14823 * "searchdecl()" function
14825 static void
14826 f_searchdecl(argvars, rettv)
14827 typval_T *argvars;
14828 typval_T *rettv;
14830 int locally = 1;
14831 int thisblock = 0;
14832 int error = FALSE;
14833 char_u *name;
14835 rettv->vval.v_number = 1; /* default: FAIL */
14837 name = get_tv_string_chk(&argvars[0]);
14838 if (argvars[1].v_type != VAR_UNKNOWN)
14840 locally = get_tv_number_chk(&argvars[1], &error) == 0;
14841 if (!error && argvars[2].v_type != VAR_UNKNOWN)
14842 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
14844 if (!error && name != NULL)
14845 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
14846 locally, thisblock, SEARCH_KEEP) == FAIL;
14850 * Used by searchpair() and searchpairpos()
14852 static int
14853 searchpair_cmn(argvars, match_pos)
14854 typval_T *argvars;
14855 pos_T *match_pos;
14857 char_u *spat, *mpat, *epat;
14858 char_u *skip;
14859 int save_p_ws = p_ws;
14860 int dir;
14861 int flags = 0;
14862 char_u nbuf1[NUMBUFLEN];
14863 char_u nbuf2[NUMBUFLEN];
14864 char_u nbuf3[NUMBUFLEN];
14865 int retval = 0; /* default: FAIL */
14866 long lnum_stop = 0;
14867 long time_limit = 0;
14869 /* Get the three pattern arguments: start, middle, end. */
14870 spat = get_tv_string_chk(&argvars[0]);
14871 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
14872 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
14873 if (spat == NULL || mpat == NULL || epat == NULL)
14874 goto theend; /* type error */
14876 /* Handle the optional fourth argument: flags */
14877 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
14878 if (dir == 0)
14879 goto theend;
14881 /* Don't accept SP_END or SP_SUBPAT.
14882 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
14884 if ((flags & (SP_END | SP_SUBPAT)) != 0
14885 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
14887 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
14888 goto theend;
14891 /* Using 'r' implies 'W', otherwise it doesn't work. */
14892 if (flags & SP_REPEAT)
14893 p_ws = FALSE;
14895 /* Optional fifth argument: skip expression */
14896 if (argvars[3].v_type == VAR_UNKNOWN
14897 || argvars[4].v_type == VAR_UNKNOWN)
14898 skip = (char_u *)"";
14899 else
14901 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
14902 if (argvars[5].v_type != VAR_UNKNOWN)
14904 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
14905 if (lnum_stop < 0)
14906 goto theend;
14907 #ifdef FEAT_RELTIME
14908 if (argvars[6].v_type != VAR_UNKNOWN)
14910 time_limit = get_tv_number_chk(&argvars[6], NULL);
14911 if (time_limit < 0)
14912 goto theend;
14914 #endif
14917 if (skip == NULL)
14918 goto theend; /* type error */
14920 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
14921 match_pos, lnum_stop, time_limit);
14923 theend:
14924 p_ws = save_p_ws;
14926 return retval;
14930 * "searchpair()" function
14932 static void
14933 f_searchpair(argvars, rettv)
14934 typval_T *argvars;
14935 typval_T *rettv;
14937 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
14941 * "searchpairpos()" function
14943 static void
14944 f_searchpairpos(argvars, rettv)
14945 typval_T *argvars;
14946 typval_T *rettv;
14948 pos_T match_pos;
14949 int lnum = 0;
14950 int col = 0;
14952 rettv->vval.v_number = 0;
14954 if (rettv_list_alloc(rettv) == FAIL)
14955 return;
14957 if (searchpair_cmn(argvars, &match_pos) > 0)
14959 lnum = match_pos.lnum;
14960 col = match_pos.col;
14963 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
14964 list_append_number(rettv->vval.v_list, (varnumber_T)col);
14968 * Search for a start/middle/end thing.
14969 * Used by searchpair(), see its documentation for the details.
14970 * Returns 0 or -1 for no match,
14972 long
14973 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
14974 lnum_stop, time_limit)
14975 char_u *spat; /* start pattern */
14976 char_u *mpat; /* middle pattern */
14977 char_u *epat; /* end pattern */
14978 int dir; /* BACKWARD or FORWARD */
14979 char_u *skip; /* skip expression */
14980 int flags; /* SP_SETPCMARK and other SP_ values */
14981 pos_T *match_pos;
14982 linenr_T lnum_stop; /* stop at this line if not zero */
14983 long time_limit; /* stop after this many msec */
14985 char_u *save_cpo;
14986 char_u *pat, *pat2 = NULL, *pat3 = NULL;
14987 long retval = 0;
14988 pos_T pos;
14989 pos_T firstpos;
14990 pos_T foundpos;
14991 pos_T save_cursor;
14992 pos_T save_pos;
14993 int n;
14994 int r;
14995 int nest = 1;
14996 int err;
14997 int options = SEARCH_KEEP;
14998 proftime_T tm;
15000 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15001 save_cpo = p_cpo;
15002 p_cpo = (char_u *)"";
15004 #ifdef FEAT_RELTIME
15005 /* Set the time limit, if there is one. */
15006 profile_setlimit(time_limit, &tm);
15007 #endif
15009 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15010 * start/middle/end (pat3, for the top pair). */
15011 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15012 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15013 if (pat2 == NULL || pat3 == NULL)
15014 goto theend;
15015 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15016 if (*mpat == NUL)
15017 STRCPY(pat3, pat2);
15018 else
15019 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15020 spat, epat, mpat);
15021 if (flags & SP_START)
15022 options |= SEARCH_START;
15024 save_cursor = curwin->w_cursor;
15025 pos = curwin->w_cursor;
15026 clearpos(&firstpos);
15027 clearpos(&foundpos);
15028 pat = pat3;
15029 for (;;)
15031 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15032 options, RE_SEARCH, lnum_stop, &tm);
15033 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15034 /* didn't find it or found the first match again: FAIL */
15035 break;
15037 if (firstpos.lnum == 0)
15038 firstpos = pos;
15039 if (equalpos(pos, foundpos))
15041 /* Found the same position again. Can happen with a pattern that
15042 * has "\zs" at the end and searching backwards. Advance one
15043 * character and try again. */
15044 if (dir == BACKWARD)
15045 decl(&pos);
15046 else
15047 incl(&pos);
15049 foundpos = pos;
15051 /* clear the start flag to avoid getting stuck here */
15052 options &= ~SEARCH_START;
15054 /* If the skip pattern matches, ignore this match. */
15055 if (*skip != NUL)
15057 save_pos = curwin->w_cursor;
15058 curwin->w_cursor = pos;
15059 r = eval_to_bool(skip, &err, NULL, FALSE);
15060 curwin->w_cursor = save_pos;
15061 if (err)
15063 /* Evaluating {skip} caused an error, break here. */
15064 curwin->w_cursor = save_cursor;
15065 retval = -1;
15066 break;
15068 if (r)
15069 continue;
15072 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15074 /* Found end when searching backwards or start when searching
15075 * forward: nested pair. */
15076 ++nest;
15077 pat = pat2; /* nested, don't search for middle */
15079 else
15081 /* Found end when searching forward or start when searching
15082 * backward: end of (nested) pair; or found middle in outer pair. */
15083 if (--nest == 1)
15084 pat = pat3; /* outer level, search for middle */
15087 if (nest == 0)
15089 /* Found the match: return matchcount or line number. */
15090 if (flags & SP_RETCOUNT)
15091 ++retval;
15092 else
15093 retval = pos.lnum;
15094 if (flags & SP_SETPCMARK)
15095 setpcmark();
15096 curwin->w_cursor = pos;
15097 if (!(flags & SP_REPEAT))
15098 break;
15099 nest = 1; /* search for next unmatched */
15103 if (match_pos != NULL)
15105 /* Store the match cursor position */
15106 match_pos->lnum = curwin->w_cursor.lnum;
15107 match_pos->col = curwin->w_cursor.col + 1;
15110 /* If 'n' flag is used or search failed: restore cursor position. */
15111 if ((flags & SP_NOMOVE) || retval == 0)
15112 curwin->w_cursor = save_cursor;
15114 theend:
15115 vim_free(pat2);
15116 vim_free(pat3);
15117 p_cpo = save_cpo;
15119 return retval;
15123 * "searchpos()" function
15125 static void
15126 f_searchpos(argvars, rettv)
15127 typval_T *argvars;
15128 typval_T *rettv;
15130 pos_T match_pos;
15131 int lnum = 0;
15132 int col = 0;
15133 int n;
15134 int flags = 0;
15136 rettv->vval.v_number = 0;
15138 if (rettv_list_alloc(rettv) == FAIL)
15139 return;
15141 n = search_cmn(argvars, &match_pos, &flags);
15142 if (n > 0)
15144 lnum = match_pos.lnum;
15145 col = match_pos.col;
15148 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15149 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15150 if (flags & SP_SUBPAT)
15151 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15155 /*ARGSUSED*/
15156 static void
15157 f_server2client(argvars, rettv)
15158 typval_T *argvars;
15159 typval_T *rettv;
15161 #ifdef FEAT_CLIENTSERVER
15162 char_u buf[NUMBUFLEN];
15163 char_u *server = get_tv_string_chk(&argvars[0]);
15164 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15166 rettv->vval.v_number = -1;
15167 if (server == NULL || reply == NULL)
15168 return;
15169 if (check_restricted() || check_secure())
15170 return;
15171 # ifdef FEAT_X11
15172 if (check_connection() == FAIL)
15173 return;
15174 # endif
15176 if (serverSendReply(server, reply) < 0)
15178 EMSG(_("E258: Unable to send to client"));
15179 return;
15181 rettv->vval.v_number = 0;
15182 #else
15183 rettv->vval.v_number = -1;
15184 #endif
15187 /*ARGSUSED*/
15188 static void
15189 f_serverlist(argvars, rettv)
15190 typval_T *argvars;
15191 typval_T *rettv;
15193 char_u *r = NULL;
15195 #ifdef FEAT_CLIENTSERVER
15196 # if defined(WIN32) || defined(MAC_CLIENTSERVER)
15197 r = serverGetVimNames();
15198 # elif defined(FEAT_X11)
15199 make_connection();
15200 if (X_DISPLAY != NULL)
15201 r = serverGetVimNames(X_DISPLAY);
15202 # endif
15203 #endif
15204 rettv->v_type = VAR_STRING;
15205 rettv->vval.v_string = r;
15209 * "setbufvar()" function
15211 /*ARGSUSED*/
15212 static void
15213 f_setbufvar(argvars, rettv)
15214 typval_T *argvars;
15215 typval_T *rettv;
15217 buf_T *buf;
15218 aco_save_T aco;
15219 char_u *varname, *bufvarname;
15220 typval_T *varp;
15221 char_u nbuf[NUMBUFLEN];
15223 rettv->vval.v_number = 0;
15225 if (check_restricted() || check_secure())
15226 return;
15227 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15228 varname = get_tv_string_chk(&argvars[1]);
15229 buf = get_buf_tv(&argvars[0]);
15230 varp = &argvars[2];
15232 if (buf != NULL && varname != NULL && varp != NULL)
15234 /* set curbuf to be our buf, temporarily */
15235 aucmd_prepbuf(&aco, buf);
15237 if (*varname == '&')
15239 long numval;
15240 char_u *strval;
15241 int error = FALSE;
15243 ++varname;
15244 numval = get_tv_number_chk(varp, &error);
15245 strval = get_tv_string_buf_chk(varp, nbuf);
15246 if (!error && strval != NULL)
15247 set_option_value(varname, numval, strval, OPT_LOCAL);
15249 else
15251 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15252 if (bufvarname != NULL)
15254 STRCPY(bufvarname, "b:");
15255 STRCPY(bufvarname + 2, varname);
15256 set_var(bufvarname, varp, TRUE);
15257 vim_free(bufvarname);
15261 /* reset notion of buffer */
15262 aucmd_restbuf(&aco);
15267 * "setcmdpos()" function
15269 static void
15270 f_setcmdpos(argvars, rettv)
15271 typval_T *argvars;
15272 typval_T *rettv;
15274 int pos = (int)get_tv_number(&argvars[0]) - 1;
15276 if (pos >= 0)
15277 rettv->vval.v_number = set_cmdline_pos(pos);
15281 * "setline()" function
15283 static void
15284 f_setline(argvars, rettv)
15285 typval_T *argvars;
15286 typval_T *rettv;
15288 linenr_T lnum;
15289 char_u *line = NULL;
15290 list_T *l = NULL;
15291 listitem_T *li = NULL;
15292 long added = 0;
15293 linenr_T lcount = curbuf->b_ml.ml_line_count;
15295 lnum = get_tv_lnum(&argvars[0]);
15296 if (argvars[1].v_type == VAR_LIST)
15298 l = argvars[1].vval.v_list;
15299 li = l->lv_first;
15301 else
15302 line = get_tv_string_chk(&argvars[1]);
15304 rettv->vval.v_number = 0; /* OK */
15305 for (;;)
15307 if (l != NULL)
15309 /* list argument, get next string */
15310 if (li == NULL)
15311 break;
15312 line = get_tv_string_chk(&li->li_tv);
15313 li = li->li_next;
15316 rettv->vval.v_number = 1; /* FAIL */
15317 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15318 break;
15319 if (lnum <= curbuf->b_ml.ml_line_count)
15321 /* existing line, replace it */
15322 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15324 changed_bytes(lnum, 0);
15325 if (lnum == curwin->w_cursor.lnum)
15326 check_cursor_col();
15327 rettv->vval.v_number = 0; /* OK */
15330 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15332 /* lnum is one past the last line, append the line */
15333 ++added;
15334 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15335 rettv->vval.v_number = 0; /* OK */
15338 if (l == NULL) /* only one string argument */
15339 break;
15340 ++lnum;
15343 if (added > 0)
15344 appended_lines_mark(lcount, added);
15347 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15350 * Used by "setqflist()" and "setloclist()" functions
15352 /*ARGSUSED*/
15353 static void
15354 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15355 win_T *wp;
15356 typval_T *list_arg;
15357 typval_T *action_arg;
15358 typval_T *rettv;
15360 #ifdef FEAT_QUICKFIX
15361 char_u *act;
15362 int action = ' ';
15363 #endif
15365 rettv->vval.v_number = -1;
15367 #ifdef FEAT_QUICKFIX
15368 if (list_arg->v_type != VAR_LIST)
15369 EMSG(_(e_listreq));
15370 else
15372 list_T *l = list_arg->vval.v_list;
15374 if (action_arg->v_type == VAR_STRING)
15376 act = get_tv_string_chk(action_arg);
15377 if (act == NULL)
15378 return; /* type error; errmsg already given */
15379 if (*act == 'a' || *act == 'r')
15380 action = *act;
15383 if (l != NULL && set_errorlist(wp, l, action) == OK)
15384 rettv->vval.v_number = 0;
15386 #endif
15390 * "setloclist()" function
15392 /*ARGSUSED*/
15393 static void
15394 f_setloclist(argvars, rettv)
15395 typval_T *argvars;
15396 typval_T *rettv;
15398 win_T *win;
15400 rettv->vval.v_number = -1;
15402 win = find_win_by_nr(&argvars[0], NULL);
15403 if (win != NULL)
15404 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15408 * "setmatches()" function
15410 static void
15411 f_setmatches(argvars, rettv)
15412 typval_T *argvars;
15413 typval_T *rettv;
15415 #ifdef FEAT_SEARCH_EXTRA
15416 list_T *l;
15417 listitem_T *li;
15418 dict_T *d;
15420 rettv->vval.v_number = -1;
15421 if (argvars[0].v_type != VAR_LIST)
15423 EMSG(_(e_listreq));
15424 return;
15426 if ((l = argvars[0].vval.v_list) != NULL)
15429 /* To some extent make sure that we are dealing with a list from
15430 * "getmatches()". */
15431 li = l->lv_first;
15432 while (li != NULL)
15434 if (li->li_tv.v_type != VAR_DICT
15435 || (d = li->li_tv.vval.v_dict) == NULL)
15437 EMSG(_(e_invarg));
15438 return;
15440 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15441 && dict_find(d, (char_u *)"pattern", -1) != NULL
15442 && dict_find(d, (char_u *)"priority", -1) != NULL
15443 && dict_find(d, (char_u *)"id", -1) != NULL))
15445 EMSG(_(e_invarg));
15446 return;
15448 li = li->li_next;
15451 clear_matches(curwin);
15452 li = l->lv_first;
15453 while (li != NULL)
15455 d = li->li_tv.vval.v_dict;
15456 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15457 get_dict_string(d, (char_u *)"pattern", FALSE),
15458 (int)get_dict_number(d, (char_u *)"priority"),
15459 (int)get_dict_number(d, (char_u *)"id"));
15460 li = li->li_next;
15462 rettv->vval.v_number = 0;
15464 #endif
15468 * "setpos()" function
15470 /*ARGSUSED*/
15471 static void
15472 f_setpos(argvars, rettv)
15473 typval_T *argvars;
15474 typval_T *rettv;
15476 pos_T pos;
15477 int fnum;
15478 char_u *name;
15480 rettv->vval.v_number = -1;
15481 name = get_tv_string_chk(argvars);
15482 if (name != NULL)
15484 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15486 --pos.col;
15487 if (name[0] == '.' && name[1] == NUL)
15489 /* set cursor */
15490 if (fnum == curbuf->b_fnum)
15492 curwin->w_cursor = pos;
15493 check_cursor();
15494 rettv->vval.v_number = 0;
15496 else
15497 EMSG(_(e_invarg));
15499 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15501 /* set mark */
15502 if (setmark_pos(name[1], &pos, fnum) == OK)
15503 rettv->vval.v_number = 0;
15505 else
15506 EMSG(_(e_invarg));
15512 * "setqflist()" function
15514 /*ARGSUSED*/
15515 static void
15516 f_setqflist(argvars, rettv)
15517 typval_T *argvars;
15518 typval_T *rettv;
15520 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15524 * "setreg()" function
15526 static void
15527 f_setreg(argvars, rettv)
15528 typval_T *argvars;
15529 typval_T *rettv;
15531 int regname;
15532 char_u *strregname;
15533 char_u *stropt;
15534 char_u *strval;
15535 int append;
15536 char_u yank_type;
15537 long block_len;
15539 block_len = -1;
15540 yank_type = MAUTO;
15541 append = FALSE;
15543 strregname = get_tv_string_chk(argvars);
15544 rettv->vval.v_number = 1; /* FAIL is default */
15546 if (strregname == NULL)
15547 return; /* type error; errmsg already given */
15548 regname = *strregname;
15549 if (regname == 0 || regname == '@')
15550 regname = '"';
15551 else if (regname == '=')
15552 return;
15554 if (argvars[2].v_type != VAR_UNKNOWN)
15556 stropt = get_tv_string_chk(&argvars[2]);
15557 if (stropt == NULL)
15558 return; /* type error */
15559 for (; *stropt != NUL; ++stropt)
15560 switch (*stropt)
15562 case 'a': case 'A': /* append */
15563 append = TRUE;
15564 break;
15565 case 'v': case 'c': /* character-wise selection */
15566 yank_type = MCHAR;
15567 break;
15568 case 'V': case 'l': /* line-wise selection */
15569 yank_type = MLINE;
15570 break;
15571 #ifdef FEAT_VISUAL
15572 case 'b': case Ctrl_V: /* block-wise selection */
15573 yank_type = MBLOCK;
15574 if (VIM_ISDIGIT(stropt[1]))
15576 ++stropt;
15577 block_len = getdigits(&stropt) - 1;
15578 --stropt;
15580 break;
15581 #endif
15585 strval = get_tv_string_chk(&argvars[1]);
15586 if (strval != NULL)
15587 write_reg_contents_ex(regname, strval, -1,
15588 append, yank_type, block_len);
15589 rettv->vval.v_number = 0;
15593 * "settabwinvar()" function
15595 static void
15596 f_settabwinvar(argvars, rettv)
15597 typval_T *argvars;
15598 typval_T *rettv;
15600 setwinvar(argvars, rettv, 1);
15604 * "setwinvar()" function
15606 static void
15607 f_setwinvar(argvars, rettv)
15608 typval_T *argvars;
15609 typval_T *rettv;
15611 setwinvar(argvars, rettv, 0);
15615 * "setwinvar()" and "settabwinvar()" functions
15617 static void
15618 setwinvar(argvars, rettv, off)
15619 typval_T *argvars;
15620 typval_T *rettv;
15621 int off;
15623 win_T *win;
15624 #ifdef FEAT_WINDOWS
15625 win_T *save_curwin;
15626 tabpage_T *save_curtab;
15627 #endif
15628 char_u *varname, *winvarname;
15629 typval_T *varp;
15630 char_u nbuf[NUMBUFLEN];
15631 tabpage_T *tp;
15633 rettv->vval.v_number = 0;
15635 if (check_restricted() || check_secure())
15636 return;
15638 #ifdef FEAT_WINDOWS
15639 if (off == 1)
15640 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15641 else
15642 tp = curtab;
15643 #endif
15644 win = find_win_by_nr(&argvars[off], tp);
15645 varname = get_tv_string_chk(&argvars[off + 1]);
15646 varp = &argvars[off + 2];
15648 if (win != NULL && varname != NULL && varp != NULL)
15650 #ifdef FEAT_WINDOWS
15651 /* set curwin to be our win, temporarily */
15652 save_curwin = curwin;
15653 save_curtab = curtab;
15654 goto_tabpage_tp(tp);
15655 if (!win_valid(win))
15656 return;
15657 curwin = win;
15658 curbuf = curwin->w_buffer;
15659 #endif
15661 if (*varname == '&')
15663 long numval;
15664 char_u *strval;
15665 int error = FALSE;
15667 ++varname;
15668 numval = get_tv_number_chk(varp, &error);
15669 strval = get_tv_string_buf_chk(varp, nbuf);
15670 if (!error && strval != NULL)
15671 set_option_value(varname, numval, strval, OPT_LOCAL);
15673 else
15675 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15676 if (winvarname != NULL)
15678 STRCPY(winvarname, "w:");
15679 STRCPY(winvarname + 2, varname);
15680 set_var(winvarname, varp, TRUE);
15681 vim_free(winvarname);
15685 #ifdef FEAT_WINDOWS
15686 /* Restore current tabpage and window, if still valid (autocomands can
15687 * make them invalid). */
15688 if (valid_tabpage(save_curtab))
15689 goto_tabpage_tp(save_curtab);
15690 if (win_valid(save_curwin))
15692 curwin = save_curwin;
15693 curbuf = curwin->w_buffer;
15695 #endif
15700 * "shellescape({string})" function
15702 static void
15703 f_shellescape(argvars, rettv)
15704 typval_T *argvars;
15705 typval_T *rettv;
15707 rettv->vval.v_string = vim_strsave_shellescape(get_tv_string(&argvars[0]));
15708 rettv->v_type = VAR_STRING;
15712 * "simplify()" function
15714 static void
15715 f_simplify(argvars, rettv)
15716 typval_T *argvars;
15717 typval_T *rettv;
15719 char_u *p;
15721 p = get_tv_string(&argvars[0]);
15722 rettv->vval.v_string = vim_strsave(p);
15723 simplify_filename(rettv->vval.v_string); /* simplify in place */
15724 rettv->v_type = VAR_STRING;
15727 #ifdef FEAT_FLOAT
15729 * "sin()" function
15731 static void
15732 f_sin(argvars, rettv)
15733 typval_T *argvars;
15734 typval_T *rettv;
15736 float_T f;
15738 rettv->v_type = VAR_FLOAT;
15739 if (get_float_arg(argvars, &f) == OK)
15740 rettv->vval.v_float = sin(f);
15741 else
15742 rettv->vval.v_float = 0.0;
15744 #endif
15746 static int
15747 #ifdef __BORLANDC__
15748 _RTLENTRYF
15749 #endif
15750 item_compare __ARGS((const void *s1, const void *s2));
15751 static int
15752 #ifdef __BORLANDC__
15753 _RTLENTRYF
15754 #endif
15755 item_compare2 __ARGS((const void *s1, const void *s2));
15757 static int item_compare_ic;
15758 static char_u *item_compare_func;
15759 static int item_compare_func_err;
15760 #define ITEM_COMPARE_FAIL 999
15763 * Compare functions for f_sort() below.
15765 static int
15766 #ifdef __BORLANDC__
15767 _RTLENTRYF
15768 #endif
15769 item_compare(s1, s2)
15770 const void *s1;
15771 const void *s2;
15773 char_u *p1, *p2;
15774 char_u *tofree1, *tofree2;
15775 int res;
15776 char_u numbuf1[NUMBUFLEN];
15777 char_u numbuf2[NUMBUFLEN];
15779 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
15780 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
15781 if (p1 == NULL)
15782 p1 = (char_u *)"";
15783 if (p2 == NULL)
15784 p2 = (char_u *)"";
15785 if (item_compare_ic)
15786 res = STRICMP(p1, p2);
15787 else
15788 res = STRCMP(p1, p2);
15789 vim_free(tofree1);
15790 vim_free(tofree2);
15791 return res;
15794 static int
15795 #ifdef __BORLANDC__
15796 _RTLENTRYF
15797 #endif
15798 item_compare2(s1, s2)
15799 const void *s1;
15800 const void *s2;
15802 int res;
15803 typval_T rettv;
15804 typval_T argv[3];
15805 int dummy;
15807 /* shortcut after failure in previous call; compare all items equal */
15808 if (item_compare_func_err)
15809 return 0;
15811 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
15812 * in the copy without changing the original list items. */
15813 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
15814 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
15816 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
15817 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
15818 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
15819 clear_tv(&argv[0]);
15820 clear_tv(&argv[1]);
15822 if (res == FAIL)
15823 res = ITEM_COMPARE_FAIL;
15824 else
15825 /* return value has wrong type */
15826 res = get_tv_number_chk(&rettv, &item_compare_func_err);
15827 if (item_compare_func_err)
15828 res = ITEM_COMPARE_FAIL;
15829 clear_tv(&rettv);
15830 return res;
15834 * "sort({list})" function
15836 static void
15837 f_sort(argvars, rettv)
15838 typval_T *argvars;
15839 typval_T *rettv;
15841 list_T *l;
15842 listitem_T *li;
15843 listitem_T **ptrs;
15844 long len;
15845 long i;
15847 rettv->vval.v_number = 0;
15848 if (argvars[0].v_type != VAR_LIST)
15849 EMSG2(_(e_listarg), "sort()");
15850 else
15852 l = argvars[0].vval.v_list;
15853 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
15854 return;
15855 rettv->vval.v_list = l;
15856 rettv->v_type = VAR_LIST;
15857 ++l->lv_refcount;
15859 len = list_len(l);
15860 if (len <= 1)
15861 return; /* short list sorts pretty quickly */
15863 item_compare_ic = FALSE;
15864 item_compare_func = NULL;
15865 if (argvars[1].v_type != VAR_UNKNOWN)
15867 if (argvars[1].v_type == VAR_FUNC)
15868 item_compare_func = argvars[1].vval.v_string;
15869 else
15871 int error = FALSE;
15873 i = get_tv_number_chk(&argvars[1], &error);
15874 if (error)
15875 return; /* type error; errmsg already given */
15876 if (i == 1)
15877 item_compare_ic = TRUE;
15878 else
15879 item_compare_func = get_tv_string(&argvars[1]);
15883 /* Make an array with each entry pointing to an item in the List. */
15884 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
15885 if (ptrs == NULL)
15886 return;
15887 i = 0;
15888 for (li = l->lv_first; li != NULL; li = li->li_next)
15889 ptrs[i++] = li;
15891 item_compare_func_err = FALSE;
15892 /* test the compare function */
15893 if (item_compare_func != NULL
15894 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
15895 == ITEM_COMPARE_FAIL)
15896 EMSG(_("E702: Sort compare function failed"));
15897 else
15899 /* Sort the array with item pointers. */
15900 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
15901 item_compare_func == NULL ? item_compare : item_compare2);
15903 if (!item_compare_func_err)
15905 /* Clear the List and append the items in the sorted order. */
15906 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
15907 l->lv_len = 0;
15908 for (i = 0; i < len; ++i)
15909 list_append(l, ptrs[i]);
15913 vim_free(ptrs);
15918 * "soundfold({word})" function
15920 static void
15921 f_soundfold(argvars, rettv)
15922 typval_T *argvars;
15923 typval_T *rettv;
15925 char_u *s;
15927 rettv->v_type = VAR_STRING;
15928 s = get_tv_string(&argvars[0]);
15929 #ifdef FEAT_SPELL
15930 rettv->vval.v_string = eval_soundfold(s);
15931 #else
15932 rettv->vval.v_string = vim_strsave(s);
15933 #endif
15937 * "spellbadword()" function
15939 /* ARGSUSED */
15940 static void
15941 f_spellbadword(argvars, rettv)
15942 typval_T *argvars;
15943 typval_T *rettv;
15945 char_u *word = (char_u *)"";
15946 hlf_T attr = HLF_COUNT;
15947 int len = 0;
15949 if (rettv_list_alloc(rettv) == FAIL)
15950 return;
15952 #ifdef FEAT_SPELL
15953 if (argvars[0].v_type == VAR_UNKNOWN)
15955 /* Find the start and length of the badly spelled word. */
15956 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
15957 if (len != 0)
15958 word = ml_get_cursor();
15960 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
15962 char_u *str = get_tv_string_chk(&argvars[0]);
15963 int capcol = -1;
15965 if (str != NULL)
15967 /* Check the argument for spelling. */
15968 while (*str != NUL)
15970 len = spell_check(curwin, str, &attr, &capcol, FALSE);
15971 if (attr != HLF_COUNT)
15973 word = str;
15974 break;
15976 str += len;
15980 #endif
15982 list_append_string(rettv->vval.v_list, word, len);
15983 list_append_string(rettv->vval.v_list, (char_u *)(
15984 attr == HLF_SPB ? "bad" :
15985 attr == HLF_SPR ? "rare" :
15986 attr == HLF_SPL ? "local" :
15987 attr == HLF_SPC ? "caps" :
15988 ""), -1);
15992 * "spellsuggest()" function
15994 /*ARGSUSED*/
15995 static void
15996 f_spellsuggest(argvars, rettv)
15997 typval_T *argvars;
15998 typval_T *rettv;
16000 #ifdef FEAT_SPELL
16001 char_u *str;
16002 int typeerr = FALSE;
16003 int maxcount;
16004 garray_T ga;
16005 int i;
16006 listitem_T *li;
16007 int need_capital = FALSE;
16008 #endif
16010 if (rettv_list_alloc(rettv) == FAIL)
16011 return;
16013 #ifdef FEAT_SPELL
16014 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16016 str = get_tv_string(&argvars[0]);
16017 if (argvars[1].v_type != VAR_UNKNOWN)
16019 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16020 if (maxcount <= 0)
16021 return;
16022 if (argvars[2].v_type != VAR_UNKNOWN)
16024 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16025 if (typeerr)
16026 return;
16029 else
16030 maxcount = 25;
16032 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16034 for (i = 0; i < ga.ga_len; ++i)
16036 str = ((char_u **)ga.ga_data)[i];
16038 li = listitem_alloc();
16039 if (li == NULL)
16040 vim_free(str);
16041 else
16043 li->li_tv.v_type = VAR_STRING;
16044 li->li_tv.v_lock = 0;
16045 li->li_tv.vval.v_string = str;
16046 list_append(rettv->vval.v_list, li);
16049 ga_clear(&ga);
16051 #endif
16054 static void
16055 f_split(argvars, rettv)
16056 typval_T *argvars;
16057 typval_T *rettv;
16059 char_u *str;
16060 char_u *end;
16061 char_u *pat = NULL;
16062 regmatch_T regmatch;
16063 char_u patbuf[NUMBUFLEN];
16064 char_u *save_cpo;
16065 int match;
16066 colnr_T col = 0;
16067 int keepempty = FALSE;
16068 int typeerr = FALSE;
16070 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16071 save_cpo = p_cpo;
16072 p_cpo = (char_u *)"";
16074 str = get_tv_string(&argvars[0]);
16075 if (argvars[1].v_type != VAR_UNKNOWN)
16077 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16078 if (pat == NULL)
16079 typeerr = TRUE;
16080 if (argvars[2].v_type != VAR_UNKNOWN)
16081 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16083 if (pat == NULL || *pat == NUL)
16084 pat = (char_u *)"[\\x01- ]\\+";
16086 if (rettv_list_alloc(rettv) == FAIL)
16087 return;
16088 if (typeerr)
16089 return;
16091 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16092 if (regmatch.regprog != NULL)
16094 regmatch.rm_ic = FALSE;
16095 while (*str != NUL || keepempty)
16097 if (*str == NUL)
16098 match = FALSE; /* empty item at the end */
16099 else
16100 match = vim_regexec_nl(&regmatch, str, col);
16101 if (match)
16102 end = regmatch.startp[0];
16103 else
16104 end = str + STRLEN(str);
16105 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16106 && *str != NUL && match && end < regmatch.endp[0]))
16108 if (list_append_string(rettv->vval.v_list, str,
16109 (int)(end - str)) == FAIL)
16110 break;
16112 if (!match)
16113 break;
16114 /* Advance to just after the match. */
16115 if (regmatch.endp[0] > str)
16116 col = 0;
16117 else
16119 /* Don't get stuck at the same match. */
16120 #ifdef FEAT_MBYTE
16121 col = (*mb_ptr2len)(regmatch.endp[0]);
16122 #else
16123 col = 1;
16124 #endif
16126 str = regmatch.endp[0];
16129 vim_free(regmatch.regprog);
16132 p_cpo = save_cpo;
16135 #ifdef FEAT_FLOAT
16137 * "sqrt()" function
16139 static void
16140 f_sqrt(argvars, rettv)
16141 typval_T *argvars;
16142 typval_T *rettv;
16144 float_T f;
16146 rettv->v_type = VAR_FLOAT;
16147 if (get_float_arg(argvars, &f) == OK)
16148 rettv->vval.v_float = sqrt(f);
16149 else
16150 rettv->vval.v_float = 0.0;
16154 * "str2float()" function
16156 static void
16157 f_str2float(argvars, rettv)
16158 typval_T *argvars;
16159 typval_T *rettv;
16161 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16163 if (*p == '+')
16164 p = skipwhite(p + 1);
16165 (void)string2float(p, &rettv->vval.v_float);
16166 rettv->v_type = VAR_FLOAT;
16168 #endif
16171 * "str2nr()" function
16173 static void
16174 f_str2nr(argvars, rettv)
16175 typval_T *argvars;
16176 typval_T *rettv;
16178 int base = 10;
16179 char_u *p;
16180 long n;
16182 if (argvars[1].v_type != VAR_UNKNOWN)
16184 base = get_tv_number(&argvars[1]);
16185 if (base != 8 && base != 10 && base != 16)
16187 EMSG(_(e_invarg));
16188 return;
16192 p = skipwhite(get_tv_string(&argvars[0]));
16193 if (*p == '+')
16194 p = skipwhite(p + 1);
16195 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16196 rettv->vval.v_number = n;
16199 #ifdef HAVE_STRFTIME
16201 * "strftime({format}[, {time}])" function
16203 static void
16204 f_strftime(argvars, rettv)
16205 typval_T *argvars;
16206 typval_T *rettv;
16208 char_u result_buf[256];
16209 struct tm *curtime;
16210 time_t seconds;
16211 char_u *p;
16213 rettv->v_type = VAR_STRING;
16215 p = get_tv_string(&argvars[0]);
16216 if (argvars[1].v_type == VAR_UNKNOWN)
16217 seconds = time(NULL);
16218 else
16219 seconds = (time_t)get_tv_number(&argvars[1]);
16220 curtime = localtime(&seconds);
16221 /* MSVC returns NULL for an invalid value of seconds. */
16222 if (curtime == NULL)
16223 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16224 else
16226 # ifdef FEAT_MBYTE
16227 vimconv_T conv;
16228 char_u *enc;
16230 conv.vc_type = CONV_NONE;
16231 enc = enc_locale();
16232 convert_setup(&conv, p_enc, enc);
16233 if (conv.vc_type != CONV_NONE)
16234 p = string_convert(&conv, p, NULL);
16235 # endif
16236 if (p != NULL)
16237 (void)strftime((char *)result_buf, sizeof(result_buf),
16238 (char *)p, curtime);
16239 else
16240 result_buf[0] = NUL;
16242 # ifdef FEAT_MBYTE
16243 if (conv.vc_type != CONV_NONE)
16244 vim_free(p);
16245 convert_setup(&conv, enc, p_enc);
16246 if (conv.vc_type != CONV_NONE)
16247 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16248 else
16249 # endif
16250 rettv->vval.v_string = vim_strsave(result_buf);
16252 # ifdef FEAT_MBYTE
16253 /* Release conversion descriptors */
16254 convert_setup(&conv, NULL, NULL);
16255 vim_free(enc);
16256 # endif
16259 #endif
16262 * "stridx()" function
16264 static void
16265 f_stridx(argvars, rettv)
16266 typval_T *argvars;
16267 typval_T *rettv;
16269 char_u buf[NUMBUFLEN];
16270 char_u *needle;
16271 char_u *haystack;
16272 char_u *save_haystack;
16273 char_u *pos;
16274 int start_idx;
16276 needle = get_tv_string_chk(&argvars[1]);
16277 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16278 rettv->vval.v_number = -1;
16279 if (needle == NULL || haystack == NULL)
16280 return; /* type error; errmsg already given */
16282 if (argvars[2].v_type != VAR_UNKNOWN)
16284 int error = FALSE;
16286 start_idx = get_tv_number_chk(&argvars[2], &error);
16287 if (error || start_idx >= (int)STRLEN(haystack))
16288 return;
16289 if (start_idx >= 0)
16290 haystack += start_idx;
16293 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16294 if (pos != NULL)
16295 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16299 * "string()" function
16301 static void
16302 f_string(argvars, rettv)
16303 typval_T *argvars;
16304 typval_T *rettv;
16306 char_u *tofree;
16307 char_u numbuf[NUMBUFLEN];
16309 rettv->v_type = VAR_STRING;
16310 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16311 /* Make a copy if we have a value but it's not in allocated memory. */
16312 if (rettv->vval.v_string != NULL && tofree == NULL)
16313 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16317 * "strlen()" function
16319 static void
16320 f_strlen(argvars, rettv)
16321 typval_T *argvars;
16322 typval_T *rettv;
16324 rettv->vval.v_number = (varnumber_T)(STRLEN(
16325 get_tv_string(&argvars[0])));
16329 * "strpart()" function
16331 static void
16332 f_strpart(argvars, rettv)
16333 typval_T *argvars;
16334 typval_T *rettv;
16336 char_u *p;
16337 int n;
16338 int len;
16339 int slen;
16340 int error = FALSE;
16342 p = get_tv_string(&argvars[0]);
16343 slen = (int)STRLEN(p);
16345 n = get_tv_number_chk(&argvars[1], &error);
16346 if (error)
16347 len = 0;
16348 else if (argvars[2].v_type != VAR_UNKNOWN)
16349 len = get_tv_number(&argvars[2]);
16350 else
16351 len = slen - n; /* default len: all bytes that are available. */
16354 * Only return the overlap between the specified part and the actual
16355 * string.
16357 if (n < 0)
16359 len += n;
16360 n = 0;
16362 else if (n > slen)
16363 n = slen;
16364 if (len < 0)
16365 len = 0;
16366 else if (n + len > slen)
16367 len = slen - n;
16369 rettv->v_type = VAR_STRING;
16370 rettv->vval.v_string = vim_strnsave(p + n, len);
16374 * "strridx()" function
16376 static void
16377 f_strridx(argvars, rettv)
16378 typval_T *argvars;
16379 typval_T *rettv;
16381 char_u buf[NUMBUFLEN];
16382 char_u *needle;
16383 char_u *haystack;
16384 char_u *rest;
16385 char_u *lastmatch = NULL;
16386 int haystack_len, end_idx;
16388 needle = get_tv_string_chk(&argvars[1]);
16389 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16391 rettv->vval.v_number = -1;
16392 if (needle == NULL || haystack == NULL)
16393 return; /* type error; errmsg already given */
16395 haystack_len = (int)STRLEN(haystack);
16396 if (argvars[2].v_type != VAR_UNKNOWN)
16398 /* Third argument: upper limit for index */
16399 end_idx = get_tv_number_chk(&argvars[2], NULL);
16400 if (end_idx < 0)
16401 return; /* can never find a match */
16403 else
16404 end_idx = haystack_len;
16406 if (*needle == NUL)
16408 /* Empty string matches past the end. */
16409 lastmatch = haystack + end_idx;
16411 else
16413 for (rest = haystack; *rest != '\0'; ++rest)
16415 rest = (char_u *)strstr((char *)rest, (char *)needle);
16416 if (rest == NULL || rest > haystack + end_idx)
16417 break;
16418 lastmatch = rest;
16422 if (lastmatch == NULL)
16423 rettv->vval.v_number = -1;
16424 else
16425 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16429 * "strtrans()" function
16431 static void
16432 f_strtrans(argvars, rettv)
16433 typval_T *argvars;
16434 typval_T *rettv;
16436 rettv->v_type = VAR_STRING;
16437 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16441 * "submatch()" function
16443 static void
16444 f_submatch(argvars, rettv)
16445 typval_T *argvars;
16446 typval_T *rettv;
16448 rettv->v_type = VAR_STRING;
16449 rettv->vval.v_string =
16450 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16454 * "substitute()" function
16456 static void
16457 f_substitute(argvars, rettv)
16458 typval_T *argvars;
16459 typval_T *rettv;
16461 char_u patbuf[NUMBUFLEN];
16462 char_u subbuf[NUMBUFLEN];
16463 char_u flagsbuf[NUMBUFLEN];
16465 char_u *str = get_tv_string_chk(&argvars[0]);
16466 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16467 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16468 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16470 rettv->v_type = VAR_STRING;
16471 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16472 rettv->vval.v_string = NULL;
16473 else
16474 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16478 * "synID(lnum, col, trans)" function
16480 /*ARGSUSED*/
16481 static void
16482 f_synID(argvars, rettv)
16483 typval_T *argvars;
16484 typval_T *rettv;
16486 int id = 0;
16487 #ifdef FEAT_SYN_HL
16488 long lnum;
16489 long col;
16490 int trans;
16491 int transerr = FALSE;
16493 lnum = get_tv_lnum(argvars); /* -1 on type error */
16494 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16495 trans = get_tv_number_chk(&argvars[2], &transerr);
16497 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16498 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16499 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16500 #endif
16502 rettv->vval.v_number = id;
16506 * "synIDattr(id, what [, mode])" function
16508 /*ARGSUSED*/
16509 static void
16510 f_synIDattr(argvars, rettv)
16511 typval_T *argvars;
16512 typval_T *rettv;
16514 char_u *p = NULL;
16515 #ifdef FEAT_SYN_HL
16516 int id;
16517 char_u *what;
16518 char_u *mode;
16519 char_u modebuf[NUMBUFLEN];
16520 int modec;
16522 id = get_tv_number(&argvars[0]);
16523 what = get_tv_string(&argvars[1]);
16524 if (argvars[2].v_type != VAR_UNKNOWN)
16526 mode = get_tv_string_buf(&argvars[2], modebuf);
16527 modec = TOLOWER_ASC(mode[0]);
16528 if (modec != 't' && modec != 'c'
16529 #ifdef FEAT_GUI
16530 && modec != 'g'
16531 #endif
16533 modec = 0; /* replace invalid with current */
16535 else
16537 #ifdef FEAT_GUI
16538 if (gui.in_use)
16539 modec = 'g';
16540 else
16541 #endif
16542 if (t_colors > 1)
16543 modec = 'c';
16544 else
16545 modec = 't';
16549 switch (TOLOWER_ASC(what[0]))
16551 case 'b':
16552 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16553 p = highlight_color(id, what, modec);
16554 else /* bold */
16555 p = highlight_has_attr(id, HL_BOLD, modec);
16556 break;
16558 case 'f': /* fg[#] */
16559 p = highlight_color(id, what, modec);
16560 break;
16562 case 'i':
16563 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16564 p = highlight_has_attr(id, HL_INVERSE, modec);
16565 else /* italic */
16566 p = highlight_has_attr(id, HL_ITALIC, modec);
16567 break;
16569 case 'n': /* name */
16570 p = get_highlight_name(NULL, id - 1);
16571 break;
16573 case 'r': /* reverse */
16574 p = highlight_has_attr(id, HL_INVERSE, modec);
16575 break;
16577 case 's': /* standout */
16578 p = highlight_has_attr(id, HL_STANDOUT, modec);
16579 break;
16581 case 'u':
16582 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16583 /* underline */
16584 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16585 else
16586 /* undercurl */
16587 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16588 break;
16591 if (p != NULL)
16592 p = vim_strsave(p);
16593 #endif
16594 rettv->v_type = VAR_STRING;
16595 rettv->vval.v_string = p;
16599 * "synIDtrans(id)" function
16601 /*ARGSUSED*/
16602 static void
16603 f_synIDtrans(argvars, rettv)
16604 typval_T *argvars;
16605 typval_T *rettv;
16607 int id;
16609 #ifdef FEAT_SYN_HL
16610 id = get_tv_number(&argvars[0]);
16612 if (id > 0)
16613 id = syn_get_final_id(id);
16614 else
16615 #endif
16616 id = 0;
16618 rettv->vval.v_number = id;
16622 * "synstack(lnum, col)" function
16624 /*ARGSUSED*/
16625 static void
16626 f_synstack(argvars, rettv)
16627 typval_T *argvars;
16628 typval_T *rettv;
16630 #ifdef FEAT_SYN_HL
16631 long lnum;
16632 long col;
16633 int i;
16634 int id;
16635 #endif
16637 rettv->v_type = VAR_LIST;
16638 rettv->vval.v_list = NULL;
16640 #ifdef FEAT_SYN_HL
16641 lnum = get_tv_lnum(argvars); /* -1 on type error */
16642 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16644 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16645 && col >= 0 && col < (long)STRLEN(ml_get(lnum))
16646 && rettv_list_alloc(rettv) != FAIL)
16648 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16649 for (i = 0; ; ++i)
16651 id = syn_get_stack_item(i);
16652 if (id < 0)
16653 break;
16654 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16655 break;
16658 #endif
16662 * "system()" function
16664 static void
16665 f_system(argvars, rettv)
16666 typval_T *argvars;
16667 typval_T *rettv;
16669 char_u *res = NULL;
16670 char_u *p;
16671 char_u *infile = NULL;
16672 char_u buf[NUMBUFLEN];
16673 int err = FALSE;
16674 FILE *fd;
16676 if (check_restricted() || check_secure())
16677 goto done;
16679 if (argvars[1].v_type != VAR_UNKNOWN)
16682 * Write the string to a temp file, to be used for input of the shell
16683 * command.
16685 if ((infile = vim_tempname('i')) == NULL)
16687 EMSG(_(e_notmp));
16688 goto done;
16691 fd = mch_fopen((char *)infile, WRITEBIN);
16692 if (fd == NULL)
16694 EMSG2(_(e_notopen), infile);
16695 goto done;
16697 p = get_tv_string_buf_chk(&argvars[1], buf);
16698 if (p == NULL)
16700 fclose(fd);
16701 goto done; /* type error; errmsg already given */
16703 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16704 err = TRUE;
16705 if (fclose(fd) != 0)
16706 err = TRUE;
16707 if (err)
16709 EMSG(_("E677: Error writing temp file"));
16710 goto done;
16714 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16715 SHELL_SILENT | SHELL_COOKED);
16717 #ifdef USE_CR
16718 /* translate <CR> into <NL> */
16719 if (res != NULL)
16721 char_u *s;
16723 for (s = res; *s; ++s)
16725 if (*s == CAR)
16726 *s = NL;
16729 #else
16730 # ifdef USE_CRNL
16731 /* translate <CR><NL> into <NL> */
16732 if (res != NULL)
16734 char_u *s, *d;
16736 d = res;
16737 for (s = res; *s; ++s)
16739 if (s[0] == CAR && s[1] == NL)
16740 ++s;
16741 *d++ = *s;
16743 *d = NUL;
16745 # endif
16746 #endif
16748 done:
16749 if (infile != NULL)
16751 mch_remove(infile);
16752 vim_free(infile);
16754 rettv->v_type = VAR_STRING;
16755 rettv->vval.v_string = res;
16759 * "tabpagebuflist()" function
16761 /* ARGSUSED */
16762 static void
16763 f_tabpagebuflist(argvars, rettv)
16764 typval_T *argvars;
16765 typval_T *rettv;
16767 #ifndef FEAT_WINDOWS
16768 rettv->vval.v_number = 0;
16769 #else
16770 tabpage_T *tp;
16771 win_T *wp = NULL;
16773 if (argvars[0].v_type == VAR_UNKNOWN)
16774 wp = firstwin;
16775 else
16777 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16778 if (tp != NULL)
16779 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16781 if (wp == NULL)
16782 rettv->vval.v_number = 0;
16783 else
16785 if (rettv_list_alloc(rettv) == FAIL)
16786 rettv->vval.v_number = 0;
16787 else
16789 for (; wp != NULL; wp = wp->w_next)
16790 if (list_append_number(rettv->vval.v_list,
16791 wp->w_buffer->b_fnum) == FAIL)
16792 break;
16795 #endif
16800 * "tabpagenr()" function
16802 /* ARGSUSED */
16803 static void
16804 f_tabpagenr(argvars, rettv)
16805 typval_T *argvars;
16806 typval_T *rettv;
16808 int nr = 1;
16809 #ifdef FEAT_WINDOWS
16810 char_u *arg;
16812 if (argvars[0].v_type != VAR_UNKNOWN)
16814 arg = get_tv_string_chk(&argvars[0]);
16815 nr = 0;
16816 if (arg != NULL)
16818 if (STRCMP(arg, "$") == 0)
16819 nr = tabpage_index(NULL) - 1;
16820 else
16821 EMSG2(_(e_invexpr2), arg);
16824 else
16825 nr = tabpage_index(curtab);
16826 #endif
16827 rettv->vval.v_number = nr;
16831 #ifdef FEAT_WINDOWS
16832 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
16835 * Common code for tabpagewinnr() and winnr().
16837 static int
16838 get_winnr(tp, argvar)
16839 tabpage_T *tp;
16840 typval_T *argvar;
16842 win_T *twin;
16843 int nr = 1;
16844 win_T *wp;
16845 char_u *arg;
16847 twin = (tp == curtab) ? curwin : tp->tp_curwin;
16848 if (argvar->v_type != VAR_UNKNOWN)
16850 arg = get_tv_string_chk(argvar);
16851 if (arg == NULL)
16852 nr = 0; /* type error; errmsg already given */
16853 else if (STRCMP(arg, "$") == 0)
16854 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
16855 else if (STRCMP(arg, "#") == 0)
16857 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
16858 if (twin == NULL)
16859 nr = 0;
16861 else
16863 EMSG2(_(e_invexpr2), arg);
16864 nr = 0;
16868 if (nr > 0)
16869 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
16870 wp != twin; wp = wp->w_next)
16872 if (wp == NULL)
16874 /* didn't find it in this tabpage */
16875 nr = 0;
16876 break;
16878 ++nr;
16880 return nr;
16882 #endif
16885 * "tabpagewinnr()" function
16887 /* ARGSUSED */
16888 static void
16889 f_tabpagewinnr(argvars, rettv)
16890 typval_T *argvars;
16891 typval_T *rettv;
16893 int nr = 1;
16894 #ifdef FEAT_WINDOWS
16895 tabpage_T *tp;
16897 tp = find_tabpage((int)get_tv_number(&argvars[0]));
16898 if (tp == NULL)
16899 nr = 0;
16900 else
16901 nr = get_winnr(tp, &argvars[1]);
16902 #endif
16903 rettv->vval.v_number = nr;
16908 * "tagfiles()" function
16910 /*ARGSUSED*/
16911 static void
16912 f_tagfiles(argvars, rettv)
16913 typval_T *argvars;
16914 typval_T *rettv;
16916 char_u fname[MAXPATHL + 1];
16917 tagname_T tn;
16918 int first;
16920 if (rettv_list_alloc(rettv) == FAIL)
16922 rettv->vval.v_number = 0;
16923 return;
16926 for (first = TRUE; ; first = FALSE)
16927 if (get_tagfname(&tn, first, fname) == FAIL
16928 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
16929 break;
16930 tagname_free(&tn);
16934 * "taglist()" function
16936 static void
16937 f_taglist(argvars, rettv)
16938 typval_T *argvars;
16939 typval_T *rettv;
16941 char_u *tag_pattern;
16943 tag_pattern = get_tv_string(&argvars[0]);
16945 rettv->vval.v_number = FALSE;
16946 if (*tag_pattern == NUL)
16947 return;
16949 if (rettv_list_alloc(rettv) == OK)
16950 (void)get_tags(rettv->vval.v_list, tag_pattern);
16954 * "tempname()" function
16956 /*ARGSUSED*/
16957 static void
16958 f_tempname(argvars, rettv)
16959 typval_T *argvars;
16960 typval_T *rettv;
16962 static int x = 'A';
16964 rettv->v_type = VAR_STRING;
16965 rettv->vval.v_string = vim_tempname(x);
16967 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
16968 * names. Skip 'I' and 'O', they are used for shell redirection. */
16971 if (x == 'Z')
16972 x = '0';
16973 else if (x == '9')
16974 x = 'A';
16975 else
16977 #ifdef EBCDIC
16978 if (x == 'I')
16979 x = 'J';
16980 else if (x == 'R')
16981 x = 'S';
16982 else
16983 #endif
16984 ++x;
16986 } while (x == 'I' || x == 'O');
16990 * "test(list)" function: Just checking the walls...
16992 /*ARGSUSED*/
16993 static void
16994 f_test(argvars, rettv)
16995 typval_T *argvars;
16996 typval_T *rettv;
16998 /* Used for unit testing. Change the code below to your liking. */
16999 #if 0
17000 listitem_T *li;
17001 list_T *l;
17002 char_u *bad, *good;
17004 if (argvars[0].v_type != VAR_LIST)
17005 return;
17006 l = argvars[0].vval.v_list;
17007 if (l == NULL)
17008 return;
17009 li = l->lv_first;
17010 if (li == NULL)
17011 return;
17012 bad = get_tv_string(&li->li_tv);
17013 li = li->li_next;
17014 if (li == NULL)
17015 return;
17016 good = get_tv_string(&li->li_tv);
17017 rettv->vval.v_number = test_edit_score(bad, good);
17018 #endif
17022 * "tolower(string)" function
17024 static void
17025 f_tolower(argvars, rettv)
17026 typval_T *argvars;
17027 typval_T *rettv;
17029 char_u *p;
17031 p = vim_strsave(get_tv_string(&argvars[0]));
17032 rettv->v_type = VAR_STRING;
17033 rettv->vval.v_string = p;
17035 if (p != NULL)
17036 while (*p != NUL)
17038 #ifdef FEAT_MBYTE
17039 int l;
17041 if (enc_utf8)
17043 int c, lc;
17045 c = utf_ptr2char(p);
17046 lc = utf_tolower(c);
17047 l = utf_ptr2len(p);
17048 /* TODO: reallocate string when byte count changes. */
17049 if (utf_char2len(lc) == l)
17050 utf_char2bytes(lc, p);
17051 p += l;
17053 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17054 p += l; /* skip multi-byte character */
17055 else
17056 #endif
17058 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17059 ++p;
17065 * "toupper(string)" function
17067 static void
17068 f_toupper(argvars, rettv)
17069 typval_T *argvars;
17070 typval_T *rettv;
17072 rettv->v_type = VAR_STRING;
17073 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17077 * "tr(string, fromstr, tostr)" function
17079 static void
17080 f_tr(argvars, rettv)
17081 typval_T *argvars;
17082 typval_T *rettv;
17084 char_u *instr;
17085 char_u *fromstr;
17086 char_u *tostr;
17087 char_u *p;
17088 #ifdef FEAT_MBYTE
17089 int inlen;
17090 int fromlen;
17091 int tolen;
17092 int idx;
17093 char_u *cpstr;
17094 int cplen;
17095 int first = TRUE;
17096 #endif
17097 char_u buf[NUMBUFLEN];
17098 char_u buf2[NUMBUFLEN];
17099 garray_T ga;
17101 instr = get_tv_string(&argvars[0]);
17102 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17103 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17105 /* Default return value: empty string. */
17106 rettv->v_type = VAR_STRING;
17107 rettv->vval.v_string = NULL;
17108 if (fromstr == NULL || tostr == NULL)
17109 return; /* type error; errmsg already given */
17110 ga_init2(&ga, (int)sizeof(char), 80);
17112 #ifdef FEAT_MBYTE
17113 if (!has_mbyte)
17114 #endif
17115 /* not multi-byte: fromstr and tostr must be the same length */
17116 if (STRLEN(fromstr) != STRLEN(tostr))
17118 #ifdef FEAT_MBYTE
17119 error:
17120 #endif
17121 EMSG2(_(e_invarg2), fromstr);
17122 ga_clear(&ga);
17123 return;
17126 /* fromstr and tostr have to contain the same number of chars */
17127 while (*instr != NUL)
17129 #ifdef FEAT_MBYTE
17130 if (has_mbyte)
17132 inlen = (*mb_ptr2len)(instr);
17133 cpstr = instr;
17134 cplen = inlen;
17135 idx = 0;
17136 for (p = fromstr; *p != NUL; p += fromlen)
17138 fromlen = (*mb_ptr2len)(p);
17139 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17141 for (p = tostr; *p != NUL; p += tolen)
17143 tolen = (*mb_ptr2len)(p);
17144 if (idx-- == 0)
17146 cplen = tolen;
17147 cpstr = p;
17148 break;
17151 if (*p == NUL) /* tostr is shorter than fromstr */
17152 goto error;
17153 break;
17155 ++idx;
17158 if (first && cpstr == instr)
17160 /* Check that fromstr and tostr have the same number of
17161 * (multi-byte) characters. Done only once when a character
17162 * of instr doesn't appear in fromstr. */
17163 first = FALSE;
17164 for (p = tostr; *p != NUL; p += tolen)
17166 tolen = (*mb_ptr2len)(p);
17167 --idx;
17169 if (idx != 0)
17170 goto error;
17173 ga_grow(&ga, cplen);
17174 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17175 ga.ga_len += cplen;
17177 instr += inlen;
17179 else
17180 #endif
17182 /* When not using multi-byte chars we can do it faster. */
17183 p = vim_strchr(fromstr, *instr);
17184 if (p != NULL)
17185 ga_append(&ga, tostr[p - fromstr]);
17186 else
17187 ga_append(&ga, *instr);
17188 ++instr;
17192 /* add a terminating NUL */
17193 ga_grow(&ga, 1);
17194 ga_append(&ga, NUL);
17196 rettv->vval.v_string = ga.ga_data;
17199 #ifdef FEAT_FLOAT
17201 * "trunc({float})" function
17203 static void
17204 f_trunc(argvars, rettv)
17205 typval_T *argvars;
17206 typval_T *rettv;
17208 float_T f;
17210 rettv->v_type = VAR_FLOAT;
17211 if (get_float_arg(argvars, &f) == OK)
17212 /* trunc() is not in C90, use floor() or ceil() instead. */
17213 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17214 else
17215 rettv->vval.v_float = 0.0;
17217 #endif
17220 * "type(expr)" function
17222 static void
17223 f_type(argvars, rettv)
17224 typval_T *argvars;
17225 typval_T *rettv;
17227 int n;
17229 switch (argvars[0].v_type)
17231 case VAR_NUMBER: n = 0; break;
17232 case VAR_STRING: n = 1; break;
17233 case VAR_FUNC: n = 2; break;
17234 case VAR_LIST: n = 3; break;
17235 case VAR_DICT: n = 4; break;
17236 #ifdef FEAT_FLOAT
17237 case VAR_FLOAT: n = 5; break;
17238 #endif
17239 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17241 rettv->vval.v_number = n;
17245 * "values(dict)" function
17247 static void
17248 f_values(argvars, rettv)
17249 typval_T *argvars;
17250 typval_T *rettv;
17252 dict_list(argvars, rettv, 1);
17256 * "virtcol(string)" function
17258 static void
17259 f_virtcol(argvars, rettv)
17260 typval_T *argvars;
17261 typval_T *rettv;
17263 colnr_T vcol = 0;
17264 pos_T *fp;
17265 int fnum = curbuf->b_fnum;
17267 fp = var2fpos(&argvars[0], FALSE, &fnum);
17268 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17269 && fnum == curbuf->b_fnum)
17271 getvvcol(curwin, fp, NULL, NULL, &vcol);
17272 ++vcol;
17275 rettv->vval.v_number = vcol;
17279 * "visualmode()" function
17281 /*ARGSUSED*/
17282 static void
17283 f_visualmode(argvars, rettv)
17284 typval_T *argvars;
17285 typval_T *rettv;
17287 #ifdef FEAT_VISUAL
17288 char_u str[2];
17290 rettv->v_type = VAR_STRING;
17291 str[0] = curbuf->b_visual_mode_eval;
17292 str[1] = NUL;
17293 rettv->vval.v_string = vim_strsave(str);
17295 /* A non-zero number or non-empty string argument: reset mode. */
17296 if ((argvars[0].v_type == VAR_NUMBER && argvars[0].vval.v_number != 0)
17297 || (argvars[0].v_type == VAR_STRING
17298 && *get_tv_string(&argvars[0]) != NUL))
17299 curbuf->b_visual_mode_eval = NUL;
17300 #else
17301 rettv->vval.v_number = 0; /* return anything, it won't work anyway */
17302 #endif
17306 * "winbufnr(nr)" function
17308 static void
17309 f_winbufnr(argvars, rettv)
17310 typval_T *argvars;
17311 typval_T *rettv;
17313 win_T *wp;
17315 wp = find_win_by_nr(&argvars[0], NULL);
17316 if (wp == NULL)
17317 rettv->vval.v_number = -1;
17318 else
17319 rettv->vval.v_number = wp->w_buffer->b_fnum;
17323 * "wincol()" function
17325 /*ARGSUSED*/
17326 static void
17327 f_wincol(argvars, rettv)
17328 typval_T *argvars;
17329 typval_T *rettv;
17331 validate_cursor();
17332 rettv->vval.v_number = curwin->w_wcol + 1;
17336 * "winheight(nr)" function
17338 static void
17339 f_winheight(argvars, rettv)
17340 typval_T *argvars;
17341 typval_T *rettv;
17343 win_T *wp;
17345 wp = find_win_by_nr(&argvars[0], NULL);
17346 if (wp == NULL)
17347 rettv->vval.v_number = -1;
17348 else
17349 rettv->vval.v_number = wp->w_height;
17353 * "winline()" function
17355 /*ARGSUSED*/
17356 static void
17357 f_winline(argvars, rettv)
17358 typval_T *argvars;
17359 typval_T *rettv;
17361 validate_cursor();
17362 rettv->vval.v_number = curwin->w_wrow + 1;
17366 * "winnr()" function
17368 /* ARGSUSED */
17369 static void
17370 f_winnr(argvars, rettv)
17371 typval_T *argvars;
17372 typval_T *rettv;
17374 int nr = 1;
17376 #ifdef FEAT_WINDOWS
17377 nr = get_winnr(curtab, &argvars[0]);
17378 #endif
17379 rettv->vval.v_number = nr;
17383 * "winrestcmd()" function
17385 /* ARGSUSED */
17386 static void
17387 f_winrestcmd(argvars, rettv)
17388 typval_T *argvars;
17389 typval_T *rettv;
17391 #ifdef FEAT_WINDOWS
17392 win_T *wp;
17393 int winnr = 1;
17394 garray_T ga;
17395 char_u buf[50];
17397 ga_init2(&ga, (int)sizeof(char), 70);
17398 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17400 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17401 ga_concat(&ga, buf);
17402 # ifdef FEAT_VERTSPLIT
17403 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17404 ga_concat(&ga, buf);
17405 # endif
17406 ++winnr;
17408 ga_append(&ga, NUL);
17410 rettv->vval.v_string = ga.ga_data;
17411 #else
17412 rettv->vval.v_string = NULL;
17413 #endif
17414 rettv->v_type = VAR_STRING;
17418 * "winrestview()" function
17420 /* ARGSUSED */
17421 static void
17422 f_winrestview(argvars, rettv)
17423 typval_T *argvars;
17424 typval_T *rettv;
17426 dict_T *dict;
17428 if (argvars[0].v_type != VAR_DICT
17429 || (dict = argvars[0].vval.v_dict) == NULL)
17430 EMSG(_(e_invarg));
17431 else
17433 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17434 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17435 #ifdef FEAT_VIRTUALEDIT
17436 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17437 #endif
17438 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17439 curwin->w_set_curswant = FALSE;
17441 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17442 #ifdef FEAT_DIFF
17443 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17444 #endif
17445 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17446 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17448 check_cursor();
17449 changed_cline_bef_curs();
17450 invalidate_botline();
17451 redraw_later(VALID);
17453 if (curwin->w_topline == 0)
17454 curwin->w_topline = 1;
17455 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17456 curwin->w_topline = curbuf->b_ml.ml_line_count;
17457 #ifdef FEAT_DIFF
17458 check_topfill(curwin, TRUE);
17459 #endif
17464 * "winsaveview()" function
17466 /* ARGSUSED */
17467 static void
17468 f_winsaveview(argvars, rettv)
17469 typval_T *argvars;
17470 typval_T *rettv;
17472 dict_T *dict;
17474 dict = dict_alloc();
17475 if (dict == NULL)
17476 return;
17477 rettv->v_type = VAR_DICT;
17478 rettv->vval.v_dict = dict;
17479 ++dict->dv_refcount;
17481 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17482 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17483 #ifdef FEAT_VIRTUALEDIT
17484 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17485 #endif
17486 update_curswant();
17487 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17489 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17490 #ifdef FEAT_DIFF
17491 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17492 #endif
17493 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17494 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17498 * "winwidth(nr)" function
17500 static void
17501 f_winwidth(argvars, rettv)
17502 typval_T *argvars;
17503 typval_T *rettv;
17505 win_T *wp;
17507 wp = find_win_by_nr(&argvars[0], NULL);
17508 if (wp == NULL)
17509 rettv->vval.v_number = -1;
17510 else
17511 #ifdef FEAT_VERTSPLIT
17512 rettv->vval.v_number = wp->w_width;
17513 #else
17514 rettv->vval.v_number = Columns;
17515 #endif
17519 * "writefile()" function
17521 static void
17522 f_writefile(argvars, rettv)
17523 typval_T *argvars;
17524 typval_T *rettv;
17526 int binary = FALSE;
17527 char_u *fname;
17528 FILE *fd;
17529 listitem_T *li;
17530 char_u *s;
17531 int ret = 0;
17532 int c;
17534 if (check_restricted() || check_secure())
17535 return;
17537 if (argvars[0].v_type != VAR_LIST)
17539 EMSG2(_(e_listarg), "writefile()");
17540 return;
17542 if (argvars[0].vval.v_list == NULL)
17543 return;
17545 if (argvars[2].v_type != VAR_UNKNOWN
17546 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17547 binary = TRUE;
17549 /* Always open the file in binary mode, library functions have a mind of
17550 * their own about CR-LF conversion. */
17551 fname = get_tv_string(&argvars[1]);
17552 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17554 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17555 ret = -1;
17557 else
17559 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17560 li = li->li_next)
17562 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17564 if (*s == '\n')
17565 c = putc(NUL, fd);
17566 else
17567 c = putc(*s, fd);
17568 if (c == EOF)
17570 ret = -1;
17571 break;
17574 if (!binary || li->li_next != NULL)
17575 if (putc('\n', fd) == EOF)
17577 ret = -1;
17578 break;
17580 if (ret < 0)
17582 EMSG(_(e_write));
17583 break;
17586 fclose(fd);
17589 rettv->vval.v_number = ret;
17593 * Translate a String variable into a position.
17594 * Returns NULL when there is an error.
17596 static pos_T *
17597 var2fpos(varp, dollar_lnum, fnum)
17598 typval_T *varp;
17599 int dollar_lnum; /* TRUE when $ is last line */
17600 int *fnum; /* set to fnum for '0, 'A, etc. */
17602 char_u *name;
17603 static pos_T pos;
17604 pos_T *pp;
17606 /* Argument can be [lnum, col, coladd]. */
17607 if (varp->v_type == VAR_LIST)
17609 list_T *l;
17610 int len;
17611 int error = FALSE;
17612 listitem_T *li;
17614 l = varp->vval.v_list;
17615 if (l == NULL)
17616 return NULL;
17618 /* Get the line number */
17619 pos.lnum = list_find_nr(l, 0L, &error);
17620 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17621 return NULL; /* invalid line number */
17623 /* Get the column number */
17624 pos.col = list_find_nr(l, 1L, &error);
17625 if (error)
17626 return NULL;
17627 len = (long)STRLEN(ml_get(pos.lnum));
17629 /* We accept "$" for the column number: last column. */
17630 li = list_find(l, 1L);
17631 if (li != NULL && li->li_tv.v_type == VAR_STRING
17632 && li->li_tv.vval.v_string != NULL
17633 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17634 pos.col = len + 1;
17636 /* Accept a position up to the NUL after the line. */
17637 if (pos.col == 0 || (int)pos.col > len + 1)
17638 return NULL; /* invalid column number */
17639 --pos.col;
17641 #ifdef FEAT_VIRTUALEDIT
17642 /* Get the virtual offset. Defaults to zero. */
17643 pos.coladd = list_find_nr(l, 2L, &error);
17644 if (error)
17645 pos.coladd = 0;
17646 #endif
17648 return &pos;
17651 name = get_tv_string_chk(varp);
17652 if (name == NULL)
17653 return NULL;
17654 if (name[0] == '.') /* cursor */
17655 return &curwin->w_cursor;
17656 #ifdef FEAT_VISUAL
17657 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17659 if (VIsual_active)
17660 return &VIsual;
17661 return &curwin->w_cursor;
17663 #endif
17664 if (name[0] == '\'') /* mark */
17666 pp = getmark_fnum(name[1], FALSE, fnum);
17667 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17668 return NULL;
17669 return pp;
17672 #ifdef FEAT_VIRTUALEDIT
17673 pos.coladd = 0;
17674 #endif
17676 if (name[0] == 'w' && dollar_lnum)
17678 pos.col = 0;
17679 if (name[1] == '0') /* "w0": first visible line */
17681 update_topline();
17682 pos.lnum = curwin->w_topline;
17683 return &pos;
17685 else if (name[1] == '$') /* "w$": last visible line */
17687 validate_botline();
17688 pos.lnum = curwin->w_botline - 1;
17689 return &pos;
17692 else if (name[0] == '$') /* last column or line */
17694 if (dollar_lnum)
17696 pos.lnum = curbuf->b_ml.ml_line_count;
17697 pos.col = 0;
17699 else
17701 pos.lnum = curwin->w_cursor.lnum;
17702 pos.col = (colnr_T)STRLEN(ml_get_curline());
17704 return &pos;
17706 return NULL;
17710 * Convert list in "arg" into a position and optional file number.
17711 * When "fnump" is NULL there is no file number, only 3 items.
17712 * Note that the column is passed on as-is, the caller may want to decrement
17713 * it to use 1 for the first column.
17714 * Return FAIL when conversion is not possible, doesn't check the position for
17715 * validity.
17717 static int
17718 list2fpos(arg, posp, fnump)
17719 typval_T *arg;
17720 pos_T *posp;
17721 int *fnump;
17723 list_T *l = arg->vval.v_list;
17724 long i = 0;
17725 long n;
17727 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17728 * when "fnump" isn't NULL and "coladd" is optional. */
17729 if (arg->v_type != VAR_LIST
17730 || l == NULL
17731 || l->lv_len < (fnump == NULL ? 2 : 3)
17732 || l->lv_len > (fnump == NULL ? 3 : 4))
17733 return FAIL;
17735 if (fnump != NULL)
17737 n = list_find_nr(l, i++, NULL); /* fnum */
17738 if (n < 0)
17739 return FAIL;
17740 if (n == 0)
17741 n = curbuf->b_fnum; /* current buffer */
17742 *fnump = n;
17745 n = list_find_nr(l, i++, NULL); /* lnum */
17746 if (n < 0)
17747 return FAIL;
17748 posp->lnum = n;
17750 n = list_find_nr(l, i++, NULL); /* col */
17751 if (n < 0)
17752 return FAIL;
17753 posp->col = n;
17755 #ifdef FEAT_VIRTUALEDIT
17756 n = list_find_nr(l, i, NULL);
17757 if (n < 0)
17758 posp->coladd = 0;
17759 else
17760 posp->coladd = n;
17761 #endif
17763 return OK;
17767 * Get the length of an environment variable name.
17768 * Advance "arg" to the first character after the name.
17769 * Return 0 for error.
17771 static int
17772 get_env_len(arg)
17773 char_u **arg;
17775 char_u *p;
17776 int len;
17778 for (p = *arg; vim_isIDc(*p); ++p)
17780 if (p == *arg) /* no name found */
17781 return 0;
17783 len = (int)(p - *arg);
17784 *arg = p;
17785 return len;
17789 * Get the length of the name of a function or internal variable.
17790 * "arg" is advanced to the first non-white character after the name.
17791 * Return 0 if something is wrong.
17793 static int
17794 get_id_len(arg)
17795 char_u **arg;
17797 char_u *p;
17798 int len;
17800 /* Find the end of the name. */
17801 for (p = *arg; eval_isnamec(*p); ++p)
17803 if (p == *arg) /* no name found */
17804 return 0;
17806 len = (int)(p - *arg);
17807 *arg = skipwhite(p);
17809 return len;
17813 * Get the length of the name of a variable or function.
17814 * Only the name is recognized, does not handle ".key" or "[idx]".
17815 * "arg" is advanced to the first non-white character after the name.
17816 * Return -1 if curly braces expansion failed.
17817 * Return 0 if something else is wrong.
17818 * If the name contains 'magic' {}'s, expand them and return the
17819 * expanded name in an allocated string via 'alias' - caller must free.
17821 static int
17822 get_name_len(arg, alias, evaluate, verbose)
17823 char_u **arg;
17824 char_u **alias;
17825 int evaluate;
17826 int verbose;
17828 int len;
17829 char_u *p;
17830 char_u *expr_start;
17831 char_u *expr_end;
17833 *alias = NULL; /* default to no alias */
17835 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
17836 && (*arg)[2] == (int)KE_SNR)
17838 /* hard coded <SNR>, already translated */
17839 *arg += 3;
17840 return get_id_len(arg) + 3;
17842 len = eval_fname_script(*arg);
17843 if (len > 0)
17845 /* literal "<SID>", "s:" or "<SNR>" */
17846 *arg += len;
17850 * Find the end of the name; check for {} construction.
17852 p = find_name_end(*arg, &expr_start, &expr_end,
17853 len > 0 ? 0 : FNE_CHECK_START);
17854 if (expr_start != NULL)
17856 char_u *temp_string;
17858 if (!evaluate)
17860 len += (int)(p - *arg);
17861 *arg = skipwhite(p);
17862 return len;
17866 * Include any <SID> etc in the expanded string:
17867 * Thus the -len here.
17869 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
17870 if (temp_string == NULL)
17871 return -1;
17872 *alias = temp_string;
17873 *arg = skipwhite(p);
17874 return (int)STRLEN(temp_string);
17877 len += get_id_len(arg);
17878 if (len == 0 && verbose)
17879 EMSG2(_(e_invexpr2), *arg);
17881 return len;
17885 * Find the end of a variable or function name, taking care of magic braces.
17886 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
17887 * start and end of the first magic braces item.
17888 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
17889 * Return a pointer to just after the name. Equal to "arg" if there is no
17890 * valid name.
17892 static char_u *
17893 find_name_end(arg, expr_start, expr_end, flags)
17894 char_u *arg;
17895 char_u **expr_start;
17896 char_u **expr_end;
17897 int flags;
17899 int mb_nest = 0;
17900 int br_nest = 0;
17901 char_u *p;
17903 if (expr_start != NULL)
17905 *expr_start = NULL;
17906 *expr_end = NULL;
17909 /* Quick check for valid starting character. */
17910 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
17911 return arg;
17913 for (p = arg; *p != NUL
17914 && (eval_isnamec(*p)
17915 || *p == '{'
17916 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
17917 || mb_nest != 0
17918 || br_nest != 0); mb_ptr_adv(p))
17920 if (*p == '\'')
17922 /* skip over 'string' to avoid counting [ and ] inside it. */
17923 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
17925 if (*p == NUL)
17926 break;
17928 else if (*p == '"')
17930 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
17931 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
17932 if (*p == '\\' && p[1] != NUL)
17933 ++p;
17934 if (*p == NUL)
17935 break;
17938 if (mb_nest == 0)
17940 if (*p == '[')
17941 ++br_nest;
17942 else if (*p == ']')
17943 --br_nest;
17946 if (br_nest == 0)
17948 if (*p == '{')
17950 mb_nest++;
17951 if (expr_start != NULL && *expr_start == NULL)
17952 *expr_start = p;
17954 else if (*p == '}')
17956 mb_nest--;
17957 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
17958 *expr_end = p;
17963 return p;
17967 * Expands out the 'magic' {}'s in a variable/function name.
17968 * Note that this can call itself recursively, to deal with
17969 * constructs like foo{bar}{baz}{bam}
17970 * The four pointer arguments point to "foo{expre}ss{ion}bar"
17971 * "in_start" ^
17972 * "expr_start" ^
17973 * "expr_end" ^
17974 * "in_end" ^
17976 * Returns a new allocated string, which the caller must free.
17977 * Returns NULL for failure.
17979 static char_u *
17980 make_expanded_name(in_start, expr_start, expr_end, in_end)
17981 char_u *in_start;
17982 char_u *expr_start;
17983 char_u *expr_end;
17984 char_u *in_end;
17986 char_u c1;
17987 char_u *retval = NULL;
17988 char_u *temp_result;
17989 char_u *nextcmd = NULL;
17991 if (expr_end == NULL || in_end == NULL)
17992 return NULL;
17993 *expr_start = NUL;
17994 *expr_end = NUL;
17995 c1 = *in_end;
17996 *in_end = NUL;
17998 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
17999 if (temp_result != NULL && nextcmd == NULL)
18001 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18002 + (in_end - expr_end) + 1));
18003 if (retval != NULL)
18005 STRCPY(retval, in_start);
18006 STRCAT(retval, temp_result);
18007 STRCAT(retval, expr_end + 1);
18010 vim_free(temp_result);
18012 *in_end = c1; /* put char back for error messages */
18013 *expr_start = '{';
18014 *expr_end = '}';
18016 if (retval != NULL)
18018 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18019 if (expr_start != NULL)
18021 /* Further expansion! */
18022 temp_result = make_expanded_name(retval, expr_start,
18023 expr_end, temp_result);
18024 vim_free(retval);
18025 retval = temp_result;
18029 return retval;
18033 * Return TRUE if character "c" can be used in a variable or function name.
18034 * Does not include '{' or '}' for magic braces.
18036 static int
18037 eval_isnamec(c)
18038 int c;
18040 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18044 * Return TRUE if character "c" can be used as the first character in a
18045 * variable or function name (excluding '{' and '}').
18047 static int
18048 eval_isnamec1(c)
18049 int c;
18051 return (ASCII_ISALPHA(c) || c == '_');
18055 * Set number v: variable to "val".
18057 void
18058 set_vim_var_nr(idx, val)
18059 int idx;
18060 long val;
18062 vimvars[idx].vv_nr = val;
18066 * Get number v: variable value.
18068 long
18069 get_vim_var_nr(idx)
18070 int idx;
18072 return vimvars[idx].vv_nr;
18075 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18077 * Get string v: variable value. Uses a static buffer, can only be used once.
18079 char_u *
18080 get_vim_var_str(idx)
18081 int idx;
18083 return get_tv_string(&vimvars[idx].vv_tv);
18085 #endif
18088 * Set v:count, v:count1 and v:prevcount.
18090 void
18091 set_vcount(count, count1)
18092 long count;
18093 long count1;
18095 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18096 vimvars[VV_COUNT].vv_nr = count;
18097 vimvars[VV_COUNT1].vv_nr = count1;
18101 * Set string v: variable to a copy of "val".
18103 void
18104 set_vim_var_string(idx, val, len)
18105 int idx;
18106 char_u *val;
18107 int len; /* length of "val" to use or -1 (whole string) */
18109 /* Need to do this (at least) once, since we can't initialize a union.
18110 * Will always be invoked when "v:progname" is set. */
18111 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18113 vim_free(vimvars[idx].vv_str);
18114 if (val == NULL)
18115 vimvars[idx].vv_str = NULL;
18116 else if (len == -1)
18117 vimvars[idx].vv_str = vim_strsave(val);
18118 else
18119 vimvars[idx].vv_str = vim_strnsave(val, len);
18123 * Set v:register if needed.
18125 void
18126 set_reg_var(c)
18127 int c;
18129 char_u regname;
18131 if (c == 0 || c == ' ')
18132 regname = '"';
18133 else
18134 regname = c;
18135 /* Avoid free/alloc when the value is already right. */
18136 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18137 set_vim_var_string(VV_REG, &regname, 1);
18141 * Get or set v:exception. If "oldval" == NULL, return the current value.
18142 * Otherwise, restore the value to "oldval" and return NULL.
18143 * Must always be called in pairs to save and restore v:exception! Does not
18144 * take care of memory allocations.
18146 char_u *
18147 v_exception(oldval)
18148 char_u *oldval;
18150 if (oldval == NULL)
18151 return vimvars[VV_EXCEPTION].vv_str;
18153 vimvars[VV_EXCEPTION].vv_str = oldval;
18154 return NULL;
18158 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18159 * Otherwise, restore the value to "oldval" and return NULL.
18160 * Must always be called in pairs to save and restore v:throwpoint! Does not
18161 * take care of memory allocations.
18163 char_u *
18164 v_throwpoint(oldval)
18165 char_u *oldval;
18167 if (oldval == NULL)
18168 return vimvars[VV_THROWPOINT].vv_str;
18170 vimvars[VV_THROWPOINT].vv_str = oldval;
18171 return NULL;
18174 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18176 * Set v:cmdarg.
18177 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18178 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18179 * Must always be called in pairs!
18181 char_u *
18182 set_cmdarg(eap, oldarg)
18183 exarg_T *eap;
18184 char_u *oldarg;
18186 char_u *oldval;
18187 char_u *newval;
18188 unsigned len;
18190 oldval = vimvars[VV_CMDARG].vv_str;
18191 if (eap == NULL)
18193 vim_free(oldval);
18194 vimvars[VV_CMDARG].vv_str = oldarg;
18195 return NULL;
18198 if (eap->force_bin == FORCE_BIN)
18199 len = 6;
18200 else if (eap->force_bin == FORCE_NOBIN)
18201 len = 8;
18202 else
18203 len = 0;
18205 if (eap->read_edit)
18206 len += 7;
18208 if (eap->force_ff != 0)
18209 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18210 # ifdef FEAT_MBYTE
18211 if (eap->force_enc != 0)
18212 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18213 if (eap->bad_char != 0)
18214 len += (unsigned)STRLEN(eap->cmd + eap->bad_char) + 7;
18215 # endif
18217 newval = alloc(len + 1);
18218 if (newval == NULL)
18219 return NULL;
18221 if (eap->force_bin == FORCE_BIN)
18222 sprintf((char *)newval, " ++bin");
18223 else if (eap->force_bin == FORCE_NOBIN)
18224 sprintf((char *)newval, " ++nobin");
18225 else
18226 *newval = NUL;
18228 if (eap->read_edit)
18229 STRCAT(newval, " ++edit");
18231 if (eap->force_ff != 0)
18232 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18233 eap->cmd + eap->force_ff);
18234 # ifdef FEAT_MBYTE
18235 if (eap->force_enc != 0)
18236 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18237 eap->cmd + eap->force_enc);
18238 if (eap->bad_char != 0)
18239 sprintf((char *)newval + STRLEN(newval), " ++bad=%s",
18240 eap->cmd + eap->bad_char);
18241 # endif
18242 vimvars[VV_CMDARG].vv_str = newval;
18243 return oldval;
18245 #endif
18248 * Get the value of internal variable "name".
18249 * Return OK or FAIL.
18251 static int
18252 get_var_tv(name, len, rettv, verbose)
18253 char_u *name;
18254 int len; /* length of "name" */
18255 typval_T *rettv; /* NULL when only checking existence */
18256 int verbose; /* may give error message */
18258 int ret = OK;
18259 typval_T *tv = NULL;
18260 typval_T atv;
18261 dictitem_T *v;
18262 int cc;
18264 /* truncate the name, so that we can use strcmp() */
18265 cc = name[len];
18266 name[len] = NUL;
18269 * Check for "b:changedtick".
18271 if (STRCMP(name, "b:changedtick") == 0)
18273 atv.v_type = VAR_NUMBER;
18274 atv.vval.v_number = curbuf->b_changedtick;
18275 tv = &atv;
18279 * Check for user-defined variables.
18281 else
18283 v = find_var(name, NULL);
18284 if (v != NULL)
18285 tv = &v->di_tv;
18288 if (tv == NULL)
18290 if (rettv != NULL && verbose)
18291 EMSG2(_(e_undefvar), name);
18292 ret = FAIL;
18294 else if (rettv != NULL)
18295 copy_tv(tv, rettv);
18297 name[len] = cc;
18299 return ret;
18303 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18304 * Also handle function call with Funcref variable: func(expr)
18305 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18307 static int
18308 handle_subscript(arg, rettv, evaluate, verbose)
18309 char_u **arg;
18310 typval_T *rettv;
18311 int evaluate; /* do more than finding the end */
18312 int verbose; /* give error messages */
18314 int ret = OK;
18315 dict_T *selfdict = NULL;
18316 char_u *s;
18317 int len;
18318 typval_T functv;
18320 while (ret == OK
18321 && (**arg == '['
18322 || (**arg == '.' && rettv->v_type == VAR_DICT)
18323 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18324 && !vim_iswhite(*(*arg - 1)))
18326 if (**arg == '(')
18328 /* need to copy the funcref so that we can clear rettv */
18329 functv = *rettv;
18330 rettv->v_type = VAR_UNKNOWN;
18332 /* Invoke the function. Recursive! */
18333 s = functv.vval.v_string;
18334 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18335 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18336 &len, evaluate, selfdict);
18338 /* Clear the funcref afterwards, so that deleting it while
18339 * evaluating the arguments is possible (see test55). */
18340 clear_tv(&functv);
18342 /* Stop the expression evaluation when immediately aborting on
18343 * error, or when an interrupt occurred or an exception was thrown
18344 * but not caught. */
18345 if (aborting())
18347 if (ret == OK)
18348 clear_tv(rettv);
18349 ret = FAIL;
18351 dict_unref(selfdict);
18352 selfdict = NULL;
18354 else /* **arg == '[' || **arg == '.' */
18356 dict_unref(selfdict);
18357 if (rettv->v_type == VAR_DICT)
18359 selfdict = rettv->vval.v_dict;
18360 if (selfdict != NULL)
18361 ++selfdict->dv_refcount;
18363 else
18364 selfdict = NULL;
18365 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18367 clear_tv(rettv);
18368 ret = FAIL;
18372 dict_unref(selfdict);
18373 return ret;
18377 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18378 * value).
18380 static typval_T *
18381 alloc_tv()
18383 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18387 * Allocate memory for a variable type-value, and assign a string to it.
18388 * The string "s" must have been allocated, it is consumed.
18389 * Return NULL for out of memory, the variable otherwise.
18391 static typval_T *
18392 alloc_string_tv(s)
18393 char_u *s;
18395 typval_T *rettv;
18397 rettv = alloc_tv();
18398 if (rettv != NULL)
18400 rettv->v_type = VAR_STRING;
18401 rettv->vval.v_string = s;
18403 else
18404 vim_free(s);
18405 return rettv;
18409 * Free the memory for a variable type-value.
18411 void
18412 free_tv(varp)
18413 typval_T *varp;
18415 if (varp != NULL)
18417 switch (varp->v_type)
18419 case VAR_FUNC:
18420 func_unref(varp->vval.v_string);
18421 /*FALLTHROUGH*/
18422 case VAR_STRING:
18423 vim_free(varp->vval.v_string);
18424 break;
18425 case VAR_LIST:
18426 list_unref(varp->vval.v_list);
18427 break;
18428 case VAR_DICT:
18429 dict_unref(varp->vval.v_dict);
18430 break;
18431 case VAR_NUMBER:
18432 #ifdef FEAT_FLOAT
18433 case VAR_FLOAT:
18434 #endif
18435 case VAR_UNKNOWN:
18436 break;
18437 default:
18438 EMSG2(_(e_intern2), "free_tv()");
18439 break;
18441 vim_free(varp);
18446 * Free the memory for a variable value and set the value to NULL or 0.
18448 void
18449 clear_tv(varp)
18450 typval_T *varp;
18452 if (varp != NULL)
18454 switch (varp->v_type)
18456 case VAR_FUNC:
18457 func_unref(varp->vval.v_string);
18458 /*FALLTHROUGH*/
18459 case VAR_STRING:
18460 vim_free(varp->vval.v_string);
18461 varp->vval.v_string = NULL;
18462 break;
18463 case VAR_LIST:
18464 list_unref(varp->vval.v_list);
18465 varp->vval.v_list = NULL;
18466 break;
18467 case VAR_DICT:
18468 dict_unref(varp->vval.v_dict);
18469 varp->vval.v_dict = NULL;
18470 break;
18471 case VAR_NUMBER:
18472 varp->vval.v_number = 0;
18473 break;
18474 #ifdef FEAT_FLOAT
18475 case VAR_FLOAT:
18476 varp->vval.v_float = 0.0;
18477 break;
18478 #endif
18479 case VAR_UNKNOWN:
18480 break;
18481 default:
18482 EMSG2(_(e_intern2), "clear_tv()");
18484 varp->v_lock = 0;
18489 * Set the value of a variable to NULL without freeing items.
18491 static void
18492 init_tv(varp)
18493 typval_T *varp;
18495 if (varp != NULL)
18496 vim_memset(varp, 0, sizeof(typval_T));
18500 * Get the number value of a variable.
18501 * If it is a String variable, uses vim_str2nr().
18502 * For incompatible types, return 0.
18503 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18504 * caller of incompatible types: it sets *denote to TRUE if "denote"
18505 * is not NULL or returns -1 otherwise.
18507 static long
18508 get_tv_number(varp)
18509 typval_T *varp;
18511 int error = FALSE;
18513 return get_tv_number_chk(varp, &error); /* return 0L on error */
18516 long
18517 get_tv_number_chk(varp, denote)
18518 typval_T *varp;
18519 int *denote;
18521 long n = 0L;
18523 switch (varp->v_type)
18525 case VAR_NUMBER:
18526 return (long)(varp->vval.v_number);
18527 #ifdef FEAT_FLOAT
18528 case VAR_FLOAT:
18529 EMSG(_("E805: Using a Float as a Number"));
18530 break;
18531 #endif
18532 case VAR_FUNC:
18533 EMSG(_("E703: Using a Funcref as a Number"));
18534 break;
18535 case VAR_STRING:
18536 if (varp->vval.v_string != NULL)
18537 vim_str2nr(varp->vval.v_string, NULL, NULL,
18538 TRUE, TRUE, &n, NULL);
18539 return n;
18540 case VAR_LIST:
18541 EMSG(_("E745: Using a List as a Number"));
18542 break;
18543 case VAR_DICT:
18544 EMSG(_("E728: Using a Dictionary as a Number"));
18545 break;
18546 default:
18547 EMSG2(_(e_intern2), "get_tv_number()");
18548 break;
18550 if (denote == NULL) /* useful for values that must be unsigned */
18551 n = -1;
18552 else
18553 *denote = TRUE;
18554 return n;
18558 * Get the lnum from the first argument.
18559 * Also accepts ".", "$", etc., but that only works for the current buffer.
18560 * Returns -1 on error.
18562 static linenr_T
18563 get_tv_lnum(argvars)
18564 typval_T *argvars;
18566 typval_T rettv;
18567 linenr_T lnum;
18569 lnum = get_tv_number_chk(&argvars[0], NULL);
18570 if (lnum == 0) /* no valid number, try using line() */
18572 rettv.v_type = VAR_NUMBER;
18573 f_line(argvars, &rettv);
18574 lnum = rettv.vval.v_number;
18575 clear_tv(&rettv);
18577 return lnum;
18581 * Get the lnum from the first argument.
18582 * Also accepts "$", then "buf" is used.
18583 * Returns 0 on error.
18585 static linenr_T
18586 get_tv_lnum_buf(argvars, buf)
18587 typval_T *argvars;
18588 buf_T *buf;
18590 if (argvars[0].v_type == VAR_STRING
18591 && argvars[0].vval.v_string != NULL
18592 && argvars[0].vval.v_string[0] == '$'
18593 && buf != NULL)
18594 return buf->b_ml.ml_line_count;
18595 return get_tv_number_chk(&argvars[0], NULL);
18599 * Get the string value of a variable.
18600 * If it is a Number variable, the number is converted into a string.
18601 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18602 * get_tv_string_buf() uses a given buffer.
18603 * If the String variable has never been set, return an empty string.
18604 * Never returns NULL;
18605 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18606 * NULL on error.
18608 static char_u *
18609 get_tv_string(varp)
18610 typval_T *varp;
18612 static char_u mybuf[NUMBUFLEN];
18614 return get_tv_string_buf(varp, mybuf);
18617 static char_u *
18618 get_tv_string_buf(varp, buf)
18619 typval_T *varp;
18620 char_u *buf;
18622 char_u *res = get_tv_string_buf_chk(varp, buf);
18624 return res != NULL ? res : (char_u *)"";
18627 char_u *
18628 get_tv_string_chk(varp)
18629 typval_T *varp;
18631 static char_u mybuf[NUMBUFLEN];
18633 return get_tv_string_buf_chk(varp, mybuf);
18636 static char_u *
18637 get_tv_string_buf_chk(varp, buf)
18638 typval_T *varp;
18639 char_u *buf;
18641 switch (varp->v_type)
18643 case VAR_NUMBER:
18644 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18645 return buf;
18646 case VAR_FUNC:
18647 EMSG(_("E729: using Funcref as a String"));
18648 break;
18649 case VAR_LIST:
18650 EMSG(_("E730: using List as a String"));
18651 break;
18652 case VAR_DICT:
18653 EMSG(_("E731: using Dictionary as a String"));
18654 break;
18655 #ifdef FEAT_FLOAT
18656 case VAR_FLOAT:
18657 EMSG(_("E806: using Float as a String"));
18658 break;
18659 #endif
18660 case VAR_STRING:
18661 if (varp->vval.v_string != NULL)
18662 return varp->vval.v_string;
18663 return (char_u *)"";
18664 default:
18665 EMSG2(_(e_intern2), "get_tv_string_buf()");
18666 break;
18668 return NULL;
18672 * Find variable "name" in the list of variables.
18673 * Return a pointer to it if found, NULL if not found.
18674 * Careful: "a:0" variables don't have a name.
18675 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18676 * hashtab_T used.
18678 static dictitem_T *
18679 find_var(name, htp)
18680 char_u *name;
18681 hashtab_T **htp;
18683 char_u *varname;
18684 hashtab_T *ht;
18686 ht = find_var_ht(name, &varname);
18687 if (htp != NULL)
18688 *htp = ht;
18689 if (ht == NULL)
18690 return NULL;
18691 return find_var_in_ht(ht, varname, htp != NULL);
18695 * Find variable "varname" in hashtab "ht".
18696 * Returns NULL if not found.
18698 static dictitem_T *
18699 find_var_in_ht(ht, varname, writing)
18700 hashtab_T *ht;
18701 char_u *varname;
18702 int writing;
18704 hashitem_T *hi;
18706 if (*varname == NUL)
18708 /* Must be something like "s:", otherwise "ht" would be NULL. */
18709 switch (varname[-2])
18711 case 's': return &SCRIPT_SV(current_SID).sv_var;
18712 case 'g': return &globvars_var;
18713 case 'v': return &vimvars_var;
18714 case 'b': return &curbuf->b_bufvar;
18715 case 'w': return &curwin->w_winvar;
18716 #ifdef FEAT_WINDOWS
18717 case 't': return &curtab->tp_winvar;
18718 #endif
18719 case 'l': return current_funccal == NULL
18720 ? NULL : &current_funccal->l_vars_var;
18721 case 'a': return current_funccal == NULL
18722 ? NULL : &current_funccal->l_avars_var;
18724 return NULL;
18727 hi = hash_find(ht, varname);
18728 if (HASHITEM_EMPTY(hi))
18730 /* For global variables we may try auto-loading the script. If it
18731 * worked find the variable again. Don't auto-load a script if it was
18732 * loaded already, otherwise it would be loaded every time when
18733 * checking if a function name is a Funcref variable. */
18734 if (ht == &globvarht && !writing
18735 && script_autoload(varname, FALSE) && !aborting())
18736 hi = hash_find(ht, varname);
18737 if (HASHITEM_EMPTY(hi))
18738 return NULL;
18740 return HI2DI(hi);
18744 * Find the hashtab used for a variable name.
18745 * Set "varname" to the start of name without ':'.
18747 static hashtab_T *
18748 find_var_ht(name, varname)
18749 char_u *name;
18750 char_u **varname;
18752 hashitem_T *hi;
18754 if (name[1] != ':')
18756 /* The name must not start with a colon or #. */
18757 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
18758 return NULL;
18759 *varname = name;
18761 /* "version" is "v:version" in all scopes */
18762 hi = hash_find(&compat_hashtab, name);
18763 if (!HASHITEM_EMPTY(hi))
18764 return &compat_hashtab;
18766 if (current_funccal == NULL)
18767 return &globvarht; /* global variable */
18768 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
18770 *varname = name + 2;
18771 if (*name == 'g') /* global variable */
18772 return &globvarht;
18773 /* There must be no ':' or '#' in the rest of the name, unless g: is used
18775 if (vim_strchr(name + 2, ':') != NULL
18776 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
18777 return NULL;
18778 if (*name == 'b') /* buffer variable */
18779 return &curbuf->b_vars.dv_hashtab;
18780 if (*name == 'w') /* window variable */
18781 return &curwin->w_vars.dv_hashtab;
18782 #ifdef FEAT_WINDOWS
18783 if (*name == 't') /* tab page variable */
18784 return &curtab->tp_vars.dv_hashtab;
18785 #endif
18786 if (*name == 'v') /* v: variable */
18787 return &vimvarht;
18788 if (*name == 'a' && current_funccal != NULL) /* function argument */
18789 return &current_funccal->l_avars.dv_hashtab;
18790 if (*name == 'l' && current_funccal != NULL) /* local function variable */
18791 return &current_funccal->l_vars.dv_hashtab;
18792 if (*name == 's' /* script variable */
18793 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
18794 return &SCRIPT_VARS(current_SID);
18795 return NULL;
18799 * Get the string value of a (global/local) variable.
18800 * Returns NULL when it doesn't exist.
18802 char_u *
18803 get_var_value(name)
18804 char_u *name;
18806 dictitem_T *v;
18808 v = find_var(name, NULL);
18809 if (v == NULL)
18810 return NULL;
18811 return get_tv_string(&v->di_tv);
18815 * Allocate a new hashtab for a sourced script. It will be used while
18816 * sourcing this script and when executing functions defined in the script.
18818 void
18819 new_script_vars(id)
18820 scid_T id;
18822 int i;
18823 hashtab_T *ht;
18824 scriptvar_T *sv;
18826 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
18828 /* Re-allocating ga_data means that an ht_array pointing to
18829 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
18830 * at its init value. Also reset "v_dict", it's always the same. */
18831 for (i = 1; i <= ga_scripts.ga_len; ++i)
18833 ht = &SCRIPT_VARS(i);
18834 if (ht->ht_mask == HT_INIT_SIZE - 1)
18835 ht->ht_array = ht->ht_smallarray;
18836 sv = &SCRIPT_SV(i);
18837 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
18840 while (ga_scripts.ga_len < id)
18842 sv = &SCRIPT_SV(ga_scripts.ga_len + 1);
18843 init_var_dict(&sv->sv_dict, &sv->sv_var);
18844 ++ga_scripts.ga_len;
18850 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
18851 * point to it.
18853 void
18854 init_var_dict(dict, dict_var)
18855 dict_T *dict;
18856 dictitem_T *dict_var;
18858 hash_init(&dict->dv_hashtab);
18859 dict->dv_refcount = 99999;
18860 dict_var->di_tv.vval.v_dict = dict;
18861 dict_var->di_tv.v_type = VAR_DICT;
18862 dict_var->di_tv.v_lock = VAR_FIXED;
18863 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
18864 dict_var->di_key[0] = NUL;
18868 * Clean up a list of internal variables.
18869 * Frees all allocated variables and the value they contain.
18870 * Clears hashtab "ht", does not free it.
18872 void
18873 vars_clear(ht)
18874 hashtab_T *ht;
18876 vars_clear_ext(ht, TRUE);
18880 * Like vars_clear(), but only free the value if "free_val" is TRUE.
18882 static void
18883 vars_clear_ext(ht, free_val)
18884 hashtab_T *ht;
18885 int free_val;
18887 int todo;
18888 hashitem_T *hi;
18889 dictitem_T *v;
18891 hash_lock(ht);
18892 todo = (int)ht->ht_used;
18893 for (hi = ht->ht_array; todo > 0; ++hi)
18895 if (!HASHITEM_EMPTY(hi))
18897 --todo;
18899 /* Free the variable. Don't remove it from the hashtab,
18900 * ht_array might change then. hash_clear() takes care of it
18901 * later. */
18902 v = HI2DI(hi);
18903 if (free_val)
18904 clear_tv(&v->di_tv);
18905 if ((v->di_flags & DI_FLAGS_FIX) == 0)
18906 vim_free(v);
18909 hash_clear(ht);
18910 ht->ht_used = 0;
18914 * Delete a variable from hashtab "ht" at item "hi".
18915 * Clear the variable value and free the dictitem.
18917 static void
18918 delete_var(ht, hi)
18919 hashtab_T *ht;
18920 hashitem_T *hi;
18922 dictitem_T *di = HI2DI(hi);
18924 hash_remove(ht, hi);
18925 clear_tv(&di->di_tv);
18926 vim_free(di);
18930 * List the value of one internal variable.
18932 static void
18933 list_one_var(v, prefix, first)
18934 dictitem_T *v;
18935 char_u *prefix;
18936 int *first;
18938 char_u *tofree;
18939 char_u *s;
18940 char_u numbuf[NUMBUFLEN];
18942 s = echo_string(&v->di_tv, &tofree, numbuf, ++current_copyID);
18943 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
18944 s == NULL ? (char_u *)"" : s, first);
18945 vim_free(tofree);
18948 static void
18949 list_one_var_a(prefix, name, type, string, first)
18950 char_u *prefix;
18951 char_u *name;
18952 int type;
18953 char_u *string;
18954 int *first; /* when TRUE clear rest of screen and set to FALSE */
18956 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
18957 msg_start();
18958 msg_puts(prefix);
18959 if (name != NULL) /* "a:" vars don't have a name stored */
18960 msg_puts(name);
18961 msg_putchar(' ');
18962 msg_advance(22);
18963 if (type == VAR_NUMBER)
18964 msg_putchar('#');
18965 else if (type == VAR_FUNC)
18966 msg_putchar('*');
18967 else if (type == VAR_LIST)
18969 msg_putchar('[');
18970 if (*string == '[')
18971 ++string;
18973 else if (type == VAR_DICT)
18975 msg_putchar('{');
18976 if (*string == '{')
18977 ++string;
18979 else
18980 msg_putchar(' ');
18982 msg_outtrans(string);
18984 if (type == VAR_FUNC)
18985 msg_puts((char_u *)"()");
18986 if (*first)
18988 msg_clr_eos();
18989 *first = FALSE;
18994 * Set variable "name" to value in "tv".
18995 * If the variable already exists, the value is updated.
18996 * Otherwise the variable is created.
18998 static void
18999 set_var(name, tv, copy)
19000 char_u *name;
19001 typval_T *tv;
19002 int copy; /* make copy of value in "tv" */
19004 dictitem_T *v;
19005 char_u *varname;
19006 hashtab_T *ht;
19007 char_u *p;
19009 if (tv->v_type == VAR_FUNC)
19011 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19012 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19013 ? name[2] : name[0]))
19015 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19016 return;
19018 if (function_exists(name))
19020 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19021 name);
19022 return;
19026 ht = find_var_ht(name, &varname);
19027 if (ht == NULL || *varname == NUL)
19029 EMSG2(_(e_illvar), name);
19030 return;
19033 v = find_var_in_ht(ht, varname, TRUE);
19034 if (v != NULL)
19036 /* existing variable, need to clear the value */
19037 if (var_check_ro(v->di_flags, name)
19038 || tv_check_lock(v->di_tv.v_lock, name))
19039 return;
19040 if (v->di_tv.v_type != tv->v_type
19041 && !((v->di_tv.v_type == VAR_STRING
19042 || v->di_tv.v_type == VAR_NUMBER)
19043 && (tv->v_type == VAR_STRING
19044 || tv->v_type == VAR_NUMBER))
19045 #ifdef FEAT_FLOAT
19046 && !((v->di_tv.v_type == VAR_NUMBER
19047 || v->di_tv.v_type == VAR_FLOAT)
19048 && (tv->v_type == VAR_NUMBER
19049 || tv->v_type == VAR_FLOAT))
19050 #endif
19053 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19054 return;
19058 * Handle setting internal v: variables separately: we don't change
19059 * the type.
19061 if (ht == &vimvarht)
19063 if (v->di_tv.v_type == VAR_STRING)
19065 vim_free(v->di_tv.vval.v_string);
19066 if (copy || tv->v_type != VAR_STRING)
19067 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19068 else
19070 /* Take over the string to avoid an extra alloc/free. */
19071 v->di_tv.vval.v_string = tv->vval.v_string;
19072 tv->vval.v_string = NULL;
19075 else if (v->di_tv.v_type != VAR_NUMBER)
19076 EMSG2(_(e_intern2), "set_var()");
19077 else
19079 v->di_tv.vval.v_number = get_tv_number(tv);
19080 if (STRCMP(varname, "searchforward") == 0)
19081 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19083 return;
19086 clear_tv(&v->di_tv);
19088 else /* add a new variable */
19090 /* Can't add "v:" variable. */
19091 if (ht == &vimvarht)
19093 EMSG2(_(e_illvar), name);
19094 return;
19097 /* Make sure the variable name is valid. */
19098 for (p = varname; *p != NUL; ++p)
19099 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19100 && *p != AUTOLOAD_CHAR)
19102 EMSG2(_(e_illvar), varname);
19103 return;
19106 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19107 + STRLEN(varname)));
19108 if (v == NULL)
19109 return;
19110 STRCPY(v->di_key, varname);
19111 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19113 vim_free(v);
19114 return;
19116 v->di_flags = 0;
19119 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19120 copy_tv(tv, &v->di_tv);
19121 else
19123 v->di_tv = *tv;
19124 v->di_tv.v_lock = 0;
19125 init_tv(tv);
19130 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19131 * Also give an error message.
19133 static int
19134 var_check_ro(flags, name)
19135 int flags;
19136 char_u *name;
19138 if (flags & DI_FLAGS_RO)
19140 EMSG2(_(e_readonlyvar), name);
19141 return TRUE;
19143 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19145 EMSG2(_(e_readonlysbx), name);
19146 return TRUE;
19148 return FALSE;
19152 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19153 * Also give an error message.
19155 static int
19156 var_check_fixed(flags, name)
19157 int flags;
19158 char_u *name;
19160 if (flags & DI_FLAGS_FIX)
19162 EMSG2(_("E795: Cannot delete variable %s"), name);
19163 return TRUE;
19165 return FALSE;
19169 * Return TRUE if typeval "tv" is set to be locked (immutable).
19170 * Also give an error message, using "name".
19172 static int
19173 tv_check_lock(lock, name)
19174 int lock;
19175 char_u *name;
19177 if (lock & VAR_LOCKED)
19179 EMSG2(_("E741: Value is locked: %s"),
19180 name == NULL ? (char_u *)_("Unknown") : name);
19181 return TRUE;
19183 if (lock & VAR_FIXED)
19185 EMSG2(_("E742: Cannot change value of %s"),
19186 name == NULL ? (char_u *)_("Unknown") : name);
19187 return TRUE;
19189 return FALSE;
19193 * Copy the values from typval_T "from" to typval_T "to".
19194 * When needed allocates string or increases reference count.
19195 * Does not make a copy of a list or dict but copies the reference!
19197 static void
19198 copy_tv(from, to)
19199 typval_T *from;
19200 typval_T *to;
19202 to->v_type = from->v_type;
19203 to->v_lock = 0;
19204 switch (from->v_type)
19206 case VAR_NUMBER:
19207 to->vval.v_number = from->vval.v_number;
19208 break;
19209 #ifdef FEAT_FLOAT
19210 case VAR_FLOAT:
19211 to->vval.v_float = from->vval.v_float;
19212 break;
19213 #endif
19214 case VAR_STRING:
19215 case VAR_FUNC:
19216 if (from->vval.v_string == NULL)
19217 to->vval.v_string = NULL;
19218 else
19220 to->vval.v_string = vim_strsave(from->vval.v_string);
19221 if (from->v_type == VAR_FUNC)
19222 func_ref(to->vval.v_string);
19224 break;
19225 case VAR_LIST:
19226 if (from->vval.v_list == NULL)
19227 to->vval.v_list = NULL;
19228 else
19230 to->vval.v_list = from->vval.v_list;
19231 ++to->vval.v_list->lv_refcount;
19233 break;
19234 case VAR_DICT:
19235 if (from->vval.v_dict == NULL)
19236 to->vval.v_dict = NULL;
19237 else
19239 to->vval.v_dict = from->vval.v_dict;
19240 ++to->vval.v_dict->dv_refcount;
19242 break;
19243 default:
19244 EMSG2(_(e_intern2), "copy_tv()");
19245 break;
19250 * Make a copy of an item.
19251 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19252 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19253 * reference to an already copied list/dict can be used.
19254 * Returns FAIL or OK.
19256 static int
19257 item_copy(from, to, deep, copyID)
19258 typval_T *from;
19259 typval_T *to;
19260 int deep;
19261 int copyID;
19263 static int recurse = 0;
19264 int ret = OK;
19266 if (recurse >= DICT_MAXNEST)
19268 EMSG(_("E698: variable nested too deep for making a copy"));
19269 return FAIL;
19271 ++recurse;
19273 switch (from->v_type)
19275 case VAR_NUMBER:
19276 #ifdef FEAT_FLOAT
19277 case VAR_FLOAT:
19278 #endif
19279 case VAR_STRING:
19280 case VAR_FUNC:
19281 copy_tv(from, to);
19282 break;
19283 case VAR_LIST:
19284 to->v_type = VAR_LIST;
19285 to->v_lock = 0;
19286 if (from->vval.v_list == NULL)
19287 to->vval.v_list = NULL;
19288 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19290 /* use the copy made earlier */
19291 to->vval.v_list = from->vval.v_list->lv_copylist;
19292 ++to->vval.v_list->lv_refcount;
19294 else
19295 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19296 if (to->vval.v_list == NULL)
19297 ret = FAIL;
19298 break;
19299 case VAR_DICT:
19300 to->v_type = VAR_DICT;
19301 to->v_lock = 0;
19302 if (from->vval.v_dict == NULL)
19303 to->vval.v_dict = NULL;
19304 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19306 /* use the copy made earlier */
19307 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19308 ++to->vval.v_dict->dv_refcount;
19310 else
19311 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19312 if (to->vval.v_dict == NULL)
19313 ret = FAIL;
19314 break;
19315 default:
19316 EMSG2(_(e_intern2), "item_copy()");
19317 ret = FAIL;
19319 --recurse;
19320 return ret;
19324 * ":echo expr1 ..." print each argument separated with a space, add a
19325 * newline at the end.
19326 * ":echon expr1 ..." print each argument plain.
19328 void
19329 ex_echo(eap)
19330 exarg_T *eap;
19332 char_u *arg = eap->arg;
19333 typval_T rettv;
19334 char_u *tofree;
19335 char_u *p;
19336 int needclr = TRUE;
19337 int atstart = TRUE;
19338 char_u numbuf[NUMBUFLEN];
19340 if (eap->skip)
19341 ++emsg_skip;
19342 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19344 /* If eval1() causes an error message the text from the command may
19345 * still need to be cleared. E.g., "echo 22,44". */
19346 need_clr_eos = needclr;
19348 p = arg;
19349 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19352 * Report the invalid expression unless the expression evaluation
19353 * has been cancelled due to an aborting error, an interrupt, or an
19354 * exception.
19356 if (!aborting())
19357 EMSG2(_(e_invexpr2), p);
19358 need_clr_eos = FALSE;
19359 break;
19361 need_clr_eos = FALSE;
19363 if (!eap->skip)
19365 if (atstart)
19367 atstart = FALSE;
19368 /* Call msg_start() after eval1(), evaluating the expression
19369 * may cause a message to appear. */
19370 if (eap->cmdidx == CMD_echo)
19371 msg_start();
19373 else if (eap->cmdidx == CMD_echo)
19374 msg_puts_attr((char_u *)" ", echo_attr);
19375 p = echo_string(&rettv, &tofree, numbuf, ++current_copyID);
19376 if (p != NULL)
19377 for ( ; *p != NUL && !got_int; ++p)
19379 if (*p == '\n' || *p == '\r' || *p == TAB)
19381 if (*p != TAB && needclr)
19383 /* remove any text still there from the command */
19384 msg_clr_eos();
19385 needclr = FALSE;
19387 msg_putchar_attr(*p, echo_attr);
19389 else
19391 #ifdef FEAT_MBYTE
19392 if (has_mbyte)
19394 int i = (*mb_ptr2len)(p);
19396 (void)msg_outtrans_len_attr(p, i, echo_attr);
19397 p += i - 1;
19399 else
19400 #endif
19401 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19404 vim_free(tofree);
19406 clear_tv(&rettv);
19407 arg = skipwhite(arg);
19409 eap->nextcmd = check_nextcmd(arg);
19411 if (eap->skip)
19412 --emsg_skip;
19413 else
19415 /* remove text that may still be there from the command */
19416 if (needclr)
19417 msg_clr_eos();
19418 if (eap->cmdidx == CMD_echo)
19419 msg_end();
19424 * ":echohl {name}".
19426 void
19427 ex_echohl(eap)
19428 exarg_T *eap;
19430 int id;
19432 id = syn_name2id(eap->arg);
19433 if (id == 0)
19434 echo_attr = 0;
19435 else
19436 echo_attr = syn_id2attr(id);
19440 * ":execute expr1 ..." execute the result of an expression.
19441 * ":echomsg expr1 ..." Print a message
19442 * ":echoerr expr1 ..." Print an error
19443 * Each gets spaces around each argument and a newline at the end for
19444 * echo commands
19446 void
19447 ex_execute(eap)
19448 exarg_T *eap;
19450 char_u *arg = eap->arg;
19451 typval_T rettv;
19452 int ret = OK;
19453 char_u *p;
19454 garray_T ga;
19455 int len;
19456 int save_did_emsg;
19458 ga_init2(&ga, 1, 80);
19460 if (eap->skip)
19461 ++emsg_skip;
19462 while (*arg != NUL && *arg != '|' && *arg != '\n')
19464 p = arg;
19465 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19468 * Report the invalid expression unless the expression evaluation
19469 * has been cancelled due to an aborting error, an interrupt, or an
19470 * exception.
19472 if (!aborting())
19473 EMSG2(_(e_invexpr2), p);
19474 ret = FAIL;
19475 break;
19478 if (!eap->skip)
19480 p = get_tv_string(&rettv);
19481 len = (int)STRLEN(p);
19482 if (ga_grow(&ga, len + 2) == FAIL)
19484 clear_tv(&rettv);
19485 ret = FAIL;
19486 break;
19488 if (ga.ga_len)
19489 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19490 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19491 ga.ga_len += len;
19494 clear_tv(&rettv);
19495 arg = skipwhite(arg);
19498 if (ret != FAIL && ga.ga_data != NULL)
19500 if (eap->cmdidx == CMD_echomsg)
19502 MSG_ATTR(ga.ga_data, echo_attr);
19503 out_flush();
19505 else if (eap->cmdidx == CMD_echoerr)
19507 /* We don't want to abort following commands, restore did_emsg. */
19508 save_did_emsg = did_emsg;
19509 EMSG((char_u *)ga.ga_data);
19510 if (!force_abort)
19511 did_emsg = save_did_emsg;
19513 else if (eap->cmdidx == CMD_execute)
19514 do_cmdline((char_u *)ga.ga_data,
19515 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19518 ga_clear(&ga);
19520 if (eap->skip)
19521 --emsg_skip;
19523 eap->nextcmd = check_nextcmd(arg);
19527 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19528 * "arg" points to the "&" or '+' when called, to "option" when returning.
19529 * Returns NULL when no option name found. Otherwise pointer to the char
19530 * after the option name.
19532 static char_u *
19533 find_option_end(arg, opt_flags)
19534 char_u **arg;
19535 int *opt_flags;
19537 char_u *p = *arg;
19539 ++p;
19540 if (*p == 'g' && p[1] == ':')
19542 *opt_flags = OPT_GLOBAL;
19543 p += 2;
19545 else if (*p == 'l' && p[1] == ':')
19547 *opt_flags = OPT_LOCAL;
19548 p += 2;
19550 else
19551 *opt_flags = 0;
19553 if (!ASCII_ISALPHA(*p))
19554 return NULL;
19555 *arg = p;
19557 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19558 p += 4; /* termcap option */
19559 else
19560 while (ASCII_ISALPHA(*p))
19561 ++p;
19562 return p;
19566 * ":function"
19568 void
19569 ex_function(eap)
19570 exarg_T *eap;
19572 char_u *theline;
19573 int j;
19574 int c;
19575 int saved_did_emsg;
19576 char_u *name = NULL;
19577 char_u *p;
19578 char_u *arg;
19579 char_u *line_arg = NULL;
19580 garray_T newargs;
19581 garray_T newlines;
19582 int varargs = FALSE;
19583 int mustend = FALSE;
19584 int flags = 0;
19585 ufunc_T *fp;
19586 int indent;
19587 int nesting;
19588 char_u *skip_until = NULL;
19589 dictitem_T *v;
19590 funcdict_T fudi;
19591 static int func_nr = 0; /* number for nameless function */
19592 int paren;
19593 hashtab_T *ht;
19594 int todo;
19595 hashitem_T *hi;
19596 int sourcing_lnum_off;
19599 * ":function" without argument: list functions.
19601 if (ends_excmd(*eap->arg))
19603 if (!eap->skip)
19605 todo = (int)func_hashtab.ht_used;
19606 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19608 if (!HASHITEM_EMPTY(hi))
19610 --todo;
19611 fp = HI2UF(hi);
19612 if (!isdigit(*fp->uf_name))
19613 list_func_head(fp, FALSE);
19617 eap->nextcmd = check_nextcmd(eap->arg);
19618 return;
19622 * ":function /pat": list functions matching pattern.
19624 if (*eap->arg == '/')
19626 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19627 if (!eap->skip)
19629 regmatch_T regmatch;
19631 c = *p;
19632 *p = NUL;
19633 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19634 *p = c;
19635 if (regmatch.regprog != NULL)
19637 regmatch.rm_ic = p_ic;
19639 todo = (int)func_hashtab.ht_used;
19640 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19642 if (!HASHITEM_EMPTY(hi))
19644 --todo;
19645 fp = HI2UF(hi);
19646 if (!isdigit(*fp->uf_name)
19647 && vim_regexec(&regmatch, fp->uf_name, 0))
19648 list_func_head(fp, FALSE);
19653 if (*p == '/')
19654 ++p;
19655 eap->nextcmd = check_nextcmd(p);
19656 return;
19660 * Get the function name. There are these situations:
19661 * func normal function name
19662 * "name" == func, "fudi.fd_dict" == NULL
19663 * dict.func new dictionary entry
19664 * "name" == NULL, "fudi.fd_dict" set,
19665 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19666 * dict.func existing dict entry with a Funcref
19667 * "name" == func, "fudi.fd_dict" set,
19668 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19669 * dict.func existing dict entry that's not a Funcref
19670 * "name" == NULL, "fudi.fd_dict" set,
19671 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19673 p = eap->arg;
19674 name = trans_function_name(&p, eap->skip, 0, &fudi);
19675 paren = (vim_strchr(p, '(') != NULL);
19676 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19679 * Return on an invalid expression in braces, unless the expression
19680 * evaluation has been cancelled due to an aborting error, an
19681 * interrupt, or an exception.
19683 if (!aborting())
19685 if (!eap->skip && fudi.fd_newkey != NULL)
19686 EMSG2(_(e_dictkey), fudi.fd_newkey);
19687 vim_free(fudi.fd_newkey);
19688 return;
19690 else
19691 eap->skip = TRUE;
19694 /* An error in a function call during evaluation of an expression in magic
19695 * braces should not cause the function not to be defined. */
19696 saved_did_emsg = did_emsg;
19697 did_emsg = FALSE;
19700 * ":function func" with only function name: list function.
19702 if (!paren)
19704 if (!ends_excmd(*skipwhite(p)))
19706 EMSG(_(e_trailing));
19707 goto ret_free;
19709 eap->nextcmd = check_nextcmd(p);
19710 if (eap->nextcmd != NULL)
19711 *p = NUL;
19712 if (!eap->skip && !got_int)
19714 fp = find_func(name);
19715 if (fp != NULL)
19717 list_func_head(fp, TRUE);
19718 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
19720 if (FUNCLINE(fp, j) == NULL)
19721 continue;
19722 msg_putchar('\n');
19723 msg_outnum((long)(j + 1));
19724 if (j < 9)
19725 msg_putchar(' ');
19726 if (j < 99)
19727 msg_putchar(' ');
19728 msg_prt_line(FUNCLINE(fp, j), FALSE);
19729 out_flush(); /* show a line at a time */
19730 ui_breakcheck();
19732 if (!got_int)
19734 msg_putchar('\n');
19735 msg_puts((char_u *)" endfunction");
19738 else
19739 emsg_funcname("E123: Undefined function: %s", name);
19741 goto ret_free;
19745 * ":function name(arg1, arg2)" Define function.
19747 p = skipwhite(p);
19748 if (*p != '(')
19750 if (!eap->skip)
19752 EMSG2(_("E124: Missing '(': %s"), eap->arg);
19753 goto ret_free;
19755 /* attempt to continue by skipping some text */
19756 if (vim_strchr(p, '(') != NULL)
19757 p = vim_strchr(p, '(');
19759 p = skipwhite(p + 1);
19761 ga_init2(&newargs, (int)sizeof(char_u *), 3);
19762 ga_init2(&newlines, (int)sizeof(char_u *), 3);
19764 if (!eap->skip)
19766 /* Check the name of the function. Unless it's a dictionary function
19767 * (that we are overwriting). */
19768 if (name != NULL)
19769 arg = name;
19770 else
19771 arg = fudi.fd_newkey;
19772 if (arg != NULL && (fudi.fd_di == NULL
19773 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
19775 if (*arg == K_SPECIAL)
19776 j = 3;
19777 else
19778 j = 0;
19779 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
19780 : eval_isnamec(arg[j])))
19781 ++j;
19782 if (arg[j] != NUL)
19783 emsg_funcname(_(e_invarg2), arg);
19788 * Isolate the arguments: "arg1, arg2, ...)"
19790 while (*p != ')')
19792 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
19794 varargs = TRUE;
19795 p += 3;
19796 mustend = TRUE;
19798 else
19800 arg = p;
19801 while (ASCII_ISALNUM(*p) || *p == '_')
19802 ++p;
19803 if (arg == p || isdigit(*arg)
19804 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
19805 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
19807 if (!eap->skip)
19808 EMSG2(_("E125: Illegal argument: %s"), arg);
19809 break;
19811 if (ga_grow(&newargs, 1) == FAIL)
19812 goto erret;
19813 c = *p;
19814 *p = NUL;
19815 arg = vim_strsave(arg);
19816 if (arg == NULL)
19817 goto erret;
19818 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
19819 *p = c;
19820 newargs.ga_len++;
19821 if (*p == ',')
19822 ++p;
19823 else
19824 mustend = TRUE;
19826 p = skipwhite(p);
19827 if (mustend && *p != ')')
19829 if (!eap->skip)
19830 EMSG2(_(e_invarg2), eap->arg);
19831 break;
19834 ++p; /* skip the ')' */
19836 /* find extra arguments "range", "dict" and "abort" */
19837 for (;;)
19839 p = skipwhite(p);
19840 if (STRNCMP(p, "range", 5) == 0)
19842 flags |= FC_RANGE;
19843 p += 5;
19845 else if (STRNCMP(p, "dict", 4) == 0)
19847 flags |= FC_DICT;
19848 p += 4;
19850 else if (STRNCMP(p, "abort", 5) == 0)
19852 flags |= FC_ABORT;
19853 p += 5;
19855 else
19856 break;
19859 /* When there is a line break use what follows for the function body.
19860 * Makes 'exe "func Test()\n...\nendfunc"' work. */
19861 if (*p == '\n')
19862 line_arg = p + 1;
19863 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
19864 EMSG(_(e_trailing));
19867 * Read the body of the function, until ":endfunction" is found.
19869 if (KeyTyped)
19871 /* Check if the function already exists, don't let the user type the
19872 * whole function before telling him it doesn't work! For a script we
19873 * need to skip the body to be able to find what follows. */
19874 if (!eap->skip && !eap->forceit)
19876 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
19877 EMSG(_(e_funcdict));
19878 else if (name != NULL && find_func(name) != NULL)
19879 emsg_funcname(e_funcexts, name);
19882 if (!eap->skip && did_emsg)
19883 goto erret;
19885 msg_putchar('\n'); /* don't overwrite the function name */
19886 cmdline_row = msg_row;
19889 indent = 2;
19890 nesting = 0;
19891 for (;;)
19893 msg_scroll = TRUE;
19894 need_wait_return = FALSE;
19895 sourcing_lnum_off = sourcing_lnum;
19897 if (line_arg != NULL)
19899 /* Use eap->arg, split up in parts by line breaks. */
19900 theline = line_arg;
19901 p = vim_strchr(theline, '\n');
19902 if (p == NULL)
19903 line_arg += STRLEN(line_arg);
19904 else
19906 *p = NUL;
19907 line_arg = p + 1;
19910 else if (eap->getline == NULL)
19911 theline = getcmdline(':', 0L, indent);
19912 else
19913 theline = eap->getline(':', eap->cookie, indent);
19914 if (KeyTyped)
19915 lines_left = Rows - 1;
19916 if (theline == NULL)
19918 EMSG(_("E126: Missing :endfunction"));
19919 goto erret;
19922 /* Detect line continuation: sourcing_lnum increased more than one. */
19923 if (sourcing_lnum > sourcing_lnum_off + 1)
19924 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
19925 else
19926 sourcing_lnum_off = 0;
19928 if (skip_until != NULL)
19930 /* between ":append" and "." and between ":python <<EOF" and "EOF"
19931 * don't check for ":endfunc". */
19932 if (STRCMP(theline, skip_until) == 0)
19934 vim_free(skip_until);
19935 skip_until = NULL;
19938 else
19940 /* skip ':' and blanks*/
19941 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
19944 /* Check for "endfunction". */
19945 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
19947 if (line_arg == NULL)
19948 vim_free(theline);
19949 break;
19952 /* Increase indent inside "if", "while", "for" and "try", decrease
19953 * at "end". */
19954 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
19955 indent -= 2;
19956 else if (STRNCMP(p, "if", 2) == 0
19957 || STRNCMP(p, "wh", 2) == 0
19958 || STRNCMP(p, "for", 3) == 0
19959 || STRNCMP(p, "try", 3) == 0)
19960 indent += 2;
19962 /* Check for defining a function inside this function. */
19963 if (checkforcmd(&p, "function", 2))
19965 if (*p == '!')
19966 p = skipwhite(p + 1);
19967 p += eval_fname_script(p);
19968 if (ASCII_ISALPHA(*p))
19970 vim_free(trans_function_name(&p, TRUE, 0, NULL));
19971 if (*skipwhite(p) == '(')
19973 ++nesting;
19974 indent += 2;
19979 /* Check for ":append" or ":insert". */
19980 p = skip_range(p, NULL);
19981 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
19982 || (p[0] == 'i'
19983 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
19984 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
19985 skip_until = vim_strsave((char_u *)".");
19987 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
19988 arg = skipwhite(skiptowhite(p));
19989 if (arg[0] == '<' && arg[1] =='<'
19990 && ((p[0] == 'p' && p[1] == 'y'
19991 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
19992 || (p[0] == 'p' && p[1] == 'e'
19993 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
19994 || (p[0] == 't' && p[1] == 'c'
19995 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
19996 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
19997 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
19998 || (p[0] == 'm' && p[1] == 'z'
19999 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20002 /* ":python <<" continues until a dot, like ":append" */
20003 p = skipwhite(arg + 2);
20004 if (*p == NUL)
20005 skip_until = vim_strsave((char_u *)".");
20006 else
20007 skip_until = vim_strsave(p);
20011 /* Add the line to the function. */
20012 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20014 if (line_arg == NULL)
20015 vim_free(theline);
20016 goto erret;
20019 /* Copy the line to newly allocated memory. get_one_sourceline()
20020 * allocates 250 bytes per line, this saves 80% on average. The cost
20021 * is an extra alloc/free. */
20022 p = vim_strsave(theline);
20023 if (p != NULL)
20025 if (line_arg == NULL)
20026 vim_free(theline);
20027 theline = p;
20030 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20032 /* Add NULL lines for continuation lines, so that the line count is
20033 * equal to the index in the growarray. */
20034 while (sourcing_lnum_off-- > 0)
20035 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20037 /* Check for end of eap->arg. */
20038 if (line_arg != NULL && *line_arg == NUL)
20039 line_arg = NULL;
20042 /* Don't define the function when skipping commands or when an error was
20043 * detected. */
20044 if (eap->skip || did_emsg)
20045 goto erret;
20048 * If there are no errors, add the function
20050 if (fudi.fd_dict == NULL)
20052 v = find_var(name, &ht);
20053 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20055 emsg_funcname("E707: Function name conflicts with variable: %s",
20056 name);
20057 goto erret;
20060 fp = find_func(name);
20061 if (fp != NULL)
20063 if (!eap->forceit)
20065 emsg_funcname(e_funcexts, name);
20066 goto erret;
20068 if (fp->uf_calls > 0)
20070 emsg_funcname("E127: Cannot redefine function %s: It is in use",
20071 name);
20072 goto erret;
20074 /* redefine existing function */
20075 ga_clear_strings(&(fp->uf_args));
20076 ga_clear_strings(&(fp->uf_lines));
20077 vim_free(name);
20078 name = NULL;
20081 else
20083 char numbuf[20];
20085 fp = NULL;
20086 if (fudi.fd_newkey == NULL && !eap->forceit)
20088 EMSG(_(e_funcdict));
20089 goto erret;
20091 if (fudi.fd_di == NULL)
20093 /* Can't add a function to a locked dictionary */
20094 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20095 goto erret;
20097 /* Can't change an existing function if it is locked */
20098 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20099 goto erret;
20101 /* Give the function a sequential number. Can only be used with a
20102 * Funcref! */
20103 vim_free(name);
20104 sprintf(numbuf, "%d", ++func_nr);
20105 name = vim_strsave((char_u *)numbuf);
20106 if (name == NULL)
20107 goto erret;
20110 if (fp == NULL)
20112 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20114 int slen, plen;
20115 char_u *scriptname;
20117 /* Check that the autoload name matches the script name. */
20118 j = FAIL;
20119 if (sourcing_name != NULL)
20121 scriptname = autoload_name(name);
20122 if (scriptname != NULL)
20124 p = vim_strchr(scriptname, '/');
20125 plen = (int)STRLEN(p);
20126 slen = (int)STRLEN(sourcing_name);
20127 if (slen > plen && fnamecmp(p,
20128 sourcing_name + slen - plen) == 0)
20129 j = OK;
20130 vim_free(scriptname);
20133 if (j == FAIL)
20135 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20136 goto erret;
20140 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20141 if (fp == NULL)
20142 goto erret;
20144 if (fudi.fd_dict != NULL)
20146 if (fudi.fd_di == NULL)
20148 /* add new dict entry */
20149 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20150 if (fudi.fd_di == NULL)
20152 vim_free(fp);
20153 goto erret;
20155 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20157 vim_free(fudi.fd_di);
20158 vim_free(fp);
20159 goto erret;
20162 else
20163 /* overwrite existing dict entry */
20164 clear_tv(&fudi.fd_di->di_tv);
20165 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20166 fudi.fd_di->di_tv.v_lock = 0;
20167 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20168 fp->uf_refcount = 1;
20170 /* behave like "dict" was used */
20171 flags |= FC_DICT;
20174 /* insert the new function in the function list */
20175 STRCPY(fp->uf_name, name);
20176 hash_add(&func_hashtab, UF2HIKEY(fp));
20178 fp->uf_args = newargs;
20179 fp->uf_lines = newlines;
20180 #ifdef FEAT_PROFILE
20181 fp->uf_tml_count = NULL;
20182 fp->uf_tml_total = NULL;
20183 fp->uf_tml_self = NULL;
20184 fp->uf_profiling = FALSE;
20185 if (prof_def_func())
20186 func_do_profile(fp);
20187 #endif
20188 fp->uf_varargs = varargs;
20189 fp->uf_flags = flags;
20190 fp->uf_calls = 0;
20191 fp->uf_script_ID = current_SID;
20192 goto ret_free;
20194 erret:
20195 ga_clear_strings(&newargs);
20196 ga_clear_strings(&newlines);
20197 ret_free:
20198 vim_free(skip_until);
20199 vim_free(fudi.fd_newkey);
20200 vim_free(name);
20201 did_emsg |= saved_did_emsg;
20205 * Get a function name, translating "<SID>" and "<SNR>".
20206 * Also handles a Funcref in a List or Dictionary.
20207 * Returns the function name in allocated memory, or NULL for failure.
20208 * flags:
20209 * TFN_INT: internal function name OK
20210 * TFN_QUIET: be quiet
20211 * Advances "pp" to just after the function name (if no error).
20213 static char_u *
20214 trans_function_name(pp, skip, flags, fdp)
20215 char_u **pp;
20216 int skip; /* only find the end, don't evaluate */
20217 int flags;
20218 funcdict_T *fdp; /* return: info about dictionary used */
20220 char_u *name = NULL;
20221 char_u *start;
20222 char_u *end;
20223 int lead;
20224 char_u sid_buf[20];
20225 int len;
20226 lval_T lv;
20228 if (fdp != NULL)
20229 vim_memset(fdp, 0, sizeof(funcdict_T));
20230 start = *pp;
20232 /* Check for hard coded <SNR>: already translated function ID (from a user
20233 * command). */
20234 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20235 && (*pp)[2] == (int)KE_SNR)
20237 *pp += 3;
20238 len = get_id_len(pp) + 3;
20239 return vim_strnsave(start, len);
20242 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20243 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20244 lead = eval_fname_script(start);
20245 if (lead > 2)
20246 start += lead;
20248 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20249 lead > 2 ? 0 : FNE_CHECK_START);
20250 if (end == start)
20252 if (!skip)
20253 EMSG(_("E129: Function name required"));
20254 goto theend;
20256 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20259 * Report an invalid expression in braces, unless the expression
20260 * evaluation has been cancelled due to an aborting error, an
20261 * interrupt, or an exception.
20263 if (!aborting())
20265 if (end != NULL)
20266 EMSG2(_(e_invarg2), start);
20268 else
20269 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20270 goto theend;
20273 if (lv.ll_tv != NULL)
20275 if (fdp != NULL)
20277 fdp->fd_dict = lv.ll_dict;
20278 fdp->fd_newkey = lv.ll_newkey;
20279 lv.ll_newkey = NULL;
20280 fdp->fd_di = lv.ll_di;
20282 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20284 name = vim_strsave(lv.ll_tv->vval.v_string);
20285 *pp = end;
20287 else
20289 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20290 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20291 EMSG(_(e_funcref));
20292 else
20293 *pp = end;
20294 name = NULL;
20296 goto theend;
20299 if (lv.ll_name == NULL)
20301 /* Error found, but continue after the function name. */
20302 *pp = end;
20303 goto theend;
20306 /* Check if the name is a Funcref. If so, use the value. */
20307 if (lv.ll_exp_name != NULL)
20309 len = (int)STRLEN(lv.ll_exp_name);
20310 name = deref_func_name(lv.ll_exp_name, &len);
20311 if (name == lv.ll_exp_name)
20312 name = NULL;
20314 else
20316 len = (int)(end - *pp);
20317 name = deref_func_name(*pp, &len);
20318 if (name == *pp)
20319 name = NULL;
20321 if (name != NULL)
20323 name = vim_strsave(name);
20324 *pp = end;
20325 goto theend;
20328 if (lv.ll_exp_name != NULL)
20330 len = (int)STRLEN(lv.ll_exp_name);
20331 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20332 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20334 /* When there was "s:" already or the name expanded to get a
20335 * leading "s:" then remove it. */
20336 lv.ll_name += 2;
20337 len -= 2;
20338 lead = 2;
20341 else
20343 if (lead == 2) /* skip over "s:" */
20344 lv.ll_name += 2;
20345 len = (int)(end - lv.ll_name);
20349 * Copy the function name to allocated memory.
20350 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20351 * Accept <SNR>123_name() outside a script.
20353 if (skip)
20354 lead = 0; /* do nothing */
20355 else if (lead > 0)
20357 lead = 3;
20358 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20359 || eval_fname_sid(*pp))
20361 /* It's "s:" or "<SID>" */
20362 if (current_SID <= 0)
20364 EMSG(_(e_usingsid));
20365 goto theend;
20367 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20368 lead += (int)STRLEN(sid_buf);
20371 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20373 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20374 goto theend;
20376 name = alloc((unsigned)(len + lead + 1));
20377 if (name != NULL)
20379 if (lead > 0)
20381 name[0] = K_SPECIAL;
20382 name[1] = KS_EXTRA;
20383 name[2] = (int)KE_SNR;
20384 if (lead > 3) /* If it's "<SID>" */
20385 STRCPY(name + 3, sid_buf);
20387 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20388 name[len + lead] = NUL;
20390 *pp = end;
20392 theend:
20393 clear_lval(&lv);
20394 return name;
20398 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20399 * Return 2 if "p" starts with "s:".
20400 * Return 0 otherwise.
20402 static int
20403 eval_fname_script(p)
20404 char_u *p;
20406 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20407 || STRNICMP(p + 1, "SNR>", 4) == 0))
20408 return 5;
20409 if (p[0] == 's' && p[1] == ':')
20410 return 2;
20411 return 0;
20415 * Return TRUE if "p" starts with "<SID>" or "s:".
20416 * Only works if eval_fname_script() returned non-zero for "p"!
20418 static int
20419 eval_fname_sid(p)
20420 char_u *p;
20422 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20426 * List the head of the function: "name(arg1, arg2)".
20428 static void
20429 list_func_head(fp, indent)
20430 ufunc_T *fp;
20431 int indent;
20433 int j;
20435 msg_start();
20436 if (indent)
20437 MSG_PUTS(" ");
20438 MSG_PUTS("function ");
20439 if (fp->uf_name[0] == K_SPECIAL)
20441 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20442 msg_puts(fp->uf_name + 3);
20444 else
20445 msg_puts(fp->uf_name);
20446 msg_putchar('(');
20447 for (j = 0; j < fp->uf_args.ga_len; ++j)
20449 if (j)
20450 MSG_PUTS(", ");
20451 msg_puts(FUNCARG(fp, j));
20453 if (fp->uf_varargs)
20455 if (j)
20456 MSG_PUTS(", ");
20457 MSG_PUTS("...");
20459 msg_putchar(')');
20460 msg_clr_eos();
20461 if (p_verbose > 0)
20462 last_set_msg(fp->uf_script_ID);
20466 * Find a function by name, return pointer to it in ufuncs.
20467 * Return NULL for unknown function.
20469 static ufunc_T *
20470 find_func(name)
20471 char_u *name;
20473 hashitem_T *hi;
20475 hi = hash_find(&func_hashtab, name);
20476 if (!HASHITEM_EMPTY(hi))
20477 return HI2UF(hi);
20478 return NULL;
20481 #if defined(EXITFREE) || defined(PROTO)
20482 void
20483 free_all_functions()
20485 hashitem_T *hi;
20487 /* Need to start all over every time, because func_free() may change the
20488 * hash table. */
20489 while (func_hashtab.ht_used > 0)
20490 for (hi = func_hashtab.ht_array; ; ++hi)
20491 if (!HASHITEM_EMPTY(hi))
20493 func_free(HI2UF(hi));
20494 break;
20497 #endif
20500 * Return TRUE if a function "name" exists.
20502 static int
20503 function_exists(name)
20504 char_u *name;
20506 char_u *nm = name;
20507 char_u *p;
20508 int n = FALSE;
20510 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20511 nm = skipwhite(nm);
20513 /* Only accept "funcname", "funcname ", "funcname (..." and
20514 * "funcname(...", not "funcname!...". */
20515 if (p != NULL && (*nm == NUL || *nm == '('))
20517 if (builtin_function(p))
20518 n = (find_internal_func(p) >= 0);
20519 else
20520 n = (find_func(p) != NULL);
20522 vim_free(p);
20523 return n;
20527 * Return TRUE if "name" looks like a builtin function name: starts with a
20528 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20530 static int
20531 builtin_function(name)
20532 char_u *name;
20534 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20535 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20538 #if defined(FEAT_PROFILE) || defined(PROTO)
20540 * Start profiling function "fp".
20542 static void
20543 func_do_profile(fp)
20544 ufunc_T *fp;
20546 fp->uf_tm_count = 0;
20547 profile_zero(&fp->uf_tm_self);
20548 profile_zero(&fp->uf_tm_total);
20549 if (fp->uf_tml_count == NULL)
20550 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20551 (sizeof(int) * fp->uf_lines.ga_len));
20552 if (fp->uf_tml_total == NULL)
20553 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20554 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20555 if (fp->uf_tml_self == NULL)
20556 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20557 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20558 fp->uf_tml_idx = -1;
20559 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20560 || fp->uf_tml_self == NULL)
20561 return; /* out of memory */
20563 fp->uf_profiling = TRUE;
20567 * Dump the profiling results for all functions in file "fd".
20569 void
20570 func_dump_profile(fd)
20571 FILE *fd;
20573 hashitem_T *hi;
20574 int todo;
20575 ufunc_T *fp;
20576 int i;
20577 ufunc_T **sorttab;
20578 int st_len = 0;
20580 todo = (int)func_hashtab.ht_used;
20581 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20583 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20585 if (!HASHITEM_EMPTY(hi))
20587 --todo;
20588 fp = HI2UF(hi);
20589 if (fp->uf_profiling)
20591 if (sorttab != NULL)
20592 sorttab[st_len++] = fp;
20594 if (fp->uf_name[0] == K_SPECIAL)
20595 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20596 else
20597 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20598 if (fp->uf_tm_count == 1)
20599 fprintf(fd, "Called 1 time\n");
20600 else
20601 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20602 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20603 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20604 fprintf(fd, "\n");
20605 fprintf(fd, "count total (s) self (s)\n");
20607 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20609 if (FUNCLINE(fp, i) == NULL)
20610 continue;
20611 prof_func_line(fd, fp->uf_tml_count[i],
20612 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20613 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20615 fprintf(fd, "\n");
20620 if (sorttab != NULL && st_len > 0)
20622 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20623 prof_total_cmp);
20624 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20625 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20626 prof_self_cmp);
20627 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20631 static void
20632 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20633 FILE *fd;
20634 ufunc_T **sorttab;
20635 int st_len;
20636 char *title;
20637 int prefer_self; /* when equal print only self time */
20639 int i;
20640 ufunc_T *fp;
20642 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20643 fprintf(fd, "count total (s) self (s) function\n");
20644 for (i = 0; i < 20 && i < st_len; ++i)
20646 fp = sorttab[i];
20647 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20648 prefer_self);
20649 if (fp->uf_name[0] == K_SPECIAL)
20650 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20651 else
20652 fprintf(fd, " %s()\n", fp->uf_name);
20654 fprintf(fd, "\n");
20658 * Print the count and times for one function or function line.
20660 static void
20661 prof_func_line(fd, count, total, self, prefer_self)
20662 FILE *fd;
20663 int count;
20664 proftime_T *total;
20665 proftime_T *self;
20666 int prefer_self; /* when equal print only self time */
20668 if (count > 0)
20670 fprintf(fd, "%5d ", count);
20671 if (prefer_self && profile_equal(total, self))
20672 fprintf(fd, " ");
20673 else
20674 fprintf(fd, "%s ", profile_msg(total));
20675 if (!prefer_self && profile_equal(total, self))
20676 fprintf(fd, " ");
20677 else
20678 fprintf(fd, "%s ", profile_msg(self));
20680 else
20681 fprintf(fd, " ");
20685 * Compare function for total time sorting.
20687 static int
20688 #ifdef __BORLANDC__
20689 _RTLENTRYF
20690 #endif
20691 prof_total_cmp(s1, s2)
20692 const void *s1;
20693 const void *s2;
20695 ufunc_T *p1, *p2;
20697 p1 = *(ufunc_T **)s1;
20698 p2 = *(ufunc_T **)s2;
20699 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
20703 * Compare function for self time sorting.
20705 static int
20706 #ifdef __BORLANDC__
20707 _RTLENTRYF
20708 #endif
20709 prof_self_cmp(s1, s2)
20710 const void *s1;
20711 const void *s2;
20713 ufunc_T *p1, *p2;
20715 p1 = *(ufunc_T **)s1;
20716 p2 = *(ufunc_T **)s2;
20717 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
20720 #endif
20723 * If "name" has a package name try autoloading the script for it.
20724 * Return TRUE if a package was loaded.
20726 static int
20727 script_autoload(name, reload)
20728 char_u *name;
20729 int reload; /* load script again when already loaded */
20731 char_u *p;
20732 char_u *scriptname, *tofree;
20733 int ret = FALSE;
20734 int i;
20736 /* If there is no '#' after name[0] there is no package name. */
20737 p = vim_strchr(name, AUTOLOAD_CHAR);
20738 if (p == NULL || p == name)
20739 return FALSE;
20741 tofree = scriptname = autoload_name(name);
20743 /* Find the name in the list of previously loaded package names. Skip
20744 * "autoload/", it's always the same. */
20745 for (i = 0; i < ga_loaded.ga_len; ++i)
20746 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
20747 break;
20748 if (!reload && i < ga_loaded.ga_len)
20749 ret = FALSE; /* was loaded already */
20750 else
20752 /* Remember the name if it wasn't loaded already. */
20753 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
20755 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
20756 tofree = NULL;
20759 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
20760 if (source_runtime(scriptname, FALSE) == OK)
20761 ret = TRUE;
20764 vim_free(tofree);
20765 return ret;
20769 * Return the autoload script name for a function or variable name.
20770 * Returns NULL when out of memory.
20772 static char_u *
20773 autoload_name(name)
20774 char_u *name;
20776 char_u *p;
20777 char_u *scriptname;
20779 /* Get the script file name: replace '#' with '/', append ".vim". */
20780 scriptname = alloc((unsigned)(STRLEN(name) + 14));
20781 if (scriptname == NULL)
20782 return FALSE;
20783 STRCPY(scriptname, "autoload/");
20784 STRCAT(scriptname, name);
20785 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
20786 STRCAT(scriptname, ".vim");
20787 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
20788 *p = '/';
20789 return scriptname;
20792 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
20795 * Function given to ExpandGeneric() to obtain the list of user defined
20796 * function names.
20798 char_u *
20799 get_user_func_name(xp, idx)
20800 expand_T *xp;
20801 int idx;
20803 static long_u done;
20804 static hashitem_T *hi;
20805 ufunc_T *fp;
20807 if (idx == 0)
20809 done = 0;
20810 hi = func_hashtab.ht_array;
20812 if (done < func_hashtab.ht_used)
20814 if (done++ > 0)
20815 ++hi;
20816 while (HASHITEM_EMPTY(hi))
20817 ++hi;
20818 fp = HI2UF(hi);
20820 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
20821 return fp->uf_name; /* prevents overflow */
20823 cat_func_name(IObuff, fp);
20824 if (xp->xp_context != EXPAND_USER_FUNC)
20826 STRCAT(IObuff, "(");
20827 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
20828 STRCAT(IObuff, ")");
20830 return IObuff;
20832 return NULL;
20835 #endif /* FEAT_CMDL_COMPL */
20838 * Copy the function name of "fp" to buffer "buf".
20839 * "buf" must be able to hold the function name plus three bytes.
20840 * Takes care of script-local function names.
20842 static void
20843 cat_func_name(buf, fp)
20844 char_u *buf;
20845 ufunc_T *fp;
20847 if (fp->uf_name[0] == K_SPECIAL)
20849 STRCPY(buf, "<SNR>");
20850 STRCAT(buf, fp->uf_name + 3);
20852 else
20853 STRCPY(buf, fp->uf_name);
20857 * ":delfunction {name}"
20859 void
20860 ex_delfunction(eap)
20861 exarg_T *eap;
20863 ufunc_T *fp = NULL;
20864 char_u *p;
20865 char_u *name;
20866 funcdict_T fudi;
20868 p = eap->arg;
20869 name = trans_function_name(&p, eap->skip, 0, &fudi);
20870 vim_free(fudi.fd_newkey);
20871 if (name == NULL)
20873 if (fudi.fd_dict != NULL && !eap->skip)
20874 EMSG(_(e_funcref));
20875 return;
20877 if (!ends_excmd(*skipwhite(p)))
20879 vim_free(name);
20880 EMSG(_(e_trailing));
20881 return;
20883 eap->nextcmd = check_nextcmd(p);
20884 if (eap->nextcmd != NULL)
20885 *p = NUL;
20887 if (!eap->skip)
20888 fp = find_func(name);
20889 vim_free(name);
20891 if (!eap->skip)
20893 if (fp == NULL)
20895 EMSG2(_(e_nofunc), eap->arg);
20896 return;
20898 if (fp->uf_calls > 0)
20900 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
20901 return;
20904 if (fudi.fd_dict != NULL)
20906 /* Delete the dict item that refers to the function, it will
20907 * invoke func_unref() and possibly delete the function. */
20908 dictitem_remove(fudi.fd_dict, fudi.fd_di);
20910 else
20911 func_free(fp);
20916 * Free a function and remove it from the list of functions.
20918 static void
20919 func_free(fp)
20920 ufunc_T *fp;
20922 hashitem_T *hi;
20924 /* clear this function */
20925 ga_clear_strings(&(fp->uf_args));
20926 ga_clear_strings(&(fp->uf_lines));
20927 #ifdef FEAT_PROFILE
20928 vim_free(fp->uf_tml_count);
20929 vim_free(fp->uf_tml_total);
20930 vim_free(fp->uf_tml_self);
20931 #endif
20933 /* remove the function from the function hashtable */
20934 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
20935 if (HASHITEM_EMPTY(hi))
20936 EMSG2(_(e_intern2), "func_free()");
20937 else
20938 hash_remove(&func_hashtab, hi);
20940 vim_free(fp);
20944 * Unreference a Function: decrement the reference count and free it when it
20945 * becomes zero. Only for numbered functions.
20947 static void
20948 func_unref(name)
20949 char_u *name;
20951 ufunc_T *fp;
20953 if (name != NULL && isdigit(*name))
20955 fp = find_func(name);
20956 if (fp == NULL)
20957 EMSG2(_(e_intern2), "func_unref()");
20958 else if (--fp->uf_refcount <= 0)
20960 /* Only delete it when it's not being used. Otherwise it's done
20961 * when "uf_calls" becomes zero. */
20962 if (fp->uf_calls == 0)
20963 func_free(fp);
20969 * Count a reference to a Function.
20971 static void
20972 func_ref(name)
20973 char_u *name;
20975 ufunc_T *fp;
20977 if (name != NULL && isdigit(*name))
20979 fp = find_func(name);
20980 if (fp == NULL)
20981 EMSG2(_(e_intern2), "func_ref()");
20982 else
20983 ++fp->uf_refcount;
20988 * Call a user function.
20990 static void
20991 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
20992 ufunc_T *fp; /* pointer to function */
20993 int argcount; /* nr of args */
20994 typval_T *argvars; /* arguments */
20995 typval_T *rettv; /* return value */
20996 linenr_T firstline; /* first line of range */
20997 linenr_T lastline; /* last line of range */
20998 dict_T *selfdict; /* Dictionary for "self" */
21000 char_u *save_sourcing_name;
21001 linenr_T save_sourcing_lnum;
21002 scid_T save_current_SID;
21003 funccall_T fc;
21004 int save_did_emsg;
21005 static int depth = 0;
21006 dictitem_T *v;
21007 int fixvar_idx = 0; /* index in fixvar[] */
21008 int i;
21009 int ai;
21010 char_u numbuf[NUMBUFLEN];
21011 char_u *name;
21012 #ifdef FEAT_PROFILE
21013 proftime_T wait_start;
21014 proftime_T call_start;
21015 #endif
21017 /* If depth of calling is getting too high, don't execute the function */
21018 if (depth >= p_mfd)
21020 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21021 rettv->v_type = VAR_NUMBER;
21022 rettv->vval.v_number = -1;
21023 return;
21025 ++depth;
21027 line_breakcheck(); /* check for CTRL-C hit */
21029 fc.caller = current_funccal;
21030 current_funccal = &fc;
21031 fc.func = fp;
21032 fc.rettv = rettv;
21033 rettv->vval.v_number = 0;
21034 fc.linenr = 0;
21035 fc.returned = FALSE;
21036 fc.level = ex_nesting_level;
21037 /* Check if this function has a breakpoint. */
21038 fc.breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21039 fc.dbg_tick = debug_tick;
21042 * Note about using fc.fixvar[]: This is an array of FIXVAR_CNT variables
21043 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21044 * each argument variable and saves a lot of time.
21047 * Init l: variables.
21049 init_var_dict(&fc.l_vars, &fc.l_vars_var);
21050 if (selfdict != NULL)
21052 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21053 * some compiler that checks the destination size. */
21054 v = &fc.fixvar[fixvar_idx++].var;
21055 name = v->di_key;
21056 STRCPY(name, "self");
21057 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21058 hash_add(&fc.l_vars.dv_hashtab, DI2HIKEY(v));
21059 v->di_tv.v_type = VAR_DICT;
21060 v->di_tv.v_lock = 0;
21061 v->di_tv.vval.v_dict = selfdict;
21062 ++selfdict->dv_refcount;
21066 * Init a: variables.
21067 * Set a:0 to "argcount".
21068 * Set a:000 to a list with room for the "..." arguments.
21070 init_var_dict(&fc.l_avars, &fc.l_avars_var);
21071 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "0",
21072 (varnumber_T)(argcount - fp->uf_args.ga_len));
21073 v = &fc.fixvar[fixvar_idx++].var;
21074 STRCPY(v->di_key, "000");
21075 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21076 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
21077 v->di_tv.v_type = VAR_LIST;
21078 v->di_tv.v_lock = VAR_FIXED;
21079 v->di_tv.vval.v_list = &fc.l_varlist;
21080 vim_memset(&fc.l_varlist, 0, sizeof(list_T));
21081 fc.l_varlist.lv_refcount = 99999;
21082 fc.l_varlist.lv_lock = VAR_FIXED;
21085 * Set a:firstline to "firstline" and a:lastline to "lastline".
21086 * Set a:name to named arguments.
21087 * Set a:N to the "..." arguments.
21089 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "firstline",
21090 (varnumber_T)firstline);
21091 add_nr_var(&fc.l_avars, &fc.fixvar[fixvar_idx++].var, "lastline",
21092 (varnumber_T)lastline);
21093 for (i = 0; i < argcount; ++i)
21095 ai = i - fp->uf_args.ga_len;
21096 if (ai < 0)
21097 /* named argument a:name */
21098 name = FUNCARG(fp, i);
21099 else
21101 /* "..." argument a:1, a:2, etc. */
21102 sprintf((char *)numbuf, "%d", ai + 1);
21103 name = numbuf;
21105 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21107 v = &fc.fixvar[fixvar_idx++].var;
21108 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21110 else
21112 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21113 + STRLEN(name)));
21114 if (v == NULL)
21115 break;
21116 v->di_flags = DI_FLAGS_RO;
21118 STRCPY(v->di_key, name);
21119 hash_add(&fc.l_avars.dv_hashtab, DI2HIKEY(v));
21121 /* Note: the values are copied directly to avoid alloc/free.
21122 * "argvars" must have VAR_FIXED for v_lock. */
21123 v->di_tv = argvars[i];
21124 v->di_tv.v_lock = VAR_FIXED;
21126 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21128 list_append(&fc.l_varlist, &fc.l_listitems[ai]);
21129 fc.l_listitems[ai].li_tv = argvars[i];
21130 fc.l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21134 /* Don't redraw while executing the function. */
21135 ++RedrawingDisabled;
21136 save_sourcing_name = sourcing_name;
21137 save_sourcing_lnum = sourcing_lnum;
21138 sourcing_lnum = 1;
21139 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21140 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21141 if (sourcing_name != NULL)
21143 if (save_sourcing_name != NULL
21144 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21145 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21146 else
21147 STRCPY(sourcing_name, "function ");
21148 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21150 if (p_verbose >= 12)
21152 ++no_wait_return;
21153 verbose_enter_scroll();
21155 smsg((char_u *)_("calling %s"), sourcing_name);
21156 if (p_verbose >= 14)
21158 char_u buf[MSG_BUF_LEN];
21159 char_u numbuf2[NUMBUFLEN];
21160 char_u *tofree;
21161 char_u *s;
21163 msg_puts((char_u *)"(");
21164 for (i = 0; i < argcount; ++i)
21166 if (i > 0)
21167 msg_puts((char_u *)", ");
21168 if (argvars[i].v_type == VAR_NUMBER)
21169 msg_outnum((long)argvars[i].vval.v_number);
21170 else
21172 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21173 if (s != NULL)
21175 trunc_string(s, buf, MSG_BUF_CLEN);
21176 msg_puts(buf);
21177 vim_free(tofree);
21181 msg_puts((char_u *)")");
21183 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21185 verbose_leave_scroll();
21186 --no_wait_return;
21189 #ifdef FEAT_PROFILE
21190 if (do_profiling == PROF_YES)
21192 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21193 func_do_profile(fp);
21194 if (fp->uf_profiling
21195 || (fc.caller != NULL && &fc.caller->func->uf_profiling))
21197 ++fp->uf_tm_count;
21198 profile_start(&call_start);
21199 profile_zero(&fp->uf_tm_children);
21201 script_prof_save(&wait_start);
21203 #endif
21205 save_current_SID = current_SID;
21206 current_SID = fp->uf_script_ID;
21207 save_did_emsg = did_emsg;
21208 did_emsg = FALSE;
21210 /* call do_cmdline() to execute the lines */
21211 do_cmdline(NULL, get_func_line, (void *)&fc,
21212 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21214 --RedrawingDisabled;
21216 /* when the function was aborted because of an error, return -1 */
21217 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21219 clear_tv(rettv);
21220 rettv->v_type = VAR_NUMBER;
21221 rettv->vval.v_number = -1;
21224 #ifdef FEAT_PROFILE
21225 if (do_profiling == PROF_YES && (fp->uf_profiling
21226 || (fc.caller != NULL && &fc.caller->func->uf_profiling)))
21228 profile_end(&call_start);
21229 profile_sub_wait(&wait_start, &call_start);
21230 profile_add(&fp->uf_tm_total, &call_start);
21231 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21232 if (fc.caller != NULL && &fc.caller->func->uf_profiling)
21234 profile_add(&fc.caller->func->uf_tm_children, &call_start);
21235 profile_add(&fc.caller->func->uf_tml_children, &call_start);
21238 #endif
21240 /* when being verbose, mention the return value */
21241 if (p_verbose >= 12)
21243 ++no_wait_return;
21244 verbose_enter_scroll();
21246 if (aborting())
21247 smsg((char_u *)_("%s aborted"), sourcing_name);
21248 else if (fc.rettv->v_type == VAR_NUMBER)
21249 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21250 (long)fc.rettv->vval.v_number);
21251 else
21253 char_u buf[MSG_BUF_LEN];
21254 char_u numbuf2[NUMBUFLEN];
21255 char_u *tofree;
21256 char_u *s;
21258 /* The value may be very long. Skip the middle part, so that we
21259 * have some idea how it starts and ends. smsg() would always
21260 * truncate it at the end. */
21261 s = tv2string(fc.rettv, &tofree, numbuf2, 0);
21262 if (s != NULL)
21264 trunc_string(s, buf, MSG_BUF_CLEN);
21265 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21266 vim_free(tofree);
21269 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21271 verbose_leave_scroll();
21272 --no_wait_return;
21275 vim_free(sourcing_name);
21276 sourcing_name = save_sourcing_name;
21277 sourcing_lnum = save_sourcing_lnum;
21278 current_SID = save_current_SID;
21279 #ifdef FEAT_PROFILE
21280 if (do_profiling == PROF_YES)
21281 script_prof_restore(&wait_start);
21282 #endif
21284 if (p_verbose >= 12 && sourcing_name != NULL)
21286 ++no_wait_return;
21287 verbose_enter_scroll();
21289 smsg((char_u *)_("continuing in %s"), sourcing_name);
21290 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21292 verbose_leave_scroll();
21293 --no_wait_return;
21296 did_emsg |= save_did_emsg;
21297 current_funccal = fc.caller;
21299 /* The a: variables typevals were not allocated, only free the allocated
21300 * variables. */
21301 vars_clear_ext(&fc.l_avars.dv_hashtab, FALSE);
21303 vars_clear(&fc.l_vars.dv_hashtab); /* free all l: variables */
21304 --depth;
21308 * Add a number variable "name" to dict "dp" with value "nr".
21310 static void
21311 add_nr_var(dp, v, name, nr)
21312 dict_T *dp;
21313 dictitem_T *v;
21314 char *name;
21315 varnumber_T nr;
21317 STRCPY(v->di_key, name);
21318 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21319 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21320 v->di_tv.v_type = VAR_NUMBER;
21321 v->di_tv.v_lock = VAR_FIXED;
21322 v->di_tv.vval.v_number = nr;
21326 * ":return [expr]"
21328 void
21329 ex_return(eap)
21330 exarg_T *eap;
21332 char_u *arg = eap->arg;
21333 typval_T rettv;
21334 int returning = FALSE;
21336 if (current_funccal == NULL)
21338 EMSG(_("E133: :return not inside a function"));
21339 return;
21342 if (eap->skip)
21343 ++emsg_skip;
21345 eap->nextcmd = NULL;
21346 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21347 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21349 if (!eap->skip)
21350 returning = do_return(eap, FALSE, TRUE, &rettv);
21351 else
21352 clear_tv(&rettv);
21354 /* It's safer to return also on error. */
21355 else if (!eap->skip)
21358 * Return unless the expression evaluation has been cancelled due to an
21359 * aborting error, an interrupt, or an exception.
21361 if (!aborting())
21362 returning = do_return(eap, FALSE, TRUE, NULL);
21365 /* When skipping or the return gets pending, advance to the next command
21366 * in this line (!returning). Otherwise, ignore the rest of the line.
21367 * Following lines will be ignored by get_func_line(). */
21368 if (returning)
21369 eap->nextcmd = NULL;
21370 else if (eap->nextcmd == NULL) /* no argument */
21371 eap->nextcmd = check_nextcmd(arg);
21373 if (eap->skip)
21374 --emsg_skip;
21378 * Return from a function. Possibly makes the return pending. Also called
21379 * for a pending return at the ":endtry" or after returning from an extra
21380 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21381 * when called due to a ":return" command. "rettv" may point to a typval_T
21382 * with the return rettv. Returns TRUE when the return can be carried out,
21383 * FALSE when the return gets pending.
21386 do_return(eap, reanimate, is_cmd, rettv)
21387 exarg_T *eap;
21388 int reanimate;
21389 int is_cmd;
21390 void *rettv;
21392 int idx;
21393 struct condstack *cstack = eap->cstack;
21395 if (reanimate)
21396 /* Undo the return. */
21397 current_funccal->returned = FALSE;
21400 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21401 * not in its finally clause (which then is to be executed next) is found.
21402 * In this case, make the ":return" pending for execution at the ":endtry".
21403 * Otherwise, return normally.
21405 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21406 if (idx >= 0)
21408 cstack->cs_pending[idx] = CSTP_RETURN;
21410 if (!is_cmd && !reanimate)
21411 /* A pending return again gets pending. "rettv" points to an
21412 * allocated variable with the rettv of the original ":return"'s
21413 * argument if present or is NULL else. */
21414 cstack->cs_rettv[idx] = rettv;
21415 else
21417 /* When undoing a return in order to make it pending, get the stored
21418 * return rettv. */
21419 if (reanimate)
21420 rettv = current_funccal->rettv;
21422 if (rettv != NULL)
21424 /* Store the value of the pending return. */
21425 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21426 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21427 else
21428 EMSG(_(e_outofmem));
21430 else
21431 cstack->cs_rettv[idx] = NULL;
21433 if (reanimate)
21435 /* The pending return value could be overwritten by a ":return"
21436 * without argument in a finally clause; reset the default
21437 * return value. */
21438 current_funccal->rettv->v_type = VAR_NUMBER;
21439 current_funccal->rettv->vval.v_number = 0;
21442 report_make_pending(CSTP_RETURN, rettv);
21444 else
21446 current_funccal->returned = TRUE;
21448 /* If the return is carried out now, store the return value. For
21449 * a return immediately after reanimation, the value is already
21450 * there. */
21451 if (!reanimate && rettv != NULL)
21453 clear_tv(current_funccal->rettv);
21454 *current_funccal->rettv = *(typval_T *)rettv;
21455 if (!is_cmd)
21456 vim_free(rettv);
21460 return idx < 0;
21464 * Free the variable with a pending return value.
21466 void
21467 discard_pending_return(rettv)
21468 void *rettv;
21470 free_tv((typval_T *)rettv);
21474 * Generate a return command for producing the value of "rettv". The result
21475 * is an allocated string. Used by report_pending() for verbose messages.
21477 char_u *
21478 get_return_cmd(rettv)
21479 void *rettv;
21481 char_u *s = NULL;
21482 char_u *tofree = NULL;
21483 char_u numbuf[NUMBUFLEN];
21485 if (rettv != NULL)
21486 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21487 if (s == NULL)
21488 s = (char_u *)"";
21490 STRCPY(IObuff, ":return ");
21491 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21492 if (STRLEN(s) + 8 >= IOSIZE)
21493 STRCPY(IObuff + IOSIZE - 4, "...");
21494 vim_free(tofree);
21495 return vim_strsave(IObuff);
21499 * Get next function line.
21500 * Called by do_cmdline() to get the next line.
21501 * Returns allocated string, or NULL for end of function.
21503 /* ARGSUSED */
21504 char_u *
21505 get_func_line(c, cookie, indent)
21506 int c; /* not used */
21507 void *cookie;
21508 int indent; /* not used */
21510 funccall_T *fcp = (funccall_T *)cookie;
21511 ufunc_T *fp = fcp->func;
21512 char_u *retval;
21513 garray_T *gap; /* growarray with function lines */
21515 /* If breakpoints have been added/deleted need to check for it. */
21516 if (fcp->dbg_tick != debug_tick)
21518 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21519 sourcing_lnum);
21520 fcp->dbg_tick = debug_tick;
21522 #ifdef FEAT_PROFILE
21523 if (do_profiling == PROF_YES)
21524 func_line_end(cookie);
21525 #endif
21527 gap = &fp->uf_lines;
21528 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21529 || fcp->returned)
21530 retval = NULL;
21531 else
21533 /* Skip NULL lines (continuation lines). */
21534 while (fcp->linenr < gap->ga_len
21535 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21536 ++fcp->linenr;
21537 if (fcp->linenr >= gap->ga_len)
21538 retval = NULL;
21539 else
21541 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21542 sourcing_lnum = fcp->linenr;
21543 #ifdef FEAT_PROFILE
21544 if (do_profiling == PROF_YES)
21545 func_line_start(cookie);
21546 #endif
21550 /* Did we encounter a breakpoint? */
21551 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21553 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21554 /* Find next breakpoint. */
21555 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21556 sourcing_lnum);
21557 fcp->dbg_tick = debug_tick;
21560 return retval;
21563 #if defined(FEAT_PROFILE) || defined(PROTO)
21565 * Called when starting to read a function line.
21566 * "sourcing_lnum" must be correct!
21567 * When skipping lines it may not actually be executed, but we won't find out
21568 * until later and we need to store the time now.
21570 void
21571 func_line_start(cookie)
21572 void *cookie;
21574 funccall_T *fcp = (funccall_T *)cookie;
21575 ufunc_T *fp = fcp->func;
21577 if (fp->uf_profiling && sourcing_lnum >= 1
21578 && sourcing_lnum <= fp->uf_lines.ga_len)
21580 fp->uf_tml_idx = sourcing_lnum - 1;
21581 /* Skip continuation lines. */
21582 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21583 --fp->uf_tml_idx;
21584 fp->uf_tml_execed = FALSE;
21585 profile_start(&fp->uf_tml_start);
21586 profile_zero(&fp->uf_tml_children);
21587 profile_get_wait(&fp->uf_tml_wait);
21592 * Called when actually executing a function line.
21594 void
21595 func_line_exec(cookie)
21596 void *cookie;
21598 funccall_T *fcp = (funccall_T *)cookie;
21599 ufunc_T *fp = fcp->func;
21601 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21602 fp->uf_tml_execed = TRUE;
21606 * Called when done with a function line.
21608 void
21609 func_line_end(cookie)
21610 void *cookie;
21612 funccall_T *fcp = (funccall_T *)cookie;
21613 ufunc_T *fp = fcp->func;
21615 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21617 if (fp->uf_tml_execed)
21619 ++fp->uf_tml_count[fp->uf_tml_idx];
21620 profile_end(&fp->uf_tml_start);
21621 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
21622 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
21623 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
21624 &fp->uf_tml_children);
21626 fp->uf_tml_idx = -1;
21629 #endif
21632 * Return TRUE if the currently active function should be ended, because a
21633 * return was encountered or an error occurred. Used inside a ":while".
21636 func_has_ended(cookie)
21637 void *cookie;
21639 funccall_T *fcp = (funccall_T *)cookie;
21641 /* Ignore the "abort" flag if the abortion behavior has been changed due to
21642 * an error inside a try conditional. */
21643 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21644 || fcp->returned);
21648 * return TRUE if cookie indicates a function which "abort"s on errors.
21651 func_has_abort(cookie)
21652 void *cookie;
21654 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
21657 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
21658 typedef enum
21660 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
21661 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
21662 VAR_FLAVOUR_VIMINFO /* all uppercase */
21663 } var_flavour_T;
21665 static var_flavour_T var_flavour __ARGS((char_u *varname));
21667 static var_flavour_T
21668 var_flavour(varname)
21669 char_u *varname;
21671 char_u *p = varname;
21673 if (ASCII_ISUPPER(*p))
21675 while (*(++p))
21676 if (ASCII_ISLOWER(*p))
21677 return VAR_FLAVOUR_SESSION;
21678 return VAR_FLAVOUR_VIMINFO;
21680 else
21681 return VAR_FLAVOUR_DEFAULT;
21683 #endif
21685 #if defined(FEAT_VIMINFO) || defined(PROTO)
21687 * Restore global vars that start with a capital from the viminfo file
21690 read_viminfo_varlist(virp, writing)
21691 vir_T *virp;
21692 int writing;
21694 char_u *tab;
21695 int type = VAR_NUMBER;
21696 typval_T tv;
21698 if (!writing && (find_viminfo_parameter('!') != NULL))
21700 tab = vim_strchr(virp->vir_line + 1, '\t');
21701 if (tab != NULL)
21703 *tab++ = '\0'; /* isolate the variable name */
21704 if (*tab == 'S') /* string var */
21705 type = VAR_STRING;
21706 #ifdef FEAT_FLOAT
21707 else if (*tab == 'F')
21708 type = VAR_FLOAT;
21709 #endif
21711 tab = vim_strchr(tab, '\t');
21712 if (tab != NULL)
21714 tv.v_type = type;
21715 if (type == VAR_STRING)
21716 tv.vval.v_string = viminfo_readstring(virp,
21717 (int)(tab - virp->vir_line + 1), TRUE);
21718 #ifdef FEAT_FLOAT
21719 else if (type == VAR_FLOAT)
21720 (void)string2float(tab + 1, &tv.vval.v_float);
21721 #endif
21722 else
21723 tv.vval.v_number = atol((char *)tab + 1);
21724 set_var(virp->vir_line + 1, &tv, FALSE);
21725 if (type == VAR_STRING)
21726 vim_free(tv.vval.v_string);
21731 return viminfo_readline(virp);
21735 * Write global vars that start with a capital to the viminfo file
21737 void
21738 write_viminfo_varlist(fp)
21739 FILE *fp;
21741 hashitem_T *hi;
21742 dictitem_T *this_var;
21743 int todo;
21744 char *s;
21745 char_u *p;
21746 char_u *tofree;
21747 char_u numbuf[NUMBUFLEN];
21749 if (find_viminfo_parameter('!') == NULL)
21750 return;
21752 fprintf(fp, _("\n# global variables:\n"));
21754 todo = (int)globvarht.ht_used;
21755 for (hi = globvarht.ht_array; todo > 0; ++hi)
21757 if (!HASHITEM_EMPTY(hi))
21759 --todo;
21760 this_var = HI2DI(hi);
21761 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
21763 switch (this_var->di_tv.v_type)
21765 case VAR_STRING: s = "STR"; break;
21766 case VAR_NUMBER: s = "NUM"; break;
21767 #ifdef FEAT_FLOAT
21768 case VAR_FLOAT: s = "FLO"; break;
21769 #endif
21770 default: continue;
21772 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
21773 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
21774 if (p != NULL)
21775 viminfo_writestring(fp, p);
21776 vim_free(tofree);
21781 #endif
21783 #if defined(FEAT_SESSION) || defined(PROTO)
21785 store_session_globals(fd)
21786 FILE *fd;
21788 hashitem_T *hi;
21789 dictitem_T *this_var;
21790 int todo;
21791 char_u *p, *t;
21793 todo = (int)globvarht.ht_used;
21794 for (hi = globvarht.ht_array; todo > 0; ++hi)
21796 if (!HASHITEM_EMPTY(hi))
21798 --todo;
21799 this_var = HI2DI(hi);
21800 if ((this_var->di_tv.v_type == VAR_NUMBER
21801 || this_var->di_tv.v_type == VAR_STRING)
21802 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21804 /* Escape special characters with a backslash. Turn a LF and
21805 * CR into \n and \r. */
21806 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
21807 (char_u *)"\\\"\n\r");
21808 if (p == NULL) /* out of memory */
21809 break;
21810 for (t = p; *t != NUL; ++t)
21811 if (*t == '\n')
21812 *t = 'n';
21813 else if (*t == '\r')
21814 *t = 'r';
21815 if ((fprintf(fd, "let %s = %c%s%c",
21816 this_var->di_key,
21817 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21818 : ' ',
21820 (this_var->di_tv.v_type == VAR_STRING) ? '"'
21821 : ' ') < 0)
21822 || put_eol(fd) == FAIL)
21824 vim_free(p);
21825 return FAIL;
21827 vim_free(p);
21829 #ifdef FEAT_FLOAT
21830 else if (this_var->di_tv.v_type == VAR_FLOAT
21831 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
21833 float_T f = this_var->di_tv.vval.v_float;
21834 int sign = ' ';
21836 if (f < 0)
21838 f = -f;
21839 sign = '-';
21841 if ((fprintf(fd, "let %s = %c&%f",
21842 this_var->di_key, sign, f) < 0)
21843 || put_eol(fd) == FAIL)
21844 return FAIL;
21846 #endif
21849 return OK;
21851 #endif
21854 * Display script name where an item was last set.
21855 * Should only be invoked when 'verbose' is non-zero.
21857 void
21858 last_set_msg(scriptID)
21859 scid_T scriptID;
21861 char_u *p;
21863 if (scriptID != 0)
21865 p = home_replace_save(NULL, get_scriptname(scriptID));
21866 if (p != NULL)
21868 verbose_enter();
21869 MSG_PUTS(_("\n\tLast set from "));
21870 MSG_PUTS(p);
21871 vim_free(p);
21872 verbose_leave();
21877 #endif /* FEAT_EVAL */
21880 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
21882 #ifdef WIN3264
21884 * Functions for ":8" filename modifier: get 8.3 version of a filename.
21886 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21887 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
21888 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
21891 * Get the short path (8.3) for the filename in "fnamep".
21892 * Only works for a valid file name.
21893 * When the path gets longer "fnamep" is changed and the allocated buffer
21894 * is put in "bufp".
21895 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
21896 * Returns OK on success, FAIL on failure.
21898 static int
21899 get_short_pathname(fnamep, bufp, fnamelen)
21900 char_u **fnamep;
21901 char_u **bufp;
21902 int *fnamelen;
21904 int l, len;
21905 char_u *newbuf;
21907 len = *fnamelen;
21908 l = GetShortPathName(*fnamep, *fnamep, len);
21909 if (l > len - 1)
21911 /* If that doesn't work (not enough space), then save the string
21912 * and try again with a new buffer big enough. */
21913 newbuf = vim_strnsave(*fnamep, l);
21914 if (newbuf == NULL)
21915 return FAIL;
21917 vim_free(*bufp);
21918 *fnamep = *bufp = newbuf;
21920 /* Really should always succeed, as the buffer is big enough. */
21921 l = GetShortPathName(*fnamep, *fnamep, l+1);
21924 *fnamelen = l;
21925 return OK;
21929 * Get the short path (8.3) for the filename in "fname". The converted
21930 * path is returned in "bufp".
21932 * Some of the directories specified in "fname" may not exist. This function
21933 * will shorten the existing directories at the beginning of the path and then
21934 * append the remaining non-existing path.
21936 * fname - Pointer to the filename to shorten. On return, contains the
21937 * pointer to the shortened pathname
21938 * bufp - Pointer to an allocated buffer for the filename.
21939 * fnamelen - Length of the filename pointed to by fname
21941 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
21943 static int
21944 shortpath_for_invalid_fname(fname, bufp, fnamelen)
21945 char_u **fname;
21946 char_u **bufp;
21947 int *fnamelen;
21949 char_u *short_fname, *save_fname, *pbuf_unused;
21950 char_u *endp, *save_endp;
21951 char_u ch;
21952 int old_len, len;
21953 int new_len, sfx_len;
21954 int retval = OK;
21956 /* Make a copy */
21957 old_len = *fnamelen;
21958 save_fname = vim_strnsave(*fname, old_len);
21959 pbuf_unused = NULL;
21960 short_fname = NULL;
21962 endp = save_fname + old_len - 1; /* Find the end of the copy */
21963 save_endp = endp;
21966 * Try shortening the supplied path till it succeeds by removing one
21967 * directory at a time from the tail of the path.
21969 len = 0;
21970 for (;;)
21972 /* go back one path-separator */
21973 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
21974 --endp;
21975 if (endp <= save_fname)
21976 break; /* processed the complete path */
21979 * Replace the path separator with a NUL and try to shorten the
21980 * resulting path.
21982 ch = *endp;
21983 *endp = 0;
21984 short_fname = save_fname;
21985 len = STRLEN(short_fname) + 1;
21986 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
21988 retval = FAIL;
21989 goto theend;
21991 *endp = ch; /* preserve the string */
21993 if (len > 0)
21994 break; /* successfully shortened the path */
21996 /* failed to shorten the path. Skip the path separator */
21997 --endp;
22000 if (len > 0)
22003 * Succeeded in shortening the path. Now concatenate the shortened
22004 * path with the remaining path at the tail.
22007 /* Compute the length of the new path. */
22008 sfx_len = (int)(save_endp - endp) + 1;
22009 new_len = len + sfx_len;
22011 *fnamelen = new_len;
22012 vim_free(*bufp);
22013 if (new_len > old_len)
22015 /* There is not enough space in the currently allocated string,
22016 * copy it to a buffer big enough. */
22017 *fname = *bufp = vim_strnsave(short_fname, new_len);
22018 if (*fname == NULL)
22020 retval = FAIL;
22021 goto theend;
22024 else
22026 /* Transfer short_fname to the main buffer (it's big enough),
22027 * unless get_short_pathname() did its work in-place. */
22028 *fname = *bufp = save_fname;
22029 if (short_fname != save_fname)
22030 vim_strncpy(save_fname, short_fname, len);
22031 save_fname = NULL;
22034 /* concat the not-shortened part of the path */
22035 vim_strncpy(*fname + len, endp, sfx_len);
22036 (*fname)[new_len] = NUL;
22039 theend:
22040 vim_free(pbuf_unused);
22041 vim_free(save_fname);
22043 return retval;
22047 * Get a pathname for a partial path.
22048 * Returns OK for success, FAIL for failure.
22050 static int
22051 shortpath_for_partial(fnamep, bufp, fnamelen)
22052 char_u **fnamep;
22053 char_u **bufp;
22054 int *fnamelen;
22056 int sepcount, len, tflen;
22057 char_u *p;
22058 char_u *pbuf, *tfname;
22059 int hasTilde;
22061 /* Count up the path separators from the RHS.. so we know which part
22062 * of the path to return. */
22063 sepcount = 0;
22064 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22065 if (vim_ispathsep(*p))
22066 ++sepcount;
22068 /* Need full path first (use expand_env() to remove a "~/") */
22069 hasTilde = (**fnamep == '~');
22070 if (hasTilde)
22071 pbuf = tfname = expand_env_save(*fnamep);
22072 else
22073 pbuf = tfname = FullName_save(*fnamep, FALSE);
22075 len = tflen = (int)STRLEN(tfname);
22077 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22078 return FAIL;
22080 if (len == 0)
22082 /* Don't have a valid filename, so shorten the rest of the
22083 * path if we can. This CAN give us invalid 8.3 filenames, but
22084 * there's not a lot of point in guessing what it might be.
22086 len = tflen;
22087 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22088 return FAIL;
22091 /* Count the paths backward to find the beginning of the desired string. */
22092 for (p = tfname + len - 1; p >= tfname; --p)
22094 #ifdef FEAT_MBYTE
22095 if (has_mbyte)
22096 p -= mb_head_off(tfname, p);
22097 #endif
22098 if (vim_ispathsep(*p))
22100 if (sepcount == 0 || (hasTilde && sepcount == 1))
22101 break;
22102 else
22103 sepcount --;
22106 if (hasTilde)
22108 --p;
22109 if (p >= tfname)
22110 *p = '~';
22111 else
22112 return FAIL;
22114 else
22115 ++p;
22117 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22118 vim_free(*bufp);
22119 *fnamelen = (int)STRLEN(p);
22120 *bufp = pbuf;
22121 *fnamep = p;
22123 return OK;
22125 #endif /* WIN3264 */
22128 * Adjust a filename, according to a string of modifiers.
22129 * *fnamep must be NUL terminated when called. When returning, the length is
22130 * determined by *fnamelen.
22131 * Returns VALID_ flags or -1 for failure.
22132 * When there is an error, *fnamep is set to NULL.
22135 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22136 char_u *src; /* string with modifiers */
22137 int *usedlen; /* characters after src that are used */
22138 char_u **fnamep; /* file name so far */
22139 char_u **bufp; /* buffer for allocated file name or NULL */
22140 int *fnamelen; /* length of fnamep */
22142 int valid = 0;
22143 char_u *tail;
22144 char_u *s, *p, *pbuf;
22145 char_u dirname[MAXPATHL];
22146 int c;
22147 int has_fullname = 0;
22148 #ifdef WIN3264
22149 int has_shortname = 0;
22150 #endif
22152 repeat:
22153 /* ":p" - full path/file_name */
22154 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22156 has_fullname = 1;
22158 valid |= VALID_PATH;
22159 *usedlen += 2;
22161 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22162 if ((*fnamep)[0] == '~'
22163 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22164 && ((*fnamep)[1] == '/'
22165 # ifdef BACKSLASH_IN_FILENAME
22166 || (*fnamep)[1] == '\\'
22167 # endif
22168 || (*fnamep)[1] == NUL)
22170 #endif
22173 *fnamep = expand_env_save(*fnamep);
22174 vim_free(*bufp); /* free any allocated file name */
22175 *bufp = *fnamep;
22176 if (*fnamep == NULL)
22177 return -1;
22180 /* When "/." or "/.." is used: force expansion to get rid of it. */
22181 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22183 if (vim_ispathsep(*p)
22184 && p[1] == '.'
22185 && (p[2] == NUL
22186 || vim_ispathsep(p[2])
22187 || (p[2] == '.'
22188 && (p[3] == NUL || vim_ispathsep(p[3])))))
22189 break;
22192 /* FullName_save() is slow, don't use it when not needed. */
22193 if (*p != NUL || !vim_isAbsName(*fnamep))
22195 *fnamep = FullName_save(*fnamep, *p != NUL);
22196 vim_free(*bufp); /* free any allocated file name */
22197 *bufp = *fnamep;
22198 if (*fnamep == NULL)
22199 return -1;
22202 /* Append a path separator to a directory. */
22203 if (mch_isdir(*fnamep))
22205 /* Make room for one or two extra characters. */
22206 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22207 vim_free(*bufp); /* free any allocated file name */
22208 *bufp = *fnamep;
22209 if (*fnamep == NULL)
22210 return -1;
22211 add_pathsep(*fnamep);
22215 /* ":." - path relative to the current directory */
22216 /* ":~" - path relative to the home directory */
22217 /* ":8" - shortname path - postponed till after */
22218 while (src[*usedlen] == ':'
22219 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22221 *usedlen += 2;
22222 if (c == '8')
22224 #ifdef WIN3264
22225 has_shortname = 1; /* Postpone this. */
22226 #endif
22227 continue;
22229 pbuf = NULL;
22230 /* Need full path first (use expand_env() to remove a "~/") */
22231 if (!has_fullname)
22233 if (c == '.' && **fnamep == '~')
22234 p = pbuf = expand_env_save(*fnamep);
22235 else
22236 p = pbuf = FullName_save(*fnamep, FALSE);
22238 else
22239 p = *fnamep;
22241 has_fullname = 0;
22243 if (p != NULL)
22245 if (c == '.')
22247 mch_dirname(dirname, MAXPATHL);
22248 s = shorten_fname(p, dirname);
22249 if (s != NULL)
22251 *fnamep = s;
22252 if (pbuf != NULL)
22254 vim_free(*bufp); /* free any allocated file name */
22255 *bufp = pbuf;
22256 pbuf = NULL;
22260 else
22262 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22263 /* Only replace it when it starts with '~' */
22264 if (*dirname == '~')
22266 s = vim_strsave(dirname);
22267 if (s != NULL)
22269 *fnamep = s;
22270 vim_free(*bufp);
22271 *bufp = s;
22275 vim_free(pbuf);
22279 tail = gettail(*fnamep);
22280 *fnamelen = (int)STRLEN(*fnamep);
22282 /* ":h" - head, remove "/file_name", can be repeated */
22283 /* Don't remove the first "/" or "c:\" */
22284 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22286 valid |= VALID_HEAD;
22287 *usedlen += 2;
22288 s = get_past_head(*fnamep);
22289 while (tail > s && after_pathsep(s, tail))
22290 mb_ptr_back(*fnamep, tail);
22291 *fnamelen = (int)(tail - *fnamep);
22292 #ifdef VMS
22293 if (*fnamelen > 0)
22294 *fnamelen += 1; /* the path separator is part of the path */
22295 #endif
22296 if (*fnamelen == 0)
22298 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22299 p = vim_strsave((char_u *)".");
22300 if (p == NULL)
22301 return -1;
22302 vim_free(*bufp);
22303 *bufp = *fnamep = tail = p;
22304 *fnamelen = 1;
22306 else
22308 while (tail > s && !after_pathsep(s, tail))
22309 mb_ptr_back(*fnamep, tail);
22313 /* ":8" - shortname */
22314 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22316 *usedlen += 2;
22317 #ifdef WIN3264
22318 has_shortname = 1;
22319 #endif
22322 #ifdef WIN3264
22323 /* Check shortname after we have done 'heads' and before we do 'tails'
22325 if (has_shortname)
22327 pbuf = NULL;
22328 /* Copy the string if it is shortened by :h */
22329 if (*fnamelen < (int)STRLEN(*fnamep))
22331 p = vim_strnsave(*fnamep, *fnamelen);
22332 if (p == 0)
22333 return -1;
22334 vim_free(*bufp);
22335 *bufp = *fnamep = p;
22338 /* Split into two implementations - makes it easier. First is where
22339 * there isn't a full name already, second is where there is.
22341 if (!has_fullname && !vim_isAbsName(*fnamep))
22343 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22344 return -1;
22346 else
22348 int l;
22350 /* Simple case, already have the full-name
22351 * Nearly always shorter, so try first time. */
22352 l = *fnamelen;
22353 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22354 return -1;
22356 if (l == 0)
22358 /* Couldn't find the filename.. search the paths.
22360 l = *fnamelen;
22361 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22362 return -1;
22364 *fnamelen = l;
22367 #endif /* WIN3264 */
22369 /* ":t" - tail, just the basename */
22370 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22372 *usedlen += 2;
22373 *fnamelen -= (int)(tail - *fnamep);
22374 *fnamep = tail;
22377 /* ":e" - extension, can be repeated */
22378 /* ":r" - root, without extension, can be repeated */
22379 while (src[*usedlen] == ':'
22380 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22382 /* find a '.' in the tail:
22383 * - for second :e: before the current fname
22384 * - otherwise: The last '.'
22386 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22387 s = *fnamep - 2;
22388 else
22389 s = *fnamep + *fnamelen - 1;
22390 for ( ; s > tail; --s)
22391 if (s[0] == '.')
22392 break;
22393 if (src[*usedlen + 1] == 'e') /* :e */
22395 if (s > tail)
22397 *fnamelen += (int)(*fnamep - (s + 1));
22398 *fnamep = s + 1;
22399 #ifdef VMS
22400 /* cut version from the extension */
22401 s = *fnamep + *fnamelen - 1;
22402 for ( ; s > *fnamep; --s)
22403 if (s[0] == ';')
22404 break;
22405 if (s > *fnamep)
22406 *fnamelen = s - *fnamep;
22407 #endif
22409 else if (*fnamep <= tail)
22410 *fnamelen = 0;
22412 else /* :r */
22414 if (s > tail) /* remove one extension */
22415 *fnamelen = (int)(s - *fnamep);
22417 *usedlen += 2;
22420 /* ":s?pat?foo?" - substitute */
22421 /* ":gs?pat?foo?" - global substitute */
22422 if (src[*usedlen] == ':'
22423 && (src[*usedlen + 1] == 's'
22424 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22426 char_u *str;
22427 char_u *pat;
22428 char_u *sub;
22429 int sep;
22430 char_u *flags;
22431 int didit = FALSE;
22433 flags = (char_u *)"";
22434 s = src + *usedlen + 2;
22435 if (src[*usedlen + 1] == 'g')
22437 flags = (char_u *)"g";
22438 ++s;
22441 sep = *s++;
22442 if (sep)
22444 /* find end of pattern */
22445 p = vim_strchr(s, sep);
22446 if (p != NULL)
22448 pat = vim_strnsave(s, (int)(p - s));
22449 if (pat != NULL)
22451 s = p + 1;
22452 /* find end of substitution */
22453 p = vim_strchr(s, sep);
22454 if (p != NULL)
22456 sub = vim_strnsave(s, (int)(p - s));
22457 str = vim_strnsave(*fnamep, *fnamelen);
22458 if (sub != NULL && str != NULL)
22460 *usedlen = (int)(p + 1 - src);
22461 s = do_string_sub(str, pat, sub, flags);
22462 if (s != NULL)
22464 *fnamep = s;
22465 *fnamelen = (int)STRLEN(s);
22466 vim_free(*bufp);
22467 *bufp = s;
22468 didit = TRUE;
22471 vim_free(sub);
22472 vim_free(str);
22474 vim_free(pat);
22477 /* after using ":s", repeat all the modifiers */
22478 if (didit)
22479 goto repeat;
22483 return valid;
22487 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22488 * "flags" can be "g" to do a global substitute.
22489 * Returns an allocated string, NULL for error.
22491 char_u *
22492 do_string_sub(str, pat, sub, flags)
22493 char_u *str;
22494 char_u *pat;
22495 char_u *sub;
22496 char_u *flags;
22498 int sublen;
22499 regmatch_T regmatch;
22500 int i;
22501 int do_all;
22502 char_u *tail;
22503 garray_T ga;
22504 char_u *ret;
22505 char_u *save_cpo;
22507 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22508 save_cpo = p_cpo;
22509 p_cpo = (char_u *)"";
22511 ga_init2(&ga, 1, 200);
22513 do_all = (flags[0] == 'g');
22515 regmatch.rm_ic = p_ic;
22516 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22517 if (regmatch.regprog != NULL)
22519 tail = str;
22520 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22523 * Get some space for a temporary buffer to do the substitution
22524 * into. It will contain:
22525 * - The text up to where the match is.
22526 * - The substituted text.
22527 * - The text after the match.
22529 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22530 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22531 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22533 ga_clear(&ga);
22534 break;
22537 /* copy the text up to where the match is */
22538 i = (int)(regmatch.startp[0] - tail);
22539 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22540 /* add the substituted text */
22541 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22542 + ga.ga_len + i, TRUE, TRUE, FALSE);
22543 ga.ga_len += i + sublen - 1;
22544 /* avoid getting stuck on a match with an empty string */
22545 if (tail == regmatch.endp[0])
22547 if (*tail == NUL)
22548 break;
22549 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
22550 ++ga.ga_len;
22552 else
22554 tail = regmatch.endp[0];
22555 if (*tail == NUL)
22556 break;
22558 if (!do_all)
22559 break;
22562 if (ga.ga_data != NULL)
22563 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
22565 vim_free(regmatch.regprog);
22568 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
22569 ga_clear(&ga);
22570 p_cpo = save_cpo;
22572 return ret;
22575 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */