Merge branch 'vim-with-runtime' into feat/float-point-ext
[vim_extended.git] / src / eval.c
blobfa3938dd5833eab7aa3e682c48853abc2609f55a
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * eval.c: Expression evaluation.
13 #if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
14 # include "vimio.h" /* for mch_open(), must be before vim.h */
15 #endif
17 #include "vim.h"
19 #if defined(FEAT_EVAL) || defined(PROTO)
21 #ifdef AMIGA
22 # include <time.h> /* for strftime() */
23 #endif
25 #ifdef MACOS
26 # include <time.h> /* for time_t */
27 #endif
29 #if defined(FEAT_FLOAT) && defined(HAVE_MATH_H)
30 # include <math.h>
31 #endif
33 #define DICT_MAXNEST 100 /* maximum nesting of lists and dicts */
35 #define DO_NOT_FREE_CNT 99999 /* refcount for dict or list that should not
36 be freed. */
39 * In a hashtab item "hi_key" points to "di_key" in a dictitem.
40 * This avoids adding a pointer to the hashtab item.
41 * DI2HIKEY() converts a dictitem pointer to a hashitem key pointer.
42 * HIKEY2DI() converts a hashitem key pointer to a dictitem pointer.
43 * HI2DI() converts a hashitem pointer to a dictitem pointer.
45 static dictitem_T dumdi;
46 #define DI2HIKEY(di) ((di)->di_key)
47 #define HIKEY2DI(p) ((dictitem_T *)(p - (dumdi.di_key - (char_u *)&dumdi)))
48 #define HI2DI(hi) HIKEY2DI((hi)->hi_key)
51 * Structure returned by get_lval() and used by set_var_lval().
52 * For a plain name:
53 * "name" points to the variable name.
54 * "exp_name" is NULL.
55 * "tv" is NULL
56 * For a magic braces name:
57 * "name" points to the expanded variable name.
58 * "exp_name" is non-NULL, to be freed later.
59 * "tv" is NULL
60 * For an index in a list:
61 * "name" points to the (expanded) variable name.
62 * "exp_name" NULL or non-NULL, to be freed later.
63 * "tv" points to the (first) list item value
64 * "li" points to the (first) list item
65 * "range", "n1", "n2" and "empty2" indicate what items are used.
66 * For an existing Dict item:
67 * "name" points to the (expanded) variable name.
68 * "exp_name" NULL or non-NULL, to be freed later.
69 * "tv" points to the dict item value
70 * "newkey" is NULL
71 * For a non-existing Dict item:
72 * "name" points to the (expanded) variable name.
73 * "exp_name" NULL or non-NULL, to be freed later.
74 * "tv" points to the Dictionary typval_T
75 * "newkey" is the key for the new item.
77 typedef struct lval_S
79 char_u *ll_name; /* start of variable name (can be NULL) */
80 char_u *ll_exp_name; /* NULL or expanded name in allocated memory. */
81 typval_T *ll_tv; /* Typeval of item being used. If "newkey"
82 isn't NULL it's the Dict to which to add
83 the item. */
84 listitem_T *ll_li; /* The list item or NULL. */
85 list_T *ll_list; /* The list or NULL. */
86 int ll_range; /* TRUE when a [i:j] range was used */
87 long ll_n1; /* First index for list */
88 long ll_n2; /* Second index for list range */
89 int ll_empty2; /* Second index is empty: [i:] */
90 dict_T *ll_dict; /* The Dictionary or NULL */
91 dictitem_T *ll_di; /* The dictitem or NULL */
92 char_u *ll_newkey; /* New key for Dict in alloc. mem or NULL. */
93 } lval_T;
96 static char *e_letunexp = N_("E18: Unexpected characters in :let");
97 static char *e_listidx = N_("E684: list index out of range: %ld");
98 static char *e_undefvar = N_("E121: Undefined variable: %s");
99 static char *e_missbrac = N_("E111: Missing ']'");
100 static char *e_listarg = N_("E686: Argument of %s must be a List");
101 static char *e_listdictarg = N_("E712: Argument of %s must be a List or Dictionary");
102 static char *e_emptykey = N_("E713: Cannot use empty key for Dictionary");
103 static char *e_listreq = N_("E714: List required");
104 static char *e_dictreq = N_("E715: Dictionary required");
105 static char *e_toomanyarg = N_("E118: Too many arguments for function: %s");
106 static char *e_dictkey = N_("E716: Key not present in Dictionary: %s");
107 static char *e_funcexts = N_("E122: Function %s already exists, add ! to replace it");
108 static char *e_funcdict = N_("E717: Dictionary entry already exists");
109 static char *e_funcref = N_("E718: Funcref required");
110 static char *e_dictrange = N_("E719: Cannot use [:] with a Dictionary");
111 static char *e_letwrong = N_("E734: Wrong variable type for %s=");
112 static char *e_nofunc = N_("E130: Unknown function: %s");
113 static char *e_illvar = N_("E461: Illegal variable name: %s");
116 * All user-defined global variables are stored in dictionary "globvardict".
117 * "globvars_var" is the variable that is used for "g:".
119 static dict_T globvardict;
120 static dictitem_T globvars_var;
121 #define globvarht globvardict.dv_hashtab
124 * Old Vim variables such as "v:version" are also available without the "v:".
125 * Also in functions. We need a special hashtable for them.
127 static hashtab_T compat_hashtab;
130 * When recursively copying lists and dicts we need to remember which ones we
131 * have done to avoid endless recursiveness. This unique ID is used for that.
132 * The last bit is used for previous_funccal, ignored when comparing.
134 static int current_copyID = 0;
135 #define COPYID_INC 2
136 #define COPYID_MASK (~0x1)
139 * Array to hold the hashtab with variables local to each sourced script.
140 * Each item holds a variable (nameless) that points to the dict_T.
142 typedef struct
144 dictitem_T sv_var;
145 dict_T sv_dict;
146 } scriptvar_T;
148 static garray_T ga_scripts = {0, 0, sizeof(scriptvar_T *), 4, NULL};
149 #define SCRIPT_SV(id) (((scriptvar_T **)ga_scripts.ga_data)[(id) - 1])
150 #define SCRIPT_VARS(id) (SCRIPT_SV(id)->sv_dict.dv_hashtab)
152 static int echo_attr = 0; /* attributes used for ":echo" */
154 /* Values for trans_function_name() argument: */
155 #define TFN_INT 1 /* internal function name OK */
156 #define TFN_QUIET 2 /* no error messages */
159 * Structure to hold info for a user function.
161 typedef struct ufunc ufunc_T;
163 struct ufunc
165 int uf_varargs; /* variable nr of arguments */
166 int uf_flags;
167 int uf_calls; /* nr of active calls */
168 garray_T uf_args; /* arguments */
169 garray_T uf_lines; /* function lines */
170 #ifdef FEAT_PROFILE
171 int uf_profiling; /* TRUE when func is being profiled */
172 /* profiling the function as a whole */
173 int uf_tm_count; /* nr of calls */
174 proftime_T uf_tm_total; /* time spent in function + children */
175 proftime_T uf_tm_self; /* time spent in function itself */
176 proftime_T uf_tm_children; /* time spent in children this call */
177 /* profiling the function per line */
178 int *uf_tml_count; /* nr of times line was executed */
179 proftime_T *uf_tml_total; /* time spent in a line + children */
180 proftime_T *uf_tml_self; /* time spent in a line itself */
181 proftime_T uf_tml_start; /* start time for current line */
182 proftime_T uf_tml_children; /* time spent in children for this line */
183 proftime_T uf_tml_wait; /* start wait time for current line */
184 int uf_tml_idx; /* index of line being timed; -1 if none */
185 int uf_tml_execed; /* line being timed was executed */
186 #endif
187 scid_T uf_script_ID; /* ID of script where function was defined,
188 used for s: variables */
189 int uf_refcount; /* for numbered function: reference count */
190 char_u uf_name[1]; /* name of function (actually longer); can
191 start with <SNR>123_ (<SNR> is K_SPECIAL
192 KS_EXTRA KE_SNR) */
195 /* function flags */
196 #define FC_ABORT 1 /* abort function on error */
197 #define FC_RANGE 2 /* function accepts range */
198 #define FC_DICT 4 /* Dict function, uses "self" */
201 * All user-defined functions are found in this hashtable.
203 static hashtab_T func_hashtab;
205 /* The names of packages that once were loaded are remembered. */
206 static garray_T ga_loaded = {0, 0, sizeof(char_u *), 4, NULL};
208 /* list heads for garbage collection */
209 static dict_T *first_dict = NULL; /* list of all dicts */
210 static list_T *first_list = NULL; /* list of all lists */
212 /* From user function to hashitem and back. */
213 static ufunc_T dumuf;
214 #define UF2HIKEY(fp) ((fp)->uf_name)
215 #define HIKEY2UF(p) ((ufunc_T *)(p - (dumuf.uf_name - (char_u *)&dumuf)))
216 #define HI2UF(hi) HIKEY2UF((hi)->hi_key)
218 #define FUNCARG(fp, j) ((char_u **)(fp->uf_args.ga_data))[j]
219 #define FUNCLINE(fp, j) ((char_u **)(fp->uf_lines.ga_data))[j]
221 #define MAX_FUNC_ARGS 20 /* maximum number of function arguments */
222 #define VAR_SHORT_LEN 20 /* short variable name length */
223 #define FIXVAR_CNT 12 /* number of fixed variables */
225 /* structure to hold info for a function that is currently being executed. */
226 typedef struct funccall_S funccall_T;
228 struct funccall_S
230 ufunc_T *func; /* function being called */
231 int linenr; /* next line to be executed */
232 int returned; /* ":return" used */
233 struct /* fixed variables for arguments */
235 dictitem_T var; /* variable (without room for name) */
236 char_u room[VAR_SHORT_LEN]; /* room for the name */
237 } fixvar[FIXVAR_CNT];
238 dict_T l_vars; /* l: local function variables */
239 dictitem_T l_vars_var; /* variable for l: scope */
240 dict_T l_avars; /* a: argument variables */
241 dictitem_T l_avars_var; /* variable for a: scope */
242 list_T l_varlist; /* list for a:000 */
243 listitem_T l_listitems[MAX_FUNC_ARGS]; /* listitems for a:000 */
244 typval_T *rettv; /* return value */
245 linenr_T breakpoint; /* next line with breakpoint or zero */
246 int dbg_tick; /* debug_tick when breakpoint was set */
247 int level; /* top nesting level of executed function */
248 #ifdef FEAT_PROFILE
249 proftime_T prof_child; /* time spent in a child */
250 #endif
251 funccall_T *caller; /* calling function or NULL */
255 * Info used by a ":for" loop.
257 typedef struct
259 int fi_semicolon; /* TRUE if ending in '; var]' */
260 int fi_varcount; /* nr of variables in the list */
261 listwatch_T fi_lw; /* keep an eye on the item used. */
262 list_T *fi_list; /* list being used */
263 } forinfo_T;
266 * Struct used by trans_function_name()
268 typedef struct
270 dict_T *fd_dict; /* Dictionary used */
271 char_u *fd_newkey; /* new key in "dict" in allocated memory */
272 dictitem_T *fd_di; /* Dictionary item used */
273 } funcdict_T;
277 * Array to hold the value of v: variables.
278 * The value is in a dictitem, so that it can also be used in the v: scope.
279 * The reason to use this table anyway is for very quick access to the
280 * variables with the VV_ defines.
282 #include "version.h"
284 /* values for vv_flags: */
285 #define VV_COMPAT 1 /* compatible, also used without "v:" */
286 #define VV_RO 2 /* read-only */
287 #define VV_RO_SBX 4 /* read-only in the sandbox */
289 #define VV_NAME(s, t) s, {{t, 0, {0}}, 0, {0}}, {0}
291 static struct vimvar
293 char *vv_name; /* name of variable, without v: */
294 dictitem_T vv_di; /* value and name for key */
295 char vv_filler[16]; /* space for LONGEST name below!!! */
296 char vv_flags; /* VV_COMPAT, VV_RO, VV_RO_SBX */
297 } vimvars[VV_LEN] =
300 * The order here must match the VV_ defines in vim.h!
301 * Initializing a union does not work, leave tv.vval empty to get zero's.
303 {VV_NAME("count", VAR_NUMBER), VV_COMPAT+VV_RO},
304 {VV_NAME("count1", VAR_NUMBER), VV_RO},
305 {VV_NAME("prevcount", VAR_NUMBER), VV_RO},
306 {VV_NAME("errmsg", VAR_STRING), VV_COMPAT},
307 {VV_NAME("warningmsg", VAR_STRING), 0},
308 {VV_NAME("statusmsg", VAR_STRING), 0},
309 {VV_NAME("shell_error", VAR_NUMBER), VV_COMPAT+VV_RO},
310 {VV_NAME("this_session", VAR_STRING), VV_COMPAT},
311 {VV_NAME("version", VAR_NUMBER), VV_COMPAT+VV_RO},
312 {VV_NAME("lnum", VAR_NUMBER), VV_RO_SBX},
313 {VV_NAME("termresponse", VAR_STRING), VV_RO},
314 {VV_NAME("fname", VAR_STRING), VV_RO},
315 {VV_NAME("lang", VAR_STRING), VV_RO},
316 {VV_NAME("lc_time", VAR_STRING), VV_RO},
317 {VV_NAME("ctype", VAR_STRING), VV_RO},
318 {VV_NAME("charconvert_from", VAR_STRING), VV_RO},
319 {VV_NAME("charconvert_to", VAR_STRING), VV_RO},
320 {VV_NAME("fname_in", VAR_STRING), VV_RO},
321 {VV_NAME("fname_out", VAR_STRING), VV_RO},
322 {VV_NAME("fname_new", VAR_STRING), VV_RO},
323 {VV_NAME("fname_diff", VAR_STRING), VV_RO},
324 {VV_NAME("cmdarg", VAR_STRING), VV_RO},
325 {VV_NAME("foldstart", VAR_NUMBER), VV_RO_SBX},
326 {VV_NAME("foldend", VAR_NUMBER), VV_RO_SBX},
327 {VV_NAME("folddashes", VAR_STRING), VV_RO_SBX},
328 {VV_NAME("foldlevel", VAR_NUMBER), VV_RO_SBX},
329 {VV_NAME("progname", VAR_STRING), VV_RO},
330 {VV_NAME("servername", VAR_STRING), VV_RO},
331 {VV_NAME("dying", VAR_NUMBER), VV_RO},
332 {VV_NAME("exception", VAR_STRING), VV_RO},
333 {VV_NAME("throwpoint", VAR_STRING), VV_RO},
334 {VV_NAME("register", VAR_STRING), VV_RO},
335 {VV_NAME("cmdbang", VAR_NUMBER), VV_RO},
336 {VV_NAME("insertmode", VAR_STRING), VV_RO},
337 {VV_NAME("val", VAR_UNKNOWN), VV_RO},
338 {VV_NAME("key", VAR_UNKNOWN), VV_RO},
339 {VV_NAME("profiling", VAR_NUMBER), VV_RO},
340 {VV_NAME("fcs_reason", VAR_STRING), VV_RO},
341 {VV_NAME("fcs_choice", VAR_STRING), 0},
342 {VV_NAME("beval_bufnr", VAR_NUMBER), VV_RO},
343 {VV_NAME("beval_winnr", VAR_NUMBER), VV_RO},
344 {VV_NAME("beval_lnum", VAR_NUMBER), VV_RO},
345 {VV_NAME("beval_col", VAR_NUMBER), VV_RO},
346 {VV_NAME("beval_text", VAR_STRING), VV_RO},
347 {VV_NAME("scrollstart", VAR_STRING), 0},
348 {VV_NAME("swapname", VAR_STRING), VV_RO},
349 {VV_NAME("swapchoice", VAR_STRING), 0},
350 {VV_NAME("swapcommand", VAR_STRING), VV_RO},
351 {VV_NAME("char", VAR_STRING), VV_RO},
352 {VV_NAME("mouse_win", VAR_NUMBER), 0},
353 {VV_NAME("mouse_lnum", VAR_NUMBER), 0},
354 {VV_NAME("mouse_col", VAR_NUMBER), 0},
355 {VV_NAME("operator", VAR_STRING), VV_RO},
356 {VV_NAME("searchforward", VAR_NUMBER), 0},
357 {VV_NAME("oldfiles", VAR_LIST), 0},
360 /* shorthand */
361 #define vv_type vv_di.di_tv.v_type
362 #define vv_nr vv_di.di_tv.vval.v_number
363 #define vv_float vv_di.di_tv.vval.v_float
364 #define vv_str vv_di.di_tv.vval.v_string
365 #define vv_list vv_di.di_tv.vval.v_list
366 #define vv_tv vv_di.di_tv
369 * The v: variables are stored in dictionary "vimvardict".
370 * "vimvars_var" is the variable that is used for the "l:" scope.
372 static dict_T vimvardict;
373 static dictitem_T vimvars_var;
374 #define vimvarht vimvardict.dv_hashtab
376 static void prepare_vimvar __ARGS((int idx, typval_T *save_tv));
377 static void restore_vimvar __ARGS((int idx, typval_T *save_tv));
378 #if defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)
379 static int call_vim_function __ARGS((char_u *func, int argc, char_u **argv, int safe, typval_T *rettv));
380 #endif
381 static int ex_let_vars __ARGS((char_u *arg, typval_T *tv, int copy, int semicolon, int var_count, char_u *nextchars));
382 static char_u *skip_var_list __ARGS((char_u *arg, int *var_count, int *semicolon));
383 static char_u *skip_var_one __ARGS((char_u *arg));
384 static void list_hashtable_vars __ARGS((hashtab_T *ht, char_u *prefix, int empty, int *first));
385 static void list_glob_vars __ARGS((int *first));
386 static void list_buf_vars __ARGS((int *first));
387 static void list_win_vars __ARGS((int *first));
388 #ifdef FEAT_WINDOWS
389 static void list_tab_vars __ARGS((int *first));
390 #endif
391 static void list_vim_vars __ARGS((int *first));
392 static void list_script_vars __ARGS((int *first));
393 static void list_func_vars __ARGS((int *first));
394 static char_u *list_arg_vars __ARGS((exarg_T *eap, char_u *arg, int *first));
395 static char_u *ex_let_one __ARGS((char_u *arg, typval_T *tv, int copy, char_u *endchars, char_u *op));
396 static int check_changedtick __ARGS((char_u *arg));
397 static char_u *get_lval __ARGS((char_u *name, typval_T *rettv, lval_T *lp, int unlet, int skip, int quiet, int fne_flags));
398 static void clear_lval __ARGS((lval_T *lp));
399 static void set_var_lval __ARGS((lval_T *lp, char_u *endp, typval_T *rettv, int copy, char_u *op));
400 static int tv_op __ARGS((typval_T *tv1, typval_T *tv2, char_u *op));
401 static void list_add_watch __ARGS((list_T *l, listwatch_T *lw));
402 static void list_rem_watch __ARGS((list_T *l, listwatch_T *lwrem));
403 static void list_fix_watch __ARGS((list_T *l, listitem_T *item));
404 static void ex_unletlock __ARGS((exarg_T *eap, char_u *argstart, int deep));
405 static int do_unlet_var __ARGS((lval_T *lp, char_u *name_end, int forceit));
406 static int do_lock_var __ARGS((lval_T *lp, char_u *name_end, int deep, int lock));
407 static void item_lock __ARGS((typval_T *tv, int deep, int lock));
408 static int tv_islocked __ARGS((typval_T *tv));
410 static int eval0 __ARGS((char_u *arg, typval_T *rettv, char_u **nextcmd, int evaluate));
411 static int eval1 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
412 static int eval2 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
413 static int eval3 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
414 static int eval4 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
415 static int eval5 __ARGS((char_u **arg, typval_T *rettv, int evaluate));
416 static int eval6 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
417 static int eval7 __ARGS((char_u **arg, typval_T *rettv, int evaluate, int want_string));
419 static int eval_index __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
420 static int get_option_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
421 static int get_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
422 static int get_lit_string_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
423 static int get_list_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
424 static int rettv_list_alloc __ARGS((typval_T *rettv));
425 static listitem_T *listitem_alloc __ARGS((void));
426 static void listitem_free __ARGS((listitem_T *item));
427 static void listitem_remove __ARGS((list_T *l, listitem_T *item));
428 static long list_len __ARGS((list_T *l));
429 static int list_equal __ARGS((list_T *l1, list_T *l2, int ic));
430 static int dict_equal __ARGS((dict_T *d1, dict_T *d2, int ic));
431 static int tv_equal __ARGS((typval_T *tv1, typval_T *tv2, int ic));
432 static listitem_T *list_find __ARGS((list_T *l, long n));
433 static long list_find_nr __ARGS((list_T *l, long idx, int *errorp));
434 static long list_idx_of_item __ARGS((list_T *l, listitem_T *item));
435 static void list_append __ARGS((list_T *l, listitem_T *item));
436 static int list_append_number __ARGS((list_T *l, varnumber_T n));
437 static int list_insert_tv __ARGS((list_T *l, typval_T *tv, listitem_T *item));
438 static int list_extend __ARGS((list_T *l1, list_T *l2, listitem_T *bef));
439 static int list_concat __ARGS((list_T *l1, list_T *l2, typval_T *tv));
440 static list_T *list_copy __ARGS((list_T *orig, int deep, int copyID));
441 static void list_remove __ARGS((list_T *l, listitem_T *item, listitem_T *item2));
442 static char_u *list2string __ARGS((typval_T *tv, int copyID));
443 static int list_join __ARGS((garray_T *gap, list_T *l, char_u *sep, int echo, int copyID));
444 static int free_unref_items __ARGS((int copyID));
445 static void set_ref_in_ht __ARGS((hashtab_T *ht, int copyID));
446 static void set_ref_in_list __ARGS((list_T *l, int copyID));
447 static void set_ref_in_item __ARGS((typval_T *tv, int copyID));
448 static void dict_unref __ARGS((dict_T *d));
449 static void dict_free __ARGS((dict_T *d, int recurse));
450 static dictitem_T *dictitem_copy __ARGS((dictitem_T *org));
451 static void dictitem_remove __ARGS((dict_T *dict, dictitem_T *item));
452 static dict_T *dict_copy __ARGS((dict_T *orig, int deep, int copyID));
453 static long dict_len __ARGS((dict_T *d));
454 static dictitem_T *dict_find __ARGS((dict_T *d, char_u *key, int len));
455 static char_u *dict2string __ARGS((typval_T *tv, int copyID));
456 static int get_dict_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
457 static char_u *echo_string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
458 static char_u *tv2string __ARGS((typval_T *tv, char_u **tofree, char_u *numbuf, int copyID));
459 static char_u *string_quote __ARGS((char_u *str, int function));
460 #ifdef FEAT_FLOAT
461 static int string2float __ARGS((char_u *text, float_T *value));
462 #endif
463 static int get_env_tv __ARGS((char_u **arg, typval_T *rettv, int evaluate));
464 static int find_internal_func __ARGS((char_u *name));
465 static char_u *deref_func_name __ARGS((char_u *name, int *lenp));
466 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));
467 static int call_func __ARGS((char_u *func_name, int len, typval_T *rettv, int argcount, typval_T *argvars, linenr_T firstline, linenr_T lastline, int *doesrange, int evaluate, dict_T *selfdict));
468 static void emsg_funcname __ARGS((char *ermsg, char_u *name));
469 static int non_zero_arg __ARGS((typval_T *argvars));
471 #ifdef FEAT_FLOAT
472 static void f_abs __ARGS((typval_T *argvars, typval_T *rettv));
474 /* Below are the 10 added FP functions - I've kept them together */
475 /* here and in their definitions later on. Because the functions[] */
476 /* table must be in ASCII order, they are scattered there - WJMc */
478 static void f_acos __ARGS((typval_T *argvars, typval_T *rettv));
479 static void f_asin __ARGS((typval_T *argvars, typval_T *rettv));
480 static void f_atan2 __ARGS((typval_T *argvars, typval_T *rettv)); /* 2 args */
481 static void f_cosh __ARGS((typval_T *argvars, typval_T *rettv));
482 static void f_exp __ARGS((typval_T *argvars, typval_T *rettv));
483 static void f_fmod __ARGS((typval_T *argvars, typval_T *rettv)); /* 2 args */
484 static void f_log __ARGS((typval_T *argvars, typval_T *rettv));
485 static void f_sinh __ARGS((typval_T *argvars, typval_T *rettv));
486 static void f_tan __ARGS((typval_T *argvars, typval_T *rettv));
487 static void f_tanh __ARGS((typval_T *argvars, typval_T *rettv));
488 #endif
489 static void f_add __ARGS((typval_T *argvars, typval_T *rettv));
490 static void f_append __ARGS((typval_T *argvars, typval_T *rettv));
491 static void f_argc __ARGS((typval_T *argvars, typval_T *rettv));
492 static void f_argidx __ARGS((typval_T *argvars, typval_T *rettv));
493 static void f_argv __ARGS((typval_T *argvars, typval_T *rettv));
494 #ifdef FEAT_FLOAT
495 static void f_atan __ARGS((typval_T *argvars, typval_T *rettv));
496 #endif
497 static void f_browse __ARGS((typval_T *argvars, typval_T *rettv));
498 static void f_browsedir __ARGS((typval_T *argvars, typval_T *rettv));
499 static void f_bufexists __ARGS((typval_T *argvars, typval_T *rettv));
500 static void f_buflisted __ARGS((typval_T *argvars, typval_T *rettv));
501 static void f_bufloaded __ARGS((typval_T *argvars, typval_T *rettv));
502 static void f_bufname __ARGS((typval_T *argvars, typval_T *rettv));
503 static void f_bufnr __ARGS((typval_T *argvars, typval_T *rettv));
504 static void f_bufwinnr __ARGS((typval_T *argvars, typval_T *rettv));
505 static void f_byte2line __ARGS((typval_T *argvars, typval_T *rettv));
506 static void f_byteidx __ARGS((typval_T *argvars, typval_T *rettv));
507 static void f_call __ARGS((typval_T *argvars, typval_T *rettv));
508 #ifdef FEAT_FLOAT
509 static void f_ceil __ARGS((typval_T *argvars, typval_T *rettv));
510 #endif
511 static void f_changenr __ARGS((typval_T *argvars, typval_T *rettv));
512 static void f_char2nr __ARGS((typval_T *argvars, typval_T *rettv));
513 static void f_cindent __ARGS((typval_T *argvars, typval_T *rettv));
514 static void f_clearmatches __ARGS((typval_T *argvars, typval_T *rettv));
515 static void f_col __ARGS((typval_T *argvars, typval_T *rettv));
516 #if defined(FEAT_INS_EXPAND)
517 static void f_complete __ARGS((typval_T *argvars, typval_T *rettv));
518 static void f_complete_add __ARGS((typval_T *argvars, typval_T *rettv));
519 static void f_complete_check __ARGS((typval_T *argvars, typval_T *rettv));
520 #endif
521 static void f_confirm __ARGS((typval_T *argvars, typval_T *rettv));
522 static void f_copy __ARGS((typval_T *argvars, typval_T *rettv));
523 #ifdef FEAT_FLOAT
524 static void f_cos __ARGS((typval_T *argvars, typval_T *rettv));
525 #endif
526 static void f_count __ARGS((typval_T *argvars, typval_T *rettv));
527 static void f_cscope_connection __ARGS((typval_T *argvars, typval_T *rettv));
528 static void f_cursor __ARGS((typval_T *argsvars, typval_T *rettv));
529 static void f_deepcopy __ARGS((typval_T *argvars, typval_T *rettv));
530 static void f_delete __ARGS((typval_T *argvars, typval_T *rettv));
531 static void f_did_filetype __ARGS((typval_T *argvars, typval_T *rettv));
532 static void f_diff_filler __ARGS((typval_T *argvars, typval_T *rettv));
533 static void f_diff_hlID __ARGS((typval_T *argvars, typval_T *rettv));
534 static void f_empty __ARGS((typval_T *argvars, typval_T *rettv));
535 static void f_escape __ARGS((typval_T *argvars, typval_T *rettv));
536 static void f_eval __ARGS((typval_T *argvars, typval_T *rettv));
537 static void f_eventhandler __ARGS((typval_T *argvars, typval_T *rettv));
538 static void f_executable __ARGS((typval_T *argvars, typval_T *rettv));
539 static void f_exists __ARGS((typval_T *argvars, typval_T *rettv));
540 static void f_expand __ARGS((typval_T *argvars, typval_T *rettv));
541 static void f_extend __ARGS((typval_T *argvars, typval_T *rettv));
542 static void f_feedkeys __ARGS((typval_T *argvars, typval_T *rettv));
543 static void f_filereadable __ARGS((typval_T *argvars, typval_T *rettv));
544 static void f_filewritable __ARGS((typval_T *argvars, typval_T *rettv));
545 static void f_filter __ARGS((typval_T *argvars, typval_T *rettv));
546 static void f_finddir __ARGS((typval_T *argvars, typval_T *rettv));
547 static void f_findfile __ARGS((typval_T *argvars, typval_T *rettv));
548 #ifdef FEAT_FLOAT
549 static void f_float2nr __ARGS((typval_T *argvars, typval_T *rettv));
550 static void f_floor __ARGS((typval_T *argvars, typval_T *rettv));
551 #endif
552 static void f_fnameescape __ARGS((typval_T *argvars, typval_T *rettv));
553 static void f_fnamemodify __ARGS((typval_T *argvars, typval_T *rettv));
554 static void f_foldclosed __ARGS((typval_T *argvars, typval_T *rettv));
555 static void f_foldclosedend __ARGS((typval_T *argvars, typval_T *rettv));
556 static void f_foldlevel __ARGS((typval_T *argvars, typval_T *rettv));
557 static void f_foldtext __ARGS((typval_T *argvars, typval_T *rettv));
558 static void f_foldtextresult __ARGS((typval_T *argvars, typval_T *rettv));
559 static void f_foreground __ARGS((typval_T *argvars, typval_T *rettv));
560 static void f_function __ARGS((typval_T *argvars, typval_T *rettv));
561 static void f_garbagecollect __ARGS((typval_T *argvars, typval_T *rettv));
562 static void f_get __ARGS((typval_T *argvars, typval_T *rettv));
563 static void f_getbufline __ARGS((typval_T *argvars, typval_T *rettv));
564 static void f_getbufvar __ARGS((typval_T *argvars, typval_T *rettv));
565 static void f_getchar __ARGS((typval_T *argvars, typval_T *rettv));
566 static void f_getcharmod __ARGS((typval_T *argvars, typval_T *rettv));
567 static void f_getcmdline __ARGS((typval_T *argvars, typval_T *rettv));
568 static void f_getcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
569 static void f_getcmdtype __ARGS((typval_T *argvars, typval_T *rettv));
570 static void f_getcwd __ARGS((typval_T *argvars, typval_T *rettv));
571 static void f_getfontname __ARGS((typval_T *argvars, typval_T *rettv));
572 static void f_getfperm __ARGS((typval_T *argvars, typval_T *rettv));
573 static void f_getfsize __ARGS((typval_T *argvars, typval_T *rettv));
574 static void f_getftime __ARGS((typval_T *argvars, typval_T *rettv));
575 static void f_getftype __ARGS((typval_T *argvars, typval_T *rettv));
576 static void f_getline __ARGS((typval_T *argvars, typval_T *rettv));
577 static void f_getmatches __ARGS((typval_T *argvars, typval_T *rettv));
578 static void f_getpid __ARGS((typval_T *argvars, typval_T *rettv));
579 static void f_getpos __ARGS((typval_T *argvars, typval_T *rettv));
580 static void f_getqflist __ARGS((typval_T *argvars, typval_T *rettv));
581 static void f_getreg __ARGS((typval_T *argvars, typval_T *rettv));
582 static void f_getregtype __ARGS((typval_T *argvars, typval_T *rettv));
583 static void f_gettabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
584 static void f_getwinposx __ARGS((typval_T *argvars, typval_T *rettv));
585 static void f_getwinposy __ARGS((typval_T *argvars, typval_T *rettv));
586 static void f_getwinvar __ARGS((typval_T *argvars, typval_T *rettv));
587 static void f_glob __ARGS((typval_T *argvars, typval_T *rettv));
588 static void f_globpath __ARGS((typval_T *argvars, typval_T *rettv));
589 static void f_has __ARGS((typval_T *argvars, typval_T *rettv));
590 static void f_has_key __ARGS((typval_T *argvars, typval_T *rettv));
591 static void f_haslocaldir __ARGS((typval_T *argvars, typval_T *rettv));
592 static void f_hasmapto __ARGS((typval_T *argvars, typval_T *rettv));
593 static void f_histadd __ARGS((typval_T *argvars, typval_T *rettv));
594 static void f_histdel __ARGS((typval_T *argvars, typval_T *rettv));
595 static void f_histget __ARGS((typval_T *argvars, typval_T *rettv));
596 static void f_histnr __ARGS((typval_T *argvars, typval_T *rettv));
597 static void f_hlID __ARGS((typval_T *argvars, typval_T *rettv));
598 static void f_hlexists __ARGS((typval_T *argvars, typval_T *rettv));
599 static void f_hostname __ARGS((typval_T *argvars, typval_T *rettv));
600 static void f_iconv __ARGS((typval_T *argvars, typval_T *rettv));
601 static void f_indent __ARGS((typval_T *argvars, typval_T *rettv));
602 static void f_index __ARGS((typval_T *argvars, typval_T *rettv));
603 static void f_input __ARGS((typval_T *argvars, typval_T *rettv));
604 static void f_inputdialog __ARGS((typval_T *argvars, typval_T *rettv));
605 static void f_inputlist __ARGS((typval_T *argvars, typval_T *rettv));
606 static void f_inputrestore __ARGS((typval_T *argvars, typval_T *rettv));
607 static void f_inputsave __ARGS((typval_T *argvars, typval_T *rettv));
608 static void f_inputsecret __ARGS((typval_T *argvars, typval_T *rettv));
609 static void f_insert __ARGS((typval_T *argvars, typval_T *rettv));
610 static void f_isdirectory __ARGS((typval_T *argvars, typval_T *rettv));
611 static void f_islocked __ARGS((typval_T *argvars, typval_T *rettv));
612 static void f_items __ARGS((typval_T *argvars, typval_T *rettv));
613 static void f_join __ARGS((typval_T *argvars, typval_T *rettv));
614 static void f_keys __ARGS((typval_T *argvars, typval_T *rettv));
615 static void f_last_buffer_nr __ARGS((typval_T *argvars, typval_T *rettv));
616 static void f_len __ARGS((typval_T *argvars, typval_T *rettv));
617 static void f_libcall __ARGS((typval_T *argvars, typval_T *rettv));
618 static void f_libcallnr __ARGS((typval_T *argvars, typval_T *rettv));
619 static void f_line __ARGS((typval_T *argvars, typval_T *rettv));
620 static void f_line2byte __ARGS((typval_T *argvars, typval_T *rettv));
621 static void f_lispindent __ARGS((typval_T *argvars, typval_T *rettv));
622 static void f_localtime __ARGS((typval_T *argvars, typval_T *rettv));
623 #ifdef FEAT_FLOAT
624 static void f_log10 __ARGS((typval_T *argvars, typval_T *rettv));
625 #endif
626 static void f_map __ARGS((typval_T *argvars, typval_T *rettv));
627 static void f_maparg __ARGS((typval_T *argvars, typval_T *rettv));
628 static void f_mapcheck __ARGS((typval_T *argvars, typval_T *rettv));
629 static void f_match __ARGS((typval_T *argvars, typval_T *rettv));
630 static void f_matchadd __ARGS((typval_T *argvars, typval_T *rettv));
631 static void f_matcharg __ARGS((typval_T *argvars, typval_T *rettv));
632 static void f_matchdelete __ARGS((typval_T *argvars, typval_T *rettv));
633 static void f_matchend __ARGS((typval_T *argvars, typval_T *rettv));
634 static void f_matchlist __ARGS((typval_T *argvars, typval_T *rettv));
635 static void f_matchstr __ARGS((typval_T *argvars, typval_T *rettv));
636 static void f_max __ARGS((typval_T *argvars, typval_T *rettv));
637 static void f_min __ARGS((typval_T *argvars, typval_T *rettv));
638 #ifdef vim_mkdir
639 static void f_mkdir __ARGS((typval_T *argvars, typval_T *rettv));
640 #endif
641 static void f_mode __ARGS((typval_T *argvars, typval_T *rettv));
642 #ifdef FEAT_MZSCHEME
643 static void f_mzeval __ARGS((typval_T *argvars, typval_T *rettv));
644 #endif
645 static void f_nextnonblank __ARGS((typval_T *argvars, typval_T *rettv));
646 static void f_nr2char __ARGS((typval_T *argvars, typval_T *rettv));
647 static void f_pathshorten __ARGS((typval_T *argvars, typval_T *rettv));
648 #ifdef FEAT_FLOAT
649 static void f_pow __ARGS((typval_T *argvars, typval_T *rettv));
650 #endif
651 static void f_prevnonblank __ARGS((typval_T *argvars, typval_T *rettv));
652 static void f_printf __ARGS((typval_T *argvars, typval_T *rettv));
653 static void f_pumvisible __ARGS((typval_T *argvars, typval_T *rettv));
654 static void f_range __ARGS((typval_T *argvars, typval_T *rettv));
655 static void f_readfile __ARGS((typval_T *argvars, typval_T *rettv));
656 static void f_reltime __ARGS((typval_T *argvars, typval_T *rettv));
657 static void f_reltimestr __ARGS((typval_T *argvars, typval_T *rettv));
658 static void f_remote_expr __ARGS((typval_T *argvars, typval_T *rettv));
659 static void f_remote_foreground __ARGS((typval_T *argvars, typval_T *rettv));
660 static void f_remote_peek __ARGS((typval_T *argvars, typval_T *rettv));
661 static void f_remote_read __ARGS((typval_T *argvars, typval_T *rettv));
662 static void f_remote_send __ARGS((typval_T *argvars, typval_T *rettv));
663 static void f_remove __ARGS((typval_T *argvars, typval_T *rettv));
664 static void f_rename __ARGS((typval_T *argvars, typval_T *rettv));
665 static void f_repeat __ARGS((typval_T *argvars, typval_T *rettv));
666 static void f_resolve __ARGS((typval_T *argvars, typval_T *rettv));
667 static void f_reverse __ARGS((typval_T *argvars, typval_T *rettv));
668 #ifdef FEAT_FLOAT
669 static void f_round __ARGS((typval_T *argvars, typval_T *rettv));
670 #endif
671 static void f_search __ARGS((typval_T *argvars, typval_T *rettv));
672 static void f_searchdecl __ARGS((typval_T *argvars, typval_T *rettv));
673 static void f_searchpair __ARGS((typval_T *argvars, typval_T *rettv));
674 static void f_searchpairpos __ARGS((typval_T *argvars, typval_T *rettv));
675 static void f_searchpos __ARGS((typval_T *argvars, typval_T *rettv));
676 static void f_server2client __ARGS((typval_T *argvars, typval_T *rettv));
677 static void f_serverlist __ARGS((typval_T *argvars, typval_T *rettv));
678 static void f_setbufvar __ARGS((typval_T *argvars, typval_T *rettv));
679 static void f_setcmdpos __ARGS((typval_T *argvars, typval_T *rettv));
680 static void f_setline __ARGS((typval_T *argvars, typval_T *rettv));
681 static void f_setloclist __ARGS((typval_T *argvars, typval_T *rettv));
682 static void f_setmatches __ARGS((typval_T *argvars, typval_T *rettv));
683 static void f_setpos __ARGS((typval_T *argvars, typval_T *rettv));
684 static void f_setqflist __ARGS((typval_T *argvars, typval_T *rettv));
685 static void f_setreg __ARGS((typval_T *argvars, typval_T *rettv));
686 static void f_settabwinvar __ARGS((typval_T *argvars, typval_T *rettv));
687 static void f_setwinvar __ARGS((typval_T *argvars, typval_T *rettv));
688 static void f_shellescape __ARGS((typval_T *argvars, typval_T *rettv));
689 static void f_simplify __ARGS((typval_T *argvars, typval_T *rettv));
690 #ifdef FEAT_FLOAT
691 static void f_sin __ARGS((typval_T *argvars, typval_T *rettv));
692 #endif
693 static void f_sort __ARGS((typval_T *argvars, typval_T *rettv));
694 static void f_soundfold __ARGS((typval_T *argvars, typval_T *rettv));
695 static void f_spellbadword __ARGS((typval_T *argvars, typval_T *rettv));
696 static void f_spellsuggest __ARGS((typval_T *argvars, typval_T *rettv));
697 static void f_split __ARGS((typval_T *argvars, typval_T *rettv));
698 #ifdef FEAT_FLOAT
699 static void f_sqrt __ARGS((typval_T *argvars, typval_T *rettv));
700 static void f_str2float __ARGS((typval_T *argvars, typval_T *rettv));
701 #endif
702 static void f_str2nr __ARGS((typval_T *argvars, typval_T *rettv));
703 #ifdef HAVE_STRFTIME
704 static void f_strftime __ARGS((typval_T *argvars, typval_T *rettv));
705 #endif
706 static void f_stridx __ARGS((typval_T *argvars, typval_T *rettv));
707 static void f_string __ARGS((typval_T *argvars, typval_T *rettv));
708 static void f_strlen __ARGS((typval_T *argvars, typval_T *rettv));
709 static void f_strpart __ARGS((typval_T *argvars, typval_T *rettv));
710 static void f_strridx __ARGS((typval_T *argvars, typval_T *rettv));
711 static void f_strtrans __ARGS((typval_T *argvars, typval_T *rettv));
712 static void f_submatch __ARGS((typval_T *argvars, typval_T *rettv));
713 static void f_substitute __ARGS((typval_T *argvars, typval_T *rettv));
714 static void f_synID __ARGS((typval_T *argvars, typval_T *rettv));
715 static void f_synIDattr __ARGS((typval_T *argvars, typval_T *rettv));
716 static void f_synIDtrans __ARGS((typval_T *argvars, typval_T *rettv));
717 static void f_synstack __ARGS((typval_T *argvars, typval_T *rettv));
718 static void f_system __ARGS((typval_T *argvars, typval_T *rettv));
719 static void f_tabpagebuflist __ARGS((typval_T *argvars, typval_T *rettv));
720 static void f_tabpagenr __ARGS((typval_T *argvars, typval_T *rettv));
721 static void f_tabpagewinnr __ARGS((typval_T *argvars, typval_T *rettv));
722 static void f_taglist __ARGS((typval_T *argvars, typval_T *rettv));
723 static void f_tagfiles __ARGS((typval_T *argvars, typval_T *rettv));
724 static void f_tempname __ARGS((typval_T *argvars, typval_T *rettv));
725 static void f_test __ARGS((typval_T *argvars, typval_T *rettv));
726 static void f_tolower __ARGS((typval_T *argvars, typval_T *rettv));
727 static void f_toupper __ARGS((typval_T *argvars, typval_T *rettv));
728 static void f_tr __ARGS((typval_T *argvars, typval_T *rettv));
729 #ifdef FEAT_FLOAT
730 static void f_trunc __ARGS((typval_T *argvars, typval_T *rettv));
731 #endif
732 static void f_type __ARGS((typval_T *argvars, typval_T *rettv));
733 static void f_values __ARGS((typval_T *argvars, typval_T *rettv));
734 static void f_virtcol __ARGS((typval_T *argvars, typval_T *rettv));
735 static void f_visualmode __ARGS((typval_T *argvars, typval_T *rettv));
736 static void f_winbufnr __ARGS((typval_T *argvars, typval_T *rettv));
737 static void f_wincol __ARGS((typval_T *argvars, typval_T *rettv));
738 static void f_winheight __ARGS((typval_T *argvars, typval_T *rettv));
739 static void f_winline __ARGS((typval_T *argvars, typval_T *rettv));
740 static void f_winnr __ARGS((typval_T *argvars, typval_T *rettv));
741 static void f_winrestcmd __ARGS((typval_T *argvars, typval_T *rettv));
742 static void f_winrestview __ARGS((typval_T *argvars, typval_T *rettv));
743 static void f_winsaveview __ARGS((typval_T *argvars, typval_T *rettv));
744 static void f_winwidth __ARGS((typval_T *argvars, typval_T *rettv));
745 static void f_writefile __ARGS((typval_T *argvars, typval_T *rettv));
747 static int list2fpos __ARGS((typval_T *arg, pos_T *posp, int *fnump));
748 static pos_T *var2fpos __ARGS((typval_T *varp, int dollar_lnum, int *fnum));
749 static int get_env_len __ARGS((char_u **arg));
750 static int get_id_len __ARGS((char_u **arg));
751 static int get_name_len __ARGS((char_u **arg, char_u **alias, int evaluate, int verbose));
752 static char_u *find_name_end __ARGS((char_u *arg, char_u **expr_start, char_u **expr_end, int flags));
753 #define FNE_INCL_BR 1 /* find_name_end(): include [] in name */
754 #define FNE_CHECK_START 2 /* find_name_end(): check name starts with
755 valid character */
756 static char_u * make_expanded_name __ARGS((char_u *in_start, char_u *expr_start, char_u *expr_end, char_u *in_end));
757 static int eval_isnamec __ARGS((int c));
758 static int eval_isnamec1 __ARGS((int c));
759 static int get_var_tv __ARGS((char_u *name, int len, typval_T *rettv, int verbose));
760 static int handle_subscript __ARGS((char_u **arg, typval_T *rettv, int evaluate, int verbose));
761 static typval_T *alloc_tv __ARGS((void));
762 static typval_T *alloc_string_tv __ARGS((char_u *string));
763 static void init_tv __ARGS((typval_T *varp));
764 static long get_tv_number __ARGS((typval_T *varp));
765 static linenr_T get_tv_lnum __ARGS((typval_T *argvars));
766 static linenr_T get_tv_lnum_buf __ARGS((typval_T *argvars, buf_T *buf));
767 static char_u *get_tv_string __ARGS((typval_T *varp));
768 static char_u *get_tv_string_buf __ARGS((typval_T *varp, char_u *buf));
769 static char_u *get_tv_string_buf_chk __ARGS((typval_T *varp, char_u *buf));
770 static dictitem_T *find_var __ARGS((char_u *name, hashtab_T **htp));
771 static dictitem_T *find_var_in_ht __ARGS((hashtab_T *ht, char_u *varname, int writing));
772 static hashtab_T *find_var_ht __ARGS((char_u *name, char_u **varname));
773 static void vars_clear_ext __ARGS((hashtab_T *ht, int free_val));
774 static void delete_var __ARGS((hashtab_T *ht, hashitem_T *hi));
775 static void list_one_var __ARGS((dictitem_T *v, char_u *prefix, int *first));
776 static void list_one_var_a __ARGS((char_u *prefix, char_u *name, int type, char_u *string, int *first));
777 static void set_var __ARGS((char_u *name, typval_T *varp, int copy));
778 static int var_check_ro __ARGS((int flags, char_u *name));
779 static int var_check_fixed __ARGS((int flags, char_u *name));
780 static int tv_check_lock __ARGS((int lock, char_u *name));
781 static int item_copy __ARGS((typval_T *from, typval_T *to, int deep, int copyID));
782 static char_u *find_option_end __ARGS((char_u **arg, int *opt_flags));
783 static char_u *trans_function_name __ARGS((char_u **pp, int skip, int flags, funcdict_T *fd));
784 static int eval_fname_script __ARGS((char_u *p));
785 static int eval_fname_sid __ARGS((char_u *p));
786 static void list_func_head __ARGS((ufunc_T *fp, int indent));
787 static ufunc_T *find_func __ARGS((char_u *name));
788 static int function_exists __ARGS((char_u *name));
789 static int builtin_function __ARGS((char_u *name));
790 #ifdef FEAT_PROFILE
791 static void func_do_profile __ARGS((ufunc_T *fp));
792 static void prof_sort_list __ARGS((FILE *fd, ufunc_T **sorttab, int st_len, char *title, int prefer_self));
793 static void prof_func_line __ARGS((FILE *fd, int count, proftime_T *total, proftime_T *self, int prefer_self));
794 static int
795 # ifdef __BORLANDC__
796 _RTLENTRYF
797 # endif
798 prof_total_cmp __ARGS((const void *s1, const void *s2));
799 static int
800 # ifdef __BORLANDC__
801 _RTLENTRYF
802 # endif
803 prof_self_cmp __ARGS((const void *s1, const void *s2));
804 #endif
805 static int script_autoload __ARGS((char_u *name, int reload));
806 static char_u *autoload_name __ARGS((char_u *name));
807 static void cat_func_name __ARGS((char_u *buf, ufunc_T *fp));
808 static void func_free __ARGS((ufunc_T *fp));
809 static void func_unref __ARGS((char_u *name));
810 static void func_ref __ARGS((char_u *name));
811 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));
812 static int can_free_funccal __ARGS((funccall_T *fc, int copyID)) ;
813 static void free_funccal __ARGS((funccall_T *fc, int free_val));
814 static void add_nr_var __ARGS((dict_T *dp, dictitem_T *v, char *name, varnumber_T nr));
815 static win_T *find_win_by_nr __ARGS((typval_T *vp, tabpage_T *tp));
816 static void getwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
817 static int searchpair_cmn __ARGS((typval_T *argvars, pos_T *match_pos));
818 static int search_cmn __ARGS((typval_T *argvars, pos_T *match_pos, int *flagsp));
819 static void setwinvar __ARGS((typval_T *argvars, typval_T *rettv, int off));
821 /* Character used as separated in autoload function/variable names. */
822 #define AUTOLOAD_CHAR '#'
825 * Initialize the global and v: variables.
827 void
828 eval_init()
830 int i;
831 struct vimvar *p;
833 init_var_dict(&globvardict, &globvars_var);
834 init_var_dict(&vimvardict, &vimvars_var);
835 hash_init(&compat_hashtab);
836 hash_init(&func_hashtab);
838 for (i = 0; i < VV_LEN; ++i)
840 p = &vimvars[i];
841 STRCPY(p->vv_di.di_key, p->vv_name);
842 if (p->vv_flags & VV_RO)
843 p->vv_di.di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
844 else if (p->vv_flags & VV_RO_SBX)
845 p->vv_di.di_flags = DI_FLAGS_RO_SBX | DI_FLAGS_FIX;
846 else
847 p->vv_di.di_flags = DI_FLAGS_FIX;
849 /* add to v: scope dict, unless the value is not always available */
850 if (p->vv_type != VAR_UNKNOWN)
851 hash_add(&vimvarht, p->vv_di.di_key);
852 if (p->vv_flags & VV_COMPAT)
853 /* add to compat scope dict */
854 hash_add(&compat_hashtab, p->vv_di.di_key);
856 set_vim_var_nr(VV_SEARCHFORWARD, 1L);
859 #if defined(EXITFREE) || defined(PROTO)
860 void
861 eval_clear()
863 int i;
864 struct vimvar *p;
866 for (i = 0; i < VV_LEN; ++i)
868 p = &vimvars[i];
869 if (p->vv_di.di_tv.v_type == VAR_STRING)
871 vim_free(p->vv_str);
872 p->vv_str = NULL;
874 else if (p->vv_di.di_tv.v_type == VAR_LIST)
876 list_unref(p->vv_list);
877 p->vv_list = NULL;
880 hash_clear(&vimvarht);
881 hash_init(&vimvarht); /* garbage_collect() will access it */
882 hash_clear(&compat_hashtab);
884 free_scriptnames();
886 /* global variables */
887 vars_clear(&globvarht);
889 /* autoloaded script names */
890 ga_clear_strings(&ga_loaded);
892 /* script-local variables */
893 for (i = 1; i <= ga_scripts.ga_len; ++i)
895 vars_clear(&SCRIPT_VARS(i));
896 vim_free(SCRIPT_SV(i));
898 ga_clear(&ga_scripts);
900 /* unreferenced lists and dicts */
901 (void)garbage_collect();
903 /* functions */
904 free_all_functions();
905 hash_clear(&func_hashtab);
907 #endif
910 * Return the name of the executed function.
912 char_u *
913 func_name(cookie)
914 void *cookie;
916 return ((funccall_T *)cookie)->func->uf_name;
920 * Return the address holding the next breakpoint line for a funccall cookie.
922 linenr_T *
923 func_breakpoint(cookie)
924 void *cookie;
926 return &((funccall_T *)cookie)->breakpoint;
930 * Return the address holding the debug tick for a funccall cookie.
932 int *
933 func_dbg_tick(cookie)
934 void *cookie;
936 return &((funccall_T *)cookie)->dbg_tick;
940 * Return the nesting level for a funccall cookie.
943 func_level(cookie)
944 void *cookie;
946 return ((funccall_T *)cookie)->level;
949 /* pointer to funccal for currently active function */
950 funccall_T *current_funccal = NULL;
952 /* pointer to list of previously used funccal, still around because some
953 * item in it is still being used. */
954 funccall_T *previous_funccal = NULL;
957 * Return TRUE when a function was ended by a ":return" command.
960 current_func_returned()
962 return current_funccal->returned;
967 * Set an internal variable to a string value. Creates the variable if it does
968 * not already exist.
970 void
971 set_internal_string_var(name, value)
972 char_u *name;
973 char_u *value;
975 char_u *val;
976 typval_T *tvp;
978 val = vim_strsave(value);
979 if (val != NULL)
981 tvp = alloc_string_tv(val);
982 if (tvp != NULL)
984 set_var(name, tvp, FALSE);
985 free_tv(tvp);
990 static lval_T *redir_lval = NULL;
991 static garray_T redir_ga; /* only valid when redir_lval is not NULL */
992 static char_u *redir_endp = NULL;
993 static char_u *redir_varname = NULL;
996 * Start recording command output to a variable
997 * Returns OK if successfully completed the setup. FAIL otherwise.
1000 var_redir_start(name, append)
1001 char_u *name;
1002 int append; /* append to an existing variable */
1004 int save_emsg;
1005 int err;
1006 typval_T tv;
1008 /* Catch a bad name early. */
1009 if (!eval_isnamec1(*name))
1011 EMSG(_(e_invarg));
1012 return FAIL;
1015 /* Make a copy of the name, it is used in redir_lval until redir ends. */
1016 redir_varname = vim_strsave(name);
1017 if (redir_varname == NULL)
1018 return FAIL;
1020 redir_lval = (lval_T *)alloc_clear((unsigned)sizeof(lval_T));
1021 if (redir_lval == NULL)
1023 var_redir_stop();
1024 return FAIL;
1027 /* The output is stored in growarray "redir_ga" until redirection ends. */
1028 ga_init2(&redir_ga, (int)sizeof(char), 500);
1030 /* Parse the variable name (can be a dict or list entry). */
1031 redir_endp = get_lval(redir_varname, NULL, redir_lval, FALSE, FALSE, FALSE,
1032 FNE_CHECK_START);
1033 if (redir_endp == NULL || redir_lval->ll_name == NULL || *redir_endp != NUL)
1035 if (redir_endp != NULL && *redir_endp != NUL)
1036 /* Trailing characters are present after the variable name */
1037 EMSG(_(e_trailing));
1038 else
1039 EMSG(_(e_invarg));
1040 redir_endp = NULL; /* don't store a value, only cleanup */
1041 var_redir_stop();
1042 return FAIL;
1045 /* check if we can write to the variable: set it to or append an empty
1046 * string */
1047 save_emsg = did_emsg;
1048 did_emsg = FALSE;
1049 tv.v_type = VAR_STRING;
1050 tv.vval.v_string = (char_u *)"";
1051 if (append)
1052 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)".");
1053 else
1054 set_var_lval(redir_lval, redir_endp, &tv, TRUE, (char_u *)"=");
1055 err = did_emsg;
1056 did_emsg |= save_emsg;
1057 if (err)
1059 redir_endp = NULL; /* don't store a value, only cleanup */
1060 var_redir_stop();
1061 return FAIL;
1063 if (redir_lval->ll_newkey != NULL)
1065 /* Dictionary item was created, don't do it again. */
1066 vim_free(redir_lval->ll_newkey);
1067 redir_lval->ll_newkey = NULL;
1070 return OK;
1074 * Append "value[value_len]" to the variable set by var_redir_start().
1075 * The actual appending is postponed until redirection ends, because the value
1076 * appended may in fact be the string we write to, changing it may cause freed
1077 * memory to be used:
1078 * :redir => foo
1079 * :let foo
1080 * :redir END
1082 void
1083 var_redir_str(value, value_len)
1084 char_u *value;
1085 int value_len;
1087 int len;
1089 if (redir_lval == NULL)
1090 return;
1092 if (value_len == -1)
1093 len = (int)STRLEN(value); /* Append the entire string */
1094 else
1095 len = value_len; /* Append only "value_len" characters */
1097 if (ga_grow(&redir_ga, len) == OK)
1099 mch_memmove((char *)redir_ga.ga_data + redir_ga.ga_len, value, len);
1100 redir_ga.ga_len += len;
1102 else
1103 var_redir_stop();
1107 * Stop redirecting command output to a variable.
1108 * Frees the allocated memory.
1110 void
1111 var_redir_stop()
1113 typval_T tv;
1115 if (redir_lval != NULL)
1117 /* If there was no error: assign the text to the variable. */
1118 if (redir_endp != NULL)
1120 ga_append(&redir_ga, NUL); /* Append the trailing NUL. */
1121 tv.v_type = VAR_STRING;
1122 tv.vval.v_string = redir_ga.ga_data;
1123 set_var_lval(redir_lval, redir_endp, &tv, FALSE, (char_u *)".");
1126 /* free the collected output */
1127 vim_free(redir_ga.ga_data);
1128 redir_ga.ga_data = NULL;
1130 clear_lval(redir_lval);
1131 vim_free(redir_lval);
1132 redir_lval = NULL;
1134 vim_free(redir_varname);
1135 redir_varname = NULL;
1138 # if defined(FEAT_MBYTE) || defined(PROTO)
1140 eval_charconvert(enc_from, enc_to, fname_from, fname_to)
1141 char_u *enc_from;
1142 char_u *enc_to;
1143 char_u *fname_from;
1144 char_u *fname_to;
1146 int err = FALSE;
1148 set_vim_var_string(VV_CC_FROM, enc_from, -1);
1149 set_vim_var_string(VV_CC_TO, enc_to, -1);
1150 set_vim_var_string(VV_FNAME_IN, fname_from, -1);
1151 set_vim_var_string(VV_FNAME_OUT, fname_to, -1);
1152 if (eval_to_bool(p_ccv, &err, NULL, FALSE))
1153 err = TRUE;
1154 set_vim_var_string(VV_CC_FROM, NULL, -1);
1155 set_vim_var_string(VV_CC_TO, NULL, -1);
1156 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1157 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1159 if (err)
1160 return FAIL;
1161 return OK;
1163 # endif
1165 # if defined(FEAT_POSTSCRIPT) || defined(PROTO)
1167 eval_printexpr(fname, args)
1168 char_u *fname;
1169 char_u *args;
1171 int err = FALSE;
1173 set_vim_var_string(VV_FNAME_IN, fname, -1);
1174 set_vim_var_string(VV_CMDARG, args, -1);
1175 if (eval_to_bool(p_pexpr, &err, NULL, FALSE))
1176 err = TRUE;
1177 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1178 set_vim_var_string(VV_CMDARG, NULL, -1);
1180 if (err)
1182 mch_remove(fname);
1183 return FAIL;
1185 return OK;
1187 # endif
1189 # if defined(FEAT_DIFF) || defined(PROTO)
1190 void
1191 eval_diff(origfile, newfile, outfile)
1192 char_u *origfile;
1193 char_u *newfile;
1194 char_u *outfile;
1196 int err = FALSE;
1198 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1199 set_vim_var_string(VV_FNAME_NEW, newfile, -1);
1200 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1201 (void)eval_to_bool(p_dex, &err, NULL, FALSE);
1202 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1203 set_vim_var_string(VV_FNAME_NEW, NULL, -1);
1204 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1207 void
1208 eval_patch(origfile, difffile, outfile)
1209 char_u *origfile;
1210 char_u *difffile;
1211 char_u *outfile;
1213 int err;
1215 set_vim_var_string(VV_FNAME_IN, origfile, -1);
1216 set_vim_var_string(VV_FNAME_DIFF, difffile, -1);
1217 set_vim_var_string(VV_FNAME_OUT, outfile, -1);
1218 (void)eval_to_bool(p_pex, &err, NULL, FALSE);
1219 set_vim_var_string(VV_FNAME_IN, NULL, -1);
1220 set_vim_var_string(VV_FNAME_DIFF, NULL, -1);
1221 set_vim_var_string(VV_FNAME_OUT, NULL, -1);
1223 # endif
1226 * Top level evaluation function, returning a boolean.
1227 * Sets "error" to TRUE if there was an error.
1228 * Return TRUE or FALSE.
1231 eval_to_bool(arg, error, nextcmd, skip)
1232 char_u *arg;
1233 int *error;
1234 char_u **nextcmd;
1235 int skip; /* only parse, don't execute */
1237 typval_T tv;
1238 int retval = FALSE;
1240 if (skip)
1241 ++emsg_skip;
1242 if (eval0(arg, &tv, nextcmd, !skip) == FAIL)
1243 *error = TRUE;
1244 else
1246 *error = FALSE;
1247 if (!skip)
1249 retval = (get_tv_number_chk(&tv, error) != 0);
1250 clear_tv(&tv);
1253 if (skip)
1254 --emsg_skip;
1256 return retval;
1260 * Top level evaluation function, returning a string. If "skip" is TRUE,
1261 * only parsing to "nextcmd" is done, without reporting errors. Return
1262 * pointer to allocated memory, or NULL for failure or when "skip" is TRUE.
1264 char_u *
1265 eval_to_string_skip(arg, nextcmd, skip)
1266 char_u *arg;
1267 char_u **nextcmd;
1268 int skip; /* only parse, don't execute */
1270 typval_T tv;
1271 char_u *retval;
1273 if (skip)
1274 ++emsg_skip;
1275 if (eval0(arg, &tv, nextcmd, !skip) == FAIL || skip)
1276 retval = NULL;
1277 else
1279 retval = vim_strsave(get_tv_string(&tv));
1280 clear_tv(&tv);
1282 if (skip)
1283 --emsg_skip;
1285 return retval;
1289 * Skip over an expression at "*pp".
1290 * Return FAIL for an error, OK otherwise.
1293 skip_expr(pp)
1294 char_u **pp;
1296 typval_T rettv;
1298 *pp = skipwhite(*pp);
1299 return eval1(pp, &rettv, FALSE);
1303 * Top level evaluation function, returning a string.
1304 * When "convert" is TRUE convert a List into a sequence of lines and convert
1305 * a Float to a String.
1306 * Return pointer to allocated memory, or NULL for failure.
1308 char_u *
1309 eval_to_string(arg, nextcmd, convert)
1310 char_u *arg;
1311 char_u **nextcmd;
1312 int convert;
1314 typval_T tv;
1315 char_u *retval;
1316 garray_T ga;
1317 #ifdef FEAT_FLOAT
1318 char_u numbuf[NUMBUFLEN];
1319 #endif
1321 if (eval0(arg, &tv, nextcmd, TRUE) == FAIL)
1322 retval = NULL;
1323 else
1325 if (convert && tv.v_type == VAR_LIST)
1327 ga_init2(&ga, (int)sizeof(char), 80);
1328 if (tv.vval.v_list != NULL)
1329 list_join(&ga, tv.vval.v_list, (char_u *)"\n", TRUE, 0);
1330 ga_append(&ga, NUL);
1331 retval = (char_u *)ga.ga_data;
1333 #ifdef FEAT_FLOAT
1334 else if (convert && tv.v_type == VAR_FLOAT)
1336 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv.vval.v_float);
1337 retval = vim_strsave(numbuf);
1339 #endif
1340 else
1341 retval = vim_strsave(get_tv_string(&tv));
1342 clear_tv(&tv);
1345 return retval;
1349 * Call eval_to_string() without using current local variables and using
1350 * textlock. When "use_sandbox" is TRUE use the sandbox.
1352 char_u *
1353 eval_to_string_safe(arg, nextcmd, use_sandbox)
1354 char_u *arg;
1355 char_u **nextcmd;
1356 int use_sandbox;
1358 char_u *retval;
1359 void *save_funccalp;
1361 save_funccalp = save_funccal();
1362 if (use_sandbox)
1363 ++sandbox;
1364 ++textlock;
1365 retval = eval_to_string(arg, nextcmd, FALSE);
1366 if (use_sandbox)
1367 --sandbox;
1368 --textlock;
1369 restore_funccal(save_funccalp);
1370 return retval;
1374 * Top level evaluation function, returning a number.
1375 * Evaluates "expr" silently.
1376 * Returns -1 for an error.
1379 eval_to_number(expr)
1380 char_u *expr;
1382 typval_T rettv;
1383 int retval;
1384 char_u *p = skipwhite(expr);
1386 ++emsg_off;
1388 if (eval1(&p, &rettv, TRUE) == FAIL)
1389 retval = -1;
1390 else
1392 retval = get_tv_number_chk(&rettv, NULL);
1393 clear_tv(&rettv);
1395 --emsg_off;
1397 return retval;
1401 * Prepare v: variable "idx" to be used.
1402 * Save the current typeval in "save_tv".
1403 * When not used yet add the variable to the v: hashtable.
1405 static void
1406 prepare_vimvar(idx, save_tv)
1407 int idx;
1408 typval_T *save_tv;
1410 *save_tv = vimvars[idx].vv_tv;
1411 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1412 hash_add(&vimvarht, vimvars[idx].vv_di.di_key);
1416 * Restore v: variable "idx" to typeval "save_tv".
1417 * When no longer defined, remove the variable from the v: hashtable.
1419 static void
1420 restore_vimvar(idx, save_tv)
1421 int idx;
1422 typval_T *save_tv;
1424 hashitem_T *hi;
1426 vimvars[idx].vv_tv = *save_tv;
1427 if (vimvars[idx].vv_type == VAR_UNKNOWN)
1429 hi = hash_find(&vimvarht, vimvars[idx].vv_di.di_key);
1430 if (HASHITEM_EMPTY(hi))
1431 EMSG2(_(e_intern2), "restore_vimvar()");
1432 else
1433 hash_remove(&vimvarht, hi);
1437 #if defined(FEAT_SPELL) || defined(PROTO)
1439 * Evaluate an expression to a list with suggestions.
1440 * For the "expr:" part of 'spellsuggest'.
1441 * Returns NULL when there is an error.
1443 list_T *
1444 eval_spell_expr(badword, expr)
1445 char_u *badword;
1446 char_u *expr;
1448 typval_T save_val;
1449 typval_T rettv;
1450 list_T *list = NULL;
1451 char_u *p = skipwhite(expr);
1453 /* Set "v:val" to the bad word. */
1454 prepare_vimvar(VV_VAL, &save_val);
1455 vimvars[VV_VAL].vv_type = VAR_STRING;
1456 vimvars[VV_VAL].vv_str = badword;
1457 if (p_verbose == 0)
1458 ++emsg_off;
1460 if (eval1(&p, &rettv, TRUE) == OK)
1462 if (rettv.v_type != VAR_LIST)
1463 clear_tv(&rettv);
1464 else
1465 list = rettv.vval.v_list;
1468 if (p_verbose == 0)
1469 --emsg_off;
1470 restore_vimvar(VV_VAL, &save_val);
1472 return list;
1476 * "list" is supposed to contain two items: a word and a number. Return the
1477 * word in "pp" and the number as the return value.
1478 * Return -1 if anything isn't right.
1479 * Used to get the good word and score from the eval_spell_expr() result.
1482 get_spellword(list, pp)
1483 list_T *list;
1484 char_u **pp;
1486 listitem_T *li;
1488 li = list->lv_first;
1489 if (li == NULL)
1490 return -1;
1491 *pp = get_tv_string(&li->li_tv);
1493 li = li->li_next;
1494 if (li == NULL)
1495 return -1;
1496 return get_tv_number(&li->li_tv);
1498 #endif
1501 * Top level evaluation function.
1502 * Returns an allocated typval_T with the result.
1503 * Returns NULL when there is an error.
1505 typval_T *
1506 eval_expr(arg, nextcmd)
1507 char_u *arg;
1508 char_u **nextcmd;
1510 typval_T *tv;
1512 tv = (typval_T *)alloc(sizeof(typval_T));
1513 if (tv != NULL && eval0(arg, tv, nextcmd, TRUE) == FAIL)
1515 vim_free(tv);
1516 tv = NULL;
1519 return tv;
1523 #if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) \
1524 || defined(FEAT_COMPL_FUNC) || defined(PROTO)
1526 * Call some vimL function and return the result in "*rettv".
1527 * Uses argv[argc] for the function arguments. Only Number and String
1528 * arguments are currently supported.
1529 * Returns OK or FAIL.
1531 static int
1532 call_vim_function(func, argc, argv, safe, rettv)
1533 char_u *func;
1534 int argc;
1535 char_u **argv;
1536 int safe; /* use the sandbox */
1537 typval_T *rettv;
1539 typval_T *argvars;
1540 long n;
1541 int len;
1542 int i;
1543 int doesrange;
1544 void *save_funccalp = NULL;
1545 int ret;
1547 argvars = (typval_T *)alloc((unsigned)((argc + 1) * sizeof(typval_T)));
1548 if (argvars == NULL)
1549 return FAIL;
1551 for (i = 0; i < argc; i++)
1553 /* Pass a NULL or empty argument as an empty string */
1554 if (argv[i] == NULL || *argv[i] == NUL)
1556 argvars[i].v_type = VAR_STRING;
1557 argvars[i].vval.v_string = (char_u *)"";
1558 continue;
1561 /* Recognize a number argument, the others must be strings. */
1562 vim_str2nr(argv[i], NULL, &len, TRUE, TRUE, &n, NULL);
1563 if (len != 0 && len == (int)STRLEN(argv[i]))
1565 argvars[i].v_type = VAR_NUMBER;
1566 argvars[i].vval.v_number = n;
1568 else
1570 argvars[i].v_type = VAR_STRING;
1571 argvars[i].vval.v_string = argv[i];
1575 if (safe)
1577 save_funccalp = save_funccal();
1578 ++sandbox;
1581 rettv->v_type = VAR_UNKNOWN; /* clear_tv() uses this */
1582 ret = call_func(func, (int)STRLEN(func), rettv, argc, argvars,
1583 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
1584 &doesrange, TRUE, NULL);
1585 if (safe)
1587 --sandbox;
1588 restore_funccal(save_funccalp);
1590 vim_free(argvars);
1592 if (ret == FAIL)
1593 clear_tv(rettv);
1595 return ret;
1598 # if (defined(FEAT_USR_CMDS) && defined(FEAT_CMDL_COMPL)) || defined(PROTO)
1600 * Call vimL function "func" and return the result as a string.
1601 * Returns NULL when calling the function fails.
1602 * Uses argv[argc] for the function arguments.
1604 void *
1605 call_func_retstr(func, argc, argv, safe)
1606 char_u *func;
1607 int argc;
1608 char_u **argv;
1609 int safe; /* use the sandbox */
1611 typval_T rettv;
1612 char_u *retval;
1614 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1615 return NULL;
1617 retval = vim_strsave(get_tv_string(&rettv));
1618 clear_tv(&rettv);
1619 return retval;
1621 # endif
1623 # if defined(FEAT_COMPL_FUNC) || defined(PROTO)
1625 * Call vimL function "func" and return the result as a number.
1626 * Returns -1 when calling the function fails.
1627 * Uses argv[argc] for the function arguments.
1629 long
1630 call_func_retnr(func, argc, argv, safe)
1631 char_u *func;
1632 int argc;
1633 char_u **argv;
1634 int safe; /* use the sandbox */
1636 typval_T rettv;
1637 long retval;
1639 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1640 return -1;
1642 retval = get_tv_number_chk(&rettv, NULL);
1643 clear_tv(&rettv);
1644 return retval;
1646 # endif
1649 * Call vimL function "func" and return the result as a List.
1650 * Uses argv[argc] for the function arguments.
1651 * Returns NULL when there is something wrong.
1653 void *
1654 call_func_retlist(func, argc, argv, safe)
1655 char_u *func;
1656 int argc;
1657 char_u **argv;
1658 int safe; /* use the sandbox */
1660 typval_T rettv;
1662 if (call_vim_function(func, argc, argv, safe, &rettv) == FAIL)
1663 return NULL;
1665 if (rettv.v_type != VAR_LIST)
1667 clear_tv(&rettv);
1668 return NULL;
1671 return rettv.vval.v_list;
1673 #endif
1677 * Save the current function call pointer, and set it to NULL.
1678 * Used when executing autocommands and for ":source".
1680 void *
1681 save_funccal()
1683 funccall_T *fc = current_funccal;
1685 current_funccal = NULL;
1686 return (void *)fc;
1689 void
1690 restore_funccal(vfc)
1691 void *vfc;
1693 funccall_T *fc = (funccall_T *)vfc;
1695 current_funccal = fc;
1698 #if defined(FEAT_PROFILE) || defined(PROTO)
1700 * Prepare profiling for entering a child or something else that is not
1701 * counted for the script/function itself.
1702 * Should always be called in pair with prof_child_exit().
1704 void
1705 prof_child_enter(tm)
1706 proftime_T *tm; /* place to store waittime */
1708 funccall_T *fc = current_funccal;
1710 if (fc != NULL && fc->func->uf_profiling)
1711 profile_start(&fc->prof_child);
1712 script_prof_save(tm);
1716 * Take care of time spent in a child.
1717 * Should always be called after prof_child_enter().
1719 void
1720 prof_child_exit(tm)
1721 proftime_T *tm; /* where waittime was stored */
1723 funccall_T *fc = current_funccal;
1725 if (fc != NULL && fc->func->uf_profiling)
1727 profile_end(&fc->prof_child);
1728 profile_sub_wait(tm, &fc->prof_child); /* don't count waiting time */
1729 profile_add(&fc->func->uf_tm_children, &fc->prof_child);
1730 profile_add(&fc->func->uf_tml_children, &fc->prof_child);
1732 script_prof_restore(tm);
1734 #endif
1737 #ifdef FEAT_FOLDING
1739 * Evaluate 'foldexpr'. Returns the foldlevel, and any character preceding
1740 * it in "*cp". Doesn't give error messages.
1743 eval_foldexpr(arg, cp)
1744 char_u *arg;
1745 int *cp;
1747 typval_T tv;
1748 int retval;
1749 char_u *s;
1750 int use_sandbox = was_set_insecurely((char_u *)"foldexpr",
1751 OPT_LOCAL);
1753 ++emsg_off;
1754 if (use_sandbox)
1755 ++sandbox;
1756 ++textlock;
1757 *cp = NUL;
1758 if (eval0(arg, &tv, NULL, TRUE) == FAIL)
1759 retval = 0;
1760 else
1762 /* If the result is a number, just return the number. */
1763 if (tv.v_type == VAR_NUMBER)
1764 retval = tv.vval.v_number;
1765 else if (tv.v_type != VAR_STRING || tv.vval.v_string == NULL)
1766 retval = 0;
1767 else
1769 /* If the result is a string, check if there is a non-digit before
1770 * the number. */
1771 s = tv.vval.v_string;
1772 if (!VIM_ISDIGIT(*s) && *s != '-')
1773 *cp = *s++;
1774 retval = atol((char *)s);
1776 clear_tv(&tv);
1778 --emsg_off;
1779 if (use_sandbox)
1780 --sandbox;
1781 --textlock;
1783 return retval;
1785 #endif
1788 * ":let" list all variable values
1789 * ":let var1 var2" list variable values
1790 * ":let var = expr" assignment command.
1791 * ":let var += expr" assignment command.
1792 * ":let var -= expr" assignment command.
1793 * ":let var .= expr" assignment command.
1794 * ":let [var1, var2] = expr" unpack list.
1796 void
1797 ex_let(eap)
1798 exarg_T *eap;
1800 char_u *arg = eap->arg;
1801 char_u *expr = NULL;
1802 typval_T rettv;
1803 int i;
1804 int var_count = 0;
1805 int semicolon = 0;
1806 char_u op[2];
1807 char_u *argend;
1808 int first = TRUE;
1810 argend = skip_var_list(arg, &var_count, &semicolon);
1811 if (argend == NULL)
1812 return;
1813 if (argend > arg && argend[-1] == '.') /* for var.='str' */
1814 --argend;
1815 expr = vim_strchr(argend, '=');
1816 if (expr == NULL)
1819 * ":let" without "=": list variables
1821 if (*arg == '[')
1822 EMSG(_(e_invarg));
1823 else if (!ends_excmd(*arg))
1824 /* ":let var1 var2" */
1825 arg = list_arg_vars(eap, arg, &first);
1826 else if (!eap->skip)
1828 /* ":let" */
1829 list_glob_vars(&first);
1830 list_buf_vars(&first);
1831 list_win_vars(&first);
1832 #ifdef FEAT_WINDOWS
1833 list_tab_vars(&first);
1834 #endif
1835 list_script_vars(&first);
1836 list_func_vars(&first);
1837 list_vim_vars(&first);
1839 eap->nextcmd = check_nextcmd(arg);
1841 else
1843 op[0] = '=';
1844 op[1] = NUL;
1845 if (expr > argend)
1847 if (vim_strchr((char_u *)"+-.", expr[-1]) != NULL)
1848 op[0] = expr[-1]; /* +=, -= or .= */
1850 expr = skipwhite(expr + 1);
1852 if (eap->skip)
1853 ++emsg_skip;
1854 i = eval0(expr, &rettv, &eap->nextcmd, !eap->skip);
1855 if (eap->skip)
1857 if (i != FAIL)
1858 clear_tv(&rettv);
1859 --emsg_skip;
1861 else if (i != FAIL)
1863 (void)ex_let_vars(eap->arg, &rettv, FALSE, semicolon, var_count,
1864 op);
1865 clear_tv(&rettv);
1871 * Assign the typevalue "tv" to the variable or variables at "arg_start".
1872 * Handles both "var" with any type and "[var, var; var]" with a list type.
1873 * When "nextchars" is not NULL it points to a string with characters that
1874 * must appear after the variable(s). Use "+", "-" or "." for add, subtract
1875 * or concatenate.
1876 * Returns OK or FAIL;
1878 static int
1879 ex_let_vars(arg_start, tv, copy, semicolon, var_count, nextchars)
1880 char_u *arg_start;
1881 typval_T *tv;
1882 int copy; /* copy values from "tv", don't move */
1883 int semicolon; /* from skip_var_list() */
1884 int var_count; /* from skip_var_list() */
1885 char_u *nextchars;
1887 char_u *arg = arg_start;
1888 list_T *l;
1889 int i;
1890 listitem_T *item;
1891 typval_T ltv;
1893 if (*arg != '[')
1896 * ":let var = expr" or ":for var in list"
1898 if (ex_let_one(arg, tv, copy, nextchars, nextchars) == NULL)
1899 return FAIL;
1900 return OK;
1904 * ":let [v1, v2] = list" or ":for [v1, v2] in listlist"
1906 if (tv->v_type != VAR_LIST || (l = tv->vval.v_list) == NULL)
1908 EMSG(_(e_listreq));
1909 return FAIL;
1912 i = list_len(l);
1913 if (semicolon == 0 && var_count < i)
1915 EMSG(_("E687: Less targets than List items"));
1916 return FAIL;
1918 if (var_count - semicolon > i)
1920 EMSG(_("E688: More targets than List items"));
1921 return FAIL;
1924 item = l->lv_first;
1925 while (*arg != ']')
1927 arg = skipwhite(arg + 1);
1928 arg = ex_let_one(arg, &item->li_tv, TRUE, (char_u *)",;]", nextchars);
1929 item = item->li_next;
1930 if (arg == NULL)
1931 return FAIL;
1933 arg = skipwhite(arg);
1934 if (*arg == ';')
1936 /* Put the rest of the list (may be empty) in the var after ';'.
1937 * Create a new list for this. */
1938 l = list_alloc();
1939 if (l == NULL)
1940 return FAIL;
1941 while (item != NULL)
1943 list_append_tv(l, &item->li_tv);
1944 item = item->li_next;
1947 ltv.v_type = VAR_LIST;
1948 ltv.v_lock = 0;
1949 ltv.vval.v_list = l;
1950 l->lv_refcount = 1;
1952 arg = ex_let_one(skipwhite(arg + 1), &ltv, FALSE,
1953 (char_u *)"]", nextchars);
1954 clear_tv(&ltv);
1955 if (arg == NULL)
1956 return FAIL;
1957 break;
1959 else if (*arg != ',' && *arg != ']')
1961 EMSG2(_(e_intern2), "ex_let_vars()");
1962 return FAIL;
1966 return OK;
1970 * Skip over assignable variable "var" or list of variables "[var, var]".
1971 * Used for ":let varvar = expr" and ":for varvar in expr".
1972 * For "[var, var]" increment "*var_count" for each variable.
1973 * for "[var, var; var]" set "semicolon".
1974 * Return NULL for an error.
1976 static char_u *
1977 skip_var_list(arg, var_count, semicolon)
1978 char_u *arg;
1979 int *var_count;
1980 int *semicolon;
1982 char_u *p, *s;
1984 if (*arg == '[')
1986 /* "[var, var]": find the matching ']'. */
1987 p = arg;
1988 for (;;)
1990 p = skipwhite(p + 1); /* skip whites after '[', ';' or ',' */
1991 s = skip_var_one(p);
1992 if (s == p)
1994 EMSG2(_(e_invarg2), p);
1995 return NULL;
1997 ++*var_count;
1999 p = skipwhite(s);
2000 if (*p == ']')
2001 break;
2002 else if (*p == ';')
2004 if (*semicolon == 1)
2006 EMSG(_("Double ; in list of variables"));
2007 return NULL;
2009 *semicolon = 1;
2011 else if (*p != ',')
2013 EMSG2(_(e_invarg2), p);
2014 return NULL;
2017 return p + 1;
2019 else
2020 return skip_var_one(arg);
2024 * Skip one (assignable) variable name, including @r, $VAR, &option, d.key,
2025 * l[idx].
2027 static char_u *
2028 skip_var_one(arg)
2029 char_u *arg;
2031 if (*arg == '@' && arg[1] != NUL)
2032 return arg + 2;
2033 return find_name_end(*arg == '$' || *arg == '&' ? arg + 1 : arg,
2034 NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2038 * List variables for hashtab "ht" with prefix "prefix".
2039 * If "empty" is TRUE also list NULL strings as empty strings.
2041 static void
2042 list_hashtable_vars(ht, prefix, empty, first)
2043 hashtab_T *ht;
2044 char_u *prefix;
2045 int empty;
2046 int *first;
2048 hashitem_T *hi;
2049 dictitem_T *di;
2050 int todo;
2052 todo = (int)ht->ht_used;
2053 for (hi = ht->ht_array; todo > 0 && !got_int; ++hi)
2055 if (!HASHITEM_EMPTY(hi))
2057 --todo;
2058 di = HI2DI(hi);
2059 if (empty || di->di_tv.v_type != VAR_STRING
2060 || di->di_tv.vval.v_string != NULL)
2061 list_one_var(di, prefix, first);
2067 * List global variables.
2069 static void
2070 list_glob_vars(first)
2071 int *first;
2073 list_hashtable_vars(&globvarht, (char_u *)"", TRUE, first);
2077 * List buffer variables.
2079 static void
2080 list_buf_vars(first)
2081 int *first;
2083 char_u numbuf[NUMBUFLEN];
2085 list_hashtable_vars(&curbuf->b_vars.dv_hashtab, (char_u *)"b:",
2086 TRUE, first);
2088 sprintf((char *)numbuf, "%ld", (long)curbuf->b_changedtick);
2089 list_one_var_a((char_u *)"b:", (char_u *)"changedtick", VAR_NUMBER,
2090 numbuf, first);
2094 * List window variables.
2096 static void
2097 list_win_vars(first)
2098 int *first;
2100 list_hashtable_vars(&curwin->w_vars.dv_hashtab,
2101 (char_u *)"w:", TRUE, first);
2104 #ifdef FEAT_WINDOWS
2106 * List tab page variables.
2108 static void
2109 list_tab_vars(first)
2110 int *first;
2112 list_hashtable_vars(&curtab->tp_vars.dv_hashtab,
2113 (char_u *)"t:", TRUE, first);
2115 #endif
2118 * List Vim variables.
2120 static void
2121 list_vim_vars(first)
2122 int *first;
2124 list_hashtable_vars(&vimvarht, (char_u *)"v:", FALSE, first);
2128 * List script-local variables, if there is a script.
2130 static void
2131 list_script_vars(first)
2132 int *first;
2134 if (current_SID > 0 && current_SID <= ga_scripts.ga_len)
2135 list_hashtable_vars(&SCRIPT_VARS(current_SID),
2136 (char_u *)"s:", FALSE, first);
2140 * List function variables, if there is a function.
2142 static void
2143 list_func_vars(first)
2144 int *first;
2146 if (current_funccal != NULL)
2147 list_hashtable_vars(&current_funccal->l_vars.dv_hashtab,
2148 (char_u *)"l:", FALSE, first);
2152 * List variables in "arg".
2154 static char_u *
2155 list_arg_vars(eap, arg, first)
2156 exarg_T *eap;
2157 char_u *arg;
2158 int *first;
2160 int error = FALSE;
2161 int len;
2162 char_u *name;
2163 char_u *name_start;
2164 char_u *arg_subsc;
2165 char_u *tofree;
2166 typval_T tv;
2168 while (!ends_excmd(*arg) && !got_int)
2170 if (error || eap->skip)
2172 arg = find_name_end(arg, NULL, NULL, FNE_INCL_BR | FNE_CHECK_START);
2173 if (!vim_iswhite(*arg) && !ends_excmd(*arg))
2175 emsg_severe = TRUE;
2176 EMSG(_(e_trailing));
2177 break;
2180 else
2182 /* get_name_len() takes care of expanding curly braces */
2183 name_start = name = arg;
2184 len = get_name_len(&arg, &tofree, TRUE, TRUE);
2185 if (len <= 0)
2187 /* This is mainly to keep test 49 working: when expanding
2188 * curly braces fails overrule the exception error message. */
2189 if (len < 0 && !aborting())
2191 emsg_severe = TRUE;
2192 EMSG2(_(e_invarg2), arg);
2193 break;
2195 error = TRUE;
2197 else
2199 if (tofree != NULL)
2200 name = tofree;
2201 if (get_var_tv(name, len, &tv, TRUE) == FAIL)
2202 error = TRUE;
2203 else
2205 /* handle d.key, l[idx], f(expr) */
2206 arg_subsc = arg;
2207 if (handle_subscript(&arg, &tv, TRUE, TRUE) == FAIL)
2208 error = TRUE;
2209 else
2211 if (arg == arg_subsc && len == 2 && name[1] == ':')
2213 switch (*name)
2215 case 'g': list_glob_vars(first); break;
2216 case 'b': list_buf_vars(first); break;
2217 case 'w': list_win_vars(first); break;
2218 #ifdef FEAT_WINDOWS
2219 case 't': list_tab_vars(first); break;
2220 #endif
2221 case 'v': list_vim_vars(first); break;
2222 case 's': list_script_vars(first); break;
2223 case 'l': list_func_vars(first); break;
2224 default:
2225 EMSG2(_("E738: Can't list variables for %s"), name);
2228 else
2230 char_u numbuf[NUMBUFLEN];
2231 char_u *tf;
2232 int c;
2233 char_u *s;
2235 s = echo_string(&tv, &tf, numbuf, 0);
2236 c = *arg;
2237 *arg = NUL;
2238 list_one_var_a((char_u *)"",
2239 arg == arg_subsc ? name : name_start,
2240 tv.v_type,
2241 s == NULL ? (char_u *)"" : s,
2242 first);
2243 *arg = c;
2244 vim_free(tf);
2246 clear_tv(&tv);
2251 vim_free(tofree);
2254 arg = skipwhite(arg);
2257 return arg;
2261 * Set one item of ":let var = expr" or ":let [v1, v2] = list" to its value.
2262 * Returns a pointer to the char just after the var name.
2263 * Returns NULL if there is an error.
2265 static char_u *
2266 ex_let_one(arg, tv, copy, endchars, op)
2267 char_u *arg; /* points to variable name */
2268 typval_T *tv; /* value to assign to variable */
2269 int copy; /* copy value from "tv" */
2270 char_u *endchars; /* valid chars after variable name or NULL */
2271 char_u *op; /* "+", "-", "." or NULL*/
2273 int c1;
2274 char_u *name;
2275 char_u *p;
2276 char_u *arg_end = NULL;
2277 int len;
2278 int opt_flags;
2279 char_u *tofree = NULL;
2282 * ":let $VAR = expr": Set environment variable.
2284 if (*arg == '$')
2286 /* Find the end of the name. */
2287 ++arg;
2288 name = arg;
2289 len = get_env_len(&arg);
2290 if (len == 0)
2291 EMSG2(_(e_invarg2), name - 1);
2292 else
2294 if (op != NULL && (*op == '+' || *op == '-'))
2295 EMSG2(_(e_letwrong), op);
2296 else if (endchars != NULL
2297 && vim_strchr(endchars, *skipwhite(arg)) == NULL)
2298 EMSG(_(e_letunexp));
2299 else
2301 c1 = name[len];
2302 name[len] = NUL;
2303 p = get_tv_string_chk(tv);
2304 if (p != NULL && op != NULL && *op == '.')
2306 int mustfree = FALSE;
2307 char_u *s = vim_getenv(name, &mustfree);
2309 if (s != NULL)
2311 p = tofree = concat_str(s, p);
2312 if (mustfree)
2313 vim_free(s);
2316 if (p != NULL)
2318 vim_setenv(name, p);
2319 if (STRICMP(name, "HOME") == 0)
2320 init_homedir();
2321 else if (didset_vim && STRICMP(name, "VIM") == 0)
2322 didset_vim = FALSE;
2323 else if (didset_vimruntime
2324 && STRICMP(name, "VIMRUNTIME") == 0)
2325 didset_vimruntime = FALSE;
2326 arg_end = arg;
2328 name[len] = c1;
2329 vim_free(tofree);
2335 * ":let &option = expr": Set option value.
2336 * ":let &l:option = expr": Set local option value.
2337 * ":let &g:option = expr": Set global option value.
2339 else if (*arg == '&')
2341 /* Find the end of the name. */
2342 p = find_option_end(&arg, &opt_flags);
2343 if (p == NULL || (endchars != NULL
2344 && vim_strchr(endchars, *skipwhite(p)) == NULL))
2345 EMSG(_(e_letunexp));
2346 else
2348 long n;
2349 int opt_type;
2350 long numval;
2351 char_u *stringval = NULL;
2352 char_u *s;
2354 c1 = *p;
2355 *p = NUL;
2357 n = get_tv_number(tv);
2358 s = get_tv_string_chk(tv); /* != NULL if number or string */
2359 if (s != NULL && op != NULL && *op != '=')
2361 opt_type = get_option_value(arg, &numval,
2362 &stringval, opt_flags);
2363 if ((opt_type == 1 && *op == '.')
2364 || (opt_type == 0 && *op != '.'))
2365 EMSG2(_(e_letwrong), op);
2366 else
2368 if (opt_type == 1) /* number */
2370 if (*op == '+')
2371 n = numval + n;
2372 else
2373 n = numval - n;
2375 else if (opt_type == 0 && stringval != NULL) /* string */
2377 s = concat_str(stringval, s);
2378 vim_free(stringval);
2379 stringval = s;
2383 if (s != NULL)
2385 set_option_value(arg, n, s, opt_flags);
2386 arg_end = p;
2388 *p = c1;
2389 vim_free(stringval);
2394 * ":let @r = expr": Set register contents.
2396 else if (*arg == '@')
2398 ++arg;
2399 if (op != NULL && (*op == '+' || *op == '-'))
2400 EMSG2(_(e_letwrong), op);
2401 else if (endchars != NULL
2402 && vim_strchr(endchars, *skipwhite(arg + 1)) == NULL)
2403 EMSG(_(e_letunexp));
2404 else
2406 char_u *ptofree = NULL;
2407 char_u *s;
2409 p = get_tv_string_chk(tv);
2410 if (p != NULL && op != NULL && *op == '.')
2412 s = get_reg_contents(*arg == '@' ? '"' : *arg, TRUE, TRUE);
2413 if (s != NULL)
2415 p = ptofree = concat_str(s, p);
2416 vim_free(s);
2419 if (p != NULL)
2421 write_reg_contents(*arg == '@' ? '"' : *arg, p, -1, FALSE);
2422 arg_end = arg + 1;
2424 vim_free(ptofree);
2429 * ":let var = expr": Set internal variable.
2430 * ":let {expr} = expr": Idem, name made with curly braces
2432 else if (eval_isnamec1(*arg) || *arg == '{')
2434 lval_T lv;
2436 p = get_lval(arg, tv, &lv, FALSE, FALSE, FALSE, FNE_CHECK_START);
2437 if (p != NULL && lv.ll_name != NULL)
2439 if (endchars != NULL && vim_strchr(endchars, *skipwhite(p)) == NULL)
2440 EMSG(_(e_letunexp));
2441 else
2443 set_var_lval(&lv, p, tv, copy, op);
2444 arg_end = p;
2447 clear_lval(&lv);
2450 else
2451 EMSG2(_(e_invarg2), arg);
2453 return arg_end;
2457 * If "arg" is equal to "b:changedtick" give an error and return TRUE.
2459 static int
2460 check_changedtick(arg)
2461 char_u *arg;
2463 if (STRNCMP(arg, "b:changedtick", 13) == 0 && !eval_isnamec(arg[13]))
2465 EMSG2(_(e_readonlyvar), arg);
2466 return TRUE;
2468 return FALSE;
2472 * Get an lval: variable, Dict item or List item that can be assigned a value
2473 * to: "name", "na{me}", "name[expr]", "name[expr:expr]", "name[expr][expr]",
2474 * "name.key", "name.key[expr]" etc.
2475 * Indexing only works if "name" is an existing List or Dictionary.
2476 * "name" points to the start of the name.
2477 * If "rettv" is not NULL it points to the value to be assigned.
2478 * "unlet" is TRUE for ":unlet": slightly different behavior when something is
2479 * wrong; must end in space or cmd separator.
2481 * Returns a pointer to just after the name, including indexes.
2482 * When an evaluation error occurs "lp->ll_name" is NULL;
2483 * Returns NULL for a parsing error. Still need to free items in "lp"!
2485 static char_u *
2486 get_lval(name, rettv, lp, unlet, skip, quiet, fne_flags)
2487 char_u *name;
2488 typval_T *rettv;
2489 lval_T *lp;
2490 int unlet;
2491 int skip;
2492 int quiet; /* don't give error messages */
2493 int fne_flags; /* flags for find_name_end() */
2495 char_u *p;
2496 char_u *expr_start, *expr_end;
2497 int cc;
2498 dictitem_T *v;
2499 typval_T var1;
2500 typval_T var2;
2501 int empty1 = FALSE;
2502 listitem_T *ni;
2503 char_u *key = NULL;
2504 int len;
2505 hashtab_T *ht;
2507 /* Clear everything in "lp". */
2508 vim_memset(lp, 0, sizeof(lval_T));
2510 if (skip)
2512 /* When skipping just find the end of the name. */
2513 lp->ll_name = name;
2514 return find_name_end(name, NULL, NULL, FNE_INCL_BR | fne_flags);
2517 /* Find the end of the name. */
2518 p = find_name_end(name, &expr_start, &expr_end, fne_flags);
2519 if (expr_start != NULL)
2521 /* Don't expand the name when we already know there is an error. */
2522 if (unlet && !vim_iswhite(*p) && !ends_excmd(*p)
2523 && *p != '[' && *p != '.')
2525 EMSG(_(e_trailing));
2526 return NULL;
2529 lp->ll_exp_name = make_expanded_name(name, expr_start, expr_end, p);
2530 if (lp->ll_exp_name == NULL)
2532 /* Report an invalid expression in braces, unless the
2533 * expression evaluation has been cancelled due to an
2534 * aborting error, an interrupt, or an exception. */
2535 if (!aborting() && !quiet)
2537 emsg_severe = TRUE;
2538 EMSG2(_(e_invarg2), name);
2539 return NULL;
2542 lp->ll_name = lp->ll_exp_name;
2544 else
2545 lp->ll_name = name;
2547 /* Without [idx] or .key we are done. */
2548 if ((*p != '[' && *p != '.') || lp->ll_name == NULL)
2549 return p;
2551 cc = *p;
2552 *p = NUL;
2553 v = find_var(lp->ll_name, &ht);
2554 if (v == NULL && !quiet)
2555 EMSG2(_(e_undefvar), lp->ll_name);
2556 *p = cc;
2557 if (v == NULL)
2558 return NULL;
2561 * Loop until no more [idx] or .key is following.
2563 lp->ll_tv = &v->di_tv;
2564 while (*p == '[' || (*p == '.' && lp->ll_tv->v_type == VAR_DICT))
2566 if (!(lp->ll_tv->v_type == VAR_LIST && lp->ll_tv->vval.v_list != NULL)
2567 && !(lp->ll_tv->v_type == VAR_DICT
2568 && lp->ll_tv->vval.v_dict != NULL))
2570 if (!quiet)
2571 EMSG(_("E689: Can only index a List or Dictionary"));
2572 return NULL;
2574 if (lp->ll_range)
2576 if (!quiet)
2577 EMSG(_("E708: [:] must come last"));
2578 return NULL;
2581 len = -1;
2582 if (*p == '.')
2584 key = p + 1;
2585 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
2587 if (len == 0)
2589 if (!quiet)
2590 EMSG(_(e_emptykey));
2591 return NULL;
2593 p = key + len;
2595 else
2597 /* Get the index [expr] or the first index [expr: ]. */
2598 p = skipwhite(p + 1);
2599 if (*p == ':')
2600 empty1 = TRUE;
2601 else
2603 empty1 = FALSE;
2604 if (eval1(&p, &var1, TRUE) == FAIL) /* recursive! */
2605 return NULL;
2606 if (get_tv_string_chk(&var1) == NULL)
2608 /* not a number or string */
2609 clear_tv(&var1);
2610 return NULL;
2614 /* Optionally get the second index [ :expr]. */
2615 if (*p == ':')
2617 if (lp->ll_tv->v_type == VAR_DICT)
2619 if (!quiet)
2620 EMSG(_(e_dictrange));
2621 if (!empty1)
2622 clear_tv(&var1);
2623 return NULL;
2625 if (rettv != NULL && (rettv->v_type != VAR_LIST
2626 || rettv->vval.v_list == NULL))
2628 if (!quiet)
2629 EMSG(_("E709: [:] requires a List value"));
2630 if (!empty1)
2631 clear_tv(&var1);
2632 return NULL;
2634 p = skipwhite(p + 1);
2635 if (*p == ']')
2636 lp->ll_empty2 = TRUE;
2637 else
2639 lp->ll_empty2 = FALSE;
2640 if (eval1(&p, &var2, TRUE) == FAIL) /* recursive! */
2642 if (!empty1)
2643 clear_tv(&var1);
2644 return NULL;
2646 if (get_tv_string_chk(&var2) == NULL)
2648 /* not a number or string */
2649 if (!empty1)
2650 clear_tv(&var1);
2651 clear_tv(&var2);
2652 return NULL;
2655 lp->ll_range = TRUE;
2657 else
2658 lp->ll_range = FALSE;
2660 if (*p != ']')
2662 if (!quiet)
2663 EMSG(_(e_missbrac));
2664 if (!empty1)
2665 clear_tv(&var1);
2666 if (lp->ll_range && !lp->ll_empty2)
2667 clear_tv(&var2);
2668 return NULL;
2671 /* Skip to past ']'. */
2672 ++p;
2675 if (lp->ll_tv->v_type == VAR_DICT)
2677 if (len == -1)
2679 /* "[key]": get key from "var1" */
2680 key = get_tv_string(&var1); /* is number or string */
2681 if (*key == NUL)
2683 if (!quiet)
2684 EMSG(_(e_emptykey));
2685 clear_tv(&var1);
2686 return NULL;
2689 lp->ll_list = NULL;
2690 lp->ll_dict = lp->ll_tv->vval.v_dict;
2691 lp->ll_di = dict_find(lp->ll_dict, key, len);
2692 if (lp->ll_di == NULL)
2694 /* Key does not exist in dict: may need to add it. */
2695 if (*p == '[' || *p == '.' || unlet)
2697 if (!quiet)
2698 EMSG2(_(e_dictkey), key);
2699 if (len == -1)
2700 clear_tv(&var1);
2701 return NULL;
2703 if (len == -1)
2704 lp->ll_newkey = vim_strsave(key);
2705 else
2706 lp->ll_newkey = vim_strnsave(key, len);
2707 if (len == -1)
2708 clear_tv(&var1);
2709 if (lp->ll_newkey == NULL)
2710 p = NULL;
2711 break;
2713 if (len == -1)
2714 clear_tv(&var1);
2715 lp->ll_tv = &lp->ll_di->di_tv;
2717 else
2720 * Get the number and item for the only or first index of the List.
2722 if (empty1)
2723 lp->ll_n1 = 0;
2724 else
2726 lp->ll_n1 = get_tv_number(&var1); /* is number or string */
2727 clear_tv(&var1);
2729 lp->ll_dict = NULL;
2730 lp->ll_list = lp->ll_tv->vval.v_list;
2731 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2732 if (lp->ll_li == NULL)
2734 if (lp->ll_n1 < 0)
2736 lp->ll_n1 = 0;
2737 lp->ll_li = list_find(lp->ll_list, lp->ll_n1);
2740 if (lp->ll_li == NULL)
2742 if (lp->ll_range && !lp->ll_empty2)
2743 clear_tv(&var2);
2744 return NULL;
2748 * May need to find the item or absolute index for the second
2749 * index of a range.
2750 * When no index given: "lp->ll_empty2" is TRUE.
2751 * Otherwise "lp->ll_n2" is set to the second index.
2753 if (lp->ll_range && !lp->ll_empty2)
2755 lp->ll_n2 = get_tv_number(&var2); /* is number or string */
2756 clear_tv(&var2);
2757 if (lp->ll_n2 < 0)
2759 ni = list_find(lp->ll_list, lp->ll_n2);
2760 if (ni == NULL)
2761 return NULL;
2762 lp->ll_n2 = list_idx_of_item(lp->ll_list, ni);
2765 /* Check that lp->ll_n2 isn't before lp->ll_n1. */
2766 if (lp->ll_n1 < 0)
2767 lp->ll_n1 = list_idx_of_item(lp->ll_list, lp->ll_li);
2768 if (lp->ll_n2 < lp->ll_n1)
2769 return NULL;
2772 lp->ll_tv = &lp->ll_li->li_tv;
2776 return p;
2780 * Clear lval "lp" that was filled by get_lval().
2782 static void
2783 clear_lval(lp)
2784 lval_T *lp;
2786 vim_free(lp->ll_exp_name);
2787 vim_free(lp->ll_newkey);
2791 * Set a variable that was parsed by get_lval() to "rettv".
2792 * "endp" points to just after the parsed name.
2793 * "op" is NULL, "+" for "+=", "-" for "-=", "." for ".=" or "=" for "=".
2795 static void
2796 set_var_lval(lp, endp, rettv, copy, op)
2797 lval_T *lp;
2798 char_u *endp;
2799 typval_T *rettv;
2800 int copy;
2801 char_u *op;
2803 int cc;
2804 listitem_T *ri;
2805 dictitem_T *di;
2807 if (lp->ll_tv == NULL)
2809 if (!check_changedtick(lp->ll_name))
2811 cc = *endp;
2812 *endp = NUL;
2813 if (op != NULL && *op != '=')
2815 typval_T tv;
2817 /* handle +=, -= and .= */
2818 if (get_var_tv(lp->ll_name, (int)STRLEN(lp->ll_name),
2819 &tv, TRUE) == OK)
2821 if (tv_op(&tv, rettv, op) == OK)
2822 set_var(lp->ll_name, &tv, FALSE);
2823 clear_tv(&tv);
2826 else
2827 set_var(lp->ll_name, rettv, copy);
2828 *endp = cc;
2831 else if (tv_check_lock(lp->ll_newkey == NULL
2832 ? lp->ll_tv->v_lock
2833 : lp->ll_tv->vval.v_dict->dv_lock, lp->ll_name))
2835 else if (lp->ll_range)
2838 * Assign the List values to the list items.
2840 for (ri = rettv->vval.v_list->lv_first; ri != NULL; )
2842 if (op != NULL && *op != '=')
2843 tv_op(&lp->ll_li->li_tv, &ri->li_tv, op);
2844 else
2846 clear_tv(&lp->ll_li->li_tv);
2847 copy_tv(&ri->li_tv, &lp->ll_li->li_tv);
2849 ri = ri->li_next;
2850 if (ri == NULL || (!lp->ll_empty2 && lp->ll_n2 == lp->ll_n1))
2851 break;
2852 if (lp->ll_li->li_next == NULL)
2854 /* Need to add an empty item. */
2855 if (list_append_number(lp->ll_list, 0) == FAIL)
2857 ri = NULL;
2858 break;
2861 lp->ll_li = lp->ll_li->li_next;
2862 ++lp->ll_n1;
2864 if (ri != NULL)
2865 EMSG(_("E710: List value has more items than target"));
2866 else if (lp->ll_empty2
2867 ? (lp->ll_li != NULL && lp->ll_li->li_next != NULL)
2868 : lp->ll_n1 != lp->ll_n2)
2869 EMSG(_("E711: List value has not enough items"));
2871 else
2874 * Assign to a List or Dictionary item.
2876 if (lp->ll_newkey != NULL)
2878 if (op != NULL && *op != '=')
2880 EMSG2(_(e_letwrong), op);
2881 return;
2884 /* Need to add an item to the Dictionary. */
2885 di = dictitem_alloc(lp->ll_newkey);
2886 if (di == NULL)
2887 return;
2888 if (dict_add(lp->ll_tv->vval.v_dict, di) == FAIL)
2890 vim_free(di);
2891 return;
2893 lp->ll_tv = &di->di_tv;
2895 else if (op != NULL && *op != '=')
2897 tv_op(lp->ll_tv, rettv, op);
2898 return;
2900 else
2901 clear_tv(lp->ll_tv);
2904 * Assign the value to the variable or list item.
2906 if (copy)
2907 copy_tv(rettv, lp->ll_tv);
2908 else
2910 *lp->ll_tv = *rettv;
2911 lp->ll_tv->v_lock = 0;
2912 init_tv(rettv);
2918 * Handle "tv1 += tv2", "tv1 -= tv2" and "tv1 .= tv2"
2919 * Returns OK or FAIL.
2921 static int
2922 tv_op(tv1, tv2, op)
2923 typval_T *tv1;
2924 typval_T *tv2;
2925 char_u *op;
2927 long n;
2928 char_u numbuf[NUMBUFLEN];
2929 char_u *s;
2931 /* Can't do anything with a Funcref or a Dict on the right. */
2932 if (tv2->v_type != VAR_FUNC && tv2->v_type != VAR_DICT)
2934 switch (tv1->v_type)
2936 case VAR_DICT:
2937 case VAR_FUNC:
2938 break;
2940 case VAR_LIST:
2941 if (*op != '+' || tv2->v_type != VAR_LIST)
2942 break;
2943 /* List += List */
2944 if (tv1->vval.v_list != NULL && tv2->vval.v_list != NULL)
2945 list_extend(tv1->vval.v_list, tv2->vval.v_list, NULL);
2946 return OK;
2948 case VAR_NUMBER:
2949 case VAR_STRING:
2950 if (tv2->v_type == VAR_LIST)
2951 break;
2952 if (*op == '+' || *op == '-')
2954 /* nr += nr or nr -= nr*/
2955 n = get_tv_number(tv1);
2956 #ifdef FEAT_FLOAT
2957 if (tv2->v_type == VAR_FLOAT)
2959 float_T f = n;
2961 if (*op == '+')
2962 f += tv2->vval.v_float;
2963 else
2964 f -= tv2->vval.v_float;
2965 clear_tv(tv1);
2966 tv1->v_type = VAR_FLOAT;
2967 tv1->vval.v_float = f;
2969 else
2970 #endif
2972 if (*op == '+')
2973 n += get_tv_number(tv2);
2974 else
2975 n -= get_tv_number(tv2);
2976 clear_tv(tv1);
2977 tv1->v_type = VAR_NUMBER;
2978 tv1->vval.v_number = n;
2981 else
2983 if (tv2->v_type == VAR_FLOAT)
2984 break;
2986 /* str .= str */
2987 s = get_tv_string(tv1);
2988 s = concat_str(s, get_tv_string_buf(tv2, numbuf));
2989 clear_tv(tv1);
2990 tv1->v_type = VAR_STRING;
2991 tv1->vval.v_string = s;
2993 return OK;
2995 #ifdef FEAT_FLOAT
2996 case VAR_FLOAT:
2998 float_T f;
3000 if (*op == '.' || (tv2->v_type != VAR_FLOAT
3001 && tv2->v_type != VAR_NUMBER
3002 && tv2->v_type != VAR_STRING))
3003 break;
3004 if (tv2->v_type == VAR_FLOAT)
3005 f = tv2->vval.v_float;
3006 else
3007 f = get_tv_number(tv2);
3008 if (*op == '+')
3009 tv1->vval.v_float += f;
3010 else
3011 tv1->vval.v_float -= f;
3013 return OK;
3014 #endif
3018 EMSG2(_(e_letwrong), op);
3019 return FAIL;
3023 * Add a watcher to a list.
3025 static void
3026 list_add_watch(l, lw)
3027 list_T *l;
3028 listwatch_T *lw;
3030 lw->lw_next = l->lv_watch;
3031 l->lv_watch = lw;
3035 * Remove a watcher from a list.
3036 * No warning when it isn't found...
3038 static void
3039 list_rem_watch(l, lwrem)
3040 list_T *l;
3041 listwatch_T *lwrem;
3043 listwatch_T *lw, **lwp;
3045 lwp = &l->lv_watch;
3046 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3048 if (lw == lwrem)
3050 *lwp = lw->lw_next;
3051 break;
3053 lwp = &lw->lw_next;
3058 * Just before removing an item from a list: advance watchers to the next
3059 * item.
3061 static void
3062 list_fix_watch(l, item)
3063 list_T *l;
3064 listitem_T *item;
3066 listwatch_T *lw;
3068 for (lw = l->lv_watch; lw != NULL; lw = lw->lw_next)
3069 if (lw->lw_item == item)
3070 lw->lw_item = item->li_next;
3074 * Evaluate the expression used in a ":for var in expr" command.
3075 * "arg" points to "var".
3076 * Set "*errp" to TRUE for an error, FALSE otherwise;
3077 * Return a pointer that holds the info. Null when there is an error.
3079 void *
3080 eval_for_line(arg, errp, nextcmdp, skip)
3081 char_u *arg;
3082 int *errp;
3083 char_u **nextcmdp;
3084 int skip;
3086 forinfo_T *fi;
3087 char_u *expr;
3088 typval_T tv;
3089 list_T *l;
3091 *errp = TRUE; /* default: there is an error */
3093 fi = (forinfo_T *)alloc_clear(sizeof(forinfo_T));
3094 if (fi == NULL)
3095 return NULL;
3097 expr = skip_var_list(arg, &fi->fi_varcount, &fi->fi_semicolon);
3098 if (expr == NULL)
3099 return fi;
3101 expr = skipwhite(expr);
3102 if (expr[0] != 'i' || expr[1] != 'n' || !vim_iswhite(expr[2]))
3104 EMSG(_("E690: Missing \"in\" after :for"));
3105 return fi;
3108 if (skip)
3109 ++emsg_skip;
3110 if (eval0(skipwhite(expr + 2), &tv, nextcmdp, !skip) == OK)
3112 *errp = FALSE;
3113 if (!skip)
3115 l = tv.vval.v_list;
3116 if (tv.v_type != VAR_LIST || l == NULL)
3118 EMSG(_(e_listreq));
3119 clear_tv(&tv);
3121 else
3123 /* No need to increment the refcount, it's already set for the
3124 * list being used in "tv". */
3125 fi->fi_list = l;
3126 list_add_watch(l, &fi->fi_lw);
3127 fi->fi_lw.lw_item = l->lv_first;
3131 if (skip)
3132 --emsg_skip;
3134 return fi;
3138 * Use the first item in a ":for" list. Advance to the next.
3139 * Assign the values to the variable (list). "arg" points to the first one.
3140 * Return TRUE when a valid item was found, FALSE when at end of list or
3141 * something wrong.
3144 next_for_item(fi_void, arg)
3145 void *fi_void;
3146 char_u *arg;
3148 forinfo_T *fi = (forinfo_T *)fi_void;
3149 int result;
3150 listitem_T *item;
3152 item = fi->fi_lw.lw_item;
3153 if (item == NULL)
3154 result = FALSE;
3155 else
3157 fi->fi_lw.lw_item = item->li_next;
3158 result = (ex_let_vars(arg, &item->li_tv, TRUE,
3159 fi->fi_semicolon, fi->fi_varcount, NULL) == OK);
3161 return result;
3165 * Free the structure used to store info used by ":for".
3167 void
3168 free_for_info(fi_void)
3169 void *fi_void;
3171 forinfo_T *fi = (forinfo_T *)fi_void;
3173 if (fi != NULL && fi->fi_list != NULL)
3175 list_rem_watch(fi->fi_list, &fi->fi_lw);
3176 list_unref(fi->fi_list);
3178 vim_free(fi);
3181 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3183 void
3184 set_context_for_expression(xp, arg, cmdidx)
3185 expand_T *xp;
3186 char_u *arg;
3187 cmdidx_T cmdidx;
3189 int got_eq = FALSE;
3190 int c;
3191 char_u *p;
3193 if (cmdidx == CMD_let)
3195 xp->xp_context = EXPAND_USER_VARS;
3196 if (vim_strpbrk(arg, (char_u *)"\"'+-*/%.=!?~|&$([<>,#") == NULL)
3198 /* ":let var1 var2 ...": find last space. */
3199 for (p = arg + STRLEN(arg); p >= arg; )
3201 xp->xp_pattern = p;
3202 mb_ptr_back(arg, p);
3203 if (vim_iswhite(*p))
3204 break;
3206 return;
3209 else
3210 xp->xp_context = cmdidx == CMD_call ? EXPAND_FUNCTIONS
3211 : EXPAND_EXPRESSION;
3212 while ((xp->xp_pattern = vim_strpbrk(arg,
3213 (char_u *)"\"'+-*/%.=!?~|&$([<>,#")) != NULL)
3215 c = *xp->xp_pattern;
3216 if (c == '&')
3218 c = xp->xp_pattern[1];
3219 if (c == '&')
3221 ++xp->xp_pattern;
3222 xp->xp_context = cmdidx != CMD_let || got_eq
3223 ? EXPAND_EXPRESSION : EXPAND_NOTHING;
3225 else if (c != ' ')
3227 xp->xp_context = EXPAND_SETTINGS;
3228 if ((c == 'l' || c == 'g') && xp->xp_pattern[2] == ':')
3229 xp->xp_pattern += 2;
3233 else if (c == '$')
3235 /* environment variable */
3236 xp->xp_context = EXPAND_ENV_VARS;
3238 else if (c == '=')
3240 got_eq = TRUE;
3241 xp->xp_context = EXPAND_EXPRESSION;
3243 else if (c == '<'
3244 && xp->xp_context == EXPAND_FUNCTIONS
3245 && vim_strchr(xp->xp_pattern, '(') == NULL)
3247 /* Function name can start with "<SNR>" */
3248 break;
3250 else if (cmdidx != CMD_let || got_eq)
3252 if (c == '"') /* string */
3254 while ((c = *++xp->xp_pattern) != NUL && c != '"')
3255 if (c == '\\' && xp->xp_pattern[1] != NUL)
3256 ++xp->xp_pattern;
3257 xp->xp_context = EXPAND_NOTHING;
3259 else if (c == '\'') /* literal string */
3261 /* Trick: '' is like stopping and starting a literal string. */
3262 while ((c = *++xp->xp_pattern) != NUL && c != '\'')
3263 /* skip */ ;
3264 xp->xp_context = EXPAND_NOTHING;
3266 else if (c == '|')
3268 if (xp->xp_pattern[1] == '|')
3270 ++xp->xp_pattern;
3271 xp->xp_context = EXPAND_EXPRESSION;
3273 else
3274 xp->xp_context = EXPAND_COMMANDS;
3276 else
3277 xp->xp_context = EXPAND_EXPRESSION;
3279 else
3280 /* Doesn't look like something valid, expand as an expression
3281 * anyway. */
3282 xp->xp_context = EXPAND_EXPRESSION;
3283 arg = xp->xp_pattern;
3284 if (*arg != NUL)
3285 while ((c = *++arg) != NUL && (c == ' ' || c == '\t'))
3286 /* skip */ ;
3288 xp->xp_pattern = arg;
3291 #endif /* FEAT_CMDL_COMPL */
3294 * ":1,25call func(arg1, arg2)" function call.
3296 void
3297 ex_call(eap)
3298 exarg_T *eap;
3300 char_u *arg = eap->arg;
3301 char_u *startarg;
3302 char_u *name;
3303 char_u *tofree;
3304 int len;
3305 typval_T rettv;
3306 linenr_T lnum;
3307 int doesrange;
3308 int failed = FALSE;
3309 funcdict_T fudi;
3311 tofree = trans_function_name(&arg, eap->skip, TFN_INT, &fudi);
3312 if (fudi.fd_newkey != NULL)
3314 /* Still need to give an error message for missing key. */
3315 EMSG2(_(e_dictkey), fudi.fd_newkey);
3316 vim_free(fudi.fd_newkey);
3318 if (tofree == NULL)
3319 return;
3321 /* Increase refcount on dictionary, it could get deleted when evaluating
3322 * the arguments. */
3323 if (fudi.fd_dict != NULL)
3324 ++fudi.fd_dict->dv_refcount;
3326 /* If it is the name of a variable of type VAR_FUNC use its contents. */
3327 len = (int)STRLEN(tofree);
3328 name = deref_func_name(tofree, &len);
3330 /* Skip white space to allow ":call func ()". Not good, but required for
3331 * backward compatibility. */
3332 startarg = skipwhite(arg);
3333 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
3335 if (*startarg != '(')
3337 EMSG2(_("E107: Missing parentheses: %s"), eap->arg);
3338 goto end;
3342 * When skipping, evaluate the function once, to find the end of the
3343 * arguments.
3344 * When the function takes a range, this is discovered after the first
3345 * call, and the loop is broken.
3347 if (eap->skip)
3349 ++emsg_skip;
3350 lnum = eap->line2; /* do it once, also with an invalid range */
3352 else
3353 lnum = eap->line1;
3354 for ( ; lnum <= eap->line2; ++lnum)
3356 if (!eap->skip && eap->addr_count > 0)
3358 curwin->w_cursor.lnum = lnum;
3359 curwin->w_cursor.col = 0;
3361 arg = startarg;
3362 if (get_func_tv(name, (int)STRLEN(name), &rettv, &arg,
3363 eap->line1, eap->line2, &doesrange,
3364 !eap->skip, fudi.fd_dict) == FAIL)
3366 failed = TRUE;
3367 break;
3370 /* Handle a function returning a Funcref, Dictionary or List. */
3371 if (handle_subscript(&arg, &rettv, !eap->skip, TRUE) == FAIL)
3373 failed = TRUE;
3374 break;
3377 clear_tv(&rettv);
3378 if (doesrange || eap->skip)
3379 break;
3381 /* Stop when immediately aborting on error, or when an interrupt
3382 * occurred or an exception was thrown but not caught.
3383 * get_func_tv() returned OK, so that the check for trailing
3384 * characters below is executed. */
3385 if (aborting())
3386 break;
3388 if (eap->skip)
3389 --emsg_skip;
3391 if (!failed)
3393 /* Check for trailing illegal characters and a following command. */
3394 if (!ends_excmd(*arg))
3396 emsg_severe = TRUE;
3397 EMSG(_(e_trailing));
3399 else
3400 eap->nextcmd = check_nextcmd(arg);
3403 end:
3404 dict_unref(fudi.fd_dict);
3405 vim_free(tofree);
3409 * ":unlet[!] var1 ... " command.
3411 void
3412 ex_unlet(eap)
3413 exarg_T *eap;
3415 ex_unletlock(eap, eap->arg, 0);
3419 * ":lockvar" and ":unlockvar" commands
3421 void
3422 ex_lockvar(eap)
3423 exarg_T *eap;
3425 char_u *arg = eap->arg;
3426 int deep = 2;
3428 if (eap->forceit)
3429 deep = -1;
3430 else if (vim_isdigit(*arg))
3432 deep = getdigits(&arg);
3433 arg = skipwhite(arg);
3436 ex_unletlock(eap, arg, deep);
3440 * ":unlet", ":lockvar" and ":unlockvar" are quite similar.
3442 static void
3443 ex_unletlock(eap, argstart, deep)
3444 exarg_T *eap;
3445 char_u *argstart;
3446 int deep;
3448 char_u *arg = argstart;
3449 char_u *name_end;
3450 int error = FALSE;
3451 lval_T lv;
3455 /* Parse the name and find the end. */
3456 name_end = get_lval(arg, NULL, &lv, TRUE, eap->skip || error, FALSE,
3457 FNE_CHECK_START);
3458 if (lv.ll_name == NULL)
3459 error = TRUE; /* error but continue parsing */
3460 if (name_end == NULL || (!vim_iswhite(*name_end)
3461 && !ends_excmd(*name_end)))
3463 if (name_end != NULL)
3465 emsg_severe = TRUE;
3466 EMSG(_(e_trailing));
3468 if (!(eap->skip || error))
3469 clear_lval(&lv);
3470 break;
3473 if (!error && !eap->skip)
3475 if (eap->cmdidx == CMD_unlet)
3477 if (do_unlet_var(&lv, name_end, eap->forceit) == FAIL)
3478 error = TRUE;
3480 else
3482 if (do_lock_var(&lv, name_end, deep,
3483 eap->cmdidx == CMD_lockvar) == FAIL)
3484 error = TRUE;
3488 if (!eap->skip)
3489 clear_lval(&lv);
3491 arg = skipwhite(name_end);
3492 } while (!ends_excmd(*arg));
3494 eap->nextcmd = check_nextcmd(arg);
3497 static int
3498 do_unlet_var(lp, name_end, forceit)
3499 lval_T *lp;
3500 char_u *name_end;
3501 int forceit;
3503 int ret = OK;
3504 int cc;
3506 if (lp->ll_tv == NULL)
3508 cc = *name_end;
3509 *name_end = NUL;
3511 /* Normal name or expanded name. */
3512 if (check_changedtick(lp->ll_name))
3513 ret = FAIL;
3514 else if (do_unlet(lp->ll_name, forceit) == FAIL)
3515 ret = FAIL;
3516 *name_end = cc;
3518 else if (tv_check_lock(lp->ll_tv->v_lock, lp->ll_name))
3519 return FAIL;
3520 else if (lp->ll_range)
3522 listitem_T *li;
3524 /* Delete a range of List items. */
3525 while (lp->ll_li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3527 li = lp->ll_li->li_next;
3528 listitem_remove(lp->ll_list, lp->ll_li);
3529 lp->ll_li = li;
3530 ++lp->ll_n1;
3533 else
3535 if (lp->ll_list != NULL)
3536 /* unlet a List item. */
3537 listitem_remove(lp->ll_list, lp->ll_li);
3538 else
3539 /* unlet a Dictionary item. */
3540 dictitem_remove(lp->ll_dict, lp->ll_di);
3543 return ret;
3547 * "unlet" a variable. Return OK if it existed, FAIL if not.
3548 * When "forceit" is TRUE don't complain if the variable doesn't exist.
3551 do_unlet(name, forceit)
3552 char_u *name;
3553 int forceit;
3555 hashtab_T *ht;
3556 hashitem_T *hi;
3557 char_u *varname;
3558 dictitem_T *di;
3560 ht = find_var_ht(name, &varname);
3561 if (ht != NULL && *varname != NUL)
3563 hi = hash_find(ht, varname);
3564 if (!HASHITEM_EMPTY(hi))
3566 di = HI2DI(hi);
3567 if (var_check_fixed(di->di_flags, name)
3568 || var_check_ro(di->di_flags, name))
3569 return FAIL;
3570 delete_var(ht, hi);
3571 return OK;
3574 if (forceit)
3575 return OK;
3576 EMSG2(_("E108: No such variable: \"%s\""), name);
3577 return FAIL;
3581 * Lock or unlock variable indicated by "lp".
3582 * "deep" is the levels to go (-1 for unlimited);
3583 * "lock" is TRUE for ":lockvar", FALSE for ":unlockvar".
3585 static int
3586 do_lock_var(lp, name_end, deep, lock)
3587 lval_T *lp;
3588 char_u *name_end;
3589 int deep;
3590 int lock;
3592 int ret = OK;
3593 int cc;
3594 dictitem_T *di;
3596 if (deep == 0) /* nothing to do */
3597 return OK;
3599 if (lp->ll_tv == NULL)
3601 cc = *name_end;
3602 *name_end = NUL;
3604 /* Normal name or expanded name. */
3605 if (check_changedtick(lp->ll_name))
3606 ret = FAIL;
3607 else
3609 di = find_var(lp->ll_name, NULL);
3610 if (di == NULL)
3611 ret = FAIL;
3612 else
3614 if (lock)
3615 di->di_flags |= DI_FLAGS_LOCK;
3616 else
3617 di->di_flags &= ~DI_FLAGS_LOCK;
3618 item_lock(&di->di_tv, deep, lock);
3621 *name_end = cc;
3623 else if (lp->ll_range)
3625 listitem_T *li = lp->ll_li;
3627 /* (un)lock a range of List items. */
3628 while (li != NULL && (lp->ll_empty2 || lp->ll_n2 >= lp->ll_n1))
3630 item_lock(&li->li_tv, deep, lock);
3631 li = li->li_next;
3632 ++lp->ll_n1;
3635 else if (lp->ll_list != NULL)
3636 /* (un)lock a List item. */
3637 item_lock(&lp->ll_li->li_tv, deep, lock);
3638 else
3639 /* un(lock) a Dictionary item. */
3640 item_lock(&lp->ll_di->di_tv, deep, lock);
3642 return ret;
3646 * Lock or unlock an item. "deep" is nr of levels to go.
3648 static void
3649 item_lock(tv, deep, lock)
3650 typval_T *tv;
3651 int deep;
3652 int lock;
3654 static int recurse = 0;
3655 list_T *l;
3656 listitem_T *li;
3657 dict_T *d;
3658 hashitem_T *hi;
3659 int todo;
3661 if (recurse >= DICT_MAXNEST)
3663 EMSG(_("E743: variable nested too deep for (un)lock"));
3664 return;
3666 if (deep == 0)
3667 return;
3668 ++recurse;
3670 /* lock/unlock the item itself */
3671 if (lock)
3672 tv->v_lock |= VAR_LOCKED;
3673 else
3674 tv->v_lock &= ~VAR_LOCKED;
3676 switch (tv->v_type)
3678 case VAR_LIST:
3679 if ((l = tv->vval.v_list) != NULL)
3681 if (lock)
3682 l->lv_lock |= VAR_LOCKED;
3683 else
3684 l->lv_lock &= ~VAR_LOCKED;
3685 if (deep < 0 || deep > 1)
3686 /* recursive: lock/unlock the items the List contains */
3687 for (li = l->lv_first; li != NULL; li = li->li_next)
3688 item_lock(&li->li_tv, deep - 1, lock);
3690 break;
3691 case VAR_DICT:
3692 if ((d = tv->vval.v_dict) != NULL)
3694 if (lock)
3695 d->dv_lock |= VAR_LOCKED;
3696 else
3697 d->dv_lock &= ~VAR_LOCKED;
3698 if (deep < 0 || deep > 1)
3700 /* recursive: lock/unlock the items the List contains */
3701 todo = (int)d->dv_hashtab.ht_used;
3702 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
3704 if (!HASHITEM_EMPTY(hi))
3706 --todo;
3707 item_lock(&HI2DI(hi)->di_tv, deep - 1, lock);
3713 --recurse;
3717 * Return TRUE if typeval "tv" is locked: Either that value is locked itself
3718 * or it refers to a List or Dictionary that is locked.
3720 static int
3721 tv_islocked(tv)
3722 typval_T *tv;
3724 return (tv->v_lock & VAR_LOCKED)
3725 || (tv->v_type == VAR_LIST
3726 && tv->vval.v_list != NULL
3727 && (tv->vval.v_list->lv_lock & VAR_LOCKED))
3728 || (tv->v_type == VAR_DICT
3729 && tv->vval.v_dict != NULL
3730 && (tv->vval.v_dict->dv_lock & VAR_LOCKED));
3733 #if (defined(FEAT_MENU) && defined(FEAT_MULTI_LANG)) || defined(PROTO)
3735 * Delete all "menutrans_" variables.
3737 void
3738 del_menutrans_vars()
3740 hashitem_T *hi;
3741 int todo;
3743 hash_lock(&globvarht);
3744 todo = (int)globvarht.ht_used;
3745 for (hi = globvarht.ht_array; todo > 0 && !got_int; ++hi)
3747 if (!HASHITEM_EMPTY(hi))
3749 --todo;
3750 if (STRNCMP(HI2DI(hi)->di_key, "menutrans_", 10) == 0)
3751 delete_var(&globvarht, hi);
3754 hash_unlock(&globvarht);
3756 #endif
3758 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3761 * Local string buffer for the next two functions to store a variable name
3762 * with its prefix. Allocated in cat_prefix_varname(), freed later in
3763 * get_user_var_name().
3766 static char_u *cat_prefix_varname __ARGS((int prefix, char_u *name));
3768 static char_u *varnamebuf = NULL;
3769 static int varnamebuflen = 0;
3772 * Function to concatenate a prefix and a variable name.
3774 static char_u *
3775 cat_prefix_varname(prefix, name)
3776 int prefix;
3777 char_u *name;
3779 int len;
3781 len = (int)STRLEN(name) + 3;
3782 if (len > varnamebuflen)
3784 vim_free(varnamebuf);
3785 len += 10; /* some additional space */
3786 varnamebuf = alloc(len);
3787 if (varnamebuf == NULL)
3789 varnamebuflen = 0;
3790 return NULL;
3792 varnamebuflen = len;
3794 *varnamebuf = prefix;
3795 varnamebuf[1] = ':';
3796 STRCPY(varnamebuf + 2, name);
3797 return varnamebuf;
3801 * Function given to ExpandGeneric() to obtain the list of user defined
3802 * (global/buffer/window/built-in) variable names.
3804 char_u *
3805 get_user_var_name(xp, idx)
3806 expand_T *xp;
3807 int idx;
3809 static long_u gdone;
3810 static long_u bdone;
3811 static long_u wdone;
3812 #ifdef FEAT_WINDOWS
3813 static long_u tdone;
3814 #endif
3815 static int vidx;
3816 static hashitem_T *hi;
3817 hashtab_T *ht;
3819 if (idx == 0)
3821 gdone = bdone = wdone = vidx = 0;
3822 #ifdef FEAT_WINDOWS
3823 tdone = 0;
3824 #endif
3827 /* Global variables */
3828 if (gdone < globvarht.ht_used)
3830 if (gdone++ == 0)
3831 hi = globvarht.ht_array;
3832 else
3833 ++hi;
3834 while (HASHITEM_EMPTY(hi))
3835 ++hi;
3836 if (STRNCMP("g:", xp->xp_pattern, 2) == 0)
3837 return cat_prefix_varname('g', hi->hi_key);
3838 return hi->hi_key;
3841 /* b: variables */
3842 ht = &curbuf->b_vars.dv_hashtab;
3843 if (bdone < ht->ht_used)
3845 if (bdone++ == 0)
3846 hi = ht->ht_array;
3847 else
3848 ++hi;
3849 while (HASHITEM_EMPTY(hi))
3850 ++hi;
3851 return cat_prefix_varname('b', hi->hi_key);
3853 if (bdone == ht->ht_used)
3855 ++bdone;
3856 return (char_u *)"b:changedtick";
3859 /* w: variables */
3860 ht = &curwin->w_vars.dv_hashtab;
3861 if (wdone < ht->ht_used)
3863 if (wdone++ == 0)
3864 hi = ht->ht_array;
3865 else
3866 ++hi;
3867 while (HASHITEM_EMPTY(hi))
3868 ++hi;
3869 return cat_prefix_varname('w', hi->hi_key);
3872 #ifdef FEAT_WINDOWS
3873 /* t: variables */
3874 ht = &curtab->tp_vars.dv_hashtab;
3875 if (tdone < ht->ht_used)
3877 if (tdone++ == 0)
3878 hi = ht->ht_array;
3879 else
3880 ++hi;
3881 while (HASHITEM_EMPTY(hi))
3882 ++hi;
3883 return cat_prefix_varname('t', hi->hi_key);
3885 #endif
3887 /* v: variables */
3888 if (vidx < VV_LEN)
3889 return cat_prefix_varname('v', (char_u *)vimvars[vidx++].vv_name);
3891 vim_free(varnamebuf);
3892 varnamebuf = NULL;
3893 varnamebuflen = 0;
3894 return NULL;
3897 #endif /* FEAT_CMDL_COMPL */
3900 * types for expressions.
3902 typedef enum
3904 TYPE_UNKNOWN = 0
3905 , TYPE_EQUAL /* == */
3906 , TYPE_NEQUAL /* != */
3907 , TYPE_GREATER /* > */
3908 , TYPE_GEQUAL /* >= */
3909 , TYPE_SMALLER /* < */
3910 , TYPE_SEQUAL /* <= */
3911 , TYPE_MATCH /* =~ */
3912 , TYPE_NOMATCH /* !~ */
3913 } exptype_T;
3916 * The "evaluate" argument: When FALSE, the argument is only parsed but not
3917 * executed. The function may return OK, but the rettv will be of type
3918 * VAR_UNKNOWN. The function still returns FAIL for a syntax error.
3922 * Handle zero level expression.
3923 * This calls eval1() and handles error message and nextcmd.
3924 * Put the result in "rettv" when returning OK and "evaluate" is TRUE.
3925 * Note: "rettv.v_lock" is not set.
3926 * Return OK or FAIL.
3928 static int
3929 eval0(arg, rettv, nextcmd, evaluate)
3930 char_u *arg;
3931 typval_T *rettv;
3932 char_u **nextcmd;
3933 int evaluate;
3935 int ret;
3936 char_u *p;
3938 p = skipwhite(arg);
3939 ret = eval1(&p, rettv, evaluate);
3940 if (ret == FAIL || !ends_excmd(*p))
3942 if (ret != FAIL)
3943 clear_tv(rettv);
3945 * Report the invalid expression unless the expression evaluation has
3946 * been cancelled due to an aborting error, an interrupt, or an
3947 * exception.
3949 if (!aborting())
3950 EMSG2(_(e_invexpr2), arg);
3951 ret = FAIL;
3953 if (nextcmd != NULL)
3954 *nextcmd = check_nextcmd(p);
3956 return ret;
3960 * Handle top level expression:
3961 * expr2 ? expr1 : expr1
3963 * "arg" must point to the first non-white of the expression.
3964 * "arg" is advanced to the next non-white after the recognized expression.
3966 * Note: "rettv.v_lock" is not set.
3968 * Return OK or FAIL.
3970 static int
3971 eval1(arg, rettv, evaluate)
3972 char_u **arg;
3973 typval_T *rettv;
3974 int evaluate;
3976 int result;
3977 typval_T var2;
3980 * Get the first variable.
3982 if (eval2(arg, rettv, evaluate) == FAIL)
3983 return FAIL;
3985 if ((*arg)[0] == '?')
3987 result = FALSE;
3988 if (evaluate)
3990 int error = FALSE;
3992 if (get_tv_number_chk(rettv, &error) != 0)
3993 result = TRUE;
3994 clear_tv(rettv);
3995 if (error)
3996 return FAIL;
4000 * Get the second variable.
4002 *arg = skipwhite(*arg + 1);
4003 if (eval1(arg, rettv, evaluate && result) == FAIL) /* recursive! */
4004 return FAIL;
4007 * Check for the ":".
4009 if ((*arg)[0] != ':')
4011 EMSG(_("E109: Missing ':' after '?'"));
4012 if (evaluate && result)
4013 clear_tv(rettv);
4014 return FAIL;
4018 * Get the third variable.
4020 *arg = skipwhite(*arg + 1);
4021 if (eval1(arg, &var2, evaluate && !result) == FAIL) /* recursive! */
4023 if (evaluate && result)
4024 clear_tv(rettv);
4025 return FAIL;
4027 if (evaluate && !result)
4028 *rettv = var2;
4031 return OK;
4035 * Handle first level expression:
4036 * expr2 || expr2 || expr2 logical OR
4038 * "arg" must point to the first non-white of the expression.
4039 * "arg" is advanced to the next non-white after the recognized expression.
4041 * Return OK or FAIL.
4043 static int
4044 eval2(arg, rettv, evaluate)
4045 char_u **arg;
4046 typval_T *rettv;
4047 int evaluate;
4049 typval_T var2;
4050 long result;
4051 int first;
4052 int error = FALSE;
4055 * Get the first variable.
4057 if (eval3(arg, rettv, evaluate) == FAIL)
4058 return FAIL;
4061 * Repeat until there is no following "||".
4063 first = TRUE;
4064 result = FALSE;
4065 while ((*arg)[0] == '|' && (*arg)[1] == '|')
4067 if (evaluate && first)
4069 if (get_tv_number_chk(rettv, &error) != 0)
4070 result = TRUE;
4071 clear_tv(rettv);
4072 if (error)
4073 return FAIL;
4074 first = FALSE;
4078 * Get the second variable.
4080 *arg = skipwhite(*arg + 2);
4081 if (eval3(arg, &var2, evaluate && !result) == FAIL)
4082 return FAIL;
4085 * Compute the result.
4087 if (evaluate && !result)
4089 if (get_tv_number_chk(&var2, &error) != 0)
4090 result = TRUE;
4091 clear_tv(&var2);
4092 if (error)
4093 return FAIL;
4095 if (evaluate)
4097 rettv->v_type = VAR_NUMBER;
4098 rettv->vval.v_number = result;
4102 return OK;
4106 * Handle second level expression:
4107 * expr3 && expr3 && expr3 logical AND
4109 * "arg" must point to the first non-white of the expression.
4110 * "arg" is advanced to the next non-white after the recognized expression.
4112 * Return OK or FAIL.
4114 static int
4115 eval3(arg, rettv, evaluate)
4116 char_u **arg;
4117 typval_T *rettv;
4118 int evaluate;
4120 typval_T var2;
4121 long result;
4122 int first;
4123 int error = FALSE;
4126 * Get the first variable.
4128 if (eval4(arg, rettv, evaluate) == FAIL)
4129 return FAIL;
4132 * Repeat until there is no following "&&".
4134 first = TRUE;
4135 result = TRUE;
4136 while ((*arg)[0] == '&' && (*arg)[1] == '&')
4138 if (evaluate && first)
4140 if (get_tv_number_chk(rettv, &error) == 0)
4141 result = FALSE;
4142 clear_tv(rettv);
4143 if (error)
4144 return FAIL;
4145 first = FALSE;
4149 * Get the second variable.
4151 *arg = skipwhite(*arg + 2);
4152 if (eval4(arg, &var2, evaluate && result) == FAIL)
4153 return FAIL;
4156 * Compute the result.
4158 if (evaluate && result)
4160 if (get_tv_number_chk(&var2, &error) == 0)
4161 result = FALSE;
4162 clear_tv(&var2);
4163 if (error)
4164 return FAIL;
4166 if (evaluate)
4168 rettv->v_type = VAR_NUMBER;
4169 rettv->vval.v_number = result;
4173 return OK;
4177 * Handle third level expression:
4178 * var1 == var2
4179 * var1 =~ var2
4180 * var1 != var2
4181 * var1 !~ var2
4182 * var1 > var2
4183 * var1 >= var2
4184 * var1 < var2
4185 * var1 <= var2
4186 * var1 is var2
4187 * var1 isnot var2
4189 * "arg" must point to the first non-white of the expression.
4190 * "arg" is advanced to the next non-white after the recognized expression.
4192 * Return OK or FAIL.
4194 static int
4195 eval4(arg, rettv, evaluate)
4196 char_u **arg;
4197 typval_T *rettv;
4198 int evaluate;
4200 typval_T var2;
4201 char_u *p;
4202 int i;
4203 exptype_T type = TYPE_UNKNOWN;
4204 int type_is = FALSE; /* TRUE for "is" and "isnot" */
4205 int len = 2;
4206 long n1, n2;
4207 char_u *s1, *s2;
4208 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4209 regmatch_T regmatch;
4210 int ic;
4211 char_u *save_cpo;
4214 * Get the first variable.
4216 if (eval5(arg, rettv, evaluate) == FAIL)
4217 return FAIL;
4219 p = *arg;
4220 switch (p[0])
4222 case '=': if (p[1] == '=')
4223 type = TYPE_EQUAL;
4224 else if (p[1] == '~')
4225 type = TYPE_MATCH;
4226 break;
4227 case '!': if (p[1] == '=')
4228 type = TYPE_NEQUAL;
4229 else if (p[1] == '~')
4230 type = TYPE_NOMATCH;
4231 break;
4232 case '>': if (p[1] != '=')
4234 type = TYPE_GREATER;
4235 len = 1;
4237 else
4238 type = TYPE_GEQUAL;
4239 break;
4240 case '<': if (p[1] != '=')
4242 type = TYPE_SMALLER;
4243 len = 1;
4245 else
4246 type = TYPE_SEQUAL;
4247 break;
4248 case 'i': if (p[1] == 's')
4250 if (p[2] == 'n' && p[3] == 'o' && p[4] == 't')
4251 len = 5;
4252 if (!vim_isIDc(p[len]))
4254 type = len == 2 ? TYPE_EQUAL : TYPE_NEQUAL;
4255 type_is = TRUE;
4258 break;
4262 * If there is a comparative operator, use it.
4264 if (type != TYPE_UNKNOWN)
4266 /* extra question mark appended: ignore case */
4267 if (p[len] == '?')
4269 ic = TRUE;
4270 ++len;
4272 /* extra '#' appended: match case */
4273 else if (p[len] == '#')
4275 ic = FALSE;
4276 ++len;
4278 /* nothing appended: use 'ignorecase' */
4279 else
4280 ic = p_ic;
4283 * Get the second variable.
4285 *arg = skipwhite(p + len);
4286 if (eval5(arg, &var2, evaluate) == FAIL)
4288 clear_tv(rettv);
4289 return FAIL;
4292 if (evaluate)
4294 if (type_is && rettv->v_type != var2.v_type)
4296 /* For "is" a different type always means FALSE, for "notis"
4297 * it means TRUE. */
4298 n1 = (type == TYPE_NEQUAL);
4300 else if (rettv->v_type == VAR_LIST || var2.v_type == VAR_LIST)
4302 if (type_is)
4304 n1 = (rettv->v_type == var2.v_type
4305 && rettv->vval.v_list == var2.vval.v_list);
4306 if (type == TYPE_NEQUAL)
4307 n1 = !n1;
4309 else if (rettv->v_type != var2.v_type
4310 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4312 if (rettv->v_type != var2.v_type)
4313 EMSG(_("E691: Can only compare List with List"));
4314 else
4315 EMSG(_("E692: Invalid operation for Lists"));
4316 clear_tv(rettv);
4317 clear_tv(&var2);
4318 return FAIL;
4320 else
4322 /* Compare two Lists for being equal or unequal. */
4323 n1 = list_equal(rettv->vval.v_list, var2.vval.v_list, ic);
4324 if (type == TYPE_NEQUAL)
4325 n1 = !n1;
4329 else if (rettv->v_type == VAR_DICT || var2.v_type == VAR_DICT)
4331 if (type_is)
4333 n1 = (rettv->v_type == var2.v_type
4334 && rettv->vval.v_dict == var2.vval.v_dict);
4335 if (type == TYPE_NEQUAL)
4336 n1 = !n1;
4338 else if (rettv->v_type != var2.v_type
4339 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4341 if (rettv->v_type != var2.v_type)
4342 EMSG(_("E735: Can only compare Dictionary with Dictionary"));
4343 else
4344 EMSG(_("E736: Invalid operation for Dictionary"));
4345 clear_tv(rettv);
4346 clear_tv(&var2);
4347 return FAIL;
4349 else
4351 /* Compare two Dictionaries for being equal or unequal. */
4352 n1 = dict_equal(rettv->vval.v_dict, var2.vval.v_dict, ic);
4353 if (type == TYPE_NEQUAL)
4354 n1 = !n1;
4358 else if (rettv->v_type == VAR_FUNC || var2.v_type == VAR_FUNC)
4360 if (rettv->v_type != var2.v_type
4361 || (type != TYPE_EQUAL && type != TYPE_NEQUAL))
4363 if (rettv->v_type != var2.v_type)
4364 EMSG(_("E693: Can only compare Funcref with Funcref"));
4365 else
4366 EMSG(_("E694: Invalid operation for Funcrefs"));
4367 clear_tv(rettv);
4368 clear_tv(&var2);
4369 return FAIL;
4371 else
4373 /* Compare two Funcrefs for being equal or unequal. */
4374 if (rettv->vval.v_string == NULL
4375 || var2.vval.v_string == NULL)
4376 n1 = FALSE;
4377 else
4378 n1 = STRCMP(rettv->vval.v_string,
4379 var2.vval.v_string) == 0;
4380 if (type == TYPE_NEQUAL)
4381 n1 = !n1;
4385 #ifdef FEAT_FLOAT
4387 * If one of the two variables is a float, compare as a float.
4388 * When using "=~" or "!~", always compare as string.
4390 else if ((rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4391 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4393 float_T f1, f2;
4395 if (rettv->v_type == VAR_FLOAT)
4396 f1 = rettv->vval.v_float;
4397 else
4398 f1 = get_tv_number(rettv);
4399 if (var2.v_type == VAR_FLOAT)
4400 f2 = var2.vval.v_float;
4401 else
4402 f2 = get_tv_number(&var2);
4403 n1 = FALSE;
4404 switch (type)
4406 case TYPE_EQUAL: n1 = (f1 == f2); break;
4407 case TYPE_NEQUAL: n1 = (f1 != f2); break;
4408 case TYPE_GREATER: n1 = (f1 > f2); break;
4409 case TYPE_GEQUAL: n1 = (f1 >= f2); break;
4410 case TYPE_SMALLER: n1 = (f1 < f2); break;
4411 case TYPE_SEQUAL: n1 = (f1 <= f2); break;
4412 case TYPE_UNKNOWN:
4413 case TYPE_MATCH:
4414 case TYPE_NOMATCH: break; /* avoid gcc warning */
4417 #endif
4420 * If one of the two variables is a number, compare as a number.
4421 * When using "=~" or "!~", always compare as string.
4423 else if ((rettv->v_type == VAR_NUMBER || var2.v_type == VAR_NUMBER)
4424 && type != TYPE_MATCH && type != TYPE_NOMATCH)
4426 n1 = get_tv_number(rettv);
4427 n2 = get_tv_number(&var2);
4428 switch (type)
4430 case TYPE_EQUAL: n1 = (n1 == n2); break;
4431 case TYPE_NEQUAL: n1 = (n1 != n2); break;
4432 case TYPE_GREATER: n1 = (n1 > n2); break;
4433 case TYPE_GEQUAL: n1 = (n1 >= n2); break;
4434 case TYPE_SMALLER: n1 = (n1 < n2); break;
4435 case TYPE_SEQUAL: n1 = (n1 <= n2); break;
4436 case TYPE_UNKNOWN:
4437 case TYPE_MATCH:
4438 case TYPE_NOMATCH: break; /* avoid gcc warning */
4441 else
4443 s1 = get_tv_string_buf(rettv, buf1);
4444 s2 = get_tv_string_buf(&var2, buf2);
4445 if (type != TYPE_MATCH && type != TYPE_NOMATCH)
4446 i = ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2);
4447 else
4448 i = 0;
4449 n1 = FALSE;
4450 switch (type)
4452 case TYPE_EQUAL: n1 = (i == 0); break;
4453 case TYPE_NEQUAL: n1 = (i != 0); break;
4454 case TYPE_GREATER: n1 = (i > 0); break;
4455 case TYPE_GEQUAL: n1 = (i >= 0); break;
4456 case TYPE_SMALLER: n1 = (i < 0); break;
4457 case TYPE_SEQUAL: n1 = (i <= 0); break;
4459 case TYPE_MATCH:
4460 case TYPE_NOMATCH:
4461 /* avoid 'l' flag in 'cpoptions' */
4462 save_cpo = p_cpo;
4463 p_cpo = (char_u *)"";
4464 regmatch.regprog = vim_regcomp(s2,
4465 RE_MAGIC + RE_STRING);
4466 regmatch.rm_ic = ic;
4467 if (regmatch.regprog != NULL)
4469 n1 = vim_regexec_nl(&regmatch, s1, (colnr_T)0);
4470 vim_free(regmatch.regprog);
4471 if (type == TYPE_NOMATCH)
4472 n1 = !n1;
4474 p_cpo = save_cpo;
4475 break;
4477 case TYPE_UNKNOWN: break; /* avoid gcc warning */
4480 clear_tv(rettv);
4481 clear_tv(&var2);
4482 rettv->v_type = VAR_NUMBER;
4483 rettv->vval.v_number = n1;
4487 return OK;
4491 * Handle fourth level expression:
4492 * + number addition
4493 * - number subtraction
4494 * . string concatenation
4496 * "arg" must point to the first non-white of the expression.
4497 * "arg" is advanced to the next non-white after the recognized expression.
4499 * Return OK or FAIL.
4501 static int
4502 eval5(arg, rettv, evaluate)
4503 char_u **arg;
4504 typval_T *rettv;
4505 int evaluate;
4507 typval_T var2;
4508 typval_T var3;
4509 int op;
4510 long n1, n2;
4511 #ifdef FEAT_FLOAT
4512 float_T f1 = 0, f2 = 0;
4513 #endif
4514 char_u *s1, *s2;
4515 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
4516 char_u *p;
4519 * Get the first variable.
4521 if (eval6(arg, rettv, evaluate, FALSE) == FAIL)
4522 return FAIL;
4525 * Repeat computing, until no '+', '-' or '.' is following.
4527 for (;;)
4529 op = **arg;
4530 if (op != '+' && op != '-' && op != '.')
4531 break;
4533 if ((op != '+' || rettv->v_type != VAR_LIST)
4534 #ifdef FEAT_FLOAT
4535 && (op == '.' || rettv->v_type != VAR_FLOAT)
4536 #endif
4539 /* For "list + ...", an illegal use of the first operand as
4540 * a number cannot be determined before evaluating the 2nd
4541 * operand: if this is also a list, all is ok.
4542 * For "something . ...", "something - ..." or "non-list + ...",
4543 * we know that the first operand needs to be a string or number
4544 * without evaluating the 2nd operand. So check before to avoid
4545 * side effects after an error. */
4546 if (evaluate && get_tv_string_chk(rettv) == NULL)
4548 clear_tv(rettv);
4549 return FAIL;
4554 * Get the second variable.
4556 *arg = skipwhite(*arg + 1);
4557 if (eval6(arg, &var2, evaluate, op == '.') == FAIL)
4559 clear_tv(rettv);
4560 return FAIL;
4563 if (evaluate)
4566 * Compute the result.
4568 if (op == '.')
4570 s1 = get_tv_string_buf(rettv, buf1); /* already checked */
4571 s2 = get_tv_string_buf_chk(&var2, buf2);
4572 if (s2 == NULL) /* type error ? */
4574 clear_tv(rettv);
4575 clear_tv(&var2);
4576 return FAIL;
4578 p = concat_str(s1, s2);
4579 clear_tv(rettv);
4580 rettv->v_type = VAR_STRING;
4581 rettv->vval.v_string = p;
4583 else if (op == '+' && rettv->v_type == VAR_LIST
4584 && var2.v_type == VAR_LIST)
4586 /* concatenate Lists */
4587 if (list_concat(rettv->vval.v_list, var2.vval.v_list,
4588 &var3) == FAIL)
4590 clear_tv(rettv);
4591 clear_tv(&var2);
4592 return FAIL;
4594 clear_tv(rettv);
4595 *rettv = var3;
4597 else
4599 int error = FALSE;
4601 #ifdef FEAT_FLOAT
4602 if (rettv->v_type == VAR_FLOAT)
4604 f1 = rettv->vval.v_float;
4605 n1 = 0;
4607 else
4608 #endif
4610 n1 = get_tv_number_chk(rettv, &error);
4611 if (error)
4613 /* This can only happen for "list + non-list". For
4614 * "non-list + ..." or "something - ...", we returned
4615 * before evaluating the 2nd operand. */
4616 clear_tv(rettv);
4617 return FAIL;
4619 #ifdef FEAT_FLOAT
4620 if (var2.v_type == VAR_FLOAT)
4621 f1 = n1;
4622 #endif
4624 #ifdef FEAT_FLOAT
4625 if (var2.v_type == VAR_FLOAT)
4627 f2 = var2.vval.v_float;
4628 n2 = 0;
4630 else
4631 #endif
4633 n2 = get_tv_number_chk(&var2, &error);
4634 if (error)
4636 clear_tv(rettv);
4637 clear_tv(&var2);
4638 return FAIL;
4640 #ifdef FEAT_FLOAT
4641 if (rettv->v_type == VAR_FLOAT)
4642 f2 = n2;
4643 #endif
4645 clear_tv(rettv);
4647 #ifdef FEAT_FLOAT
4648 /* If there is a float on either side the result is a float. */
4649 if (rettv->v_type == VAR_FLOAT || var2.v_type == VAR_FLOAT)
4651 if (op == '+')
4652 f1 = f1 + f2;
4653 else
4654 f1 = f1 - f2;
4655 rettv->v_type = VAR_FLOAT;
4656 rettv->vval.v_float = f1;
4658 else
4659 #endif
4661 if (op == '+')
4662 n1 = n1 + n2;
4663 else
4664 n1 = n1 - n2;
4665 rettv->v_type = VAR_NUMBER;
4666 rettv->vval.v_number = n1;
4669 clear_tv(&var2);
4672 return OK;
4676 * Handle fifth level expression:
4677 * * number multiplication
4678 * / number division
4679 * % number modulo
4681 * "arg" must point to the first non-white of the expression.
4682 * "arg" is advanced to the next non-white after the recognized expression.
4684 * Return OK or FAIL.
4686 static int
4687 eval6(arg, rettv, evaluate, want_string)
4688 char_u **arg;
4689 typval_T *rettv;
4690 int evaluate;
4691 int want_string; /* after "." operator */
4693 typval_T var2;
4694 int op;
4695 long n1, n2;
4696 #ifdef FEAT_FLOAT
4697 int use_float = FALSE;
4698 float_T f1 = 0, f2;
4699 #endif
4700 int error = FALSE;
4703 * Get the first variable.
4705 if (eval7(arg, rettv, evaluate, want_string) == FAIL)
4706 return FAIL;
4709 * Repeat computing, until no '*', '/' or '%' is following.
4711 for (;;)
4713 op = **arg;
4714 if (op != '*' && op != '/' && op != '%')
4715 break;
4717 if (evaluate)
4719 #ifdef FEAT_FLOAT
4720 if (rettv->v_type == VAR_FLOAT)
4722 f1 = rettv->vval.v_float;
4723 use_float = TRUE;
4724 n1 = 0;
4726 else
4727 #endif
4728 n1 = get_tv_number_chk(rettv, &error);
4729 clear_tv(rettv);
4730 if (error)
4731 return FAIL;
4733 else
4734 n1 = 0;
4737 * Get the second variable.
4739 *arg = skipwhite(*arg + 1);
4740 if (eval7(arg, &var2, evaluate, FALSE) == FAIL)
4741 return FAIL;
4743 if (evaluate)
4745 #ifdef FEAT_FLOAT
4746 if (var2.v_type == VAR_FLOAT)
4748 if (!use_float)
4750 f1 = n1;
4751 use_float = TRUE;
4753 f2 = var2.vval.v_float;
4754 n2 = 0;
4756 else
4757 #endif
4759 n2 = get_tv_number_chk(&var2, &error);
4760 clear_tv(&var2);
4761 if (error)
4762 return FAIL;
4763 #ifdef FEAT_FLOAT
4764 if (use_float)
4765 f2 = n2;
4766 #endif
4770 * Compute the result.
4771 * When either side is a float the result is a float.
4773 #ifdef FEAT_FLOAT
4774 if (use_float)
4776 if (op == '*')
4777 f1 = f1 * f2;
4778 else if (op == '/')
4780 /* We rely on the floating point library to handle divide
4781 * by zero to result in "inf" and not a crash. */
4782 f1 = f1 / f2;
4784 else
4786 EMSG(_("E804: Cannot use '%' with Float"));
4787 return FAIL;
4789 rettv->v_type = VAR_FLOAT;
4790 rettv->vval.v_float = f1;
4792 else
4793 #endif
4795 if (op == '*')
4796 n1 = n1 * n2;
4797 else if (op == '/')
4799 if (n2 == 0) /* give an error message? */
4801 if (n1 == 0)
4802 n1 = -0x7fffffffL - 1L; /* similar to NaN */
4803 else if (n1 < 0)
4804 n1 = -0x7fffffffL;
4805 else
4806 n1 = 0x7fffffffL;
4808 else
4809 n1 = n1 / n2;
4811 else
4813 if (n2 == 0) /* give an error message? */
4814 n1 = 0;
4815 else
4816 n1 = n1 % n2;
4818 rettv->v_type = VAR_NUMBER;
4819 rettv->vval.v_number = n1;
4824 return OK;
4828 * Handle sixth level expression:
4829 * number number constant
4830 * "string" string constant
4831 * 'string' literal string constant
4832 * &option-name option value
4833 * @r register contents
4834 * identifier variable value
4835 * function() function call
4836 * $VAR environment variable
4837 * (expression) nested expression
4838 * [expr, expr] List
4839 * {key: val, key: val} Dictionary
4841 * Also handle:
4842 * ! in front logical NOT
4843 * - in front unary minus
4844 * + in front unary plus (ignored)
4845 * trailing [] subscript in String or List
4846 * trailing .name entry in Dictionary
4848 * "arg" must point to the first non-white of the expression.
4849 * "arg" is advanced to the next non-white after the recognized expression.
4851 * Return OK or FAIL.
4853 static int
4854 eval7(arg, rettv, evaluate, want_string)
4855 char_u **arg;
4856 typval_T *rettv;
4857 int evaluate;
4858 int want_string; /* after "." operator */
4860 long n;
4861 int len;
4862 char_u *s;
4863 char_u *start_leader, *end_leader;
4864 int ret = OK;
4865 char_u *alias;
4868 * Initialise variable so that clear_tv() can't mistake this for a
4869 * string and free a string that isn't there.
4871 rettv->v_type = VAR_UNKNOWN;
4874 * Skip '!' and '-' characters. They are handled later.
4876 start_leader = *arg;
4877 while (**arg == '!' || **arg == '-' || **arg == '+')
4878 *arg = skipwhite(*arg + 1);
4879 end_leader = *arg;
4881 switch (**arg)
4884 * Number constant.
4886 case '0':
4887 case '1':
4888 case '2':
4889 case '3':
4890 case '4':
4891 case '5':
4892 case '6':
4893 case '7':
4894 case '8':
4895 case '9':
4897 #ifdef FEAT_FLOAT
4898 char_u *p = skipdigits(*arg + 1);
4899 int get_float = FALSE;
4901 /* We accept a float when the format matches
4902 * "[0-9]\+\.[0-9]\+\([eE][+-]\?[0-9]\+\)\?". This is very
4903 * strict to avoid backwards compatibility problems.
4904 * Don't look for a float after the "." operator, so that
4905 * ":let vers = 1.2.3" doesn't fail. */
4906 if (!want_string && p[0] == '.' && vim_isdigit(p[1]))
4908 get_float = TRUE;
4909 p = skipdigits(p + 2);
4910 if (*p == 'e' || *p == 'E')
4912 ++p;
4913 if (*p == '-' || *p == '+')
4914 ++p;
4915 if (!vim_isdigit(*p))
4916 get_float = FALSE;
4917 else
4918 p = skipdigits(p + 1);
4920 if (ASCII_ISALPHA(*p) || *p == '.')
4921 get_float = FALSE;
4923 if (get_float)
4925 float_T f;
4927 *arg += string2float(*arg, &f);
4928 if (evaluate)
4930 rettv->v_type = VAR_FLOAT;
4931 rettv->vval.v_float = f;
4934 else
4935 #endif
4937 vim_str2nr(*arg, NULL, &len, TRUE, TRUE, &n, NULL);
4938 *arg += len;
4939 if (evaluate)
4941 rettv->v_type = VAR_NUMBER;
4942 rettv->vval.v_number = n;
4945 break;
4949 * String constant: "string".
4951 case '"': ret = get_string_tv(arg, rettv, evaluate);
4952 break;
4955 * Literal string constant: 'str''ing'.
4957 case '\'': ret = get_lit_string_tv(arg, rettv, evaluate);
4958 break;
4961 * List: [expr, expr]
4963 case '[': ret = get_list_tv(arg, rettv, evaluate);
4964 break;
4967 * Dictionary: {key: val, key: val}
4969 case '{': ret = get_dict_tv(arg, rettv, evaluate);
4970 break;
4973 * Option value: &name
4975 case '&': ret = get_option_tv(arg, rettv, evaluate);
4976 break;
4979 * Environment variable: $VAR.
4981 case '$': ret = get_env_tv(arg, rettv, evaluate);
4982 break;
4985 * Register contents: @r.
4987 case '@': ++*arg;
4988 if (evaluate)
4990 rettv->v_type = VAR_STRING;
4991 rettv->vval.v_string = get_reg_contents(**arg, TRUE, TRUE);
4993 if (**arg != NUL)
4994 ++*arg;
4995 break;
4998 * nested expression: (expression).
5000 case '(': *arg = skipwhite(*arg + 1);
5001 ret = eval1(arg, rettv, evaluate); /* recursive! */
5002 if (**arg == ')')
5003 ++*arg;
5004 else if (ret == OK)
5006 EMSG(_("E110: Missing ')'"));
5007 clear_tv(rettv);
5008 ret = FAIL;
5010 break;
5012 default: ret = NOTDONE;
5013 break;
5016 if (ret == NOTDONE)
5019 * Must be a variable or function name.
5020 * Can also be a curly-braces kind of name: {expr}.
5022 s = *arg;
5023 len = get_name_len(arg, &alias, evaluate, TRUE);
5024 if (alias != NULL)
5025 s = alias;
5027 if (len <= 0)
5028 ret = FAIL;
5029 else
5031 if (**arg == '(') /* recursive! */
5033 /* If "s" is the name of a variable of type VAR_FUNC
5034 * use its contents. */
5035 s = deref_func_name(s, &len);
5037 /* Invoke the function. */
5038 ret = get_func_tv(s, len, rettv, arg,
5039 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
5040 &len, evaluate, NULL);
5041 /* Stop the expression evaluation when immediately
5042 * aborting on error, or when an interrupt occurred or
5043 * an exception was thrown but not caught. */
5044 if (aborting())
5046 if (ret == OK)
5047 clear_tv(rettv);
5048 ret = FAIL;
5051 else if (evaluate)
5052 ret = get_var_tv(s, len, rettv, TRUE);
5053 else
5054 ret = OK;
5057 if (alias != NULL)
5058 vim_free(alias);
5061 *arg = skipwhite(*arg);
5063 /* Handle following '[', '(' and '.' for expr[expr], expr.name,
5064 * expr(expr). */
5065 if (ret == OK)
5066 ret = handle_subscript(arg, rettv, evaluate, TRUE);
5069 * Apply logical NOT and unary '-', from right to left, ignore '+'.
5071 if (ret == OK && evaluate && end_leader > start_leader)
5073 int error = FALSE;
5074 int val = 0;
5075 #ifdef FEAT_FLOAT
5076 float_T f = 0.0;
5078 if (rettv->v_type == VAR_FLOAT)
5079 f = rettv->vval.v_float;
5080 else
5081 #endif
5082 val = get_tv_number_chk(rettv, &error);
5083 if (error)
5085 clear_tv(rettv);
5086 ret = FAIL;
5088 else
5090 while (end_leader > start_leader)
5092 --end_leader;
5093 if (*end_leader == '!')
5095 #ifdef FEAT_FLOAT
5096 if (rettv->v_type == VAR_FLOAT)
5097 f = !f;
5098 else
5099 #endif
5100 val = !val;
5102 else if (*end_leader == '-')
5104 #ifdef FEAT_FLOAT
5105 if (rettv->v_type == VAR_FLOAT)
5106 f = -f;
5107 else
5108 #endif
5109 val = -val;
5112 #ifdef FEAT_FLOAT
5113 if (rettv->v_type == VAR_FLOAT)
5115 clear_tv(rettv);
5116 rettv->vval.v_float = f;
5118 else
5119 #endif
5121 clear_tv(rettv);
5122 rettv->v_type = VAR_NUMBER;
5123 rettv->vval.v_number = val;
5128 return ret;
5132 * Evaluate an "[expr]" or "[expr:expr]" index. Also "dict.key".
5133 * "*arg" points to the '[' or '.'.
5134 * Returns FAIL or OK. "*arg" is advanced to after the ']'.
5136 static int
5137 eval_index(arg, rettv, evaluate, verbose)
5138 char_u **arg;
5139 typval_T *rettv;
5140 int evaluate;
5141 int verbose; /* give error messages */
5143 int empty1 = FALSE, empty2 = FALSE;
5144 typval_T var1, var2;
5145 long n1, n2 = 0;
5146 long len = -1;
5147 int range = FALSE;
5148 char_u *s;
5149 char_u *key = NULL;
5151 if (rettv->v_type == VAR_FUNC
5152 #ifdef FEAT_FLOAT
5153 || rettv->v_type == VAR_FLOAT
5154 #endif
5157 if (verbose)
5158 EMSG(_("E695: Cannot index a Funcref"));
5159 return FAIL;
5162 if (**arg == '.')
5165 * dict.name
5167 key = *arg + 1;
5168 for (len = 0; ASCII_ISALNUM(key[len]) || key[len] == '_'; ++len)
5170 if (len == 0)
5171 return FAIL;
5172 *arg = skipwhite(key + len);
5174 else
5177 * something[idx]
5179 * Get the (first) variable from inside the [].
5181 *arg = skipwhite(*arg + 1);
5182 if (**arg == ':')
5183 empty1 = TRUE;
5184 else if (eval1(arg, &var1, evaluate) == FAIL) /* recursive! */
5185 return FAIL;
5186 else if (evaluate && get_tv_string_chk(&var1) == NULL)
5188 /* not a number or string */
5189 clear_tv(&var1);
5190 return FAIL;
5194 * Get the second variable from inside the [:].
5196 if (**arg == ':')
5198 range = TRUE;
5199 *arg = skipwhite(*arg + 1);
5200 if (**arg == ']')
5201 empty2 = TRUE;
5202 else if (eval1(arg, &var2, evaluate) == FAIL) /* recursive! */
5204 if (!empty1)
5205 clear_tv(&var1);
5206 return FAIL;
5208 else if (evaluate && get_tv_string_chk(&var2) == NULL)
5210 /* not a number or string */
5211 if (!empty1)
5212 clear_tv(&var1);
5213 clear_tv(&var2);
5214 return FAIL;
5218 /* Check for the ']'. */
5219 if (**arg != ']')
5221 if (verbose)
5222 EMSG(_(e_missbrac));
5223 clear_tv(&var1);
5224 if (range)
5225 clear_tv(&var2);
5226 return FAIL;
5228 *arg = skipwhite(*arg + 1); /* skip the ']' */
5231 if (evaluate)
5233 n1 = 0;
5234 if (!empty1 && rettv->v_type != VAR_DICT)
5236 n1 = get_tv_number(&var1);
5237 clear_tv(&var1);
5239 if (range)
5241 if (empty2)
5242 n2 = -1;
5243 else
5245 n2 = get_tv_number(&var2);
5246 clear_tv(&var2);
5250 switch (rettv->v_type)
5252 case VAR_NUMBER:
5253 case VAR_STRING:
5254 s = get_tv_string(rettv);
5255 len = (long)STRLEN(s);
5256 if (range)
5258 /* The resulting variable is a substring. If the indexes
5259 * are out of range the result is empty. */
5260 if (n1 < 0)
5262 n1 = len + n1;
5263 if (n1 < 0)
5264 n1 = 0;
5266 if (n2 < 0)
5267 n2 = len + n2;
5268 else if (n2 >= len)
5269 n2 = len;
5270 if (n1 >= len || n2 < 0 || n1 > n2)
5271 s = NULL;
5272 else
5273 s = vim_strnsave(s + n1, (int)(n2 - n1 + 1));
5275 else
5277 /* The resulting variable is a string of a single
5278 * character. If the index is too big or negative the
5279 * result is empty. */
5280 if (n1 >= len || n1 < 0)
5281 s = NULL;
5282 else
5283 s = vim_strnsave(s + n1, 1);
5285 clear_tv(rettv);
5286 rettv->v_type = VAR_STRING;
5287 rettv->vval.v_string = s;
5288 break;
5290 case VAR_LIST:
5291 len = list_len(rettv->vval.v_list);
5292 if (n1 < 0)
5293 n1 = len + n1;
5294 if (!empty1 && (n1 < 0 || n1 >= len))
5296 /* For a range we allow invalid values and return an empty
5297 * list. A list index out of range is an error. */
5298 if (!range)
5300 if (verbose)
5301 EMSGN(_(e_listidx), n1);
5302 return FAIL;
5304 n1 = len;
5306 if (range)
5308 list_T *l;
5309 listitem_T *item;
5311 if (n2 < 0)
5312 n2 = len + n2;
5313 else if (n2 >= len)
5314 n2 = len - 1;
5315 if (!empty2 && (n2 < 0 || n2 + 1 < n1))
5316 n2 = -1;
5317 l = list_alloc();
5318 if (l == NULL)
5319 return FAIL;
5320 for (item = list_find(rettv->vval.v_list, n1);
5321 n1 <= n2; ++n1)
5323 if (list_append_tv(l, &item->li_tv) == FAIL)
5325 list_free(l, TRUE);
5326 return FAIL;
5328 item = item->li_next;
5330 clear_tv(rettv);
5331 rettv->v_type = VAR_LIST;
5332 rettv->vval.v_list = l;
5333 ++l->lv_refcount;
5335 else
5337 copy_tv(&list_find(rettv->vval.v_list, n1)->li_tv, &var1);
5338 clear_tv(rettv);
5339 *rettv = var1;
5341 break;
5343 case VAR_DICT:
5344 if (range)
5346 if (verbose)
5347 EMSG(_(e_dictrange));
5348 if (len == -1)
5349 clear_tv(&var1);
5350 return FAIL;
5353 dictitem_T *item;
5355 if (len == -1)
5357 key = get_tv_string(&var1);
5358 if (*key == NUL)
5360 if (verbose)
5361 EMSG(_(e_emptykey));
5362 clear_tv(&var1);
5363 return FAIL;
5367 item = dict_find(rettv->vval.v_dict, key, (int)len);
5369 if (item == NULL && verbose)
5370 EMSG2(_(e_dictkey), key);
5371 if (len == -1)
5372 clear_tv(&var1);
5373 if (item == NULL)
5374 return FAIL;
5376 copy_tv(&item->di_tv, &var1);
5377 clear_tv(rettv);
5378 *rettv = var1;
5380 break;
5384 return OK;
5388 * Get an option value.
5389 * "arg" points to the '&' or '+' before the option name.
5390 * "arg" is advanced to character after the option name.
5391 * Return OK or FAIL.
5393 static int
5394 get_option_tv(arg, rettv, evaluate)
5395 char_u **arg;
5396 typval_T *rettv; /* when NULL, only check if option exists */
5397 int evaluate;
5399 char_u *option_end;
5400 long numval;
5401 char_u *stringval;
5402 int opt_type;
5403 int c;
5404 int working = (**arg == '+'); /* has("+option") */
5405 int ret = OK;
5406 int opt_flags;
5409 * Isolate the option name and find its value.
5411 option_end = find_option_end(arg, &opt_flags);
5412 if (option_end == NULL)
5414 if (rettv != NULL)
5415 EMSG2(_("E112: Option name missing: %s"), *arg);
5416 return FAIL;
5419 if (!evaluate)
5421 *arg = option_end;
5422 return OK;
5425 c = *option_end;
5426 *option_end = NUL;
5427 opt_type = get_option_value(*arg, &numval,
5428 rettv == NULL ? NULL : &stringval, opt_flags);
5430 if (opt_type == -3) /* invalid name */
5432 if (rettv != NULL)
5433 EMSG2(_("E113: Unknown option: %s"), *arg);
5434 ret = FAIL;
5436 else if (rettv != NULL)
5438 if (opt_type == -2) /* hidden string option */
5440 rettv->v_type = VAR_STRING;
5441 rettv->vval.v_string = NULL;
5443 else if (opt_type == -1) /* hidden number option */
5445 rettv->v_type = VAR_NUMBER;
5446 rettv->vval.v_number = 0;
5448 else if (opt_type == 1) /* number option */
5450 rettv->v_type = VAR_NUMBER;
5451 rettv->vval.v_number = numval;
5453 else /* string option */
5455 rettv->v_type = VAR_STRING;
5456 rettv->vval.v_string = stringval;
5459 else if (working && (opt_type == -2 || opt_type == -1))
5460 ret = FAIL;
5462 *option_end = c; /* put back for error messages */
5463 *arg = option_end;
5465 return ret;
5469 * Allocate a variable for a string constant.
5470 * Return OK or FAIL.
5472 static int
5473 get_string_tv(arg, rettv, evaluate)
5474 char_u **arg;
5475 typval_T *rettv;
5476 int evaluate;
5478 char_u *p;
5479 char_u *name;
5480 int extra = 0;
5483 * Find the end of the string, skipping backslashed characters.
5485 for (p = *arg + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
5487 if (*p == '\\' && p[1] != NUL)
5489 ++p;
5490 /* A "\<x>" form occupies at least 4 characters, and produces up
5491 * to 6 characters: reserve space for 2 extra */
5492 if (*p == '<')
5493 extra += 2;
5497 if (*p != '"')
5499 EMSG2(_("E114: Missing quote: %s"), *arg);
5500 return FAIL;
5503 /* If only parsing, set *arg and return here */
5504 if (!evaluate)
5506 *arg = p + 1;
5507 return OK;
5511 * Copy the string into allocated memory, handling backslashed
5512 * characters.
5514 name = alloc((unsigned)(p - *arg + extra));
5515 if (name == NULL)
5516 return FAIL;
5517 rettv->v_type = VAR_STRING;
5518 rettv->vval.v_string = name;
5520 for (p = *arg + 1; *p != NUL && *p != '"'; )
5522 if (*p == '\\')
5524 switch (*++p)
5526 case 'b': *name++ = BS; ++p; break;
5527 case 'e': *name++ = ESC; ++p; break;
5528 case 'f': *name++ = FF; ++p; break;
5529 case 'n': *name++ = NL; ++p; break;
5530 case 'r': *name++ = CAR; ++p; break;
5531 case 't': *name++ = TAB; ++p; break;
5533 case 'X': /* hex: "\x1", "\x12" */
5534 case 'x':
5535 case 'u': /* Unicode: "\u0023" */
5536 case 'U':
5537 if (vim_isxdigit(p[1]))
5539 int n, nr;
5540 int c = toupper(*p);
5542 if (c == 'X')
5543 n = 2;
5544 else
5545 n = 4;
5546 nr = 0;
5547 while (--n >= 0 && vim_isxdigit(p[1]))
5549 ++p;
5550 nr = (nr << 4) + hex2nr(*p);
5552 ++p;
5553 #ifdef FEAT_MBYTE
5554 /* For "\u" store the number according to
5555 * 'encoding'. */
5556 if (c != 'X')
5557 name += (*mb_char2bytes)(nr, name);
5558 else
5559 #endif
5560 *name++ = nr;
5562 break;
5564 /* octal: "\1", "\12", "\123" */
5565 case '0':
5566 case '1':
5567 case '2':
5568 case '3':
5569 case '4':
5570 case '5':
5571 case '6':
5572 case '7': *name = *p++ - '0';
5573 if (*p >= '0' && *p <= '7')
5575 *name = (*name << 3) + *p++ - '0';
5576 if (*p >= '0' && *p <= '7')
5577 *name = (*name << 3) + *p++ - '0';
5579 ++name;
5580 break;
5582 /* Special key, e.g.: "\<C-W>" */
5583 case '<': extra = trans_special(&p, name, TRUE);
5584 if (extra != 0)
5586 name += extra;
5587 break;
5589 /* FALLTHROUGH */
5591 default: MB_COPY_CHAR(p, name);
5592 break;
5595 else
5596 MB_COPY_CHAR(p, name);
5599 *name = NUL;
5600 *arg = p + 1;
5602 return OK;
5606 * Allocate a variable for a 'str''ing' constant.
5607 * Return OK or FAIL.
5609 static int
5610 get_lit_string_tv(arg, rettv, evaluate)
5611 char_u **arg;
5612 typval_T *rettv;
5613 int evaluate;
5615 char_u *p;
5616 char_u *str;
5617 int reduce = 0;
5620 * Find the end of the string, skipping ''.
5622 for (p = *arg + 1; *p != NUL; mb_ptr_adv(p))
5624 if (*p == '\'')
5626 if (p[1] != '\'')
5627 break;
5628 ++reduce;
5629 ++p;
5633 if (*p != '\'')
5635 EMSG2(_("E115: Missing quote: %s"), *arg);
5636 return FAIL;
5639 /* If only parsing return after setting "*arg" */
5640 if (!evaluate)
5642 *arg = p + 1;
5643 return OK;
5647 * Copy the string into allocated memory, handling '' to ' reduction.
5649 str = alloc((unsigned)((p - *arg) - reduce));
5650 if (str == NULL)
5651 return FAIL;
5652 rettv->v_type = VAR_STRING;
5653 rettv->vval.v_string = str;
5655 for (p = *arg + 1; *p != NUL; )
5657 if (*p == '\'')
5659 if (p[1] != '\'')
5660 break;
5661 ++p;
5663 MB_COPY_CHAR(p, str);
5665 *str = NUL;
5666 *arg = p + 1;
5668 return OK;
5672 * Allocate a variable for a List and fill it from "*arg".
5673 * Return OK or FAIL.
5675 static int
5676 get_list_tv(arg, rettv, evaluate)
5677 char_u **arg;
5678 typval_T *rettv;
5679 int evaluate;
5681 list_T *l = NULL;
5682 typval_T tv;
5683 listitem_T *item;
5685 if (evaluate)
5687 l = list_alloc();
5688 if (l == NULL)
5689 return FAIL;
5692 *arg = skipwhite(*arg + 1);
5693 while (**arg != ']' && **arg != NUL)
5695 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
5696 goto failret;
5697 if (evaluate)
5699 item = listitem_alloc();
5700 if (item != NULL)
5702 item->li_tv = tv;
5703 item->li_tv.v_lock = 0;
5704 list_append(l, item);
5706 else
5707 clear_tv(&tv);
5710 if (**arg == ']')
5711 break;
5712 if (**arg != ',')
5714 EMSG2(_("E696: Missing comma in List: %s"), *arg);
5715 goto failret;
5717 *arg = skipwhite(*arg + 1);
5720 if (**arg != ']')
5722 EMSG2(_("E697: Missing end of List ']': %s"), *arg);
5723 failret:
5724 if (evaluate)
5725 list_free(l, TRUE);
5726 return FAIL;
5729 *arg = skipwhite(*arg + 1);
5730 if (evaluate)
5732 rettv->v_type = VAR_LIST;
5733 rettv->vval.v_list = l;
5734 ++l->lv_refcount;
5737 return OK;
5741 * Allocate an empty header for a list.
5742 * Caller should take care of the reference count.
5744 list_T *
5745 list_alloc()
5747 list_T *l;
5749 l = (list_T *)alloc_clear(sizeof(list_T));
5750 if (l != NULL)
5752 /* Prepend the list to the list of lists for garbage collection. */
5753 if (first_list != NULL)
5754 first_list->lv_used_prev = l;
5755 l->lv_used_prev = NULL;
5756 l->lv_used_next = first_list;
5757 first_list = l;
5759 return l;
5763 * Allocate an empty list for a return value.
5764 * Returns OK or FAIL.
5766 static int
5767 rettv_list_alloc(rettv)
5768 typval_T *rettv;
5770 list_T *l = list_alloc();
5772 if (l == NULL)
5773 return FAIL;
5775 rettv->vval.v_list = l;
5776 rettv->v_type = VAR_LIST;
5777 ++l->lv_refcount;
5778 return OK;
5782 * Unreference a list: decrement the reference count and free it when it
5783 * becomes zero.
5785 void
5786 list_unref(l)
5787 list_T *l;
5789 if (l != NULL && --l->lv_refcount <= 0)
5790 list_free(l, TRUE);
5794 * Free a list, including all items it points to.
5795 * Ignores the reference count.
5797 void
5798 list_free(l, recurse)
5799 list_T *l;
5800 int recurse; /* Free Lists and Dictionaries recursively. */
5802 listitem_T *item;
5804 /* Remove the list from the list of lists for garbage collection. */
5805 if (l->lv_used_prev == NULL)
5806 first_list = l->lv_used_next;
5807 else
5808 l->lv_used_prev->lv_used_next = l->lv_used_next;
5809 if (l->lv_used_next != NULL)
5810 l->lv_used_next->lv_used_prev = l->lv_used_prev;
5812 for (item = l->lv_first; item != NULL; item = l->lv_first)
5814 /* Remove the item before deleting it. */
5815 l->lv_first = item->li_next;
5816 if (recurse || (item->li_tv.v_type != VAR_LIST
5817 && item->li_tv.v_type != VAR_DICT))
5818 clear_tv(&item->li_tv);
5819 vim_free(item);
5821 vim_free(l);
5825 * Allocate a list item.
5827 static listitem_T *
5828 listitem_alloc()
5830 return (listitem_T *)alloc(sizeof(listitem_T));
5834 * Free a list item. Also clears the value. Does not notify watchers.
5836 static void
5837 listitem_free(item)
5838 listitem_T *item;
5840 clear_tv(&item->li_tv);
5841 vim_free(item);
5845 * Remove a list item from a List and free it. Also clears the value.
5847 static void
5848 listitem_remove(l, item)
5849 list_T *l;
5850 listitem_T *item;
5852 list_remove(l, item, item);
5853 listitem_free(item);
5857 * Get the number of items in a list.
5859 static long
5860 list_len(l)
5861 list_T *l;
5863 if (l == NULL)
5864 return 0L;
5865 return l->lv_len;
5869 * Return TRUE when two lists have exactly the same values.
5871 static int
5872 list_equal(l1, l2, ic)
5873 list_T *l1;
5874 list_T *l2;
5875 int ic; /* ignore case for strings */
5877 listitem_T *item1, *item2;
5879 if (l1 == NULL || l2 == NULL)
5880 return FALSE;
5881 if (l1 == l2)
5882 return TRUE;
5883 if (list_len(l1) != list_len(l2))
5884 return FALSE;
5886 for (item1 = l1->lv_first, item2 = l2->lv_first;
5887 item1 != NULL && item2 != NULL;
5888 item1 = item1->li_next, item2 = item2->li_next)
5889 if (!tv_equal(&item1->li_tv, &item2->li_tv, ic))
5890 return FALSE;
5891 return item1 == NULL && item2 == NULL;
5894 #if defined(FEAT_RUBY) || defined(FEAT_PYTHON) || defined(FEAT_MZSCHEME) \
5895 || defined(PROTO)
5897 * Return the dictitem that an entry in a hashtable points to.
5899 dictitem_T *
5900 dict_lookup(hi)
5901 hashitem_T *hi;
5903 return HI2DI(hi);
5905 #endif
5908 * Return TRUE when two dictionaries have exactly the same key/values.
5910 static int
5911 dict_equal(d1, d2, ic)
5912 dict_T *d1;
5913 dict_T *d2;
5914 int ic; /* ignore case for strings */
5916 hashitem_T *hi;
5917 dictitem_T *item2;
5918 int todo;
5920 if (d1 == NULL || d2 == NULL)
5921 return FALSE;
5922 if (d1 == d2)
5923 return TRUE;
5924 if (dict_len(d1) != dict_len(d2))
5925 return FALSE;
5927 todo = (int)d1->dv_hashtab.ht_used;
5928 for (hi = d1->dv_hashtab.ht_array; todo > 0; ++hi)
5930 if (!HASHITEM_EMPTY(hi))
5932 item2 = dict_find(d2, hi->hi_key, -1);
5933 if (item2 == NULL)
5934 return FALSE;
5935 if (!tv_equal(&HI2DI(hi)->di_tv, &item2->di_tv, ic))
5936 return FALSE;
5937 --todo;
5940 return TRUE;
5944 * Return TRUE if "tv1" and "tv2" have the same value.
5945 * Compares the items just like "==" would compare them, but strings and
5946 * numbers are different. Floats and numbers are also different.
5948 static int
5949 tv_equal(tv1, tv2, ic)
5950 typval_T *tv1;
5951 typval_T *tv2;
5952 int ic; /* ignore case */
5954 char_u buf1[NUMBUFLEN], buf2[NUMBUFLEN];
5955 char_u *s1, *s2;
5956 static int recursive = 0; /* cach recursive loops */
5957 int r;
5959 if (tv1->v_type != tv2->v_type)
5960 return FALSE;
5961 /* Catch lists and dicts that have an endless loop by limiting
5962 * recursiveness to 1000. We guess they are equal then. */
5963 if (recursive >= 1000)
5964 return TRUE;
5966 switch (tv1->v_type)
5968 case VAR_LIST:
5969 ++recursive;
5970 r = list_equal(tv1->vval.v_list, tv2->vval.v_list, ic);
5971 --recursive;
5972 return r;
5974 case VAR_DICT:
5975 ++recursive;
5976 r = dict_equal(tv1->vval.v_dict, tv2->vval.v_dict, ic);
5977 --recursive;
5978 return r;
5980 case VAR_FUNC:
5981 return (tv1->vval.v_string != NULL
5982 && tv2->vval.v_string != NULL
5983 && STRCMP(tv1->vval.v_string, tv2->vval.v_string) == 0);
5985 case VAR_NUMBER:
5986 return tv1->vval.v_number == tv2->vval.v_number;
5988 #ifdef FEAT_FLOAT
5989 case VAR_FLOAT:
5990 return tv1->vval.v_float == tv2->vval.v_float;
5991 #endif
5993 case VAR_STRING:
5994 s1 = get_tv_string_buf(tv1, buf1);
5995 s2 = get_tv_string_buf(tv2, buf2);
5996 return ((ic ? MB_STRICMP(s1, s2) : STRCMP(s1, s2)) == 0);
5999 EMSG2(_(e_intern2), "tv_equal()");
6000 return TRUE;
6004 * Locate item with index "n" in list "l" and return it.
6005 * A negative index is counted from the end; -1 is the last item.
6006 * Returns NULL when "n" is out of range.
6008 static listitem_T *
6009 list_find(l, n)
6010 list_T *l;
6011 long n;
6013 listitem_T *item;
6014 long idx;
6016 if (l == NULL)
6017 return NULL;
6019 /* Negative index is relative to the end. */
6020 if (n < 0)
6021 n = l->lv_len + n;
6023 /* Check for index out of range. */
6024 if (n < 0 || n >= l->lv_len)
6025 return NULL;
6027 /* When there is a cached index may start search from there. */
6028 if (l->lv_idx_item != NULL)
6030 if (n < l->lv_idx / 2)
6032 /* closest to the start of the list */
6033 item = l->lv_first;
6034 idx = 0;
6036 else if (n > (l->lv_idx + l->lv_len) / 2)
6038 /* closest to the end of the list */
6039 item = l->lv_last;
6040 idx = l->lv_len - 1;
6042 else
6044 /* closest to the cached index */
6045 item = l->lv_idx_item;
6046 idx = l->lv_idx;
6049 else
6051 if (n < l->lv_len / 2)
6053 /* closest to the start of the list */
6054 item = l->lv_first;
6055 idx = 0;
6057 else
6059 /* closest to the end of the list */
6060 item = l->lv_last;
6061 idx = l->lv_len - 1;
6065 while (n > idx)
6067 /* search forward */
6068 item = item->li_next;
6069 ++idx;
6071 while (n < idx)
6073 /* search backward */
6074 item = item->li_prev;
6075 --idx;
6078 /* cache the used index */
6079 l->lv_idx = idx;
6080 l->lv_idx_item = item;
6082 return item;
6086 * Get list item "l[idx]" as a number.
6088 static long
6089 list_find_nr(l, idx, errorp)
6090 list_T *l;
6091 long idx;
6092 int *errorp; /* set to TRUE when something wrong */
6094 listitem_T *li;
6096 li = list_find(l, idx);
6097 if (li == NULL)
6099 if (errorp != NULL)
6100 *errorp = TRUE;
6101 return -1L;
6103 return get_tv_number_chk(&li->li_tv, errorp);
6107 * Get list item "l[idx - 1]" as a string. Returns NULL for failure.
6109 char_u *
6110 list_find_str(l, idx)
6111 list_T *l;
6112 long idx;
6114 listitem_T *li;
6116 li = list_find(l, idx - 1);
6117 if (li == NULL)
6119 EMSGN(_(e_listidx), idx);
6120 return NULL;
6122 return get_tv_string(&li->li_tv);
6126 * Locate "item" list "l" and return its index.
6127 * Returns -1 when "item" is not in the list.
6129 static long
6130 list_idx_of_item(l, item)
6131 list_T *l;
6132 listitem_T *item;
6134 long idx = 0;
6135 listitem_T *li;
6137 if (l == NULL)
6138 return -1;
6139 idx = 0;
6140 for (li = l->lv_first; li != NULL && li != item; li = li->li_next)
6141 ++idx;
6142 if (li == NULL)
6143 return -1;
6144 return idx;
6148 * Append item "item" to the end of list "l".
6150 static void
6151 list_append(l, item)
6152 list_T *l;
6153 listitem_T *item;
6155 if (l->lv_last == NULL)
6157 /* empty list */
6158 l->lv_first = item;
6159 l->lv_last = item;
6160 item->li_prev = NULL;
6162 else
6164 l->lv_last->li_next = item;
6165 item->li_prev = l->lv_last;
6166 l->lv_last = item;
6168 ++l->lv_len;
6169 item->li_next = NULL;
6173 * Append typval_T "tv" to the end of list "l".
6174 * Return FAIL when out of memory.
6177 list_append_tv(l, tv)
6178 list_T *l;
6179 typval_T *tv;
6181 listitem_T *li = listitem_alloc();
6183 if (li == NULL)
6184 return FAIL;
6185 copy_tv(tv, &li->li_tv);
6186 list_append(l, li);
6187 return OK;
6191 * Add a dictionary to a list. Used by getqflist().
6192 * Return FAIL when out of memory.
6195 list_append_dict(list, dict)
6196 list_T *list;
6197 dict_T *dict;
6199 listitem_T *li = listitem_alloc();
6201 if (li == NULL)
6202 return FAIL;
6203 li->li_tv.v_type = VAR_DICT;
6204 li->li_tv.v_lock = 0;
6205 li->li_tv.vval.v_dict = dict;
6206 list_append(list, li);
6207 ++dict->dv_refcount;
6208 return OK;
6212 * Make a copy of "str" and append it as an item to list "l".
6213 * When "len" >= 0 use "str[len]".
6214 * Returns FAIL when out of memory.
6217 list_append_string(l, str, len)
6218 list_T *l;
6219 char_u *str;
6220 int len;
6222 listitem_T *li = listitem_alloc();
6224 if (li == NULL)
6225 return FAIL;
6226 list_append(l, li);
6227 li->li_tv.v_type = VAR_STRING;
6228 li->li_tv.v_lock = 0;
6229 if (str == NULL)
6230 li->li_tv.vval.v_string = NULL;
6231 else if ((li->li_tv.vval.v_string = (len >= 0 ? vim_strnsave(str, len)
6232 : vim_strsave(str))) == NULL)
6233 return FAIL;
6234 return OK;
6238 * Append "n" to list "l".
6239 * Returns FAIL when out of memory.
6241 static int
6242 list_append_number(l, n)
6243 list_T *l;
6244 varnumber_T n;
6246 listitem_T *li;
6248 li = listitem_alloc();
6249 if (li == NULL)
6250 return FAIL;
6251 li->li_tv.v_type = VAR_NUMBER;
6252 li->li_tv.v_lock = 0;
6253 li->li_tv.vval.v_number = n;
6254 list_append(l, li);
6255 return OK;
6259 * Insert typval_T "tv" in list "l" before "item".
6260 * If "item" is NULL append at the end.
6261 * Return FAIL when out of memory.
6263 static int
6264 list_insert_tv(l, tv, item)
6265 list_T *l;
6266 typval_T *tv;
6267 listitem_T *item;
6269 listitem_T *ni = listitem_alloc();
6271 if (ni == NULL)
6272 return FAIL;
6273 copy_tv(tv, &ni->li_tv);
6274 if (item == NULL)
6275 /* Append new item at end of list. */
6276 list_append(l, ni);
6277 else
6279 /* Insert new item before existing item. */
6280 ni->li_prev = item->li_prev;
6281 ni->li_next = item;
6282 if (item->li_prev == NULL)
6284 l->lv_first = ni;
6285 ++l->lv_idx;
6287 else
6289 item->li_prev->li_next = ni;
6290 l->lv_idx_item = NULL;
6292 item->li_prev = ni;
6293 ++l->lv_len;
6295 return OK;
6299 * Extend "l1" with "l2".
6300 * If "bef" is NULL append at the end, otherwise insert before this item.
6301 * Returns FAIL when out of memory.
6303 static int
6304 list_extend(l1, l2, bef)
6305 list_T *l1;
6306 list_T *l2;
6307 listitem_T *bef;
6309 listitem_T *item;
6310 int todo = l2->lv_len;
6312 /* We also quit the loop when we have inserted the original item count of
6313 * the list, avoid a hang when we extend a list with itself. */
6314 for (item = l2->lv_first; item != NULL && --todo >= 0; item = item->li_next)
6315 if (list_insert_tv(l1, &item->li_tv, bef) == FAIL)
6316 return FAIL;
6317 return OK;
6321 * Concatenate lists "l1" and "l2" into a new list, stored in "tv".
6322 * Return FAIL when out of memory.
6324 static int
6325 list_concat(l1, l2, tv)
6326 list_T *l1;
6327 list_T *l2;
6328 typval_T *tv;
6330 list_T *l;
6332 if (l1 == NULL || l2 == NULL)
6333 return FAIL;
6335 /* make a copy of the first list. */
6336 l = list_copy(l1, FALSE, 0);
6337 if (l == NULL)
6338 return FAIL;
6339 tv->v_type = VAR_LIST;
6340 tv->vval.v_list = l;
6342 /* append all items from the second list */
6343 return list_extend(l, l2, NULL);
6347 * Make a copy of list "orig". Shallow if "deep" is FALSE.
6348 * The refcount of the new list is set to 1.
6349 * See item_copy() for "copyID".
6350 * Returns NULL when out of memory.
6352 static list_T *
6353 list_copy(orig, deep, copyID)
6354 list_T *orig;
6355 int deep;
6356 int copyID;
6358 list_T *copy;
6359 listitem_T *item;
6360 listitem_T *ni;
6362 if (orig == NULL)
6363 return NULL;
6365 copy = list_alloc();
6366 if (copy != NULL)
6368 if (copyID != 0)
6370 /* Do this before adding the items, because one of the items may
6371 * refer back to this list. */
6372 orig->lv_copyID = copyID;
6373 orig->lv_copylist = copy;
6375 for (item = orig->lv_first; item != NULL && !got_int;
6376 item = item->li_next)
6378 ni = listitem_alloc();
6379 if (ni == NULL)
6380 break;
6381 if (deep)
6383 if (item_copy(&item->li_tv, &ni->li_tv, deep, copyID) == FAIL)
6385 vim_free(ni);
6386 break;
6389 else
6390 copy_tv(&item->li_tv, &ni->li_tv);
6391 list_append(copy, ni);
6393 ++copy->lv_refcount;
6394 if (item != NULL)
6396 list_unref(copy);
6397 copy = NULL;
6401 return copy;
6405 * Remove items "item" to "item2" from list "l".
6406 * Does not free the listitem or the value!
6408 static void
6409 list_remove(l, item, item2)
6410 list_T *l;
6411 listitem_T *item;
6412 listitem_T *item2;
6414 listitem_T *ip;
6416 /* notify watchers */
6417 for (ip = item; ip != NULL; ip = ip->li_next)
6419 --l->lv_len;
6420 list_fix_watch(l, ip);
6421 if (ip == item2)
6422 break;
6425 if (item2->li_next == NULL)
6426 l->lv_last = item->li_prev;
6427 else
6428 item2->li_next->li_prev = item->li_prev;
6429 if (item->li_prev == NULL)
6430 l->lv_first = item2->li_next;
6431 else
6432 item->li_prev->li_next = item2->li_next;
6433 l->lv_idx_item = NULL;
6437 * Return an allocated string with the string representation of a list.
6438 * May return NULL.
6440 static char_u *
6441 list2string(tv, copyID)
6442 typval_T *tv;
6443 int copyID;
6445 garray_T ga;
6447 if (tv->vval.v_list == NULL)
6448 return NULL;
6449 ga_init2(&ga, (int)sizeof(char), 80);
6450 ga_append(&ga, '[');
6451 if (list_join(&ga, tv->vval.v_list, (char_u *)", ", FALSE, copyID) == FAIL)
6453 vim_free(ga.ga_data);
6454 return NULL;
6456 ga_append(&ga, ']');
6457 ga_append(&ga, NUL);
6458 return (char_u *)ga.ga_data;
6462 * Join list "l" into a string in "*gap", using separator "sep".
6463 * When "echo" is TRUE use String as echoed, otherwise as inside a List.
6464 * Return FAIL or OK.
6466 static int
6467 list_join(gap, l, sep, echo, copyID)
6468 garray_T *gap;
6469 list_T *l;
6470 char_u *sep;
6471 int echo;
6472 int copyID;
6474 int first = TRUE;
6475 char_u *tofree;
6476 char_u numbuf[NUMBUFLEN];
6477 listitem_T *item;
6478 char_u *s;
6480 for (item = l->lv_first; item != NULL && !got_int; item = item->li_next)
6482 if (first)
6483 first = FALSE;
6484 else
6485 ga_concat(gap, sep);
6487 if (echo)
6488 s = echo_string(&item->li_tv, &tofree, numbuf, copyID);
6489 else
6490 s = tv2string(&item->li_tv, &tofree, numbuf, copyID);
6491 if (s != NULL)
6492 ga_concat(gap, s);
6493 vim_free(tofree);
6494 if (s == NULL)
6495 return FAIL;
6496 line_breakcheck();
6498 return OK;
6502 * Garbage collection for lists and dictionaries.
6504 * We use reference counts to be able to free most items right away when they
6505 * are no longer used. But for composite items it's possible that it becomes
6506 * unused while the reference count is > 0: When there is a recursive
6507 * reference. Example:
6508 * :let l = [1, 2, 3]
6509 * :let d = {9: l}
6510 * :let l[1] = d
6512 * Since this is quite unusual we handle this with garbage collection: every
6513 * once in a while find out which lists and dicts are not referenced from any
6514 * variable.
6516 * Here is a good reference text about garbage collection (refers to Python
6517 * but it applies to all reference-counting mechanisms):
6518 * http://python.ca/nas/python/gc/
6522 * Do garbage collection for lists and dicts.
6523 * Return TRUE if some memory was freed.
6526 garbage_collect()
6528 int copyID;
6529 buf_T *buf;
6530 win_T *wp;
6531 int i;
6532 funccall_T *fc, **pfc;
6533 int did_free;
6534 int did_free_funccal = FALSE;
6535 #ifdef FEAT_WINDOWS
6536 tabpage_T *tp;
6537 #endif
6539 /* Only do this once. */
6540 want_garbage_collect = FALSE;
6541 may_garbage_collect = FALSE;
6542 garbage_collect_at_exit = FALSE;
6544 /* We advance by two because we add one for items referenced through
6545 * previous_funccal. */
6546 current_copyID += COPYID_INC;
6547 copyID = current_copyID;
6550 * 1. Go through all accessible variables and mark all lists and dicts
6551 * with copyID.
6554 /* Don't free variables in the previous_funccal list unless they are only
6555 * referenced through previous_funccal. This must be first, because if
6556 * the item is referenced elsewhere the funccal must not be freed. */
6557 for (fc = previous_funccal; fc != NULL; fc = fc->caller)
6559 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID + 1);
6560 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID + 1);
6563 /* script-local variables */
6564 for (i = 1; i <= ga_scripts.ga_len; ++i)
6565 set_ref_in_ht(&SCRIPT_VARS(i), copyID);
6567 /* buffer-local variables */
6568 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6569 set_ref_in_ht(&buf->b_vars.dv_hashtab, copyID);
6571 /* window-local variables */
6572 FOR_ALL_TAB_WINDOWS(tp, wp)
6573 set_ref_in_ht(&wp->w_vars.dv_hashtab, copyID);
6575 #ifdef FEAT_WINDOWS
6576 /* tabpage-local variables */
6577 for (tp = first_tabpage; tp != NULL; tp = tp->tp_next)
6578 set_ref_in_ht(&tp->tp_vars.dv_hashtab, copyID);
6579 #endif
6581 /* global variables */
6582 set_ref_in_ht(&globvarht, copyID);
6584 /* function-local variables */
6585 for (fc = current_funccal; fc != NULL; fc = fc->caller)
6587 set_ref_in_ht(&fc->l_vars.dv_hashtab, copyID);
6588 set_ref_in_ht(&fc->l_avars.dv_hashtab, copyID);
6591 /* v: vars */
6592 set_ref_in_ht(&vimvarht, copyID);
6595 * 2. Free lists and dictionaries that are not referenced.
6597 did_free = free_unref_items(copyID);
6600 * 3. Check if any funccal can be freed now.
6602 for (pfc = &previous_funccal; *pfc != NULL; )
6604 if (can_free_funccal(*pfc, copyID))
6606 fc = *pfc;
6607 *pfc = fc->caller;
6608 free_funccal(fc, TRUE);
6609 did_free = TRUE;
6610 did_free_funccal = TRUE;
6612 else
6613 pfc = &(*pfc)->caller;
6615 if (did_free_funccal)
6616 /* When a funccal was freed some more items might be garbage
6617 * collected, so run again. */
6618 (void)garbage_collect();
6620 return did_free;
6624 * Free lists and dictionaries that are no longer referenced.
6626 static int
6627 free_unref_items(copyID)
6628 int copyID;
6630 dict_T *dd;
6631 list_T *ll;
6632 int did_free = FALSE;
6635 * Go through the list of dicts and free items without the copyID.
6637 for (dd = first_dict; dd != NULL; )
6638 if ((dd->dv_copyID & COPYID_MASK) != (copyID & COPYID_MASK))
6640 /* Free the Dictionary and ordinary items it contains, but don't
6641 * recurse into Lists and Dictionaries, they will be in the list
6642 * of dicts or list of lists. */
6643 dict_free(dd, FALSE);
6644 did_free = TRUE;
6646 /* restart, next dict may also have been freed */
6647 dd = first_dict;
6649 else
6650 dd = dd->dv_used_next;
6653 * Go through the list of lists and free items without the copyID.
6654 * But don't free a list that has a watcher (used in a for loop), these
6655 * are not referenced anywhere.
6657 for (ll = first_list; ll != NULL; )
6658 if ((ll->lv_copyID & COPYID_MASK) != (copyID & COPYID_MASK)
6659 && ll->lv_watch == NULL)
6661 /* Free the List and ordinary items it contains, but don't recurse
6662 * into Lists and Dictionaries, they will be in the list of dicts
6663 * or list of lists. */
6664 list_free(ll, FALSE);
6665 did_free = TRUE;
6667 /* restart, next list may also have been freed */
6668 ll = first_list;
6670 else
6671 ll = ll->lv_used_next;
6673 return did_free;
6677 * Mark all lists and dicts referenced through hashtab "ht" with "copyID".
6679 static void
6680 set_ref_in_ht(ht, copyID)
6681 hashtab_T *ht;
6682 int copyID;
6684 int todo;
6685 hashitem_T *hi;
6687 todo = (int)ht->ht_used;
6688 for (hi = ht->ht_array; todo > 0; ++hi)
6689 if (!HASHITEM_EMPTY(hi))
6691 --todo;
6692 set_ref_in_item(&HI2DI(hi)->di_tv, copyID);
6697 * Mark all lists and dicts referenced through list "l" with "copyID".
6699 static void
6700 set_ref_in_list(l, copyID)
6701 list_T *l;
6702 int copyID;
6704 listitem_T *li;
6706 for (li = l->lv_first; li != NULL; li = li->li_next)
6707 set_ref_in_item(&li->li_tv, copyID);
6711 * Mark all lists and dicts referenced through typval "tv" with "copyID".
6713 static void
6714 set_ref_in_item(tv, copyID)
6715 typval_T *tv;
6716 int copyID;
6718 dict_T *dd;
6719 list_T *ll;
6721 switch (tv->v_type)
6723 case VAR_DICT:
6724 dd = tv->vval.v_dict;
6725 if (dd != NULL && dd->dv_copyID != copyID)
6727 /* Didn't see this dict yet. */
6728 dd->dv_copyID = copyID;
6729 set_ref_in_ht(&dd->dv_hashtab, copyID);
6731 break;
6733 case VAR_LIST:
6734 ll = tv->vval.v_list;
6735 if (ll != NULL && ll->lv_copyID != copyID)
6737 /* Didn't see this list yet. */
6738 ll->lv_copyID = copyID;
6739 set_ref_in_list(ll, copyID);
6741 break;
6743 return;
6747 * Allocate an empty header for a dictionary.
6749 dict_T *
6750 dict_alloc()
6752 dict_T *d;
6754 d = (dict_T *)alloc(sizeof(dict_T));
6755 if (d != NULL)
6757 /* Add the list to the list of dicts for garbage collection. */
6758 if (first_dict != NULL)
6759 first_dict->dv_used_prev = d;
6760 d->dv_used_next = first_dict;
6761 d->dv_used_prev = NULL;
6762 first_dict = d;
6764 hash_init(&d->dv_hashtab);
6765 d->dv_lock = 0;
6766 d->dv_refcount = 0;
6767 d->dv_copyID = 0;
6769 return d;
6773 * Unreference a Dictionary: decrement the reference count and free it when it
6774 * becomes zero.
6776 static void
6777 dict_unref(d)
6778 dict_T *d;
6780 if (d != NULL && --d->dv_refcount <= 0)
6781 dict_free(d, TRUE);
6785 * Free a Dictionary, including all items it contains.
6786 * Ignores the reference count.
6788 static void
6789 dict_free(d, recurse)
6790 dict_T *d;
6791 int recurse; /* Free Lists and Dictionaries recursively. */
6793 int todo;
6794 hashitem_T *hi;
6795 dictitem_T *di;
6797 /* Remove the dict from the list of dicts for garbage collection. */
6798 if (d->dv_used_prev == NULL)
6799 first_dict = d->dv_used_next;
6800 else
6801 d->dv_used_prev->dv_used_next = d->dv_used_next;
6802 if (d->dv_used_next != NULL)
6803 d->dv_used_next->dv_used_prev = d->dv_used_prev;
6805 /* Lock the hashtab, we don't want it to resize while freeing items. */
6806 hash_lock(&d->dv_hashtab);
6807 todo = (int)d->dv_hashtab.ht_used;
6808 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
6810 if (!HASHITEM_EMPTY(hi))
6812 /* Remove the item before deleting it, just in case there is
6813 * something recursive causing trouble. */
6814 di = HI2DI(hi);
6815 hash_remove(&d->dv_hashtab, hi);
6816 if (recurse || (di->di_tv.v_type != VAR_LIST
6817 && di->di_tv.v_type != VAR_DICT))
6818 clear_tv(&di->di_tv);
6819 vim_free(di);
6820 --todo;
6823 hash_clear(&d->dv_hashtab);
6824 vim_free(d);
6828 * Allocate a Dictionary item.
6829 * The "key" is copied to the new item.
6830 * Note that the value of the item "di_tv" still needs to be initialized!
6831 * Returns NULL when out of memory.
6833 dictitem_T *
6834 dictitem_alloc(key)
6835 char_u *key;
6837 dictitem_T *di;
6839 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T) + STRLEN(key)));
6840 if (di != NULL)
6842 STRCPY(di->di_key, key);
6843 di->di_flags = 0;
6845 return di;
6849 * Make a copy of a Dictionary item.
6851 static dictitem_T *
6852 dictitem_copy(org)
6853 dictitem_T *org;
6855 dictitem_T *di;
6857 di = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
6858 + STRLEN(org->di_key)));
6859 if (di != NULL)
6861 STRCPY(di->di_key, org->di_key);
6862 di->di_flags = 0;
6863 copy_tv(&org->di_tv, &di->di_tv);
6865 return di;
6869 * Remove item "item" from Dictionary "dict" and free it.
6871 static void
6872 dictitem_remove(dict, item)
6873 dict_T *dict;
6874 dictitem_T *item;
6876 hashitem_T *hi;
6878 hi = hash_find(&dict->dv_hashtab, item->di_key);
6879 if (HASHITEM_EMPTY(hi))
6880 EMSG2(_(e_intern2), "dictitem_remove()");
6881 else
6882 hash_remove(&dict->dv_hashtab, hi);
6883 dictitem_free(item);
6887 * Free a dict item. Also clears the value.
6889 void
6890 dictitem_free(item)
6891 dictitem_T *item;
6893 clear_tv(&item->di_tv);
6894 vim_free(item);
6898 * Make a copy of dict "d". Shallow if "deep" is FALSE.
6899 * The refcount of the new dict is set to 1.
6900 * See item_copy() for "copyID".
6901 * Returns NULL when out of memory.
6903 static dict_T *
6904 dict_copy(orig, deep, copyID)
6905 dict_T *orig;
6906 int deep;
6907 int copyID;
6909 dict_T *copy;
6910 dictitem_T *di;
6911 int todo;
6912 hashitem_T *hi;
6914 if (orig == NULL)
6915 return NULL;
6917 copy = dict_alloc();
6918 if (copy != NULL)
6920 if (copyID != 0)
6922 orig->dv_copyID = copyID;
6923 orig->dv_copydict = copy;
6925 todo = (int)orig->dv_hashtab.ht_used;
6926 for (hi = orig->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
6928 if (!HASHITEM_EMPTY(hi))
6930 --todo;
6932 di = dictitem_alloc(hi->hi_key);
6933 if (di == NULL)
6934 break;
6935 if (deep)
6937 if (item_copy(&HI2DI(hi)->di_tv, &di->di_tv, deep,
6938 copyID) == FAIL)
6940 vim_free(di);
6941 break;
6944 else
6945 copy_tv(&HI2DI(hi)->di_tv, &di->di_tv);
6946 if (dict_add(copy, di) == FAIL)
6948 dictitem_free(di);
6949 break;
6954 ++copy->dv_refcount;
6955 if (todo > 0)
6957 dict_unref(copy);
6958 copy = NULL;
6962 return copy;
6966 * Add item "item" to Dictionary "d".
6967 * Returns FAIL when out of memory and when key already existed.
6970 dict_add(d, item)
6971 dict_T *d;
6972 dictitem_T *item;
6974 return hash_add(&d->dv_hashtab, item->di_key);
6978 * Add a number or string entry to dictionary "d".
6979 * When "str" is NULL use number "nr", otherwise use "str".
6980 * Returns FAIL when out of memory and when key already exists.
6983 dict_add_nr_str(d, key, nr, str)
6984 dict_T *d;
6985 char *key;
6986 long nr;
6987 char_u *str;
6989 dictitem_T *item;
6991 item = dictitem_alloc((char_u *)key);
6992 if (item == NULL)
6993 return FAIL;
6994 item->di_tv.v_lock = 0;
6995 if (str == NULL)
6997 item->di_tv.v_type = VAR_NUMBER;
6998 item->di_tv.vval.v_number = nr;
7000 else
7002 item->di_tv.v_type = VAR_STRING;
7003 item->di_tv.vval.v_string = vim_strsave(str);
7005 if (dict_add(d, item) == FAIL)
7007 dictitem_free(item);
7008 return FAIL;
7010 return OK;
7014 * Get the number of items in a Dictionary.
7016 static long
7017 dict_len(d)
7018 dict_T *d;
7020 if (d == NULL)
7021 return 0L;
7022 return (long)d->dv_hashtab.ht_used;
7026 * Find item "key[len]" in Dictionary "d".
7027 * If "len" is negative use strlen(key).
7028 * Returns NULL when not found.
7030 static dictitem_T *
7031 dict_find(d, key, len)
7032 dict_T *d;
7033 char_u *key;
7034 int len;
7036 #define AKEYLEN 200
7037 char_u buf[AKEYLEN];
7038 char_u *akey;
7039 char_u *tofree = NULL;
7040 hashitem_T *hi;
7042 if (len < 0)
7043 akey = key;
7044 else if (len >= AKEYLEN)
7046 tofree = akey = vim_strnsave(key, len);
7047 if (akey == NULL)
7048 return NULL;
7050 else
7052 /* Avoid a malloc/free by using buf[]. */
7053 vim_strncpy(buf, key, len);
7054 akey = buf;
7057 hi = hash_find(&d->dv_hashtab, akey);
7058 vim_free(tofree);
7059 if (HASHITEM_EMPTY(hi))
7060 return NULL;
7061 return HI2DI(hi);
7065 * Get a string item from a dictionary.
7066 * When "save" is TRUE allocate memory for it.
7067 * Returns NULL if the entry doesn't exist or out of memory.
7069 char_u *
7070 get_dict_string(d, key, save)
7071 dict_T *d;
7072 char_u *key;
7073 int save;
7075 dictitem_T *di;
7076 char_u *s;
7078 di = dict_find(d, key, -1);
7079 if (di == NULL)
7080 return NULL;
7081 s = get_tv_string(&di->di_tv);
7082 if (save && s != NULL)
7083 s = vim_strsave(s);
7084 return s;
7088 * Get a number item from a dictionary.
7089 * Returns 0 if the entry doesn't exist or out of memory.
7091 long
7092 get_dict_number(d, key)
7093 dict_T *d;
7094 char_u *key;
7096 dictitem_T *di;
7098 di = dict_find(d, key, -1);
7099 if (di == NULL)
7100 return 0;
7101 return get_tv_number(&di->di_tv);
7105 * Return an allocated string with the string representation of a Dictionary.
7106 * May return NULL.
7108 static char_u *
7109 dict2string(tv, copyID)
7110 typval_T *tv;
7111 int copyID;
7113 garray_T ga;
7114 int first = TRUE;
7115 char_u *tofree;
7116 char_u numbuf[NUMBUFLEN];
7117 hashitem_T *hi;
7118 char_u *s;
7119 dict_T *d;
7120 int todo;
7122 if ((d = tv->vval.v_dict) == NULL)
7123 return NULL;
7124 ga_init2(&ga, (int)sizeof(char), 80);
7125 ga_append(&ga, '{');
7127 todo = (int)d->dv_hashtab.ht_used;
7128 for (hi = d->dv_hashtab.ht_array; todo > 0 && !got_int; ++hi)
7130 if (!HASHITEM_EMPTY(hi))
7132 --todo;
7134 if (first)
7135 first = FALSE;
7136 else
7137 ga_concat(&ga, (char_u *)", ");
7139 tofree = string_quote(hi->hi_key, FALSE);
7140 if (tofree != NULL)
7142 ga_concat(&ga, tofree);
7143 vim_free(tofree);
7145 ga_concat(&ga, (char_u *)": ");
7146 s = tv2string(&HI2DI(hi)->di_tv, &tofree, numbuf, copyID);
7147 if (s != NULL)
7148 ga_concat(&ga, s);
7149 vim_free(tofree);
7150 if (s == NULL)
7151 break;
7154 if (todo > 0)
7156 vim_free(ga.ga_data);
7157 return NULL;
7160 ga_append(&ga, '}');
7161 ga_append(&ga, NUL);
7162 return (char_u *)ga.ga_data;
7166 * Allocate a variable for a Dictionary and fill it from "*arg".
7167 * Return OK or FAIL. Returns NOTDONE for {expr}.
7169 static int
7170 get_dict_tv(arg, rettv, evaluate)
7171 char_u **arg;
7172 typval_T *rettv;
7173 int evaluate;
7175 dict_T *d = NULL;
7176 typval_T tvkey;
7177 typval_T tv;
7178 char_u *key = NULL;
7179 dictitem_T *item;
7180 char_u *start = skipwhite(*arg + 1);
7181 char_u buf[NUMBUFLEN];
7184 * First check if it's not a curly-braces thing: {expr}.
7185 * Must do this without evaluating, otherwise a function may be called
7186 * twice. Unfortunately this means we need to call eval1() twice for the
7187 * first item.
7188 * But {} is an empty Dictionary.
7190 if (*start != '}')
7192 if (eval1(&start, &tv, FALSE) == FAIL) /* recursive! */
7193 return FAIL;
7194 if (*start == '}')
7195 return NOTDONE;
7198 if (evaluate)
7200 d = dict_alloc();
7201 if (d == NULL)
7202 return FAIL;
7204 tvkey.v_type = VAR_UNKNOWN;
7205 tv.v_type = VAR_UNKNOWN;
7207 *arg = skipwhite(*arg + 1);
7208 while (**arg != '}' && **arg != NUL)
7210 if (eval1(arg, &tvkey, evaluate) == FAIL) /* recursive! */
7211 goto failret;
7212 if (**arg != ':')
7214 EMSG2(_("E720: Missing colon in Dictionary: %s"), *arg);
7215 clear_tv(&tvkey);
7216 goto failret;
7218 if (evaluate)
7220 key = get_tv_string_buf_chk(&tvkey, buf);
7221 if (key == NULL || *key == NUL)
7223 /* "key" is NULL when get_tv_string_buf_chk() gave an errmsg */
7224 if (key != NULL)
7225 EMSG(_(e_emptykey));
7226 clear_tv(&tvkey);
7227 goto failret;
7231 *arg = skipwhite(*arg + 1);
7232 if (eval1(arg, &tv, evaluate) == FAIL) /* recursive! */
7234 if (evaluate)
7235 clear_tv(&tvkey);
7236 goto failret;
7238 if (evaluate)
7240 item = dict_find(d, key, -1);
7241 if (item != NULL)
7243 EMSG2(_("E721: Duplicate key in Dictionary: \"%s\""), key);
7244 clear_tv(&tvkey);
7245 clear_tv(&tv);
7246 goto failret;
7248 item = dictitem_alloc(key);
7249 clear_tv(&tvkey);
7250 if (item != NULL)
7252 item->di_tv = tv;
7253 item->di_tv.v_lock = 0;
7254 if (dict_add(d, item) == FAIL)
7255 dictitem_free(item);
7259 if (**arg == '}')
7260 break;
7261 if (**arg != ',')
7263 EMSG2(_("E722: Missing comma in Dictionary: %s"), *arg);
7264 goto failret;
7266 *arg = skipwhite(*arg + 1);
7269 if (**arg != '}')
7271 EMSG2(_("E723: Missing end of Dictionary '}': %s"), *arg);
7272 failret:
7273 if (evaluate)
7274 dict_free(d, TRUE);
7275 return FAIL;
7278 *arg = skipwhite(*arg + 1);
7279 if (evaluate)
7281 rettv->v_type = VAR_DICT;
7282 rettv->vval.v_dict = d;
7283 ++d->dv_refcount;
7286 return OK;
7290 * Return a string with the string representation of a variable.
7291 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7292 * "numbuf" is used for a number.
7293 * Does not put quotes around strings, as ":echo" displays values.
7294 * When "copyID" is not NULL replace recursive lists and dicts with "...".
7295 * May return NULL.
7297 static char_u *
7298 echo_string(tv, tofree, numbuf, copyID)
7299 typval_T *tv;
7300 char_u **tofree;
7301 char_u *numbuf;
7302 int copyID;
7304 static int recurse = 0;
7305 char_u *r = NULL;
7307 if (recurse >= DICT_MAXNEST)
7309 EMSG(_("E724: variable nested too deep for displaying"));
7310 *tofree = NULL;
7311 return NULL;
7313 ++recurse;
7315 switch (tv->v_type)
7317 case VAR_FUNC:
7318 *tofree = NULL;
7319 r = tv->vval.v_string;
7320 break;
7322 case VAR_LIST:
7323 if (tv->vval.v_list == NULL)
7325 *tofree = NULL;
7326 r = NULL;
7328 else if (copyID != 0 && tv->vval.v_list->lv_copyID == copyID)
7330 *tofree = NULL;
7331 r = (char_u *)"[...]";
7333 else
7335 tv->vval.v_list->lv_copyID = copyID;
7336 *tofree = list2string(tv, copyID);
7337 r = *tofree;
7339 break;
7341 case VAR_DICT:
7342 if (tv->vval.v_dict == NULL)
7344 *tofree = NULL;
7345 r = NULL;
7347 else if (copyID != 0 && tv->vval.v_dict->dv_copyID == copyID)
7349 *tofree = NULL;
7350 r = (char_u *)"{...}";
7352 else
7354 tv->vval.v_dict->dv_copyID = copyID;
7355 *tofree = dict2string(tv, copyID);
7356 r = *tofree;
7358 break;
7360 case VAR_STRING:
7361 case VAR_NUMBER:
7362 *tofree = NULL;
7363 r = get_tv_string_buf(tv, numbuf);
7364 break;
7366 #ifdef FEAT_FLOAT
7367 case VAR_FLOAT:
7368 *tofree = NULL;
7369 vim_snprintf((char *)numbuf, NUMBUFLEN, "%g", tv->vval.v_float);
7370 r = numbuf;
7371 break;
7372 #endif
7374 default:
7375 EMSG2(_(e_intern2), "echo_string()");
7376 *tofree = NULL;
7379 --recurse;
7380 return r;
7384 * Return a string with the string representation of a variable.
7385 * If the memory is allocated "tofree" is set to it, otherwise NULL.
7386 * "numbuf" is used for a number.
7387 * Puts quotes around strings, so that they can be parsed back by eval().
7388 * May return NULL.
7390 static char_u *
7391 tv2string(tv, tofree, numbuf, copyID)
7392 typval_T *tv;
7393 char_u **tofree;
7394 char_u *numbuf;
7395 int copyID;
7397 switch (tv->v_type)
7399 case VAR_FUNC:
7400 *tofree = string_quote(tv->vval.v_string, TRUE);
7401 return *tofree;
7402 case VAR_STRING:
7403 *tofree = string_quote(tv->vval.v_string, FALSE);
7404 return *tofree;
7405 #ifdef FEAT_FLOAT
7406 case VAR_FLOAT:
7407 *tofree = NULL;
7408 vim_snprintf((char *)numbuf, NUMBUFLEN - 1, "%g", tv->vval.v_float);
7409 return numbuf;
7410 #endif
7411 case VAR_NUMBER:
7412 case VAR_LIST:
7413 case VAR_DICT:
7414 break;
7415 default:
7416 EMSG2(_(e_intern2), "tv2string()");
7418 return echo_string(tv, tofree, numbuf, copyID);
7422 * Return string "str" in ' quotes, doubling ' characters.
7423 * If "str" is NULL an empty string is assumed.
7424 * If "function" is TRUE make it function('string').
7426 static char_u *
7427 string_quote(str, function)
7428 char_u *str;
7429 int function;
7431 unsigned len;
7432 char_u *p, *r, *s;
7434 len = (function ? 13 : 3);
7435 if (str != NULL)
7437 len += (unsigned)STRLEN(str);
7438 for (p = str; *p != NUL; mb_ptr_adv(p))
7439 if (*p == '\'')
7440 ++len;
7442 s = r = alloc(len);
7443 if (r != NULL)
7445 if (function)
7447 STRCPY(r, "function('");
7448 r += 10;
7450 else
7451 *r++ = '\'';
7452 if (str != NULL)
7453 for (p = str; *p != NUL; )
7455 if (*p == '\'')
7456 *r++ = '\'';
7457 MB_COPY_CHAR(p, r);
7459 *r++ = '\'';
7460 if (function)
7461 *r++ = ')';
7462 *r++ = NUL;
7464 return s;
7467 #ifdef FEAT_FLOAT
7469 * Convert the string "text" to a floating point number.
7470 * This uses strtod(). setlocale(LC_NUMERIC, "C") has been used to make sure
7471 * this always uses a decimal point.
7472 * Returns the length of the text that was consumed.
7474 static int
7475 string2float(text, value)
7476 char_u *text;
7477 float_T *value; /* result stored here */
7479 char *s = (char *)text;
7480 float_T f;
7482 f = strtod(s, &s);
7483 *value = f;
7484 return (int)((char_u *)s - text);
7486 #endif
7489 * Get the value of an environment variable.
7490 * "arg" is pointing to the '$'. It is advanced to after the name.
7491 * If the environment variable was not set, silently assume it is empty.
7492 * Always return OK.
7494 static int
7495 get_env_tv(arg, rettv, evaluate)
7496 char_u **arg;
7497 typval_T *rettv;
7498 int evaluate;
7500 char_u *string = NULL;
7501 int len;
7502 int cc;
7503 char_u *name;
7504 int mustfree = FALSE;
7506 ++*arg;
7507 name = *arg;
7508 len = get_env_len(arg);
7509 if (evaluate)
7511 if (len != 0)
7513 cc = name[len];
7514 name[len] = NUL;
7515 /* first try vim_getenv(), fast for normal environment vars */
7516 string = vim_getenv(name, &mustfree);
7517 if (string != NULL && *string != NUL)
7519 if (!mustfree)
7520 string = vim_strsave(string);
7522 else
7524 if (mustfree)
7525 vim_free(string);
7527 /* next try expanding things like $VIM and ${HOME} */
7528 string = expand_env_save(name - 1);
7529 if (string != NULL && *string == '$')
7531 vim_free(string);
7532 string = NULL;
7535 name[len] = cc;
7537 rettv->v_type = VAR_STRING;
7538 rettv->vval.v_string = string;
7541 return OK;
7545 * Array with names and number of arguments of all internal functions
7546 * MUST BE KEPT SORTED IN strcmp() ORDER FOR BINARY SEARCH!
7548 static struct fst
7550 char *f_name; /* function name */
7551 char f_min_argc; /* minimal number of arguments */
7552 char f_max_argc; /* maximal number of arguments */
7553 void (*f_func) __ARGS((typval_T *args, typval_T *rvar));
7554 /* implementation of function */
7555 } functions[] =
7557 #ifdef FEAT_FLOAT
7558 {"abs", 1, 1, f_abs},
7559 {"acos", 1, 1, f_acos}, /* WJMc */
7560 #endif
7561 {"add", 2, 2, f_add},
7562 {"append", 2, 2, f_append},
7563 {"argc", 0, 0, f_argc},
7564 {"argidx", 0, 0, f_argidx},
7565 {"argv", 0, 1, f_argv},
7566 #ifdef FEAT_FLOAT
7567 {"asin", 1, 1, f_asin}, /* WJMc */
7568 {"atan", 1, 1, f_atan},
7569 {"atan2", 2, 2, f_atan2}, /* WJMc */
7570 #endif
7571 {"browse", 4, 4, f_browse},
7572 {"browsedir", 2, 2, f_browsedir},
7573 {"bufexists", 1, 1, f_bufexists},
7574 {"buffer_exists", 1, 1, f_bufexists}, /* obsolete */
7575 {"buffer_name", 1, 1, f_bufname}, /* obsolete */
7576 {"buffer_number", 1, 1, f_bufnr}, /* obsolete */
7577 {"buflisted", 1, 1, f_buflisted},
7578 {"bufloaded", 1, 1, f_bufloaded},
7579 {"bufname", 1, 1, f_bufname},
7580 {"bufnr", 1, 2, f_bufnr},
7581 {"bufwinnr", 1, 1, f_bufwinnr},
7582 {"byte2line", 1, 1, f_byte2line},
7583 {"byteidx", 2, 2, f_byteidx},
7584 {"call", 2, 3, f_call},
7585 #ifdef FEAT_FLOAT
7586 {"ceil", 1, 1, f_ceil},
7587 #endif
7588 {"changenr", 0, 0, f_changenr},
7589 {"char2nr", 1, 1, f_char2nr},
7590 {"cindent", 1, 1, f_cindent},
7591 {"clearmatches", 0, 0, f_clearmatches},
7592 {"col", 1, 1, f_col},
7593 #if defined(FEAT_INS_EXPAND)
7594 {"complete", 2, 2, f_complete},
7595 {"complete_add", 1, 1, f_complete_add},
7596 {"complete_check", 0, 0, f_complete_check},
7597 #endif
7598 {"confirm", 1, 4, f_confirm},
7599 {"copy", 1, 1, f_copy},
7600 #ifdef FEAT_FLOAT
7601 {"cos", 1, 1, f_cos},
7602 {"cosh", 1, 1, f_cosh}, /* WJMc */
7603 #endif
7604 {"count", 2, 4, f_count},
7605 {"cscope_connection",0,3, f_cscope_connection},
7606 {"cursor", 1, 3, f_cursor},
7607 {"deepcopy", 1, 2, f_deepcopy},
7608 {"delete", 1, 1, f_delete},
7609 {"did_filetype", 0, 0, f_did_filetype},
7610 {"diff_filler", 1, 1, f_diff_filler},
7611 {"diff_hlID", 2, 2, f_diff_hlID},
7612 {"empty", 1, 1, f_empty},
7613 {"escape", 2, 2, f_escape},
7614 {"eval", 1, 1, f_eval},
7615 {"eventhandler", 0, 0, f_eventhandler},
7616 {"executable", 1, 1, f_executable},
7617 {"exists", 1, 1, f_exists},
7618 #ifdef FEAT_FLOAT
7619 {"exp", 1, 1, f_exp}, /* WJMc */
7620 #endif
7621 {"expand", 1, 2, f_expand},
7622 {"extend", 2, 3, f_extend},
7623 {"feedkeys", 1, 2, f_feedkeys},
7624 {"file_readable", 1, 1, f_filereadable}, /* obsolete */
7625 {"filereadable", 1, 1, f_filereadable},
7626 {"filewritable", 1, 1, f_filewritable},
7627 {"filter", 2, 2, f_filter},
7628 {"finddir", 1, 3, f_finddir},
7629 {"findfile", 1, 3, f_findfile},
7630 #ifdef FEAT_FLOAT
7631 {"float2nr", 1, 1, f_float2nr},
7632 {"floor", 1, 1, f_floor},
7633 {"fmod", 2, 2, f_fmod}, /* WJMc */
7634 #endif
7635 {"fnameescape", 1, 1, f_fnameescape},
7636 {"fnamemodify", 2, 2, f_fnamemodify},
7637 {"foldclosed", 1, 1, f_foldclosed},
7638 {"foldclosedend", 1, 1, f_foldclosedend},
7639 {"foldlevel", 1, 1, f_foldlevel},
7640 {"foldtext", 0, 0, f_foldtext},
7641 {"foldtextresult", 1, 1, f_foldtextresult},
7642 {"foreground", 0, 0, f_foreground},
7643 {"function", 1, 1, f_function},
7644 {"garbagecollect", 0, 1, f_garbagecollect},
7645 {"get", 2, 3, f_get},
7646 {"getbufline", 2, 3, f_getbufline},
7647 {"getbufvar", 2, 2, f_getbufvar},
7648 {"getchar", 0, 1, f_getchar},
7649 {"getcharmod", 0, 0, f_getcharmod},
7650 {"getcmdline", 0, 0, f_getcmdline},
7651 {"getcmdpos", 0, 0, f_getcmdpos},
7652 {"getcmdtype", 0, 0, f_getcmdtype},
7653 {"getcwd", 0, 0, f_getcwd},
7654 {"getfontname", 0, 1, f_getfontname},
7655 {"getfperm", 1, 1, f_getfperm},
7656 {"getfsize", 1, 1, f_getfsize},
7657 {"getftime", 1, 1, f_getftime},
7658 {"getftype", 1, 1, f_getftype},
7659 {"getline", 1, 2, f_getline},
7660 {"getloclist", 1, 1, f_getqflist},
7661 {"getmatches", 0, 0, f_getmatches},
7662 {"getpid", 0, 0, f_getpid},
7663 {"getpos", 1, 1, f_getpos},
7664 {"getqflist", 0, 0, f_getqflist},
7665 {"getreg", 0, 2, f_getreg},
7666 {"getregtype", 0, 1, f_getregtype},
7667 {"gettabwinvar", 3, 3, f_gettabwinvar},
7668 {"getwinposx", 0, 0, f_getwinposx},
7669 {"getwinposy", 0, 0, f_getwinposy},
7670 {"getwinvar", 2, 2, f_getwinvar},
7671 {"glob", 1, 2, f_glob},
7672 {"globpath", 2, 3, f_globpath},
7673 {"has", 1, 1, f_has},
7674 {"has_key", 2, 2, f_has_key},
7675 {"haslocaldir", 0, 0, f_haslocaldir},
7676 {"hasmapto", 1, 3, f_hasmapto},
7677 {"highlightID", 1, 1, f_hlID}, /* obsolete */
7678 {"highlight_exists",1, 1, f_hlexists}, /* obsolete */
7679 {"histadd", 2, 2, f_histadd},
7680 {"histdel", 1, 2, f_histdel},
7681 {"histget", 1, 2, f_histget},
7682 {"histnr", 1, 1, f_histnr},
7683 {"hlID", 1, 1, f_hlID},
7684 {"hlexists", 1, 1, f_hlexists},
7685 {"hostname", 0, 0, f_hostname},
7686 {"iconv", 3, 3, f_iconv},
7687 {"indent", 1, 1, f_indent},
7688 {"index", 2, 4, f_index},
7689 {"input", 1, 3, f_input},
7690 {"inputdialog", 1, 3, f_inputdialog},
7691 {"inputlist", 1, 1, f_inputlist},
7692 {"inputrestore", 0, 0, f_inputrestore},
7693 {"inputsave", 0, 0, f_inputsave},
7694 {"inputsecret", 1, 2, f_inputsecret},
7695 {"insert", 2, 3, f_insert},
7696 {"isdirectory", 1, 1, f_isdirectory},
7697 {"islocked", 1, 1, f_islocked},
7698 {"items", 1, 1, f_items},
7699 {"join", 1, 2, f_join},
7700 {"keys", 1, 1, f_keys},
7701 {"last_buffer_nr", 0, 0, f_last_buffer_nr},/* obsolete */
7702 {"len", 1, 1, f_len},
7703 {"libcall", 3, 3, f_libcall},
7704 {"libcallnr", 3, 3, f_libcallnr},
7705 {"line", 1, 1, f_line},
7706 {"line2byte", 1, 1, f_line2byte},
7707 {"lispindent", 1, 1, f_lispindent},
7708 {"localtime", 0, 0, f_localtime},
7709 #ifdef FEAT_FLOAT
7710 {"log", 1, 1, f_log}, /* WJMc */
7711 {"log10", 1, 1, f_log10},
7712 #endif
7713 {"map", 2, 2, f_map},
7714 {"maparg", 1, 3, f_maparg},
7715 {"mapcheck", 1, 3, f_mapcheck},
7716 {"match", 2, 4, f_match},
7717 {"matchadd", 2, 4, f_matchadd},
7718 {"matcharg", 1, 1, f_matcharg},
7719 {"matchdelete", 1, 1, f_matchdelete},
7720 {"matchend", 2, 4, f_matchend},
7721 {"matchlist", 2, 4, f_matchlist},
7722 {"matchstr", 2, 4, f_matchstr},
7723 {"max", 1, 1, f_max},
7724 {"min", 1, 1, f_min},
7725 #ifdef vim_mkdir
7726 {"mkdir", 1, 3, f_mkdir},
7727 #endif
7728 {"mode", 0, 1, f_mode},
7729 #ifdef FEAT_MZSCHEME
7730 {"mzeval", 1, 1, f_mzeval},
7731 #endif
7732 {"nextnonblank", 1, 1, f_nextnonblank},
7733 {"nr2char", 1, 1, f_nr2char},
7734 {"pathshorten", 1, 1, f_pathshorten},
7735 #ifdef FEAT_FLOAT
7736 {"pow", 2, 2, f_pow},
7737 #endif
7738 {"prevnonblank", 1, 1, f_prevnonblank},
7739 {"printf", 2, 19, f_printf},
7740 {"pumvisible", 0, 0, f_pumvisible},
7741 {"range", 1, 3, f_range},
7742 {"readfile", 1, 3, f_readfile},
7743 {"reltime", 0, 2, f_reltime},
7744 {"reltimestr", 1, 1, f_reltimestr},
7745 {"remote_expr", 2, 3, f_remote_expr},
7746 {"remote_foreground", 1, 1, f_remote_foreground},
7747 {"remote_peek", 1, 2, f_remote_peek},
7748 {"remote_read", 1, 1, f_remote_read},
7749 {"remote_send", 2, 3, f_remote_send},
7750 {"remove", 2, 3, f_remove},
7751 {"rename", 2, 2, f_rename},
7752 {"repeat", 2, 2, f_repeat},
7753 {"resolve", 1, 1, f_resolve},
7754 {"reverse", 1, 1, f_reverse},
7755 #ifdef FEAT_FLOAT
7756 {"round", 1, 1, f_round},
7757 #endif
7758 {"search", 1, 4, f_search},
7759 {"searchdecl", 1, 3, f_searchdecl},
7760 {"searchpair", 3, 7, f_searchpair},
7761 {"searchpairpos", 3, 7, f_searchpairpos},
7762 {"searchpos", 1, 4, f_searchpos},
7763 {"server2client", 2, 2, f_server2client},
7764 {"serverlist", 0, 0, f_serverlist},
7765 {"setbufvar", 3, 3, f_setbufvar},
7766 {"setcmdpos", 1, 1, f_setcmdpos},
7767 {"setline", 2, 2, f_setline},
7768 {"setloclist", 2, 3, f_setloclist},
7769 {"setmatches", 1, 1, f_setmatches},
7770 {"setpos", 2, 2, f_setpos},
7771 {"setqflist", 1, 2, f_setqflist},
7772 {"setreg", 2, 3, f_setreg},
7773 {"settabwinvar", 4, 4, f_settabwinvar},
7774 {"setwinvar", 3, 3, f_setwinvar},
7775 {"shellescape", 1, 2, f_shellescape},
7776 {"simplify", 1, 1, f_simplify},
7777 #ifdef FEAT_FLOAT
7778 {"sin", 1, 1, f_sin},
7779 {"sinh", 1, 1, f_sinh}, /* WJMc */
7780 #endif
7781 {"sort", 1, 2, f_sort},
7782 {"soundfold", 1, 1, f_soundfold},
7783 {"spellbadword", 0, 1, f_spellbadword},
7784 {"spellsuggest", 1, 3, f_spellsuggest},
7785 {"split", 1, 3, f_split},
7786 #ifdef FEAT_FLOAT
7787 {"sqrt", 1, 1, f_sqrt},
7788 {"str2float", 1, 1, f_str2float},
7789 #endif
7790 {"str2nr", 1, 2, f_str2nr},
7791 #ifdef HAVE_STRFTIME
7792 {"strftime", 1, 2, f_strftime},
7793 #endif
7794 {"stridx", 2, 3, f_stridx},
7795 {"string", 1, 1, f_string},
7796 {"strlen", 1, 1, f_strlen},
7797 {"strpart", 2, 3, f_strpart},
7798 {"strridx", 2, 3, f_strridx},
7799 {"strtrans", 1, 1, f_strtrans},
7800 {"submatch", 1, 1, f_submatch},
7801 {"substitute", 4, 4, f_substitute},
7802 {"synID", 3, 3, f_synID},
7803 {"synIDattr", 2, 3, f_synIDattr},
7804 {"synIDtrans", 1, 1, f_synIDtrans},
7805 {"synstack", 2, 2, f_synstack},
7806 {"system", 1, 2, f_system},
7807 {"tabpagebuflist", 0, 1, f_tabpagebuflist},
7808 {"tabpagenr", 0, 1, f_tabpagenr},
7809 {"tabpagewinnr", 1, 2, f_tabpagewinnr},
7810 {"tagfiles", 0, 0, f_tagfiles},
7811 {"taglist", 1, 1, f_taglist},
7812 {"tan", 1, 1, f_tan}, /* WJMc */
7813 {"tanh", 1, 1, f_tanh}, /* WJMc */
7814 {"tempname", 0, 0, f_tempname},
7815 {"test", 1, 1, f_test},
7816 {"tolower", 1, 1, f_tolower},
7817 {"toupper", 1, 1, f_toupper},
7818 {"tr", 3, 3, f_tr},
7819 #ifdef FEAT_FLOAT
7820 {"trunc", 1, 1, f_trunc},
7821 #endif
7822 {"type", 1, 1, f_type},
7823 {"values", 1, 1, f_values},
7824 {"virtcol", 1, 1, f_virtcol},
7825 {"visualmode", 0, 1, f_visualmode},
7826 {"winbufnr", 1, 1, f_winbufnr},
7827 {"wincol", 0, 0, f_wincol},
7828 {"winheight", 1, 1, f_winheight},
7829 {"winline", 0, 0, f_winline},
7830 {"winnr", 0, 1, f_winnr},
7831 {"winrestcmd", 0, 0, f_winrestcmd},
7832 {"winrestview", 1, 1, f_winrestview},
7833 {"winsaveview", 0, 0, f_winsaveview},
7834 {"winwidth", 1, 1, f_winwidth},
7835 {"writefile", 2, 3, f_writefile},
7838 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
7841 * Function given to ExpandGeneric() to obtain the list of internal
7842 * or user defined function names.
7844 char_u *
7845 get_function_name(xp, idx)
7846 expand_T *xp;
7847 int idx;
7849 static int intidx = -1;
7850 char_u *name;
7852 if (idx == 0)
7853 intidx = -1;
7854 if (intidx < 0)
7856 name = get_user_func_name(xp, idx);
7857 if (name != NULL)
7858 return name;
7860 if (++intidx < (int)(sizeof(functions) / sizeof(struct fst)))
7862 STRCPY(IObuff, functions[intidx].f_name);
7863 STRCAT(IObuff, "(");
7864 if (functions[intidx].f_max_argc == 0)
7865 STRCAT(IObuff, ")");
7866 return IObuff;
7869 return NULL;
7873 * Function given to ExpandGeneric() to obtain the list of internal or
7874 * user defined variable or function names.
7876 char_u *
7877 get_expr_name(xp, idx)
7878 expand_T *xp;
7879 int idx;
7881 static int intidx = -1;
7882 char_u *name;
7884 if (idx == 0)
7885 intidx = -1;
7886 if (intidx < 0)
7888 name = get_function_name(xp, idx);
7889 if (name != NULL)
7890 return name;
7892 return get_user_var_name(xp, ++intidx);
7895 #endif /* FEAT_CMDL_COMPL */
7898 * Find internal function in table above.
7899 * Return index, or -1 if not found
7901 static int
7902 find_internal_func(name)
7903 char_u *name; /* name of the function */
7905 int first = 0;
7906 int last = (int)(sizeof(functions) / sizeof(struct fst)) - 1;
7907 int cmp;
7908 int x;
7911 * Find the function name in the table. Binary search.
7913 while (first <= last)
7915 x = first + ((unsigned)(last - first) >> 1);
7916 cmp = STRCMP(name, functions[x].f_name);
7917 if (cmp < 0)
7918 last = x - 1;
7919 else if (cmp > 0)
7920 first = x + 1;
7921 else
7922 return x;
7924 return -1;
7928 * Check if "name" is a variable of type VAR_FUNC. If so, return the function
7929 * name it contains, otherwise return "name".
7931 static char_u *
7932 deref_func_name(name, lenp)
7933 char_u *name;
7934 int *lenp;
7936 dictitem_T *v;
7937 int cc;
7939 cc = name[*lenp];
7940 name[*lenp] = NUL;
7941 v = find_var(name, NULL);
7942 name[*lenp] = cc;
7943 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
7945 if (v->di_tv.vval.v_string == NULL)
7947 *lenp = 0;
7948 return (char_u *)""; /* just in case */
7950 *lenp = (int)STRLEN(v->di_tv.vval.v_string);
7951 return v->di_tv.vval.v_string;
7954 return name;
7958 * Allocate a variable for the result of a function.
7959 * Return OK or FAIL.
7961 static int
7962 get_func_tv(name, len, rettv, arg, firstline, lastline, doesrange,
7963 evaluate, selfdict)
7964 char_u *name; /* name of the function */
7965 int len; /* length of "name" */
7966 typval_T *rettv;
7967 char_u **arg; /* argument, pointing to the '(' */
7968 linenr_T firstline; /* first line of range */
7969 linenr_T lastline; /* last line of range */
7970 int *doesrange; /* return: function handled range */
7971 int evaluate;
7972 dict_T *selfdict; /* Dictionary for "self" */
7974 char_u *argp;
7975 int ret = OK;
7976 typval_T argvars[MAX_FUNC_ARGS + 1]; /* vars for arguments */
7977 int argcount = 0; /* number of arguments found */
7980 * Get the arguments.
7982 argp = *arg;
7983 while (argcount < MAX_FUNC_ARGS)
7985 argp = skipwhite(argp + 1); /* skip the '(' or ',' */
7986 if (*argp == ')' || *argp == ',' || *argp == NUL)
7987 break;
7988 if (eval1(&argp, &argvars[argcount], evaluate) == FAIL)
7990 ret = FAIL;
7991 break;
7993 ++argcount;
7994 if (*argp != ',')
7995 break;
7997 if (*argp == ')')
7998 ++argp;
7999 else
8000 ret = FAIL;
8002 if (ret == OK)
8003 ret = call_func(name, len, rettv, argcount, argvars,
8004 firstline, lastline, doesrange, evaluate, selfdict);
8005 else if (!aborting())
8007 if (argcount == MAX_FUNC_ARGS)
8008 emsg_funcname(N_("E740: Too many arguments for function %s"), name);
8009 else
8010 emsg_funcname(N_("E116: Invalid arguments for function %s"), name);
8013 while (--argcount >= 0)
8014 clear_tv(&argvars[argcount]);
8016 *arg = skipwhite(argp);
8017 return ret;
8022 * Call a function with its resolved parameters
8023 * Return OK when the function can't be called, FAIL otherwise.
8024 * Also returns OK when an error was encountered while executing the function.
8026 static int
8027 call_func(func_name, len, rettv, argcount, argvars, firstline, lastline,
8028 doesrange, evaluate, selfdict)
8029 char_u *func_name; /* name of the function */
8030 int len; /* length of "name" */
8031 typval_T *rettv; /* return value goes here */
8032 int argcount; /* number of "argvars" */
8033 typval_T *argvars; /* vars for arguments, must have "argcount"
8034 PLUS ONE elements! */
8035 linenr_T firstline; /* first line of range */
8036 linenr_T lastline; /* last line of range */
8037 int *doesrange; /* return: function handled range */
8038 int evaluate;
8039 dict_T *selfdict; /* Dictionary for "self" */
8041 int ret = FAIL;
8042 #define ERROR_UNKNOWN 0
8043 #define ERROR_TOOMANY 1
8044 #define ERROR_TOOFEW 2
8045 #define ERROR_SCRIPT 3
8046 #define ERROR_DICT 4
8047 #define ERROR_NONE 5
8048 #define ERROR_OTHER 6
8049 int error = ERROR_NONE;
8050 int i;
8051 int llen;
8052 ufunc_T *fp;
8053 #define FLEN_FIXED 40
8054 char_u fname_buf[FLEN_FIXED + 1];
8055 char_u *fname;
8056 char_u *name;
8058 /* Make a copy of the name, if it comes from a funcref variable it could
8059 * be changed or deleted in the called function. */
8060 name = vim_strnsave(func_name, len);
8061 if (name == NULL)
8062 return ret;
8065 * In a script change <SID>name() and s:name() to K_SNR 123_name().
8066 * Change <SNR>123_name() to K_SNR 123_name().
8067 * Use fname_buf[] when it fits, otherwise allocate memory (slow).
8069 llen = eval_fname_script(name);
8070 if (llen > 0)
8072 fname_buf[0] = K_SPECIAL;
8073 fname_buf[1] = KS_EXTRA;
8074 fname_buf[2] = (int)KE_SNR;
8075 i = 3;
8076 if (eval_fname_sid(name)) /* "<SID>" or "s:" */
8078 if (current_SID <= 0)
8079 error = ERROR_SCRIPT;
8080 else
8082 sprintf((char *)fname_buf + 3, "%ld_", (long)current_SID);
8083 i = (int)STRLEN(fname_buf);
8086 if (i + STRLEN(name + llen) < FLEN_FIXED)
8088 STRCPY(fname_buf + i, name + llen);
8089 fname = fname_buf;
8091 else
8093 fname = alloc((unsigned)(i + STRLEN(name + llen) + 1));
8094 if (fname == NULL)
8095 error = ERROR_OTHER;
8096 else
8098 mch_memmove(fname, fname_buf, (size_t)i);
8099 STRCPY(fname + i, name + llen);
8103 else
8104 fname = name;
8106 *doesrange = FALSE;
8109 /* execute the function if no errors detected and executing */
8110 if (evaluate && error == ERROR_NONE)
8112 rettv->v_type = VAR_NUMBER; /* default rettv is number zero */
8113 rettv->vval.v_number = 0;
8114 error = ERROR_UNKNOWN;
8116 if (!builtin_function(fname))
8119 * User defined function.
8121 fp = find_func(fname);
8123 #ifdef FEAT_AUTOCMD
8124 /* Trigger FuncUndefined event, may load the function. */
8125 if (fp == NULL
8126 && apply_autocmds(EVENT_FUNCUNDEFINED,
8127 fname, fname, TRUE, NULL)
8128 && !aborting())
8130 /* executed an autocommand, search for the function again */
8131 fp = find_func(fname);
8133 #endif
8134 /* Try loading a package. */
8135 if (fp == NULL && script_autoload(fname, TRUE) && !aborting())
8137 /* loaded a package, search for the function again */
8138 fp = find_func(fname);
8141 if (fp != NULL)
8143 if (fp->uf_flags & FC_RANGE)
8144 *doesrange = TRUE;
8145 if (argcount < fp->uf_args.ga_len)
8146 error = ERROR_TOOFEW;
8147 else if (!fp->uf_varargs && argcount > fp->uf_args.ga_len)
8148 error = ERROR_TOOMANY;
8149 else if ((fp->uf_flags & FC_DICT) && selfdict == NULL)
8150 error = ERROR_DICT;
8151 else
8154 * Call the user function.
8155 * Save and restore search patterns, script variables and
8156 * redo buffer.
8158 save_search_patterns();
8159 saveRedobuff();
8160 ++fp->uf_calls;
8161 call_user_func(fp, argcount, argvars, rettv,
8162 firstline, lastline,
8163 (fp->uf_flags & FC_DICT) ? selfdict : NULL);
8164 if (--fp->uf_calls <= 0 && isdigit(*fp->uf_name)
8165 && fp->uf_refcount <= 0)
8166 /* Function was unreferenced while being used, free it
8167 * now. */
8168 func_free(fp);
8169 restoreRedobuff();
8170 restore_search_patterns();
8171 error = ERROR_NONE;
8175 else
8178 * Find the function name in the table, call its implementation.
8180 i = find_internal_func(fname);
8181 if (i >= 0)
8183 if (argcount < functions[i].f_min_argc)
8184 error = ERROR_TOOFEW;
8185 else if (argcount > functions[i].f_max_argc)
8186 error = ERROR_TOOMANY;
8187 else
8189 argvars[argcount].v_type = VAR_UNKNOWN;
8190 functions[i].f_func(argvars, rettv);
8191 error = ERROR_NONE;
8196 * The function call (or "FuncUndefined" autocommand sequence) might
8197 * have been aborted by an error, an interrupt, or an explicitly thrown
8198 * exception that has not been caught so far. This situation can be
8199 * tested for by calling aborting(). For an error in an internal
8200 * function or for the "E132" error in call_user_func(), however, the
8201 * throw point at which the "force_abort" flag (temporarily reset by
8202 * emsg()) is normally updated has not been reached yet. We need to
8203 * update that flag first to make aborting() reliable.
8205 update_force_abort();
8207 if (error == ERROR_NONE)
8208 ret = OK;
8211 * Report an error unless the argument evaluation or function call has been
8212 * cancelled due to an aborting error, an interrupt, or an exception.
8214 if (!aborting())
8216 switch (error)
8218 case ERROR_UNKNOWN:
8219 emsg_funcname(N_("E117: Unknown function: %s"), name);
8220 break;
8221 case ERROR_TOOMANY:
8222 emsg_funcname(e_toomanyarg, name);
8223 break;
8224 case ERROR_TOOFEW:
8225 emsg_funcname(N_("E119: Not enough arguments for function: %s"),
8226 name);
8227 break;
8228 case ERROR_SCRIPT:
8229 emsg_funcname(N_("E120: Using <SID> not in a script context: %s"),
8230 name);
8231 break;
8232 case ERROR_DICT:
8233 emsg_funcname(N_("E725: Calling dict function without Dictionary: %s"),
8234 name);
8235 break;
8239 if (fname != name && fname != fname_buf)
8240 vim_free(fname);
8241 vim_free(name);
8243 return ret;
8247 * Give an error message with a function name. Handle <SNR> things.
8248 * "ermsg" is to be passed without translation, use N_() instead of _().
8250 static void
8251 emsg_funcname(ermsg, name)
8252 char *ermsg;
8253 char_u *name;
8255 char_u *p;
8257 if (*name == K_SPECIAL)
8258 p = concat_str((char_u *)"<SNR>", name + 3);
8259 else
8260 p = name;
8261 EMSG2(_(ermsg), p);
8262 if (p != name)
8263 vim_free(p);
8267 * Return TRUE for a non-zero Number and a non-empty String.
8269 static int
8270 non_zero_arg(argvars)
8271 typval_T *argvars;
8273 return ((argvars[0].v_type == VAR_NUMBER
8274 && argvars[0].vval.v_number != 0)
8275 || (argvars[0].v_type == VAR_STRING
8276 && argvars[0].vval.v_string != NULL
8277 && *argvars[0].vval.v_string != NUL));
8280 /*********************************************
8281 * Implementation of the built-in functions
8284 #ifdef FEAT_FLOAT
8286 * "abs(expr)" function
8288 static void
8289 f_abs(argvars, rettv)
8290 typval_T *argvars;
8291 typval_T *rettv;
8293 if (argvars[0].v_type == VAR_FLOAT)
8295 rettv->v_type = VAR_FLOAT;
8296 rettv->vval.v_float = fabs(argvars[0].vval.v_float);
8298 else
8300 varnumber_T n;
8301 int error = FALSE;
8303 n = get_tv_number_chk(&argvars[0], &error);
8304 if (error)
8305 rettv->vval.v_number = -1;
8306 else if (n > 0)
8307 rettv->vval.v_number = n;
8308 else
8309 rettv->vval.v_number = -n;
8312 #endif
8315 * "add(list, item)" function
8317 static void
8318 f_add(argvars, rettv)
8319 typval_T *argvars;
8320 typval_T *rettv;
8322 list_T *l;
8324 rettv->vval.v_number = 1; /* Default: Failed */
8325 if (argvars[0].v_type == VAR_LIST)
8327 if ((l = argvars[0].vval.v_list) != NULL
8328 && !tv_check_lock(l->lv_lock, (char_u *)"add()")
8329 && list_append_tv(l, &argvars[1]) == OK)
8330 copy_tv(&argvars[0], rettv);
8332 else
8333 EMSG(_(e_listreq));
8337 * "append(lnum, string/list)" function
8339 static void
8340 f_append(argvars, rettv)
8341 typval_T *argvars;
8342 typval_T *rettv;
8344 long lnum;
8345 char_u *line;
8346 list_T *l = NULL;
8347 listitem_T *li = NULL;
8348 typval_T *tv;
8349 long added = 0;
8351 lnum = get_tv_lnum(argvars);
8352 if (lnum >= 0
8353 && lnum <= curbuf->b_ml.ml_line_count
8354 && u_save(lnum, lnum + 1) == OK)
8356 if (argvars[1].v_type == VAR_LIST)
8358 l = argvars[1].vval.v_list;
8359 if (l == NULL)
8360 return;
8361 li = l->lv_first;
8363 for (;;)
8365 if (l == NULL)
8366 tv = &argvars[1]; /* append a string */
8367 else if (li == NULL)
8368 break; /* end of list */
8369 else
8370 tv = &li->li_tv; /* append item from list */
8371 line = get_tv_string_chk(tv);
8372 if (line == NULL) /* type error */
8374 rettv->vval.v_number = 1; /* Failed */
8375 break;
8377 ml_append(lnum + added, line, (colnr_T)0, FALSE);
8378 ++added;
8379 if (l == NULL)
8380 break;
8381 li = li->li_next;
8384 appended_lines_mark(lnum, added);
8385 if (curwin->w_cursor.lnum > lnum)
8386 curwin->w_cursor.lnum += added;
8388 else
8389 rettv->vval.v_number = 1; /* Failed */
8393 * "argc()" function
8395 static void
8396 f_argc(argvars, rettv)
8397 typval_T *argvars UNUSED;
8398 typval_T *rettv;
8400 rettv->vval.v_number = ARGCOUNT;
8404 * "argidx()" function
8406 static void
8407 f_argidx(argvars, rettv)
8408 typval_T *argvars UNUSED;
8409 typval_T *rettv;
8411 rettv->vval.v_number = curwin->w_arg_idx;
8415 * "argv(nr)" function
8417 static void
8418 f_argv(argvars, rettv)
8419 typval_T *argvars;
8420 typval_T *rettv;
8422 int idx;
8424 if (argvars[0].v_type != VAR_UNKNOWN)
8426 idx = get_tv_number_chk(&argvars[0], NULL);
8427 if (idx >= 0 && idx < ARGCOUNT)
8428 rettv->vval.v_string = vim_strsave(alist_name(&ARGLIST[idx]));
8429 else
8430 rettv->vval.v_string = NULL;
8431 rettv->v_type = VAR_STRING;
8433 else if (rettv_list_alloc(rettv) == OK)
8434 for (idx = 0; idx < ARGCOUNT; ++idx)
8435 list_append_string(rettv->vval.v_list,
8436 alist_name(&ARGLIST[idx]), -1);
8439 #ifdef FEAT_FLOAT
8440 static int get_float_arg __ARGS((typval_T *argvars, float_T *f));
8443 * Get the float value of "argvars[0]" into "f".
8444 * Returns FAIL when the argument is not a Number or Float.
8446 static int
8447 get_float_arg(argvars, f)
8448 typval_T *argvars;
8449 float_T *f;
8451 if (argvars[0].v_type == VAR_FLOAT)
8453 *f = argvars[0].vval.v_float;
8454 return OK;
8456 if (argvars[0].v_type == VAR_NUMBER)
8458 *f = (float_T)argvars[0].vval.v_number;
8459 return OK;
8461 EMSG(_("E808: Number or Float required"));
8462 return FAIL;
8465 /* The 10 added FP functions are defined immediately before atan() - WJMc */
8468 * "acos()" function
8470 static void
8471 f_acos(argvars, rettv)
8472 typval_T *argvars;
8473 typval_T *rettv;
8475 float_T f;
8477 rettv->v_type = VAR_FLOAT;
8478 if (get_float_arg(argvars, &f) == OK)
8479 rettv->vval.v_float = acos(f);
8480 else
8481 rettv->vval.v_float = 0.0;
8485 * "asin()" function
8487 static void
8488 f_asin(argvars, rettv)
8489 typval_T *argvars;
8490 typval_T *rettv;
8492 float_T f;
8494 rettv->v_type = VAR_FLOAT;
8495 if (get_float_arg(argvars, &f) == OK)
8496 rettv->vval.v_float = asin(f);
8497 else
8498 rettv->vval.v_float = 0.0;
8502 * "atan2()" function
8504 static void
8505 f_atan2(argvars, rettv)
8506 typval_T *argvars;
8507 typval_T *rettv;
8509 float_T fx, fy;
8511 rettv->v_type = VAR_FLOAT;
8512 if (get_float_arg(argvars, &fx) == OK
8513 && get_float_arg(&argvars[1], &fy) == OK)
8514 rettv->vval.v_float = atan2(fx, fy);
8515 else
8516 rettv->vval.v_float = 0.0;
8520 * "cosh()" function
8522 static void
8523 f_cosh(argvars, rettv)
8524 typval_T *argvars;
8525 typval_T *rettv;
8527 float_T f;
8529 rettv->v_type = VAR_FLOAT;
8530 if (get_float_arg(argvars, &f) == OK)
8531 rettv->vval.v_float = cosh(f);
8532 else
8533 rettv->vval.v_float = 0.0;
8537 * "exp()" function
8539 static void
8540 f_exp(argvars, rettv)
8541 typval_T *argvars;
8542 typval_T *rettv;
8544 float_T f;
8546 rettv->v_type = VAR_FLOAT;
8547 if (get_float_arg(argvars, &f) == OK)
8548 rettv->vval.v_float = exp(f);
8549 else
8550 rettv->vval.v_float = 0.0;
8554 * "fmod()" function
8556 static void
8557 f_fmod(argvars, rettv)
8558 typval_T *argvars;
8559 typval_T *rettv;
8561 float_T fx, fy;
8563 rettv->v_type = VAR_FLOAT;
8564 if (get_float_arg(argvars, &fx) == OK
8565 && get_float_arg(&argvars[1], &fy) == OK)
8566 rettv->vval.v_float = fmod(fx, fy);
8567 else
8568 rettv->vval.v_float = 0.0;
8572 * "log()" function
8574 static void
8575 f_log(argvars, rettv)
8576 typval_T *argvars;
8577 typval_T *rettv;
8579 float_T f;
8581 rettv->v_type = VAR_FLOAT;
8582 if (get_float_arg(argvars, &f) == OK)
8583 rettv->vval.v_float = log(f);
8584 else
8585 rettv->vval.v_float = 0.0;
8589 * "sinh()" function
8591 static void
8592 f_sinh(argvars, rettv)
8593 typval_T *argvars;
8594 typval_T *rettv;
8596 float_T f;
8598 rettv->v_type = VAR_FLOAT;
8599 if (get_float_arg(argvars, &f) == OK)
8600 rettv->vval.v_float = sinh(f);
8601 else
8602 rettv->vval.v_float = 0.0;
8606 * "tan()" function
8608 static void
8609 f_tan(argvars, rettv)
8610 typval_T *argvars;
8611 typval_T *rettv;
8613 float_T f;
8615 rettv->v_type = VAR_FLOAT;
8616 if (get_float_arg(argvars, &f) == OK)
8617 rettv->vval.v_float = tan(f);
8618 else
8619 rettv->vval.v_float = 0.0;
8623 * "tanh()" function
8625 static void
8626 f_tanh(argvars, rettv)
8627 typval_T *argvars;
8628 typval_T *rettv;
8630 float_T f;
8632 rettv->v_type = VAR_FLOAT;
8633 if (get_float_arg(argvars, &f) == OK)
8634 rettv->vval.v_float = tanh(f);
8635 else
8636 rettv->vval.v_float = 0.0;
8639 /* End of the 10 added FP functions - WJMc */
8642 * "atan()" function
8644 static void
8645 f_atan(argvars, rettv)
8646 typval_T *argvars;
8647 typval_T *rettv;
8649 float_T f;
8651 rettv->v_type = VAR_FLOAT;
8652 if (get_float_arg(argvars, &f) == OK)
8653 rettv->vval.v_float = atan(f);
8654 else
8655 rettv->vval.v_float = 0.0;
8657 #endif
8660 * "browse(save, title, initdir, default)" function
8662 static void
8663 f_browse(argvars, rettv)
8664 typval_T *argvars UNUSED;
8665 typval_T *rettv;
8667 #ifdef FEAT_BROWSE
8668 int save;
8669 char_u *title;
8670 char_u *initdir;
8671 char_u *defname;
8672 char_u buf[NUMBUFLEN];
8673 char_u buf2[NUMBUFLEN];
8674 int error = FALSE;
8676 save = get_tv_number_chk(&argvars[0], &error);
8677 title = get_tv_string_chk(&argvars[1]);
8678 initdir = get_tv_string_buf_chk(&argvars[2], buf);
8679 defname = get_tv_string_buf_chk(&argvars[3], buf2);
8681 if (error || title == NULL || initdir == NULL || defname == NULL)
8682 rettv->vval.v_string = NULL;
8683 else
8684 rettv->vval.v_string =
8685 do_browse(save ? BROWSE_SAVE : 0,
8686 title, defname, NULL, initdir, NULL, curbuf);
8687 #else
8688 rettv->vval.v_string = NULL;
8689 #endif
8690 rettv->v_type = VAR_STRING;
8694 * "browsedir(title, initdir)" function
8696 static void
8697 f_browsedir(argvars, rettv)
8698 typval_T *argvars UNUSED;
8699 typval_T *rettv;
8701 #ifdef FEAT_BROWSE
8702 char_u *title;
8703 char_u *initdir;
8704 char_u buf[NUMBUFLEN];
8706 title = get_tv_string_chk(&argvars[0]);
8707 initdir = get_tv_string_buf_chk(&argvars[1], buf);
8709 if (title == NULL || initdir == NULL)
8710 rettv->vval.v_string = NULL;
8711 else
8712 rettv->vval.v_string = do_browse(BROWSE_DIR,
8713 title, NULL, NULL, initdir, NULL, curbuf);
8714 #else
8715 rettv->vval.v_string = NULL;
8716 #endif
8717 rettv->v_type = VAR_STRING;
8720 static buf_T *find_buffer __ARGS((typval_T *avar));
8723 * Find a buffer by number or exact name.
8725 static buf_T *
8726 find_buffer(avar)
8727 typval_T *avar;
8729 buf_T *buf = NULL;
8731 if (avar->v_type == VAR_NUMBER)
8732 buf = buflist_findnr((int)avar->vval.v_number);
8733 else if (avar->v_type == VAR_STRING && avar->vval.v_string != NULL)
8735 buf = buflist_findname_exp(avar->vval.v_string);
8736 if (buf == NULL)
8738 /* No full path name match, try a match with a URL or a "nofile"
8739 * buffer, these don't use the full path. */
8740 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8741 if (buf->b_fname != NULL
8742 && (path_with_url(buf->b_fname)
8743 #ifdef FEAT_QUICKFIX
8744 || bt_nofile(buf)
8745 #endif
8747 && STRCMP(buf->b_fname, avar->vval.v_string) == 0)
8748 break;
8751 return buf;
8755 * "bufexists(expr)" function
8757 static void
8758 f_bufexists(argvars, rettv)
8759 typval_T *argvars;
8760 typval_T *rettv;
8762 rettv->vval.v_number = (find_buffer(&argvars[0]) != NULL);
8766 * "buflisted(expr)" function
8768 static void
8769 f_buflisted(argvars, rettv)
8770 typval_T *argvars;
8771 typval_T *rettv;
8773 buf_T *buf;
8775 buf = find_buffer(&argvars[0]);
8776 rettv->vval.v_number = (buf != NULL && buf->b_p_bl);
8780 * "bufloaded(expr)" function
8782 static void
8783 f_bufloaded(argvars, rettv)
8784 typval_T *argvars;
8785 typval_T *rettv;
8787 buf_T *buf;
8789 buf = find_buffer(&argvars[0]);
8790 rettv->vval.v_number = (buf != NULL && buf->b_ml.ml_mfp != NULL);
8793 static buf_T *get_buf_tv __ARGS((typval_T *tv));
8796 * Get buffer by number or pattern.
8798 static buf_T *
8799 get_buf_tv(tv)
8800 typval_T *tv;
8802 char_u *name = tv->vval.v_string;
8803 int save_magic;
8804 char_u *save_cpo;
8805 buf_T *buf;
8807 if (tv->v_type == VAR_NUMBER)
8808 return buflist_findnr((int)tv->vval.v_number);
8809 if (tv->v_type != VAR_STRING)
8810 return NULL;
8811 if (name == NULL || *name == NUL)
8812 return curbuf;
8813 if (name[0] == '$' && name[1] == NUL)
8814 return lastbuf;
8816 /* Ignore 'magic' and 'cpoptions' here to make scripts portable */
8817 save_magic = p_magic;
8818 p_magic = TRUE;
8819 save_cpo = p_cpo;
8820 p_cpo = (char_u *)"";
8822 buf = buflist_findnr(buflist_findpat(name, name + STRLEN(name),
8823 TRUE, FALSE));
8825 p_magic = save_magic;
8826 p_cpo = save_cpo;
8828 /* If not found, try expanding the name, like done for bufexists(). */
8829 if (buf == NULL)
8830 buf = find_buffer(tv);
8832 return buf;
8836 * "bufname(expr)" function
8838 static void
8839 f_bufname(argvars, rettv)
8840 typval_T *argvars;
8841 typval_T *rettv;
8843 buf_T *buf;
8845 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8846 ++emsg_off;
8847 buf = get_buf_tv(&argvars[0]);
8848 rettv->v_type = VAR_STRING;
8849 if (buf != NULL && buf->b_fname != NULL)
8850 rettv->vval.v_string = vim_strsave(buf->b_fname);
8851 else
8852 rettv->vval.v_string = NULL;
8853 --emsg_off;
8857 * "bufnr(expr)" function
8859 static void
8860 f_bufnr(argvars, rettv)
8861 typval_T *argvars;
8862 typval_T *rettv;
8864 buf_T *buf;
8865 int error = FALSE;
8866 char_u *name;
8868 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8869 ++emsg_off;
8870 buf = get_buf_tv(&argvars[0]);
8871 --emsg_off;
8873 /* If the buffer isn't found and the second argument is not zero create a
8874 * new buffer. */
8875 if (buf == NULL
8876 && argvars[1].v_type != VAR_UNKNOWN
8877 && get_tv_number_chk(&argvars[1], &error) != 0
8878 && !error
8879 && (name = get_tv_string_chk(&argvars[0])) != NULL
8880 && !error)
8881 buf = buflist_new(name, NULL, (linenr_T)1, 0);
8883 if (buf != NULL)
8884 rettv->vval.v_number = buf->b_fnum;
8885 else
8886 rettv->vval.v_number = -1;
8890 * "bufwinnr(nr)" function
8892 static void
8893 f_bufwinnr(argvars, rettv)
8894 typval_T *argvars;
8895 typval_T *rettv;
8897 #ifdef FEAT_WINDOWS
8898 win_T *wp;
8899 int winnr = 0;
8900 #endif
8901 buf_T *buf;
8903 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
8904 ++emsg_off;
8905 buf = get_buf_tv(&argvars[0]);
8906 #ifdef FEAT_WINDOWS
8907 for (wp = firstwin; wp; wp = wp->w_next)
8909 ++winnr;
8910 if (wp->w_buffer == buf)
8911 break;
8913 rettv->vval.v_number = (wp != NULL ? winnr : -1);
8914 #else
8915 rettv->vval.v_number = (curwin->w_buffer == buf ? 1 : -1);
8916 #endif
8917 --emsg_off;
8921 * "byte2line(byte)" function
8923 static void
8924 f_byte2line(argvars, rettv)
8925 typval_T *argvars UNUSED;
8926 typval_T *rettv;
8928 #ifndef FEAT_BYTEOFF
8929 rettv->vval.v_number = -1;
8930 #else
8931 long boff = 0;
8933 boff = get_tv_number(&argvars[0]) - 1; /* boff gets -1 on type error */
8934 if (boff < 0)
8935 rettv->vval.v_number = -1;
8936 else
8937 rettv->vval.v_number = ml_find_line_or_offset(curbuf,
8938 (linenr_T)0, &boff);
8939 #endif
8943 * "byteidx()" function
8945 static void
8946 f_byteidx(argvars, rettv)
8947 typval_T *argvars;
8948 typval_T *rettv;
8950 #ifdef FEAT_MBYTE
8951 char_u *t;
8952 #endif
8953 char_u *str;
8954 long idx;
8956 str = get_tv_string_chk(&argvars[0]);
8957 idx = get_tv_number_chk(&argvars[1], NULL);
8958 rettv->vval.v_number = -1;
8959 if (str == NULL || idx < 0)
8960 return;
8962 #ifdef FEAT_MBYTE
8963 t = str;
8964 for ( ; idx > 0; idx--)
8966 if (*t == NUL) /* EOL reached */
8967 return;
8968 t += (*mb_ptr2len)(t);
8970 rettv->vval.v_number = (varnumber_T)(t - str);
8971 #else
8972 if ((size_t)idx <= STRLEN(str))
8973 rettv->vval.v_number = idx;
8974 #endif
8978 * "call(func, arglist)" function
8980 static void
8981 f_call(argvars, rettv)
8982 typval_T *argvars;
8983 typval_T *rettv;
8985 char_u *func;
8986 typval_T argv[MAX_FUNC_ARGS + 1];
8987 int argc = 0;
8988 listitem_T *item;
8989 int dummy;
8990 dict_T *selfdict = NULL;
8992 if (argvars[1].v_type != VAR_LIST)
8994 EMSG(_(e_listreq));
8995 return;
8997 if (argvars[1].vval.v_list == NULL)
8998 return;
9000 if (argvars[0].v_type == VAR_FUNC)
9001 func = argvars[0].vval.v_string;
9002 else
9003 func = get_tv_string(&argvars[0]);
9004 if (*func == NUL)
9005 return; /* type error or empty name */
9007 if (argvars[2].v_type != VAR_UNKNOWN)
9009 if (argvars[2].v_type != VAR_DICT)
9011 EMSG(_(e_dictreq));
9012 return;
9014 selfdict = argvars[2].vval.v_dict;
9017 for (item = argvars[1].vval.v_list->lv_first; item != NULL;
9018 item = item->li_next)
9020 if (argc == MAX_FUNC_ARGS)
9022 EMSG(_("E699: Too many arguments"));
9023 break;
9025 /* Make a copy of each argument. This is needed to be able to set
9026 * v_lock to VAR_FIXED in the copy without changing the original list.
9028 copy_tv(&item->li_tv, &argv[argc++]);
9031 if (item == NULL)
9032 (void)call_func(func, (int)STRLEN(func), rettv, argc, argv,
9033 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
9034 &dummy, TRUE, selfdict);
9036 /* Free the arguments. */
9037 while (argc > 0)
9038 clear_tv(&argv[--argc]);
9041 #ifdef FEAT_FLOAT
9043 * "ceil({float})" function
9045 static void
9046 f_ceil(argvars, rettv)
9047 typval_T *argvars;
9048 typval_T *rettv;
9050 float_T f;
9052 rettv->v_type = VAR_FLOAT;
9053 if (get_float_arg(argvars, &f) == OK)
9054 rettv->vval.v_float = ceil(f);
9055 else
9056 rettv->vval.v_float = 0.0;
9058 #endif
9061 * "changenr()" function
9063 static void
9064 f_changenr(argvars, rettv)
9065 typval_T *argvars UNUSED;
9066 typval_T *rettv;
9068 rettv->vval.v_number = curbuf->b_u_seq_cur;
9072 * "char2nr(string)" function
9074 static void
9075 f_char2nr(argvars, rettv)
9076 typval_T *argvars;
9077 typval_T *rettv;
9079 #ifdef FEAT_MBYTE
9080 if (has_mbyte)
9081 rettv->vval.v_number = (*mb_ptr2char)(get_tv_string(&argvars[0]));
9082 else
9083 #endif
9084 rettv->vval.v_number = get_tv_string(&argvars[0])[0];
9088 * "cindent(lnum)" function
9090 static void
9091 f_cindent(argvars, rettv)
9092 typval_T *argvars;
9093 typval_T *rettv;
9095 #ifdef FEAT_CINDENT
9096 pos_T pos;
9097 linenr_T lnum;
9099 pos = curwin->w_cursor;
9100 lnum = get_tv_lnum(argvars);
9101 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
9103 curwin->w_cursor.lnum = lnum;
9104 rettv->vval.v_number = get_c_indent();
9105 curwin->w_cursor = pos;
9107 else
9108 #endif
9109 rettv->vval.v_number = -1;
9113 * "clearmatches()" function
9115 static void
9116 f_clearmatches(argvars, rettv)
9117 typval_T *argvars UNUSED;
9118 typval_T *rettv UNUSED;
9120 #ifdef FEAT_SEARCH_EXTRA
9121 clear_matches(curwin);
9122 #endif
9126 * "col(string)" function
9128 static void
9129 f_col(argvars, rettv)
9130 typval_T *argvars;
9131 typval_T *rettv;
9133 colnr_T col = 0;
9134 pos_T *fp;
9135 int fnum = curbuf->b_fnum;
9137 fp = var2fpos(&argvars[0], FALSE, &fnum);
9138 if (fp != NULL && fnum == curbuf->b_fnum)
9140 if (fp->col == MAXCOL)
9142 /* '> can be MAXCOL, get the length of the line then */
9143 if (fp->lnum <= curbuf->b_ml.ml_line_count)
9144 col = (colnr_T)STRLEN(ml_get(fp->lnum)) + 1;
9145 else
9146 col = MAXCOL;
9148 else
9150 col = fp->col + 1;
9151 #ifdef FEAT_VIRTUALEDIT
9152 /* col(".") when the cursor is on the NUL at the end of the line
9153 * because of "coladd" can be seen as an extra column. */
9154 if (virtual_active() && fp == &curwin->w_cursor)
9156 char_u *p = ml_get_cursor();
9158 if (curwin->w_cursor.coladd >= (colnr_T)chartabsize(p,
9159 curwin->w_virtcol - curwin->w_cursor.coladd))
9161 # ifdef FEAT_MBYTE
9162 int l;
9164 if (*p != NUL && p[(l = (*mb_ptr2len)(p))] == NUL)
9165 col += l;
9166 # else
9167 if (*p != NUL && p[1] == NUL)
9168 ++col;
9169 # endif
9172 #endif
9175 rettv->vval.v_number = col;
9178 #if defined(FEAT_INS_EXPAND)
9180 * "complete()" function
9182 static void
9183 f_complete(argvars, rettv)
9184 typval_T *argvars;
9185 typval_T *rettv UNUSED;
9187 int startcol;
9189 if ((State & INSERT) == 0)
9191 EMSG(_("E785: complete() can only be used in Insert mode"));
9192 return;
9195 /* Check for undo allowed here, because if something was already inserted
9196 * the line was already saved for undo and this check isn't done. */
9197 if (!undo_allowed())
9198 return;
9200 if (argvars[1].v_type != VAR_LIST || argvars[1].vval.v_list == NULL)
9202 EMSG(_(e_invarg));
9203 return;
9206 startcol = get_tv_number_chk(&argvars[0], NULL);
9207 if (startcol <= 0)
9208 return;
9210 set_completion(startcol - 1, argvars[1].vval.v_list);
9214 * "complete_add()" function
9216 static void
9217 f_complete_add(argvars, rettv)
9218 typval_T *argvars;
9219 typval_T *rettv;
9221 rettv->vval.v_number = ins_compl_add_tv(&argvars[0], 0);
9225 * "complete_check()" function
9227 static void
9228 f_complete_check(argvars, rettv)
9229 typval_T *argvars UNUSED;
9230 typval_T *rettv;
9232 int saved = RedrawingDisabled;
9234 RedrawingDisabled = 0;
9235 ins_compl_check_keys(0);
9236 rettv->vval.v_number = compl_interrupted;
9237 RedrawingDisabled = saved;
9239 #endif
9242 * "confirm(message, buttons[, default [, type]])" function
9244 static void
9245 f_confirm(argvars, rettv)
9246 typval_T *argvars UNUSED;
9247 typval_T *rettv UNUSED;
9249 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
9250 char_u *message;
9251 char_u *buttons = NULL;
9252 char_u buf[NUMBUFLEN];
9253 char_u buf2[NUMBUFLEN];
9254 int def = 1;
9255 int type = VIM_GENERIC;
9256 char_u *typestr;
9257 int error = FALSE;
9259 message = get_tv_string_chk(&argvars[0]);
9260 if (message == NULL)
9261 error = TRUE;
9262 if (argvars[1].v_type != VAR_UNKNOWN)
9264 buttons = get_tv_string_buf_chk(&argvars[1], buf);
9265 if (buttons == NULL)
9266 error = TRUE;
9267 if (argvars[2].v_type != VAR_UNKNOWN)
9269 def = get_tv_number_chk(&argvars[2], &error);
9270 if (argvars[3].v_type != VAR_UNKNOWN)
9272 typestr = get_tv_string_buf_chk(&argvars[3], buf2);
9273 if (typestr == NULL)
9274 error = TRUE;
9275 else
9277 switch (TOUPPER_ASC(*typestr))
9279 case 'E': type = VIM_ERROR; break;
9280 case 'Q': type = VIM_QUESTION; break;
9281 case 'I': type = VIM_INFO; break;
9282 case 'W': type = VIM_WARNING; break;
9283 case 'G': type = VIM_GENERIC; break;
9290 if (buttons == NULL || *buttons == NUL)
9291 buttons = (char_u *)_("&Ok");
9293 if (!error)
9294 rettv->vval.v_number = do_dialog(type, NULL, message, buttons,
9295 def, NULL);
9296 #endif
9300 * "copy()" function
9302 static void
9303 f_copy(argvars, rettv)
9304 typval_T *argvars;
9305 typval_T *rettv;
9307 item_copy(&argvars[0], rettv, FALSE, 0);
9310 #ifdef FEAT_FLOAT
9312 * "cos()" function
9314 static void
9315 f_cos(argvars, rettv)
9316 typval_T *argvars;
9317 typval_T *rettv;
9319 float_T f;
9321 rettv->v_type = VAR_FLOAT;
9322 if (get_float_arg(argvars, &f) == OK)
9323 rettv->vval.v_float = cos(f);
9324 else
9325 rettv->vval.v_float = 0.0;
9327 #endif
9330 * "count()" function
9332 static void
9333 f_count(argvars, rettv)
9334 typval_T *argvars;
9335 typval_T *rettv;
9337 long n = 0;
9338 int ic = FALSE;
9340 if (argvars[0].v_type == VAR_LIST)
9342 listitem_T *li;
9343 list_T *l;
9344 long idx;
9346 if ((l = argvars[0].vval.v_list) != NULL)
9348 li = l->lv_first;
9349 if (argvars[2].v_type != VAR_UNKNOWN)
9351 int error = FALSE;
9353 ic = get_tv_number_chk(&argvars[2], &error);
9354 if (argvars[3].v_type != VAR_UNKNOWN)
9356 idx = get_tv_number_chk(&argvars[3], &error);
9357 if (!error)
9359 li = list_find(l, idx);
9360 if (li == NULL)
9361 EMSGN(_(e_listidx), idx);
9364 if (error)
9365 li = NULL;
9368 for ( ; li != NULL; li = li->li_next)
9369 if (tv_equal(&li->li_tv, &argvars[1], ic))
9370 ++n;
9373 else if (argvars[0].v_type == VAR_DICT)
9375 int todo;
9376 dict_T *d;
9377 hashitem_T *hi;
9379 if ((d = argvars[0].vval.v_dict) != NULL)
9381 int error = FALSE;
9383 if (argvars[2].v_type != VAR_UNKNOWN)
9385 ic = get_tv_number_chk(&argvars[2], &error);
9386 if (argvars[3].v_type != VAR_UNKNOWN)
9387 EMSG(_(e_invarg));
9390 todo = error ? 0 : (int)d->dv_hashtab.ht_used;
9391 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
9393 if (!HASHITEM_EMPTY(hi))
9395 --todo;
9396 if (tv_equal(&HI2DI(hi)->di_tv, &argvars[1], ic))
9397 ++n;
9402 else
9403 EMSG2(_(e_listdictarg), "count()");
9404 rettv->vval.v_number = n;
9408 * "cscope_connection([{num} , {dbpath} [, {prepend}]])" function
9410 * Checks the existence of a cscope connection.
9412 static void
9413 f_cscope_connection(argvars, rettv)
9414 typval_T *argvars UNUSED;
9415 typval_T *rettv UNUSED;
9417 #ifdef FEAT_CSCOPE
9418 int num = 0;
9419 char_u *dbpath = NULL;
9420 char_u *prepend = NULL;
9421 char_u buf[NUMBUFLEN];
9423 if (argvars[0].v_type != VAR_UNKNOWN
9424 && argvars[1].v_type != VAR_UNKNOWN)
9426 num = (int)get_tv_number(&argvars[0]);
9427 dbpath = get_tv_string(&argvars[1]);
9428 if (argvars[2].v_type != VAR_UNKNOWN)
9429 prepend = get_tv_string_buf(&argvars[2], buf);
9432 rettv->vval.v_number = cs_connection(num, dbpath, prepend);
9433 #endif
9437 * "cursor(lnum, col)" function
9439 * Moves the cursor to the specified line and column.
9440 * Returns 0 when the position could be set, -1 otherwise.
9442 static void
9443 f_cursor(argvars, rettv)
9444 typval_T *argvars;
9445 typval_T *rettv;
9447 long line, col;
9448 #ifdef FEAT_VIRTUALEDIT
9449 long coladd = 0;
9450 #endif
9452 rettv->vval.v_number = -1;
9453 if (argvars[1].v_type == VAR_UNKNOWN)
9455 pos_T pos;
9457 if (list2fpos(argvars, &pos, NULL) == FAIL)
9458 return;
9459 line = pos.lnum;
9460 col = pos.col;
9461 #ifdef FEAT_VIRTUALEDIT
9462 coladd = pos.coladd;
9463 #endif
9465 else
9467 line = get_tv_lnum(argvars);
9468 col = get_tv_number_chk(&argvars[1], NULL);
9469 #ifdef FEAT_VIRTUALEDIT
9470 if (argvars[2].v_type != VAR_UNKNOWN)
9471 coladd = get_tv_number_chk(&argvars[2], NULL);
9472 #endif
9474 if (line < 0 || col < 0
9475 #ifdef FEAT_VIRTUALEDIT
9476 || coladd < 0
9477 #endif
9479 return; /* type error; errmsg already given */
9480 if (line > 0)
9481 curwin->w_cursor.lnum = line;
9482 if (col > 0)
9483 curwin->w_cursor.col = col - 1;
9484 #ifdef FEAT_VIRTUALEDIT
9485 curwin->w_cursor.coladd = coladd;
9486 #endif
9488 /* Make sure the cursor is in a valid position. */
9489 check_cursor();
9490 #ifdef FEAT_MBYTE
9491 /* Correct cursor for multi-byte character. */
9492 if (has_mbyte)
9493 mb_adjust_cursor();
9494 #endif
9496 curwin->w_set_curswant = TRUE;
9497 rettv->vval.v_number = 0;
9501 * "deepcopy()" function
9503 static void
9504 f_deepcopy(argvars, rettv)
9505 typval_T *argvars;
9506 typval_T *rettv;
9508 int noref = 0;
9510 if (argvars[1].v_type != VAR_UNKNOWN)
9511 noref = get_tv_number_chk(&argvars[1], NULL);
9512 if (noref < 0 || noref > 1)
9513 EMSG(_(e_invarg));
9514 else
9516 current_copyID += COPYID_INC;
9517 item_copy(&argvars[0], rettv, TRUE, noref == 0 ? current_copyID : 0);
9522 * "delete()" function
9524 static void
9525 f_delete(argvars, rettv)
9526 typval_T *argvars;
9527 typval_T *rettv;
9529 if (check_restricted() || check_secure())
9530 rettv->vval.v_number = -1;
9531 else
9532 rettv->vval.v_number = mch_remove(get_tv_string(&argvars[0]));
9536 * "did_filetype()" function
9538 static void
9539 f_did_filetype(argvars, rettv)
9540 typval_T *argvars UNUSED;
9541 typval_T *rettv UNUSED;
9543 #ifdef FEAT_AUTOCMD
9544 rettv->vval.v_number = did_filetype;
9545 #endif
9549 * "diff_filler()" function
9551 static void
9552 f_diff_filler(argvars, rettv)
9553 typval_T *argvars UNUSED;
9554 typval_T *rettv UNUSED;
9556 #ifdef FEAT_DIFF
9557 rettv->vval.v_number = diff_check_fill(curwin, get_tv_lnum(argvars));
9558 #endif
9562 * "diff_hlID()" function
9564 static void
9565 f_diff_hlID(argvars, rettv)
9566 typval_T *argvars UNUSED;
9567 typval_T *rettv UNUSED;
9569 #ifdef FEAT_DIFF
9570 linenr_T lnum = get_tv_lnum(argvars);
9571 static linenr_T prev_lnum = 0;
9572 static int changedtick = 0;
9573 static int fnum = 0;
9574 static int change_start = 0;
9575 static int change_end = 0;
9576 static hlf_T hlID = (hlf_T)0;
9577 int filler_lines;
9578 int col;
9580 if (lnum < 0) /* ignore type error in {lnum} arg */
9581 lnum = 0;
9582 if (lnum != prev_lnum
9583 || changedtick != curbuf->b_changedtick
9584 || fnum != curbuf->b_fnum)
9586 /* New line, buffer, change: need to get the values. */
9587 filler_lines = diff_check(curwin, lnum);
9588 if (filler_lines < 0)
9590 if (filler_lines == -1)
9592 change_start = MAXCOL;
9593 change_end = -1;
9594 if (diff_find_change(curwin, lnum, &change_start, &change_end))
9595 hlID = HLF_ADD; /* added line */
9596 else
9597 hlID = HLF_CHD; /* changed line */
9599 else
9600 hlID = HLF_ADD; /* added line */
9602 else
9603 hlID = (hlf_T)0;
9604 prev_lnum = lnum;
9605 changedtick = curbuf->b_changedtick;
9606 fnum = curbuf->b_fnum;
9609 if (hlID == HLF_CHD || hlID == HLF_TXD)
9611 col = get_tv_number(&argvars[1]) - 1; /* ignore type error in {col} */
9612 if (col >= change_start && col <= change_end)
9613 hlID = HLF_TXD; /* changed text */
9614 else
9615 hlID = HLF_CHD; /* changed line */
9617 rettv->vval.v_number = hlID == (hlf_T)0 ? 0 : (int)hlID;
9618 #endif
9622 * "empty({expr})" function
9624 static void
9625 f_empty(argvars, rettv)
9626 typval_T *argvars;
9627 typval_T *rettv;
9629 int n;
9631 switch (argvars[0].v_type)
9633 case VAR_STRING:
9634 case VAR_FUNC:
9635 n = argvars[0].vval.v_string == NULL
9636 || *argvars[0].vval.v_string == NUL;
9637 break;
9638 case VAR_NUMBER:
9639 n = argvars[0].vval.v_number == 0;
9640 break;
9641 #ifdef FEAT_FLOAT
9642 case VAR_FLOAT:
9643 n = argvars[0].vval.v_float == 0.0;
9644 break;
9645 #endif
9646 case VAR_LIST:
9647 n = argvars[0].vval.v_list == NULL
9648 || argvars[0].vval.v_list->lv_first == NULL;
9649 break;
9650 case VAR_DICT:
9651 n = argvars[0].vval.v_dict == NULL
9652 || argvars[0].vval.v_dict->dv_hashtab.ht_used == 0;
9653 break;
9654 default:
9655 EMSG2(_(e_intern2), "f_empty()");
9656 n = 0;
9659 rettv->vval.v_number = n;
9663 * "escape({string}, {chars})" function
9665 static void
9666 f_escape(argvars, rettv)
9667 typval_T *argvars;
9668 typval_T *rettv;
9670 char_u buf[NUMBUFLEN];
9672 rettv->vval.v_string = vim_strsave_escaped(get_tv_string(&argvars[0]),
9673 get_tv_string_buf(&argvars[1], buf));
9674 rettv->v_type = VAR_STRING;
9678 * "eval()" function
9680 static void
9681 f_eval(argvars, rettv)
9682 typval_T *argvars;
9683 typval_T *rettv;
9685 char_u *s;
9687 s = get_tv_string_chk(&argvars[0]);
9688 if (s != NULL)
9689 s = skipwhite(s);
9691 if (s == NULL || eval1(&s, rettv, TRUE) == FAIL)
9693 rettv->v_type = VAR_NUMBER;
9694 rettv->vval.v_number = 0;
9696 else if (*s != NUL)
9697 EMSG(_(e_trailing));
9701 * "eventhandler()" function
9703 static void
9704 f_eventhandler(argvars, rettv)
9705 typval_T *argvars UNUSED;
9706 typval_T *rettv;
9708 rettv->vval.v_number = vgetc_busy;
9712 * "executable()" function
9714 static void
9715 f_executable(argvars, rettv)
9716 typval_T *argvars;
9717 typval_T *rettv;
9719 rettv->vval.v_number = mch_can_exe(get_tv_string(&argvars[0]));
9723 * "exists()" function
9725 static void
9726 f_exists(argvars, rettv)
9727 typval_T *argvars;
9728 typval_T *rettv;
9730 char_u *p;
9731 char_u *name;
9732 int n = FALSE;
9733 int len = 0;
9735 p = get_tv_string(&argvars[0]);
9736 if (*p == '$') /* environment variable */
9738 /* first try "normal" environment variables (fast) */
9739 if (mch_getenv(p + 1) != NULL)
9740 n = TRUE;
9741 else
9743 /* try expanding things like $VIM and ${HOME} */
9744 p = expand_env_save(p);
9745 if (p != NULL && *p != '$')
9746 n = TRUE;
9747 vim_free(p);
9750 else if (*p == '&' || *p == '+') /* option */
9752 n = (get_option_tv(&p, NULL, TRUE) == OK);
9753 if (*skipwhite(p) != NUL)
9754 n = FALSE; /* trailing garbage */
9756 else if (*p == '*') /* internal or user defined function */
9758 n = function_exists(p + 1);
9760 else if (*p == ':')
9762 n = cmd_exists(p + 1);
9764 else if (*p == '#')
9766 #ifdef FEAT_AUTOCMD
9767 if (p[1] == '#')
9768 n = autocmd_supported(p + 2);
9769 else
9770 n = au_exists(p + 1);
9771 #endif
9773 else /* internal variable */
9775 char_u *tofree;
9776 typval_T tv;
9778 /* get_name_len() takes care of expanding curly braces */
9779 name = p;
9780 len = get_name_len(&p, &tofree, TRUE, FALSE);
9781 if (len > 0)
9783 if (tofree != NULL)
9784 name = tofree;
9785 n = (get_var_tv(name, len, &tv, FALSE) == OK);
9786 if (n)
9788 /* handle d.key, l[idx], f(expr) */
9789 n = (handle_subscript(&p, &tv, TRUE, FALSE) == OK);
9790 if (n)
9791 clear_tv(&tv);
9794 if (*p != NUL)
9795 n = FALSE;
9797 vim_free(tofree);
9800 rettv->vval.v_number = n;
9804 * "expand()" function
9806 static void
9807 f_expand(argvars, rettv)
9808 typval_T *argvars;
9809 typval_T *rettv;
9811 char_u *s;
9812 int len;
9813 char_u *errormsg;
9814 int flags = WILD_SILENT|WILD_USE_NL|WILD_LIST_NOTFOUND;
9815 expand_T xpc;
9816 int error = FALSE;
9818 rettv->v_type = VAR_STRING;
9819 s = get_tv_string(&argvars[0]);
9820 if (*s == '%' || *s == '#' || *s == '<')
9822 ++emsg_off;
9823 rettv->vval.v_string = eval_vars(s, s, &len, NULL, &errormsg, NULL);
9824 --emsg_off;
9826 else
9828 /* When the optional second argument is non-zero, don't remove matches
9829 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
9830 if (argvars[1].v_type != VAR_UNKNOWN
9831 && get_tv_number_chk(&argvars[1], &error))
9832 flags |= WILD_KEEP_ALL;
9833 if (!error)
9835 ExpandInit(&xpc);
9836 xpc.xp_context = EXPAND_FILES;
9837 rettv->vval.v_string = ExpandOne(&xpc, s, NULL, flags, WILD_ALL);
9839 else
9840 rettv->vval.v_string = NULL;
9845 * "extend(list, list [, idx])" function
9846 * "extend(dict, dict [, action])" function
9848 static void
9849 f_extend(argvars, rettv)
9850 typval_T *argvars;
9851 typval_T *rettv;
9853 if (argvars[0].v_type == VAR_LIST && argvars[1].v_type == VAR_LIST)
9855 list_T *l1, *l2;
9856 listitem_T *item;
9857 long before;
9858 int error = FALSE;
9860 l1 = argvars[0].vval.v_list;
9861 l2 = argvars[1].vval.v_list;
9862 if (l1 != NULL && !tv_check_lock(l1->lv_lock, (char_u *)"extend()")
9863 && l2 != NULL)
9865 if (argvars[2].v_type != VAR_UNKNOWN)
9867 before = get_tv_number_chk(&argvars[2], &error);
9868 if (error)
9869 return; /* type error; errmsg already given */
9871 if (before == l1->lv_len)
9872 item = NULL;
9873 else
9875 item = list_find(l1, before);
9876 if (item == NULL)
9878 EMSGN(_(e_listidx), before);
9879 return;
9883 else
9884 item = NULL;
9885 list_extend(l1, l2, item);
9887 copy_tv(&argvars[0], rettv);
9890 else if (argvars[0].v_type == VAR_DICT && argvars[1].v_type == VAR_DICT)
9892 dict_T *d1, *d2;
9893 dictitem_T *di1;
9894 char_u *action;
9895 int i;
9896 hashitem_T *hi2;
9897 int todo;
9899 d1 = argvars[0].vval.v_dict;
9900 d2 = argvars[1].vval.v_dict;
9901 if (d1 != NULL && !tv_check_lock(d1->dv_lock, (char_u *)"extend()")
9902 && d2 != NULL)
9904 /* Check the third argument. */
9905 if (argvars[2].v_type != VAR_UNKNOWN)
9907 static char *(av[]) = {"keep", "force", "error"};
9909 action = get_tv_string_chk(&argvars[2]);
9910 if (action == NULL)
9911 return; /* type error; errmsg already given */
9912 for (i = 0; i < 3; ++i)
9913 if (STRCMP(action, av[i]) == 0)
9914 break;
9915 if (i == 3)
9917 EMSG2(_(e_invarg2), action);
9918 return;
9921 else
9922 action = (char_u *)"force";
9924 /* Go over all entries in the second dict and add them to the
9925 * first dict. */
9926 todo = (int)d2->dv_hashtab.ht_used;
9927 for (hi2 = d2->dv_hashtab.ht_array; todo > 0; ++hi2)
9929 if (!HASHITEM_EMPTY(hi2))
9931 --todo;
9932 di1 = dict_find(d1, hi2->hi_key, -1);
9933 if (di1 == NULL)
9935 di1 = dictitem_copy(HI2DI(hi2));
9936 if (di1 != NULL && dict_add(d1, di1) == FAIL)
9937 dictitem_free(di1);
9939 else if (*action == 'e')
9941 EMSG2(_("E737: Key already exists: %s"), hi2->hi_key);
9942 break;
9944 else if (*action == 'f')
9946 clear_tv(&di1->di_tv);
9947 copy_tv(&HI2DI(hi2)->di_tv, &di1->di_tv);
9952 copy_tv(&argvars[0], rettv);
9955 else
9956 EMSG2(_(e_listdictarg), "extend()");
9960 * "feedkeys()" function
9962 static void
9963 f_feedkeys(argvars, rettv)
9964 typval_T *argvars;
9965 typval_T *rettv UNUSED;
9967 int remap = TRUE;
9968 char_u *keys, *flags;
9969 char_u nbuf[NUMBUFLEN];
9970 int typed = FALSE;
9971 char_u *keys_esc;
9973 /* This is not allowed in the sandbox. If the commands would still be
9974 * executed in the sandbox it would be OK, but it probably happens later,
9975 * when "sandbox" is no longer set. */
9976 if (check_secure())
9977 return;
9979 keys = get_tv_string(&argvars[0]);
9980 if (*keys != NUL)
9982 if (argvars[1].v_type != VAR_UNKNOWN)
9984 flags = get_tv_string_buf(&argvars[1], nbuf);
9985 for ( ; *flags != NUL; ++flags)
9987 switch (*flags)
9989 case 'n': remap = FALSE; break;
9990 case 'm': remap = TRUE; break;
9991 case 't': typed = TRUE; break;
9996 /* Need to escape K_SPECIAL and CSI before putting the string in the
9997 * typeahead buffer. */
9998 keys_esc = vim_strsave_escape_csi(keys);
9999 if (keys_esc != NULL)
10001 ins_typebuf(keys_esc, (remap ? REMAP_YES : REMAP_NONE),
10002 typebuf.tb_len, !typed, FALSE);
10003 vim_free(keys_esc);
10004 if (vgetc_busy)
10005 typebuf_was_filled = TRUE;
10011 * "filereadable()" function
10013 static void
10014 f_filereadable(argvars, rettv)
10015 typval_T *argvars;
10016 typval_T *rettv;
10018 int fd;
10019 char_u *p;
10020 int n;
10022 #ifndef O_NONBLOCK
10023 # define O_NONBLOCK 0
10024 #endif
10025 p = get_tv_string(&argvars[0]);
10026 if (*p && !mch_isdir(p) && (fd = mch_open((char *)p,
10027 O_RDONLY | O_NONBLOCK, 0)) >= 0)
10029 n = TRUE;
10030 close(fd);
10032 else
10033 n = FALSE;
10035 rettv->vval.v_number = n;
10039 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
10040 * rights to write into.
10042 static void
10043 f_filewritable(argvars, rettv)
10044 typval_T *argvars;
10045 typval_T *rettv;
10047 rettv->vval.v_number = filewritable(get_tv_string(&argvars[0]));
10050 static void findfilendir __ARGS((typval_T *argvars, typval_T *rettv, int find_what));
10052 static void
10053 findfilendir(argvars, rettv, find_what)
10054 typval_T *argvars;
10055 typval_T *rettv;
10056 int find_what;
10058 #ifdef FEAT_SEARCHPATH
10059 char_u *fname;
10060 char_u *fresult = NULL;
10061 char_u *path = *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path;
10062 char_u *p;
10063 char_u pathbuf[NUMBUFLEN];
10064 int count = 1;
10065 int first = TRUE;
10066 int error = FALSE;
10067 #endif
10069 rettv->vval.v_string = NULL;
10070 rettv->v_type = VAR_STRING;
10072 #ifdef FEAT_SEARCHPATH
10073 fname = get_tv_string(&argvars[0]);
10075 if (argvars[1].v_type != VAR_UNKNOWN)
10077 p = get_tv_string_buf_chk(&argvars[1], pathbuf);
10078 if (p == NULL)
10079 error = TRUE;
10080 else
10082 if (*p != NUL)
10083 path = p;
10085 if (argvars[2].v_type != VAR_UNKNOWN)
10086 count = get_tv_number_chk(&argvars[2], &error);
10090 if (count < 0 && rettv_list_alloc(rettv) == FAIL)
10091 error = TRUE;
10093 if (*fname != NUL && !error)
10097 if (rettv->v_type == VAR_STRING)
10098 vim_free(fresult);
10099 fresult = find_file_in_path_option(first ? fname : NULL,
10100 first ? (int)STRLEN(fname) : 0,
10101 0, first, path,
10102 find_what,
10103 curbuf->b_ffname,
10104 find_what == FINDFILE_DIR
10105 ? (char_u *)"" : curbuf->b_p_sua);
10106 first = FALSE;
10108 if (fresult != NULL && rettv->v_type == VAR_LIST)
10109 list_append_string(rettv->vval.v_list, fresult, -1);
10111 } while ((rettv->v_type == VAR_LIST || --count > 0) && fresult != NULL);
10114 if (rettv->v_type == VAR_STRING)
10115 rettv->vval.v_string = fresult;
10116 #endif
10119 static void filter_map __ARGS((typval_T *argvars, typval_T *rettv, int map));
10120 static int filter_map_one __ARGS((typval_T *tv, char_u *expr, int map, int *remp));
10123 * Implementation of map() and filter().
10125 static void
10126 filter_map(argvars, rettv, map)
10127 typval_T *argvars;
10128 typval_T *rettv;
10129 int map;
10131 char_u buf[NUMBUFLEN];
10132 char_u *expr;
10133 listitem_T *li, *nli;
10134 list_T *l = NULL;
10135 dictitem_T *di;
10136 hashtab_T *ht;
10137 hashitem_T *hi;
10138 dict_T *d = NULL;
10139 typval_T save_val;
10140 typval_T save_key;
10141 int rem;
10142 int todo;
10143 char_u *ermsg = map ? (char_u *)"map()" : (char_u *)"filter()";
10144 int save_did_emsg;
10145 int index = 0;
10147 if (argvars[0].v_type == VAR_LIST)
10149 if ((l = argvars[0].vval.v_list) == NULL
10150 || (map && tv_check_lock(l->lv_lock, ermsg)))
10151 return;
10153 else if (argvars[0].v_type == VAR_DICT)
10155 if ((d = argvars[0].vval.v_dict) == NULL
10156 || (map && tv_check_lock(d->dv_lock, ermsg)))
10157 return;
10159 else
10161 EMSG2(_(e_listdictarg), ermsg);
10162 return;
10165 expr = get_tv_string_buf_chk(&argvars[1], buf);
10166 /* On type errors, the preceding call has already displayed an error
10167 * message. Avoid a misleading error message for an empty string that
10168 * was not passed as argument. */
10169 if (expr != NULL)
10171 prepare_vimvar(VV_VAL, &save_val);
10172 expr = skipwhite(expr);
10174 /* We reset "did_emsg" to be able to detect whether an error
10175 * occurred during evaluation of the expression. */
10176 save_did_emsg = did_emsg;
10177 did_emsg = FALSE;
10179 prepare_vimvar(VV_KEY, &save_key);
10180 if (argvars[0].v_type == VAR_DICT)
10182 vimvars[VV_KEY].vv_type = VAR_STRING;
10184 ht = &d->dv_hashtab;
10185 hash_lock(ht);
10186 todo = (int)ht->ht_used;
10187 for (hi = ht->ht_array; todo > 0; ++hi)
10189 if (!HASHITEM_EMPTY(hi))
10191 --todo;
10192 di = HI2DI(hi);
10193 if (tv_check_lock(di->di_tv.v_lock, ermsg))
10194 break;
10195 vimvars[VV_KEY].vv_str = vim_strsave(di->di_key);
10196 if (filter_map_one(&di->di_tv, expr, map, &rem) == FAIL
10197 || did_emsg)
10198 break;
10199 if (!map && rem)
10200 dictitem_remove(d, di);
10201 clear_tv(&vimvars[VV_KEY].vv_tv);
10204 hash_unlock(ht);
10206 else
10208 vimvars[VV_KEY].vv_type = VAR_NUMBER;
10210 for (li = l->lv_first; li != NULL; li = nli)
10212 if (tv_check_lock(li->li_tv.v_lock, ermsg))
10213 break;
10214 nli = li->li_next;
10215 vimvars[VV_KEY].vv_nr = index;
10216 if (filter_map_one(&li->li_tv, expr, map, &rem) == FAIL
10217 || did_emsg)
10218 break;
10219 if (!map && rem)
10220 listitem_remove(l, li);
10221 ++index;
10225 restore_vimvar(VV_KEY, &save_key);
10226 restore_vimvar(VV_VAL, &save_val);
10228 did_emsg |= save_did_emsg;
10231 copy_tv(&argvars[0], rettv);
10234 static int
10235 filter_map_one(tv, expr, map, remp)
10236 typval_T *tv;
10237 char_u *expr;
10238 int map;
10239 int *remp;
10241 typval_T rettv;
10242 char_u *s;
10243 int retval = FAIL;
10245 copy_tv(tv, &vimvars[VV_VAL].vv_tv);
10246 s = expr;
10247 if (eval1(&s, &rettv, TRUE) == FAIL)
10248 goto theend;
10249 if (*s != NUL) /* check for trailing chars after expr */
10251 EMSG2(_(e_invexpr2), s);
10252 goto theend;
10254 if (map)
10256 /* map(): replace the list item value */
10257 clear_tv(tv);
10258 rettv.v_lock = 0;
10259 *tv = rettv;
10261 else
10263 int error = FALSE;
10265 /* filter(): when expr is zero remove the item */
10266 *remp = (get_tv_number_chk(&rettv, &error) == 0);
10267 clear_tv(&rettv);
10268 /* On type error, nothing has been removed; return FAIL to stop the
10269 * loop. The error message was given by get_tv_number_chk(). */
10270 if (error)
10271 goto theend;
10273 retval = OK;
10274 theend:
10275 clear_tv(&vimvars[VV_VAL].vv_tv);
10276 return retval;
10280 * "filter()" function
10282 static void
10283 f_filter(argvars, rettv)
10284 typval_T *argvars;
10285 typval_T *rettv;
10287 filter_map(argvars, rettv, FALSE);
10291 * "finddir({fname}[, {path}[, {count}]])" function
10293 static void
10294 f_finddir(argvars, rettv)
10295 typval_T *argvars;
10296 typval_T *rettv;
10298 findfilendir(argvars, rettv, FINDFILE_DIR);
10302 * "findfile({fname}[, {path}[, {count}]])" function
10304 static void
10305 f_findfile(argvars, rettv)
10306 typval_T *argvars;
10307 typval_T *rettv;
10309 findfilendir(argvars, rettv, FINDFILE_FILE);
10312 #ifdef FEAT_FLOAT
10314 * "float2nr({float})" function
10316 static void
10317 f_float2nr(argvars, rettv)
10318 typval_T *argvars;
10319 typval_T *rettv;
10321 float_T f;
10323 if (get_float_arg(argvars, &f) == OK)
10325 if (f < -0x7fffffff)
10326 rettv->vval.v_number = -0x7fffffff;
10327 else if (f > 0x7fffffff)
10328 rettv->vval.v_number = 0x7fffffff;
10329 else
10330 rettv->vval.v_number = (varnumber_T)f;
10335 * "floor({float})" function
10337 static void
10338 f_floor(argvars, rettv)
10339 typval_T *argvars;
10340 typval_T *rettv;
10342 float_T f;
10344 rettv->v_type = VAR_FLOAT;
10345 if (get_float_arg(argvars, &f) == OK)
10346 rettv->vval.v_float = floor(f);
10347 else
10348 rettv->vval.v_float = 0.0;
10350 #endif
10353 * "fnameescape({string})" function
10355 static void
10356 f_fnameescape(argvars, rettv)
10357 typval_T *argvars;
10358 typval_T *rettv;
10360 rettv->vval.v_string = vim_strsave_fnameescape(
10361 get_tv_string(&argvars[0]), FALSE);
10362 rettv->v_type = VAR_STRING;
10366 * "fnamemodify({fname}, {mods})" function
10368 static void
10369 f_fnamemodify(argvars, rettv)
10370 typval_T *argvars;
10371 typval_T *rettv;
10373 char_u *fname;
10374 char_u *mods;
10375 int usedlen = 0;
10376 int len;
10377 char_u *fbuf = NULL;
10378 char_u buf[NUMBUFLEN];
10380 fname = get_tv_string_chk(&argvars[0]);
10381 mods = get_tv_string_buf_chk(&argvars[1], buf);
10382 if (fname == NULL || mods == NULL)
10383 fname = NULL;
10384 else
10386 len = (int)STRLEN(fname);
10387 (void)modify_fname(mods, &usedlen, &fname, &fbuf, &len);
10390 rettv->v_type = VAR_STRING;
10391 if (fname == NULL)
10392 rettv->vval.v_string = NULL;
10393 else
10394 rettv->vval.v_string = vim_strnsave(fname, len);
10395 vim_free(fbuf);
10398 static void foldclosed_both __ARGS((typval_T *argvars, typval_T *rettv, int end));
10401 * "foldclosed()" function
10403 static void
10404 foldclosed_both(argvars, rettv, end)
10405 typval_T *argvars;
10406 typval_T *rettv;
10407 int end;
10409 #ifdef FEAT_FOLDING
10410 linenr_T lnum;
10411 linenr_T first, last;
10413 lnum = get_tv_lnum(argvars);
10414 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10416 if (hasFoldingWin(curwin, lnum, &first, &last, FALSE, NULL))
10418 if (end)
10419 rettv->vval.v_number = (varnumber_T)last;
10420 else
10421 rettv->vval.v_number = (varnumber_T)first;
10422 return;
10425 #endif
10426 rettv->vval.v_number = -1;
10430 * "foldclosed()" function
10432 static void
10433 f_foldclosed(argvars, rettv)
10434 typval_T *argvars;
10435 typval_T *rettv;
10437 foldclosed_both(argvars, rettv, FALSE);
10441 * "foldclosedend()" function
10443 static void
10444 f_foldclosedend(argvars, rettv)
10445 typval_T *argvars;
10446 typval_T *rettv;
10448 foldclosed_both(argvars, rettv, TRUE);
10452 * "foldlevel()" function
10454 static void
10455 f_foldlevel(argvars, rettv)
10456 typval_T *argvars;
10457 typval_T *rettv;
10459 #ifdef FEAT_FOLDING
10460 linenr_T lnum;
10462 lnum = get_tv_lnum(argvars);
10463 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
10464 rettv->vval.v_number = foldLevel(lnum);
10465 #endif
10469 * "foldtext()" function
10471 static void
10472 f_foldtext(argvars, rettv)
10473 typval_T *argvars UNUSED;
10474 typval_T *rettv;
10476 #ifdef FEAT_FOLDING
10477 linenr_T lnum;
10478 char_u *s;
10479 char_u *r;
10480 int len;
10481 char *txt;
10482 #endif
10484 rettv->v_type = VAR_STRING;
10485 rettv->vval.v_string = NULL;
10486 #ifdef FEAT_FOLDING
10487 if ((linenr_T)vimvars[VV_FOLDSTART].vv_nr > 0
10488 && (linenr_T)vimvars[VV_FOLDEND].vv_nr
10489 <= curbuf->b_ml.ml_line_count
10490 && vimvars[VV_FOLDDASHES].vv_str != NULL)
10492 /* Find first non-empty line in the fold. */
10493 lnum = (linenr_T)vimvars[VV_FOLDSTART].vv_nr;
10494 while (lnum < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10496 if (!linewhite(lnum))
10497 break;
10498 ++lnum;
10501 /* Find interesting text in this line. */
10502 s = skipwhite(ml_get(lnum));
10503 /* skip C comment-start */
10504 if (s[0] == '/' && (s[1] == '*' || s[1] == '/'))
10506 s = skipwhite(s + 2);
10507 if (*skipwhite(s) == NUL
10508 && lnum + 1 < (linenr_T)vimvars[VV_FOLDEND].vv_nr)
10510 s = skipwhite(ml_get(lnum + 1));
10511 if (*s == '*')
10512 s = skipwhite(s + 1);
10515 txt = _("+-%s%3ld lines: ");
10516 r = alloc((unsigned)(STRLEN(txt)
10517 + STRLEN(vimvars[VV_FOLDDASHES].vv_str) /* for %s */
10518 + 20 /* for %3ld */
10519 + STRLEN(s))); /* concatenated */
10520 if (r != NULL)
10522 sprintf((char *)r, txt, vimvars[VV_FOLDDASHES].vv_str,
10523 (long)((linenr_T)vimvars[VV_FOLDEND].vv_nr
10524 - (linenr_T)vimvars[VV_FOLDSTART].vv_nr + 1));
10525 len = (int)STRLEN(r);
10526 STRCAT(r, s);
10527 /* remove 'foldmarker' and 'commentstring' */
10528 foldtext_cleanup(r + len);
10529 rettv->vval.v_string = r;
10532 #endif
10536 * "foldtextresult(lnum)" function
10538 static void
10539 f_foldtextresult(argvars, rettv)
10540 typval_T *argvars UNUSED;
10541 typval_T *rettv;
10543 #ifdef FEAT_FOLDING
10544 linenr_T lnum;
10545 char_u *text;
10546 char_u buf[51];
10547 foldinfo_T foldinfo;
10548 int fold_count;
10549 #endif
10551 rettv->v_type = VAR_STRING;
10552 rettv->vval.v_string = NULL;
10553 #ifdef FEAT_FOLDING
10554 lnum = get_tv_lnum(argvars);
10555 /* treat illegal types and illegal string values for {lnum} the same */
10556 if (lnum < 0)
10557 lnum = 0;
10558 fold_count = foldedCount(curwin, lnum, &foldinfo);
10559 if (fold_count > 0)
10561 text = get_foldtext(curwin, lnum, lnum + fold_count - 1,
10562 &foldinfo, buf);
10563 if (text == buf)
10564 text = vim_strsave(text);
10565 rettv->vval.v_string = text;
10567 #endif
10571 * "foreground()" function
10573 static void
10574 f_foreground(argvars, rettv)
10575 typval_T *argvars UNUSED;
10576 typval_T *rettv UNUSED;
10578 #ifdef FEAT_GUI
10579 if (gui.in_use)
10580 gui_mch_set_foreground();
10581 #else
10582 # ifdef WIN32
10583 win32_set_foreground();
10584 # endif
10585 #endif
10589 * "function()" function
10591 static void
10592 f_function(argvars, rettv)
10593 typval_T *argvars;
10594 typval_T *rettv;
10596 char_u *s;
10598 s = get_tv_string(&argvars[0]);
10599 if (s == NULL || *s == NUL || VIM_ISDIGIT(*s))
10600 EMSG2(_(e_invarg2), s);
10601 /* Don't check an autoload name for existence here. */
10602 else if (vim_strchr(s, AUTOLOAD_CHAR) == NULL && !function_exists(s))
10603 EMSG2(_("E700: Unknown function: %s"), s);
10604 else
10606 rettv->vval.v_string = vim_strsave(s);
10607 rettv->v_type = VAR_FUNC;
10612 * "garbagecollect()" function
10614 static void
10615 f_garbagecollect(argvars, rettv)
10616 typval_T *argvars;
10617 typval_T *rettv UNUSED;
10619 /* This is postponed until we are back at the toplevel, because we may be
10620 * using Lists and Dicts internally. E.g.: ":echo [garbagecollect()]". */
10621 want_garbage_collect = TRUE;
10623 if (argvars[0].v_type != VAR_UNKNOWN && get_tv_number(&argvars[0]) == 1)
10624 garbage_collect_at_exit = TRUE;
10628 * "get()" function
10630 static void
10631 f_get(argvars, rettv)
10632 typval_T *argvars;
10633 typval_T *rettv;
10635 listitem_T *li;
10636 list_T *l;
10637 dictitem_T *di;
10638 dict_T *d;
10639 typval_T *tv = NULL;
10641 if (argvars[0].v_type == VAR_LIST)
10643 if ((l = argvars[0].vval.v_list) != NULL)
10645 int error = FALSE;
10647 li = list_find(l, get_tv_number_chk(&argvars[1], &error));
10648 if (!error && li != NULL)
10649 tv = &li->li_tv;
10652 else if (argvars[0].v_type == VAR_DICT)
10654 if ((d = argvars[0].vval.v_dict) != NULL)
10656 di = dict_find(d, get_tv_string(&argvars[1]), -1);
10657 if (di != NULL)
10658 tv = &di->di_tv;
10661 else
10662 EMSG2(_(e_listdictarg), "get()");
10664 if (tv == NULL)
10666 if (argvars[2].v_type != VAR_UNKNOWN)
10667 copy_tv(&argvars[2], rettv);
10669 else
10670 copy_tv(tv, rettv);
10673 static void get_buffer_lines __ARGS((buf_T *buf, linenr_T start, linenr_T end, int retlist, typval_T *rettv));
10676 * Get line or list of lines from buffer "buf" into "rettv".
10677 * Return a range (from start to end) of lines in rettv from the specified
10678 * buffer.
10679 * If 'retlist' is TRUE, then the lines are returned as a Vim List.
10681 static void
10682 get_buffer_lines(buf, start, end, retlist, rettv)
10683 buf_T *buf;
10684 linenr_T start;
10685 linenr_T end;
10686 int retlist;
10687 typval_T *rettv;
10689 char_u *p;
10691 if (retlist && rettv_list_alloc(rettv) == FAIL)
10692 return;
10694 if (buf == NULL || buf->b_ml.ml_mfp == NULL || start < 0)
10695 return;
10697 if (!retlist)
10699 if (start >= 1 && start <= buf->b_ml.ml_line_count)
10700 p = ml_get_buf(buf, start, FALSE);
10701 else
10702 p = (char_u *)"";
10704 rettv->v_type = VAR_STRING;
10705 rettv->vval.v_string = vim_strsave(p);
10707 else
10709 if (end < start)
10710 return;
10712 if (start < 1)
10713 start = 1;
10714 if (end > buf->b_ml.ml_line_count)
10715 end = buf->b_ml.ml_line_count;
10716 while (start <= end)
10717 if (list_append_string(rettv->vval.v_list,
10718 ml_get_buf(buf, start++, FALSE), -1) == FAIL)
10719 break;
10724 * "getbufline()" function
10726 static void
10727 f_getbufline(argvars, rettv)
10728 typval_T *argvars;
10729 typval_T *rettv;
10731 linenr_T lnum;
10732 linenr_T end;
10733 buf_T *buf;
10735 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10736 ++emsg_off;
10737 buf = get_buf_tv(&argvars[0]);
10738 --emsg_off;
10740 lnum = get_tv_lnum_buf(&argvars[1], buf);
10741 if (argvars[2].v_type == VAR_UNKNOWN)
10742 end = lnum;
10743 else
10744 end = get_tv_lnum_buf(&argvars[2], buf);
10746 get_buffer_lines(buf, lnum, end, TRUE, rettv);
10750 * "getbufvar()" function
10752 static void
10753 f_getbufvar(argvars, rettv)
10754 typval_T *argvars;
10755 typval_T *rettv;
10757 buf_T *buf;
10758 buf_T *save_curbuf;
10759 char_u *varname;
10760 dictitem_T *v;
10762 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
10763 varname = get_tv_string_chk(&argvars[1]);
10764 ++emsg_off;
10765 buf = get_buf_tv(&argvars[0]);
10767 rettv->v_type = VAR_STRING;
10768 rettv->vval.v_string = NULL;
10770 if (buf != NULL && varname != NULL)
10772 /* set curbuf to be our buf, temporarily */
10773 save_curbuf = curbuf;
10774 curbuf = buf;
10776 if (*varname == '&') /* buffer-local-option */
10777 get_option_tv(&varname, rettv, TRUE);
10778 else
10780 if (*varname == NUL)
10781 /* let getbufvar({nr}, "") return the "b:" dictionary. The
10782 * scope prefix before the NUL byte is required by
10783 * find_var_in_ht(). */
10784 varname = (char_u *)"b:" + 2;
10785 /* look up the variable */
10786 v = find_var_in_ht(&curbuf->b_vars.dv_hashtab, varname, FALSE);
10787 if (v != NULL)
10788 copy_tv(&v->di_tv, rettv);
10791 /* restore previous notion of curbuf */
10792 curbuf = save_curbuf;
10795 --emsg_off;
10799 * "getchar()" function
10801 static void
10802 f_getchar(argvars, rettv)
10803 typval_T *argvars;
10804 typval_T *rettv;
10806 varnumber_T n;
10807 int error = FALSE;
10809 /* Position the cursor. Needed after a message that ends in a space. */
10810 windgoto(msg_row, msg_col);
10812 ++no_mapping;
10813 ++allow_keys;
10814 for (;;)
10816 if (argvars[0].v_type == VAR_UNKNOWN)
10817 /* getchar(): blocking wait. */
10818 n = safe_vgetc();
10819 else if (get_tv_number_chk(&argvars[0], &error) == 1)
10820 /* getchar(1): only check if char avail */
10821 n = vpeekc();
10822 else if (error || vpeekc() == NUL)
10823 /* illegal argument or getchar(0) and no char avail: return zero */
10824 n = 0;
10825 else
10826 /* getchar(0) and char avail: return char */
10827 n = safe_vgetc();
10828 if (n == K_IGNORE)
10829 continue;
10830 break;
10832 --no_mapping;
10833 --allow_keys;
10835 vimvars[VV_MOUSE_WIN].vv_nr = 0;
10836 vimvars[VV_MOUSE_LNUM].vv_nr = 0;
10837 vimvars[VV_MOUSE_COL].vv_nr = 0;
10839 rettv->vval.v_number = n;
10840 if (IS_SPECIAL(n) || mod_mask != 0)
10842 char_u temp[10]; /* modifier: 3, mbyte-char: 6, NUL: 1 */
10843 int i = 0;
10845 /* Turn a special key into three bytes, plus modifier. */
10846 if (mod_mask != 0)
10848 temp[i++] = K_SPECIAL;
10849 temp[i++] = KS_MODIFIER;
10850 temp[i++] = mod_mask;
10852 if (IS_SPECIAL(n))
10854 temp[i++] = K_SPECIAL;
10855 temp[i++] = K_SECOND(n);
10856 temp[i++] = K_THIRD(n);
10858 #ifdef FEAT_MBYTE
10859 else if (has_mbyte)
10860 i += (*mb_char2bytes)(n, temp + i);
10861 #endif
10862 else
10863 temp[i++] = n;
10864 temp[i++] = NUL;
10865 rettv->v_type = VAR_STRING;
10866 rettv->vval.v_string = vim_strsave(temp);
10868 #ifdef FEAT_MOUSE
10869 if (n == K_LEFTMOUSE
10870 || n == K_LEFTMOUSE_NM
10871 || n == K_LEFTDRAG
10872 || n == K_LEFTRELEASE
10873 || n == K_LEFTRELEASE_NM
10874 || n == K_MIDDLEMOUSE
10875 || n == K_MIDDLEDRAG
10876 || n == K_MIDDLERELEASE
10877 || n == K_RIGHTMOUSE
10878 || n == K_RIGHTDRAG
10879 || n == K_RIGHTRELEASE
10880 || n == K_X1MOUSE
10881 || n == K_X1DRAG
10882 || n == K_X1RELEASE
10883 || n == K_X2MOUSE
10884 || n == K_X2DRAG
10885 || n == K_X2RELEASE
10886 || n == K_MOUSEDOWN
10887 || n == K_MOUSEUP)
10889 int row = mouse_row;
10890 int col = mouse_col;
10891 win_T *win;
10892 linenr_T lnum;
10893 # ifdef FEAT_WINDOWS
10894 win_T *wp;
10895 # endif
10896 int winnr = 1;
10898 if (row >= 0 && col >= 0)
10900 /* Find the window at the mouse coordinates and compute the
10901 * text position. */
10902 win = mouse_find_win(&row, &col);
10903 (void)mouse_comp_pos(win, &row, &col, &lnum);
10904 # ifdef FEAT_WINDOWS
10905 for (wp = firstwin; wp != win; wp = wp->w_next)
10906 ++winnr;
10907 # endif
10908 vimvars[VV_MOUSE_WIN].vv_nr = winnr;
10909 vimvars[VV_MOUSE_LNUM].vv_nr = lnum;
10910 vimvars[VV_MOUSE_COL].vv_nr = col + 1;
10913 #endif
10918 * "getcharmod()" function
10920 static void
10921 f_getcharmod(argvars, rettv)
10922 typval_T *argvars UNUSED;
10923 typval_T *rettv;
10925 rettv->vval.v_number = mod_mask;
10929 * "getcmdline()" function
10931 static void
10932 f_getcmdline(argvars, rettv)
10933 typval_T *argvars UNUSED;
10934 typval_T *rettv;
10936 rettv->v_type = VAR_STRING;
10937 rettv->vval.v_string = get_cmdline_str();
10941 * "getcmdpos()" function
10943 static void
10944 f_getcmdpos(argvars, rettv)
10945 typval_T *argvars UNUSED;
10946 typval_T *rettv;
10948 rettv->vval.v_number = get_cmdline_pos() + 1;
10952 * "getcmdtype()" function
10954 static void
10955 f_getcmdtype(argvars, rettv)
10956 typval_T *argvars UNUSED;
10957 typval_T *rettv;
10959 rettv->v_type = VAR_STRING;
10960 rettv->vval.v_string = alloc(2);
10961 if (rettv->vval.v_string != NULL)
10963 rettv->vval.v_string[0] = get_cmdline_type();
10964 rettv->vval.v_string[1] = NUL;
10969 * "getcwd()" function
10971 static void
10972 f_getcwd(argvars, rettv)
10973 typval_T *argvars UNUSED;
10974 typval_T *rettv;
10976 char_u cwd[MAXPATHL];
10978 rettv->v_type = VAR_STRING;
10979 if (mch_dirname(cwd, MAXPATHL) == FAIL)
10980 rettv->vval.v_string = NULL;
10981 else
10983 rettv->vval.v_string = vim_strsave(cwd);
10984 #ifdef BACKSLASH_IN_FILENAME
10985 if (rettv->vval.v_string != NULL)
10986 slash_adjust(rettv->vval.v_string);
10987 #endif
10992 * "getfontname()" function
10994 static void
10995 f_getfontname(argvars, rettv)
10996 typval_T *argvars UNUSED;
10997 typval_T *rettv;
10999 rettv->v_type = VAR_STRING;
11000 rettv->vval.v_string = NULL;
11001 #ifdef FEAT_GUI
11002 if (gui.in_use)
11004 GuiFont font;
11005 char_u *name = NULL;
11007 if (argvars[0].v_type == VAR_UNKNOWN)
11009 /* Get the "Normal" font. Either the name saved by
11010 * hl_set_font_name() or from the font ID. */
11011 font = gui.norm_font;
11012 name = hl_get_font_name();
11014 else
11016 name = get_tv_string(&argvars[0]);
11017 if (STRCMP(name, "*") == 0) /* don't use font dialog */
11018 return;
11019 font = gui_mch_get_font(name, FALSE);
11020 if (font == NOFONT)
11021 return; /* Invalid font name, return empty string. */
11023 rettv->vval.v_string = gui_mch_get_fontname(font, name);
11024 if (argvars[0].v_type != VAR_UNKNOWN)
11025 gui_mch_free_font(font);
11027 #endif
11031 * "getfperm({fname})" function
11033 static void
11034 f_getfperm(argvars, rettv)
11035 typval_T *argvars;
11036 typval_T *rettv;
11038 char_u *fname;
11039 struct stat st;
11040 char_u *perm = NULL;
11041 char_u flags[] = "rwx";
11042 int i;
11044 fname = get_tv_string(&argvars[0]);
11046 rettv->v_type = VAR_STRING;
11047 if (mch_stat((char *)fname, &st) >= 0)
11049 perm = vim_strsave((char_u *)"---------");
11050 if (perm != NULL)
11052 for (i = 0; i < 9; i++)
11054 if (st.st_mode & (1 << (8 - i)))
11055 perm[i] = flags[i % 3];
11059 rettv->vval.v_string = perm;
11063 * "getfsize({fname})" function
11065 static void
11066 f_getfsize(argvars, rettv)
11067 typval_T *argvars;
11068 typval_T *rettv;
11070 char_u *fname;
11071 struct stat st;
11073 fname = get_tv_string(&argvars[0]);
11075 rettv->v_type = VAR_NUMBER;
11077 if (mch_stat((char *)fname, &st) >= 0)
11079 if (mch_isdir(fname))
11080 rettv->vval.v_number = 0;
11081 else
11083 rettv->vval.v_number = (varnumber_T)st.st_size;
11085 /* non-perfect check for overflow */
11086 if ((off_t)rettv->vval.v_number != (off_t)st.st_size)
11087 rettv->vval.v_number = -2;
11090 else
11091 rettv->vval.v_number = -1;
11095 * "getftime({fname})" function
11097 static void
11098 f_getftime(argvars, rettv)
11099 typval_T *argvars;
11100 typval_T *rettv;
11102 char_u *fname;
11103 struct stat st;
11105 fname = get_tv_string(&argvars[0]);
11107 if (mch_stat((char *)fname, &st) >= 0)
11108 rettv->vval.v_number = (varnumber_T)st.st_mtime;
11109 else
11110 rettv->vval.v_number = -1;
11114 * "getftype({fname})" function
11116 static void
11117 f_getftype(argvars, rettv)
11118 typval_T *argvars;
11119 typval_T *rettv;
11121 char_u *fname;
11122 struct stat st;
11123 char_u *type = NULL;
11124 char *t;
11126 fname = get_tv_string(&argvars[0]);
11128 rettv->v_type = VAR_STRING;
11129 if (mch_lstat((char *)fname, &st) >= 0)
11131 #ifdef S_ISREG
11132 if (S_ISREG(st.st_mode))
11133 t = "file";
11134 else if (S_ISDIR(st.st_mode))
11135 t = "dir";
11136 # ifdef S_ISLNK
11137 else if (S_ISLNK(st.st_mode))
11138 t = "link";
11139 # endif
11140 # ifdef S_ISBLK
11141 else if (S_ISBLK(st.st_mode))
11142 t = "bdev";
11143 # endif
11144 # ifdef S_ISCHR
11145 else if (S_ISCHR(st.st_mode))
11146 t = "cdev";
11147 # endif
11148 # ifdef S_ISFIFO
11149 else if (S_ISFIFO(st.st_mode))
11150 t = "fifo";
11151 # endif
11152 # ifdef S_ISSOCK
11153 else if (S_ISSOCK(st.st_mode))
11154 t = "fifo";
11155 # endif
11156 else
11157 t = "other";
11158 #else
11159 # ifdef S_IFMT
11160 switch (st.st_mode & S_IFMT)
11162 case S_IFREG: t = "file"; break;
11163 case S_IFDIR: t = "dir"; break;
11164 # ifdef S_IFLNK
11165 case S_IFLNK: t = "link"; break;
11166 # endif
11167 # ifdef S_IFBLK
11168 case S_IFBLK: t = "bdev"; break;
11169 # endif
11170 # ifdef S_IFCHR
11171 case S_IFCHR: t = "cdev"; break;
11172 # endif
11173 # ifdef S_IFIFO
11174 case S_IFIFO: t = "fifo"; break;
11175 # endif
11176 # ifdef S_IFSOCK
11177 case S_IFSOCK: t = "socket"; break;
11178 # endif
11179 default: t = "other";
11181 # else
11182 if (mch_isdir(fname))
11183 t = "dir";
11184 else
11185 t = "file";
11186 # endif
11187 #endif
11188 type = vim_strsave((char_u *)t);
11190 rettv->vval.v_string = type;
11194 * "getline(lnum, [end])" function
11196 static void
11197 f_getline(argvars, rettv)
11198 typval_T *argvars;
11199 typval_T *rettv;
11201 linenr_T lnum;
11202 linenr_T end;
11203 int retlist;
11205 lnum = get_tv_lnum(argvars);
11206 if (argvars[1].v_type == VAR_UNKNOWN)
11208 end = 0;
11209 retlist = FALSE;
11211 else
11213 end = get_tv_lnum(&argvars[1]);
11214 retlist = TRUE;
11217 get_buffer_lines(curbuf, lnum, end, retlist, rettv);
11221 * "getmatches()" function
11223 static void
11224 f_getmatches(argvars, rettv)
11225 typval_T *argvars UNUSED;
11226 typval_T *rettv;
11228 #ifdef FEAT_SEARCH_EXTRA
11229 dict_T *dict;
11230 matchitem_T *cur = curwin->w_match_head;
11232 if (rettv_list_alloc(rettv) == OK)
11234 while (cur != NULL)
11236 dict = dict_alloc();
11237 if (dict == NULL)
11238 return;
11239 dict_add_nr_str(dict, "group", 0L, syn_id2name(cur->hlg_id));
11240 dict_add_nr_str(dict, "pattern", 0L, cur->pattern);
11241 dict_add_nr_str(dict, "priority", (long)cur->priority, NULL);
11242 dict_add_nr_str(dict, "id", (long)cur->id, NULL);
11243 list_append_dict(rettv->vval.v_list, dict);
11244 cur = cur->next;
11247 #endif
11251 * "getpid()" function
11253 static void
11254 f_getpid(argvars, rettv)
11255 typval_T *argvars UNUSED;
11256 typval_T *rettv;
11258 rettv->vval.v_number = mch_get_pid();
11262 * "getpos(string)" function
11264 static void
11265 f_getpos(argvars, rettv)
11266 typval_T *argvars;
11267 typval_T *rettv;
11269 pos_T *fp;
11270 list_T *l;
11271 int fnum = -1;
11273 if (rettv_list_alloc(rettv) == OK)
11275 l = rettv->vval.v_list;
11276 fp = var2fpos(&argvars[0], TRUE, &fnum);
11277 if (fnum != -1)
11278 list_append_number(l, (varnumber_T)fnum);
11279 else
11280 list_append_number(l, (varnumber_T)0);
11281 list_append_number(l, (fp != NULL) ? (varnumber_T)fp->lnum
11282 : (varnumber_T)0);
11283 list_append_number(l, (fp != NULL)
11284 ? (varnumber_T)(fp->col == MAXCOL ? MAXCOL : fp->col + 1)
11285 : (varnumber_T)0);
11286 list_append_number(l,
11287 #ifdef FEAT_VIRTUALEDIT
11288 (fp != NULL) ? (varnumber_T)fp->coladd :
11289 #endif
11290 (varnumber_T)0);
11292 else
11293 rettv->vval.v_number = FALSE;
11297 * "getqflist()" and "getloclist()" functions
11299 static void
11300 f_getqflist(argvars, rettv)
11301 typval_T *argvars UNUSED;
11302 typval_T *rettv UNUSED;
11304 #ifdef FEAT_QUICKFIX
11305 win_T *wp;
11306 #endif
11308 #ifdef FEAT_QUICKFIX
11309 if (rettv_list_alloc(rettv) == OK)
11311 wp = NULL;
11312 if (argvars[0].v_type != VAR_UNKNOWN) /* getloclist() */
11314 wp = find_win_by_nr(&argvars[0], NULL);
11315 if (wp == NULL)
11316 return;
11319 (void)get_errorlist(wp, rettv->vval.v_list);
11321 #endif
11325 * "getreg()" function
11327 static void
11328 f_getreg(argvars, rettv)
11329 typval_T *argvars;
11330 typval_T *rettv;
11332 char_u *strregname;
11333 int regname;
11334 int arg2 = FALSE;
11335 int error = FALSE;
11337 if (argvars[0].v_type != VAR_UNKNOWN)
11339 strregname = get_tv_string_chk(&argvars[0]);
11340 error = strregname == NULL;
11341 if (argvars[1].v_type != VAR_UNKNOWN)
11342 arg2 = get_tv_number_chk(&argvars[1], &error);
11344 else
11345 strregname = vimvars[VV_REG].vv_str;
11346 regname = (strregname == NULL ? '"' : *strregname);
11347 if (regname == 0)
11348 regname = '"';
11350 rettv->v_type = VAR_STRING;
11351 rettv->vval.v_string = error ? NULL :
11352 get_reg_contents(regname, TRUE, arg2);
11356 * "getregtype()" function
11358 static void
11359 f_getregtype(argvars, rettv)
11360 typval_T *argvars;
11361 typval_T *rettv;
11363 char_u *strregname;
11364 int regname;
11365 char_u buf[NUMBUFLEN + 2];
11366 long reglen = 0;
11368 if (argvars[0].v_type != VAR_UNKNOWN)
11370 strregname = get_tv_string_chk(&argvars[0]);
11371 if (strregname == NULL) /* type error; errmsg already given */
11373 rettv->v_type = VAR_STRING;
11374 rettv->vval.v_string = NULL;
11375 return;
11378 else
11379 /* Default to v:register */
11380 strregname = vimvars[VV_REG].vv_str;
11382 regname = (strregname == NULL ? '"' : *strregname);
11383 if (regname == 0)
11384 regname = '"';
11386 buf[0] = NUL;
11387 buf[1] = NUL;
11388 switch (get_reg_type(regname, &reglen))
11390 case MLINE: buf[0] = 'V'; break;
11391 case MCHAR: buf[0] = 'v'; break;
11392 #ifdef FEAT_VISUAL
11393 case MBLOCK:
11394 buf[0] = Ctrl_V;
11395 sprintf((char *)buf + 1, "%ld", reglen + 1);
11396 break;
11397 #endif
11399 rettv->v_type = VAR_STRING;
11400 rettv->vval.v_string = vim_strsave(buf);
11404 * "gettabwinvar()" function
11406 static void
11407 f_gettabwinvar(argvars, rettv)
11408 typval_T *argvars;
11409 typval_T *rettv;
11411 getwinvar(argvars, rettv, 1);
11415 * "getwinposx()" function
11417 static void
11418 f_getwinposx(argvars, rettv)
11419 typval_T *argvars UNUSED;
11420 typval_T *rettv;
11422 rettv->vval.v_number = -1;
11423 #ifdef FEAT_GUI
11424 if (gui.in_use)
11426 int x, y;
11428 if (gui_mch_get_winpos(&x, &y) == OK)
11429 rettv->vval.v_number = x;
11431 #endif
11435 * "getwinposy()" function
11437 static void
11438 f_getwinposy(argvars, rettv)
11439 typval_T *argvars UNUSED;
11440 typval_T *rettv;
11442 rettv->vval.v_number = -1;
11443 #ifdef FEAT_GUI
11444 if (gui.in_use)
11446 int x, y;
11448 if (gui_mch_get_winpos(&x, &y) == OK)
11449 rettv->vval.v_number = y;
11451 #endif
11455 * Find window specified by "vp" in tabpage "tp".
11457 static win_T *
11458 find_win_by_nr(vp, tp)
11459 typval_T *vp;
11460 tabpage_T *tp; /* NULL for current tab page */
11462 #ifdef FEAT_WINDOWS
11463 win_T *wp;
11464 #endif
11465 int nr;
11467 nr = get_tv_number_chk(vp, NULL);
11469 #ifdef FEAT_WINDOWS
11470 if (nr < 0)
11471 return NULL;
11472 if (nr == 0)
11473 return curwin;
11475 for (wp = (tp == NULL || tp == curtab) ? firstwin : tp->tp_firstwin;
11476 wp != NULL; wp = wp->w_next)
11477 if (--nr <= 0)
11478 break;
11479 return wp;
11480 #else
11481 if (nr == 0 || nr == 1)
11482 return curwin;
11483 return NULL;
11484 #endif
11488 * "getwinvar()" function
11490 static void
11491 f_getwinvar(argvars, rettv)
11492 typval_T *argvars;
11493 typval_T *rettv;
11495 getwinvar(argvars, rettv, 0);
11499 * getwinvar() and gettabwinvar()
11501 static void
11502 getwinvar(argvars, rettv, off)
11503 typval_T *argvars;
11504 typval_T *rettv;
11505 int off; /* 1 for gettabwinvar() */
11507 win_T *win, *oldcurwin;
11508 char_u *varname;
11509 dictitem_T *v;
11510 tabpage_T *tp;
11512 #ifdef FEAT_WINDOWS
11513 if (off == 1)
11514 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
11515 else
11516 tp = curtab;
11517 #endif
11518 win = find_win_by_nr(&argvars[off], tp);
11519 varname = get_tv_string_chk(&argvars[off + 1]);
11520 ++emsg_off;
11522 rettv->v_type = VAR_STRING;
11523 rettv->vval.v_string = NULL;
11525 if (win != NULL && varname != NULL)
11527 /* Set curwin to be our win, temporarily. Also set curbuf, so
11528 * that we can get buffer-local options. */
11529 oldcurwin = curwin;
11530 curwin = win;
11531 curbuf = win->w_buffer;
11533 if (*varname == '&') /* window-local-option */
11534 get_option_tv(&varname, rettv, 1);
11535 else
11537 if (*varname == NUL)
11538 /* let getwinvar({nr}, "") return the "w:" dictionary. The
11539 * scope prefix before the NUL byte is required by
11540 * find_var_in_ht(). */
11541 varname = (char_u *)"w:" + 2;
11542 /* look up the variable */
11543 v = find_var_in_ht(&win->w_vars.dv_hashtab, varname, FALSE);
11544 if (v != NULL)
11545 copy_tv(&v->di_tv, rettv);
11548 /* restore previous notion of curwin */
11549 curwin = oldcurwin;
11550 curbuf = curwin->w_buffer;
11553 --emsg_off;
11557 * "glob()" function
11559 static void
11560 f_glob(argvars, rettv)
11561 typval_T *argvars;
11562 typval_T *rettv;
11564 int flags = WILD_SILENT|WILD_USE_NL;
11565 expand_T xpc;
11566 int error = FALSE;
11568 /* When the optional second argument is non-zero, don't remove matches
11569 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11570 if (argvars[1].v_type != VAR_UNKNOWN
11571 && get_tv_number_chk(&argvars[1], &error))
11572 flags |= WILD_KEEP_ALL;
11573 rettv->v_type = VAR_STRING;
11574 if (!error)
11576 ExpandInit(&xpc);
11577 xpc.xp_context = EXPAND_FILES;
11578 rettv->vval.v_string = ExpandOne(&xpc, get_tv_string(&argvars[0]),
11579 NULL, flags, WILD_ALL);
11581 else
11582 rettv->vval.v_string = NULL;
11586 * "globpath()" function
11588 static void
11589 f_globpath(argvars, rettv)
11590 typval_T *argvars;
11591 typval_T *rettv;
11593 int flags = 0;
11594 char_u buf1[NUMBUFLEN];
11595 char_u *file = get_tv_string_buf_chk(&argvars[1], buf1);
11596 int error = FALSE;
11598 /* When the optional second argument is non-zero, don't remove matches
11599 * for 'wildignore' and don't put matches for 'suffixes' at the end. */
11600 if (argvars[2].v_type != VAR_UNKNOWN
11601 && get_tv_number_chk(&argvars[2], &error))
11602 flags |= WILD_KEEP_ALL;
11603 rettv->v_type = VAR_STRING;
11604 if (file == NULL || error)
11605 rettv->vval.v_string = NULL;
11606 else
11607 rettv->vval.v_string = globpath(get_tv_string(&argvars[0]), file,
11608 flags);
11612 * "has()" function
11614 static void
11615 f_has(argvars, rettv)
11616 typval_T *argvars;
11617 typval_T *rettv;
11619 int i;
11620 char_u *name;
11621 int n = FALSE;
11622 static char *(has_list[]) =
11624 #ifdef AMIGA
11625 "amiga",
11626 # ifdef FEAT_ARP
11627 "arp",
11628 # endif
11629 #endif
11630 #ifdef __BEOS__
11631 "beos",
11632 #endif
11633 #ifdef MSDOS
11634 # ifdef DJGPP
11635 "dos32",
11636 # else
11637 "dos16",
11638 # endif
11639 #endif
11640 #ifdef MACOS
11641 "mac",
11642 #endif
11643 #if defined(MACOS_X_UNIX)
11644 "macunix",
11645 #endif
11646 #ifdef OS2
11647 "os2",
11648 #endif
11649 #ifdef __QNX__
11650 "qnx",
11651 #endif
11652 #ifdef RISCOS
11653 "riscos",
11654 #endif
11655 #ifdef UNIX
11656 "unix",
11657 #endif
11658 #ifdef VMS
11659 "vms",
11660 #endif
11661 #ifdef WIN16
11662 "win16",
11663 #endif
11664 #ifdef WIN32
11665 "win32",
11666 #endif
11667 #if defined(UNIX) && (defined(__CYGWIN32__) || defined(__CYGWIN__))
11668 "win32unix",
11669 #endif
11670 #if defined(WIN64) || defined(_WIN64)
11671 "win64",
11672 #endif
11673 #ifdef EBCDIC
11674 "ebcdic",
11675 #endif
11676 #ifndef CASE_INSENSITIVE_FILENAME
11677 "fname_case",
11678 #endif
11679 #ifdef FEAT_ARABIC
11680 "arabic",
11681 #endif
11682 #ifdef FEAT_AUTOCMD
11683 "autocmd",
11684 #endif
11685 #ifdef FEAT_BEVAL
11686 "balloon_eval",
11687 # ifndef FEAT_GUI_W32 /* other GUIs always have multiline balloons */
11688 "balloon_multiline",
11689 # endif
11690 #endif
11691 #if defined(SOME_BUILTIN_TCAPS) || defined(ALL_BUILTIN_TCAPS)
11692 "builtin_terms",
11693 # ifdef ALL_BUILTIN_TCAPS
11694 "all_builtin_terms",
11695 # endif
11696 #endif
11697 #ifdef FEAT_BYTEOFF
11698 "byte_offset",
11699 #endif
11700 #ifdef FEAT_CINDENT
11701 "cindent",
11702 #endif
11703 #ifdef FEAT_CLIENTSERVER
11704 "clientserver",
11705 #endif
11706 #ifdef FEAT_CLIPBOARD
11707 "clipboard",
11708 #endif
11709 #ifdef FEAT_CMDL_COMPL
11710 "cmdline_compl",
11711 #endif
11712 #ifdef FEAT_CMDHIST
11713 "cmdline_hist",
11714 #endif
11715 #ifdef FEAT_COMMENTS
11716 "comments",
11717 #endif
11718 #ifdef FEAT_CRYPT
11719 "cryptv",
11720 #endif
11721 #ifdef FEAT_CSCOPE
11722 "cscope",
11723 #endif
11724 #ifdef CURSOR_SHAPE
11725 "cursorshape",
11726 #endif
11727 #ifdef DEBUG
11728 "debug",
11729 #endif
11730 #ifdef FEAT_CON_DIALOG
11731 "dialog_con",
11732 #endif
11733 #ifdef FEAT_GUI_DIALOG
11734 "dialog_gui",
11735 #endif
11736 #ifdef FEAT_DIFF
11737 "diff",
11738 #endif
11739 #ifdef FEAT_DIGRAPHS
11740 "digraphs",
11741 #endif
11742 #ifdef FEAT_DND
11743 "dnd",
11744 #endif
11745 #ifdef FEAT_EMACS_TAGS
11746 "emacs_tags",
11747 #endif
11748 "eval", /* always present, of course! */
11749 #ifdef FEAT_EX_EXTRA
11750 "ex_extra",
11751 #endif
11752 #ifdef FEAT_SEARCH_EXTRA
11753 "extra_search",
11754 #endif
11755 #ifdef FEAT_FKMAP
11756 "farsi",
11757 #endif
11758 #ifdef FEAT_SEARCHPATH
11759 "file_in_path",
11760 #endif
11761 #if defined(UNIX) && !defined(USE_SYSTEM)
11762 "filterpipe",
11763 #endif
11764 #ifdef FEAT_FIND_ID
11765 "find_in_path",
11766 #endif
11767 #ifdef FEAT_FLOAT
11768 "float",
11769 #endif
11770 #ifdef FEAT_FOLDING
11771 "folding",
11772 #endif
11773 #ifdef FEAT_FOOTER
11774 "footer",
11775 #endif
11776 #if !defined(USE_SYSTEM) && defined(UNIX)
11777 "fork",
11778 #endif
11779 #ifdef FEAT_GETTEXT
11780 "gettext",
11781 #endif
11782 #ifdef FEAT_GUI
11783 "gui",
11784 #endif
11785 #ifdef FEAT_GUI_ATHENA
11786 # ifdef FEAT_GUI_NEXTAW
11787 "gui_neXtaw",
11788 # else
11789 "gui_athena",
11790 # endif
11791 #endif
11792 #ifdef FEAT_GUI_GTK
11793 "gui_gtk",
11794 # ifdef HAVE_GTK2
11795 "gui_gtk2",
11796 # endif
11797 #endif
11798 #ifdef FEAT_GUI_GNOME
11799 "gui_gnome",
11800 #endif
11801 #ifdef FEAT_GUI_MAC
11802 "gui_mac",
11803 #endif
11804 #ifdef FEAT_GUI_MOTIF
11805 "gui_motif",
11806 #endif
11807 #ifdef FEAT_GUI_PHOTON
11808 "gui_photon",
11809 #endif
11810 #ifdef FEAT_GUI_W16
11811 "gui_win16",
11812 #endif
11813 #ifdef FEAT_GUI_W32
11814 "gui_win32",
11815 #endif
11816 #ifdef FEAT_HANGULIN
11817 "hangul_input",
11818 #endif
11819 #if defined(HAVE_ICONV_H) && defined(USE_ICONV)
11820 "iconv",
11821 #endif
11822 #ifdef FEAT_INS_EXPAND
11823 "insert_expand",
11824 #endif
11825 #ifdef FEAT_JUMPLIST
11826 "jumplist",
11827 #endif
11828 #ifdef FEAT_KEYMAP
11829 "keymap",
11830 #endif
11831 #ifdef FEAT_LANGMAP
11832 "langmap",
11833 #endif
11834 #ifdef FEAT_LIBCALL
11835 "libcall",
11836 #endif
11837 #ifdef FEAT_LINEBREAK
11838 "linebreak",
11839 #endif
11840 #ifdef FEAT_LISP
11841 "lispindent",
11842 #endif
11843 #ifdef FEAT_LISTCMDS
11844 "listcmds",
11845 #endif
11846 #ifdef FEAT_LOCALMAP
11847 "localmap",
11848 #endif
11849 #ifdef FEAT_MENU
11850 "menu",
11851 #endif
11852 #ifdef FEAT_SESSION
11853 "mksession",
11854 #endif
11855 #ifdef FEAT_MODIFY_FNAME
11856 "modify_fname",
11857 #endif
11858 #ifdef FEAT_MOUSE
11859 "mouse",
11860 #endif
11861 #ifdef FEAT_MOUSESHAPE
11862 "mouseshape",
11863 #endif
11864 #if defined(UNIX) || defined(VMS)
11865 # ifdef FEAT_MOUSE_DEC
11866 "mouse_dec",
11867 # endif
11868 # ifdef FEAT_MOUSE_GPM
11869 "mouse_gpm",
11870 # endif
11871 # ifdef FEAT_MOUSE_JSB
11872 "mouse_jsbterm",
11873 # endif
11874 # ifdef FEAT_MOUSE_NET
11875 "mouse_netterm",
11876 # endif
11877 # ifdef FEAT_MOUSE_PTERM
11878 "mouse_pterm",
11879 # endif
11880 # ifdef FEAT_SYSMOUSE
11881 "mouse_sysmouse",
11882 # endif
11883 # ifdef FEAT_MOUSE_XTERM
11884 "mouse_xterm",
11885 # endif
11886 #endif
11887 #ifdef FEAT_MBYTE
11888 "multi_byte",
11889 #endif
11890 #ifdef FEAT_MBYTE_IME
11891 "multi_byte_ime",
11892 #endif
11893 #ifdef FEAT_MULTI_LANG
11894 "multi_lang",
11895 #endif
11896 #ifdef FEAT_MZSCHEME
11897 #ifndef DYNAMIC_MZSCHEME
11898 "mzscheme",
11899 #endif
11900 #endif
11901 #ifdef FEAT_OLE
11902 "ole",
11903 #endif
11904 #ifdef FEAT_OSFILETYPE
11905 "osfiletype",
11906 #endif
11907 #ifdef FEAT_PATH_EXTRA
11908 "path_extra",
11909 #endif
11910 #ifdef FEAT_PERL
11911 #ifndef DYNAMIC_PERL
11912 "perl",
11913 #endif
11914 #endif
11915 #ifdef FEAT_PYTHON
11916 #ifndef DYNAMIC_PYTHON
11917 "python",
11918 #endif
11919 #endif
11920 #ifdef FEAT_POSTSCRIPT
11921 "postscript",
11922 #endif
11923 #ifdef FEAT_PRINTER
11924 "printer",
11925 #endif
11926 #ifdef FEAT_PROFILE
11927 "profile",
11928 #endif
11929 #ifdef FEAT_RELTIME
11930 "reltime",
11931 #endif
11932 #ifdef FEAT_QUICKFIX
11933 "quickfix",
11934 #endif
11935 #ifdef FEAT_RIGHTLEFT
11936 "rightleft",
11937 #endif
11938 #if defined(FEAT_RUBY) && !defined(DYNAMIC_RUBY)
11939 "ruby",
11940 #endif
11941 #ifdef FEAT_SCROLLBIND
11942 "scrollbind",
11943 #endif
11944 #ifdef FEAT_CMDL_INFO
11945 "showcmd",
11946 "cmdline_info",
11947 #endif
11948 #ifdef FEAT_SIGNS
11949 "signs",
11950 #endif
11951 #ifdef FEAT_SMARTINDENT
11952 "smartindent",
11953 #endif
11954 #ifdef FEAT_SNIFF
11955 "sniff",
11956 #endif
11957 #ifdef STARTUPTIME
11958 "startuptime",
11959 #endif
11960 #ifdef FEAT_STL_OPT
11961 "statusline",
11962 #endif
11963 #ifdef FEAT_SUN_WORKSHOP
11964 "sun_workshop",
11965 #endif
11966 #ifdef FEAT_NETBEANS_INTG
11967 "netbeans_intg",
11968 #endif
11969 #ifdef FEAT_SPELL
11970 "spell",
11971 #endif
11972 #ifdef FEAT_SYN_HL
11973 "syntax",
11974 #endif
11975 #if defined(USE_SYSTEM) || !defined(UNIX)
11976 "system",
11977 #endif
11978 #ifdef FEAT_TAG_BINS
11979 "tag_binary",
11980 #endif
11981 #ifdef FEAT_TAG_OLDSTATIC
11982 "tag_old_static",
11983 #endif
11984 #ifdef FEAT_TAG_ANYWHITE
11985 "tag_any_white",
11986 #endif
11987 #ifdef FEAT_TCL
11988 # ifndef DYNAMIC_TCL
11989 "tcl",
11990 # endif
11991 #endif
11992 #ifdef TERMINFO
11993 "terminfo",
11994 #endif
11995 #ifdef FEAT_TERMRESPONSE
11996 "termresponse",
11997 #endif
11998 #ifdef FEAT_TEXTOBJ
11999 "textobjects",
12000 #endif
12001 #ifdef HAVE_TGETENT
12002 "tgetent",
12003 #endif
12004 #ifdef FEAT_TITLE
12005 "title",
12006 #endif
12007 #ifdef FEAT_TOOLBAR
12008 "toolbar",
12009 #endif
12010 #ifdef FEAT_USR_CMDS
12011 "user-commands", /* was accidentally included in 5.4 */
12012 "user_commands",
12013 #endif
12014 #ifdef FEAT_VIMINFO
12015 "viminfo",
12016 #endif
12017 #ifdef FEAT_VERTSPLIT
12018 "vertsplit",
12019 #endif
12020 #ifdef FEAT_VIRTUALEDIT
12021 "virtualedit",
12022 #endif
12023 #ifdef FEAT_VISUAL
12024 "visual",
12025 #endif
12026 #ifdef FEAT_VISUALEXTRA
12027 "visualextra",
12028 #endif
12029 #ifdef FEAT_VREPLACE
12030 "vreplace",
12031 #endif
12032 #ifdef FEAT_WILDIGN
12033 "wildignore",
12034 #endif
12035 #ifdef FEAT_WILDMENU
12036 "wildmenu",
12037 #endif
12038 #ifdef FEAT_WINDOWS
12039 "windows",
12040 #endif
12041 #ifdef FEAT_WAK
12042 "winaltkeys",
12043 #endif
12044 #ifdef FEAT_WRITEBACKUP
12045 "writebackup",
12046 #endif
12047 #ifdef FEAT_XIM
12048 "xim",
12049 #endif
12050 #ifdef FEAT_XFONTSET
12051 "xfontset",
12052 #endif
12053 #ifdef USE_XSMP
12054 "xsmp",
12055 #endif
12056 #ifdef USE_XSMP_INTERACT
12057 "xsmp_interact",
12058 #endif
12059 #ifdef FEAT_XCLIPBOARD
12060 "xterm_clipboard",
12061 #endif
12062 #ifdef FEAT_XTERM_SAVE
12063 "xterm_save",
12064 #endif
12065 #if defined(UNIX) && defined(FEAT_X11)
12066 "X11",
12067 #endif
12068 NULL
12071 name = get_tv_string(&argvars[0]);
12072 for (i = 0; has_list[i] != NULL; ++i)
12073 if (STRICMP(name, has_list[i]) == 0)
12075 n = TRUE;
12076 break;
12079 if (n == FALSE)
12081 if (STRNICMP(name, "patch", 5) == 0)
12082 n = has_patch(atoi((char *)name + 5));
12083 else if (STRICMP(name, "vim_starting") == 0)
12084 n = (starting != 0);
12085 #ifdef FEAT_MBYTE
12086 else if (STRICMP(name, "multi_byte_encoding") == 0)
12087 n = has_mbyte;
12088 #endif
12089 #if defined(FEAT_BEVAL) && defined(FEAT_GUI_W32)
12090 else if (STRICMP(name, "balloon_multiline") == 0)
12091 n = multiline_balloon_available();
12092 #endif
12093 #ifdef DYNAMIC_TCL
12094 else if (STRICMP(name, "tcl") == 0)
12095 n = tcl_enabled(FALSE);
12096 #endif
12097 #if defined(USE_ICONV) && defined(DYNAMIC_ICONV)
12098 else if (STRICMP(name, "iconv") == 0)
12099 n = iconv_enabled(FALSE);
12100 #endif
12101 #ifdef DYNAMIC_MZSCHEME
12102 else if (STRICMP(name, "mzscheme") == 0)
12103 n = mzscheme_enabled(FALSE);
12104 #endif
12105 #ifdef DYNAMIC_RUBY
12106 else if (STRICMP(name, "ruby") == 0)
12107 n = ruby_enabled(FALSE);
12108 #endif
12109 #ifdef DYNAMIC_PYTHON
12110 else if (STRICMP(name, "python") == 0)
12111 n = python_enabled(FALSE);
12112 #endif
12113 #ifdef DYNAMIC_PERL
12114 else if (STRICMP(name, "perl") == 0)
12115 n = perl_enabled(FALSE);
12116 #endif
12117 #ifdef FEAT_GUI
12118 else if (STRICMP(name, "gui_running") == 0)
12119 n = (gui.in_use || gui.starting);
12120 # ifdef FEAT_GUI_W32
12121 else if (STRICMP(name, "gui_win32s") == 0)
12122 n = gui_is_win32s();
12123 # endif
12124 # ifdef FEAT_BROWSE
12125 else if (STRICMP(name, "browse") == 0)
12126 n = gui.in_use; /* gui_mch_browse() works when GUI is running */
12127 # endif
12128 #endif
12129 #ifdef FEAT_SYN_HL
12130 else if (STRICMP(name, "syntax_items") == 0)
12131 n = syntax_present(curbuf);
12132 #endif
12133 #if defined(WIN3264)
12134 else if (STRICMP(name, "win95") == 0)
12135 n = mch_windows95();
12136 #endif
12137 #ifdef FEAT_NETBEANS_INTG
12138 else if (STRICMP(name, "netbeans_enabled") == 0)
12139 n = usingNetbeans;
12140 #endif
12143 rettv->vval.v_number = n;
12147 * "has_key()" function
12149 static void
12150 f_has_key(argvars, rettv)
12151 typval_T *argvars;
12152 typval_T *rettv;
12154 if (argvars[0].v_type != VAR_DICT)
12156 EMSG(_(e_dictreq));
12157 return;
12159 if (argvars[0].vval.v_dict == NULL)
12160 return;
12162 rettv->vval.v_number = dict_find(argvars[0].vval.v_dict,
12163 get_tv_string(&argvars[1]), -1) != NULL;
12167 * "haslocaldir()" function
12169 static void
12170 f_haslocaldir(argvars, rettv)
12171 typval_T *argvars UNUSED;
12172 typval_T *rettv;
12174 rettv->vval.v_number = (curwin->w_localdir != NULL);
12178 * "hasmapto()" function
12180 static void
12181 f_hasmapto(argvars, rettv)
12182 typval_T *argvars;
12183 typval_T *rettv;
12185 char_u *name;
12186 char_u *mode;
12187 char_u buf[NUMBUFLEN];
12188 int abbr = FALSE;
12190 name = get_tv_string(&argvars[0]);
12191 if (argvars[1].v_type == VAR_UNKNOWN)
12192 mode = (char_u *)"nvo";
12193 else
12195 mode = get_tv_string_buf(&argvars[1], buf);
12196 if (argvars[2].v_type != VAR_UNKNOWN)
12197 abbr = get_tv_number(&argvars[2]);
12200 if (map_to_exists(name, mode, abbr))
12201 rettv->vval.v_number = TRUE;
12202 else
12203 rettv->vval.v_number = FALSE;
12207 * "histadd()" function
12209 static void
12210 f_histadd(argvars, rettv)
12211 typval_T *argvars UNUSED;
12212 typval_T *rettv;
12214 #ifdef FEAT_CMDHIST
12215 int histype;
12216 char_u *str;
12217 char_u buf[NUMBUFLEN];
12218 #endif
12220 rettv->vval.v_number = FALSE;
12221 if (check_restricted() || check_secure())
12222 return;
12223 #ifdef FEAT_CMDHIST
12224 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12225 histype = str != NULL ? get_histtype(str) : -1;
12226 if (histype >= 0)
12228 str = get_tv_string_buf(&argvars[1], buf);
12229 if (*str != NUL)
12231 init_history();
12232 add_to_history(histype, str, FALSE, NUL);
12233 rettv->vval.v_number = TRUE;
12234 return;
12237 #endif
12241 * "histdel()" function
12243 static void
12244 f_histdel(argvars, rettv)
12245 typval_T *argvars UNUSED;
12246 typval_T *rettv UNUSED;
12248 #ifdef FEAT_CMDHIST
12249 int n;
12250 char_u buf[NUMBUFLEN];
12251 char_u *str;
12253 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12254 if (str == NULL)
12255 n = 0;
12256 else if (argvars[1].v_type == VAR_UNKNOWN)
12257 /* only one argument: clear entire history */
12258 n = clr_history(get_histtype(str));
12259 else if (argvars[1].v_type == VAR_NUMBER)
12260 /* index given: remove that entry */
12261 n = del_history_idx(get_histtype(str),
12262 (int)get_tv_number(&argvars[1]));
12263 else
12264 /* string given: remove all matching entries */
12265 n = del_history_entry(get_histtype(str),
12266 get_tv_string_buf(&argvars[1], buf));
12267 rettv->vval.v_number = n;
12268 #endif
12272 * "histget()" function
12274 static void
12275 f_histget(argvars, rettv)
12276 typval_T *argvars UNUSED;
12277 typval_T *rettv;
12279 #ifdef FEAT_CMDHIST
12280 int type;
12281 int idx;
12282 char_u *str;
12284 str = get_tv_string_chk(&argvars[0]); /* NULL on type error */
12285 if (str == NULL)
12286 rettv->vval.v_string = NULL;
12287 else
12289 type = get_histtype(str);
12290 if (argvars[1].v_type == VAR_UNKNOWN)
12291 idx = get_history_idx(type);
12292 else
12293 idx = (int)get_tv_number_chk(&argvars[1], NULL);
12294 /* -1 on type error */
12295 rettv->vval.v_string = vim_strsave(get_history_entry(type, idx));
12297 #else
12298 rettv->vval.v_string = NULL;
12299 #endif
12300 rettv->v_type = VAR_STRING;
12304 * "histnr()" function
12306 static void
12307 f_histnr(argvars, rettv)
12308 typval_T *argvars UNUSED;
12309 typval_T *rettv;
12311 int i;
12313 #ifdef FEAT_CMDHIST
12314 char_u *history = get_tv_string_chk(&argvars[0]);
12316 i = history == NULL ? HIST_CMD - 1 : get_histtype(history);
12317 if (i >= HIST_CMD && i < HIST_COUNT)
12318 i = get_history_idx(i);
12319 else
12320 #endif
12321 i = -1;
12322 rettv->vval.v_number = i;
12326 * "highlightID(name)" function
12328 static void
12329 f_hlID(argvars, rettv)
12330 typval_T *argvars;
12331 typval_T *rettv;
12333 rettv->vval.v_number = syn_name2id(get_tv_string(&argvars[0]));
12337 * "highlight_exists()" function
12339 static void
12340 f_hlexists(argvars, rettv)
12341 typval_T *argvars;
12342 typval_T *rettv;
12344 rettv->vval.v_number = highlight_exists(get_tv_string(&argvars[0]));
12348 * "hostname()" function
12350 static void
12351 f_hostname(argvars, rettv)
12352 typval_T *argvars UNUSED;
12353 typval_T *rettv;
12355 char_u hostname[256];
12357 mch_get_host_name(hostname, 256);
12358 rettv->v_type = VAR_STRING;
12359 rettv->vval.v_string = vim_strsave(hostname);
12363 * iconv() function
12365 static void
12366 f_iconv(argvars, rettv)
12367 typval_T *argvars UNUSED;
12368 typval_T *rettv;
12370 #ifdef FEAT_MBYTE
12371 char_u buf1[NUMBUFLEN];
12372 char_u buf2[NUMBUFLEN];
12373 char_u *from, *to, *str;
12374 vimconv_T vimconv;
12375 #endif
12377 rettv->v_type = VAR_STRING;
12378 rettv->vval.v_string = NULL;
12380 #ifdef FEAT_MBYTE
12381 str = get_tv_string(&argvars[0]);
12382 from = enc_canonize(enc_skip(get_tv_string_buf(&argvars[1], buf1)));
12383 to = enc_canonize(enc_skip(get_tv_string_buf(&argvars[2], buf2)));
12384 vimconv.vc_type = CONV_NONE;
12385 convert_setup(&vimconv, from, to);
12387 /* If the encodings are equal, no conversion needed. */
12388 if (vimconv.vc_type == CONV_NONE)
12389 rettv->vval.v_string = vim_strsave(str);
12390 else
12391 rettv->vval.v_string = string_convert(&vimconv, str, NULL);
12393 convert_setup(&vimconv, NULL, NULL);
12394 vim_free(from);
12395 vim_free(to);
12396 #endif
12400 * "indent()" function
12402 static void
12403 f_indent(argvars, rettv)
12404 typval_T *argvars;
12405 typval_T *rettv;
12407 linenr_T lnum;
12409 lnum = get_tv_lnum(argvars);
12410 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
12411 rettv->vval.v_number = get_indent_lnum(lnum);
12412 else
12413 rettv->vval.v_number = -1;
12417 * "index()" function
12419 static void
12420 f_index(argvars, rettv)
12421 typval_T *argvars;
12422 typval_T *rettv;
12424 list_T *l;
12425 listitem_T *item;
12426 long idx = 0;
12427 int ic = FALSE;
12429 rettv->vval.v_number = -1;
12430 if (argvars[0].v_type != VAR_LIST)
12432 EMSG(_(e_listreq));
12433 return;
12435 l = argvars[0].vval.v_list;
12436 if (l != NULL)
12438 item = l->lv_first;
12439 if (argvars[2].v_type != VAR_UNKNOWN)
12441 int error = FALSE;
12443 /* Start at specified item. Use the cached index that list_find()
12444 * sets, so that a negative number also works. */
12445 item = list_find(l, get_tv_number_chk(&argvars[2], &error));
12446 idx = l->lv_idx;
12447 if (argvars[3].v_type != VAR_UNKNOWN)
12448 ic = get_tv_number_chk(&argvars[3], &error);
12449 if (error)
12450 item = NULL;
12453 for ( ; item != NULL; item = item->li_next, ++idx)
12454 if (tv_equal(&item->li_tv, &argvars[1], ic))
12456 rettv->vval.v_number = idx;
12457 break;
12462 static int inputsecret_flag = 0;
12464 static void get_user_input __ARGS((typval_T *argvars, typval_T *rettv, int inputdialog));
12467 * This function is used by f_input() and f_inputdialog() functions. The third
12468 * argument to f_input() specifies the type of completion to use at the
12469 * prompt. The third argument to f_inputdialog() specifies the value to return
12470 * when the user cancels the prompt.
12472 static void
12473 get_user_input(argvars, rettv, inputdialog)
12474 typval_T *argvars;
12475 typval_T *rettv;
12476 int inputdialog;
12478 char_u *prompt = get_tv_string_chk(&argvars[0]);
12479 char_u *p = NULL;
12480 int c;
12481 char_u buf[NUMBUFLEN];
12482 int cmd_silent_save = cmd_silent;
12483 char_u *defstr = (char_u *)"";
12484 int xp_type = EXPAND_NOTHING;
12485 char_u *xp_arg = NULL;
12487 rettv->v_type = VAR_STRING;
12488 rettv->vval.v_string = NULL;
12490 #ifdef NO_CONSOLE_INPUT
12491 /* While starting up, there is no place to enter text. */
12492 if (no_console_input())
12493 return;
12494 #endif
12496 cmd_silent = FALSE; /* Want to see the prompt. */
12497 if (prompt != NULL)
12499 /* Only the part of the message after the last NL is considered as
12500 * prompt for the command line */
12501 p = vim_strrchr(prompt, '\n');
12502 if (p == NULL)
12503 p = prompt;
12504 else
12506 ++p;
12507 c = *p;
12508 *p = NUL;
12509 msg_start();
12510 msg_clr_eos();
12511 msg_puts_attr(prompt, echo_attr);
12512 msg_didout = FALSE;
12513 msg_starthere();
12514 *p = c;
12516 cmdline_row = msg_row;
12518 if (argvars[1].v_type != VAR_UNKNOWN)
12520 defstr = get_tv_string_buf_chk(&argvars[1], buf);
12521 if (defstr != NULL)
12522 stuffReadbuffSpec(defstr);
12524 if (!inputdialog && argvars[2].v_type != VAR_UNKNOWN)
12526 char_u *xp_name;
12527 int xp_namelen;
12528 long argt;
12530 rettv->vval.v_string = NULL;
12532 xp_name = get_tv_string_buf_chk(&argvars[2], buf);
12533 if (xp_name == NULL)
12534 return;
12536 xp_namelen = (int)STRLEN(xp_name);
12538 if (parse_compl_arg(xp_name, xp_namelen, &xp_type, &argt,
12539 &xp_arg) == FAIL)
12540 return;
12544 if (defstr != NULL)
12545 rettv->vval.v_string =
12546 getcmdline_prompt(inputsecret_flag ? NUL : '@', p, echo_attr,
12547 xp_type, xp_arg);
12549 vim_free(xp_arg);
12551 /* since the user typed this, no need to wait for return */
12552 need_wait_return = FALSE;
12553 msg_didout = FALSE;
12555 cmd_silent = cmd_silent_save;
12559 * "input()" function
12560 * Also handles inputsecret() when inputsecret is set.
12562 static void
12563 f_input(argvars, rettv)
12564 typval_T *argvars;
12565 typval_T *rettv;
12567 get_user_input(argvars, rettv, FALSE);
12571 * "inputdialog()" function
12573 static void
12574 f_inputdialog(argvars, rettv)
12575 typval_T *argvars;
12576 typval_T *rettv;
12578 #if defined(FEAT_GUI_TEXTDIALOG)
12579 /* Use a GUI dialog if the GUI is running and 'c' is not in 'guioptions' */
12580 if (gui.in_use && vim_strchr(p_go, GO_CONDIALOG) == NULL)
12582 char_u *message;
12583 char_u buf[NUMBUFLEN];
12584 char_u *defstr = (char_u *)"";
12586 message = get_tv_string_chk(&argvars[0]);
12587 if (argvars[1].v_type != VAR_UNKNOWN
12588 && (defstr = get_tv_string_buf_chk(&argvars[1], buf)) != NULL)
12589 vim_strncpy(IObuff, defstr, IOSIZE - 1);
12590 else
12591 IObuff[0] = NUL;
12592 if (message != NULL && defstr != NULL
12593 && do_dialog(VIM_QUESTION, NULL, message,
12594 (char_u *)_("&OK\n&Cancel"), 1, IObuff) == 1)
12595 rettv->vval.v_string = vim_strsave(IObuff);
12596 else
12598 if (message != NULL && defstr != NULL
12599 && argvars[1].v_type != VAR_UNKNOWN
12600 && argvars[2].v_type != VAR_UNKNOWN)
12601 rettv->vval.v_string = vim_strsave(
12602 get_tv_string_buf(&argvars[2], buf));
12603 else
12604 rettv->vval.v_string = NULL;
12606 rettv->v_type = VAR_STRING;
12608 else
12609 #endif
12610 get_user_input(argvars, rettv, TRUE);
12614 * "inputlist()" function
12616 static void
12617 f_inputlist(argvars, rettv)
12618 typval_T *argvars;
12619 typval_T *rettv;
12621 listitem_T *li;
12622 int selected;
12623 int mouse_used;
12625 #ifdef NO_CONSOLE_INPUT
12626 /* While starting up, there is no place to enter text. */
12627 if (no_console_input())
12628 return;
12629 #endif
12630 if (argvars[0].v_type != VAR_LIST || argvars[0].vval.v_list == NULL)
12632 EMSG2(_(e_listarg), "inputlist()");
12633 return;
12636 msg_start();
12637 msg_row = Rows - 1; /* for when 'cmdheight' > 1 */
12638 lines_left = Rows; /* avoid more prompt */
12639 msg_scroll = TRUE;
12640 msg_clr_eos();
12642 for (li = argvars[0].vval.v_list->lv_first; li != NULL; li = li->li_next)
12644 msg_puts(get_tv_string(&li->li_tv));
12645 msg_putchar('\n');
12648 /* Ask for choice. */
12649 selected = prompt_for_number(&mouse_used);
12650 if (mouse_used)
12651 selected -= lines_left;
12653 rettv->vval.v_number = selected;
12657 static garray_T ga_userinput = {0, 0, sizeof(tasave_T), 4, NULL};
12660 * "inputrestore()" function
12662 static void
12663 f_inputrestore(argvars, rettv)
12664 typval_T *argvars UNUSED;
12665 typval_T *rettv;
12667 if (ga_userinput.ga_len > 0)
12669 --ga_userinput.ga_len;
12670 restore_typeahead((tasave_T *)(ga_userinput.ga_data)
12671 + ga_userinput.ga_len);
12672 /* default return is zero == OK */
12674 else if (p_verbose > 1)
12676 verb_msg((char_u *)_("called inputrestore() more often than inputsave()"));
12677 rettv->vval.v_number = 1; /* Failed */
12682 * "inputsave()" function
12684 static void
12685 f_inputsave(argvars, rettv)
12686 typval_T *argvars UNUSED;
12687 typval_T *rettv;
12689 /* Add an entry to the stack of typeahead storage. */
12690 if (ga_grow(&ga_userinput, 1) == OK)
12692 save_typeahead((tasave_T *)(ga_userinput.ga_data)
12693 + ga_userinput.ga_len);
12694 ++ga_userinput.ga_len;
12695 /* default return is zero == OK */
12697 else
12698 rettv->vval.v_number = 1; /* Failed */
12702 * "inputsecret()" function
12704 static void
12705 f_inputsecret(argvars, rettv)
12706 typval_T *argvars;
12707 typval_T *rettv;
12709 ++cmdline_star;
12710 ++inputsecret_flag;
12711 f_input(argvars, rettv);
12712 --cmdline_star;
12713 --inputsecret_flag;
12717 * "insert()" function
12719 static void
12720 f_insert(argvars, rettv)
12721 typval_T *argvars;
12722 typval_T *rettv;
12724 long before = 0;
12725 listitem_T *item;
12726 list_T *l;
12727 int error = FALSE;
12729 if (argvars[0].v_type != VAR_LIST)
12730 EMSG2(_(e_listarg), "insert()");
12731 else if ((l = argvars[0].vval.v_list) != NULL
12732 && !tv_check_lock(l->lv_lock, (char_u *)"insert()"))
12734 if (argvars[2].v_type != VAR_UNKNOWN)
12735 before = get_tv_number_chk(&argvars[2], &error);
12736 if (error)
12737 return; /* type error; errmsg already given */
12739 if (before == l->lv_len)
12740 item = NULL;
12741 else
12743 item = list_find(l, before);
12744 if (item == NULL)
12746 EMSGN(_(e_listidx), before);
12747 l = NULL;
12750 if (l != NULL)
12752 list_insert_tv(l, &argvars[1], item);
12753 copy_tv(&argvars[0], rettv);
12759 * "isdirectory()" function
12761 static void
12762 f_isdirectory(argvars, rettv)
12763 typval_T *argvars;
12764 typval_T *rettv;
12766 rettv->vval.v_number = mch_isdir(get_tv_string(&argvars[0]));
12770 * "islocked()" function
12772 static void
12773 f_islocked(argvars, rettv)
12774 typval_T *argvars;
12775 typval_T *rettv;
12777 lval_T lv;
12778 char_u *end;
12779 dictitem_T *di;
12781 rettv->vval.v_number = -1;
12782 end = get_lval(get_tv_string(&argvars[0]), NULL, &lv, FALSE, FALSE, FALSE,
12783 FNE_CHECK_START);
12784 if (end != NULL && lv.ll_name != NULL)
12786 if (*end != NUL)
12787 EMSG(_(e_trailing));
12788 else
12790 if (lv.ll_tv == NULL)
12792 if (check_changedtick(lv.ll_name))
12793 rettv->vval.v_number = 1; /* always locked */
12794 else
12796 di = find_var(lv.ll_name, NULL);
12797 if (di != NULL)
12799 /* Consider a variable locked when:
12800 * 1. the variable itself is locked
12801 * 2. the value of the variable is locked.
12802 * 3. the List or Dict value is locked.
12804 rettv->vval.v_number = ((di->di_flags & DI_FLAGS_LOCK)
12805 || tv_islocked(&di->di_tv));
12809 else if (lv.ll_range)
12810 EMSG(_("E786: Range not allowed"));
12811 else if (lv.ll_newkey != NULL)
12812 EMSG2(_(e_dictkey), lv.ll_newkey);
12813 else if (lv.ll_list != NULL)
12814 /* List item. */
12815 rettv->vval.v_number = tv_islocked(&lv.ll_li->li_tv);
12816 else
12817 /* Dictionary item. */
12818 rettv->vval.v_number = tv_islocked(&lv.ll_di->di_tv);
12822 clear_lval(&lv);
12825 static void dict_list __ARGS((typval_T *argvars, typval_T *rettv, int what));
12828 * Turn a dict into a list:
12829 * "what" == 0: list of keys
12830 * "what" == 1: list of values
12831 * "what" == 2: list of items
12833 static void
12834 dict_list(argvars, rettv, what)
12835 typval_T *argvars;
12836 typval_T *rettv;
12837 int what;
12839 list_T *l2;
12840 dictitem_T *di;
12841 hashitem_T *hi;
12842 listitem_T *li;
12843 listitem_T *li2;
12844 dict_T *d;
12845 int todo;
12847 if (argvars[0].v_type != VAR_DICT)
12849 EMSG(_(e_dictreq));
12850 return;
12852 if ((d = argvars[0].vval.v_dict) == NULL)
12853 return;
12855 if (rettv_list_alloc(rettv) == FAIL)
12856 return;
12858 todo = (int)d->dv_hashtab.ht_used;
12859 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
12861 if (!HASHITEM_EMPTY(hi))
12863 --todo;
12864 di = HI2DI(hi);
12866 li = listitem_alloc();
12867 if (li == NULL)
12868 break;
12869 list_append(rettv->vval.v_list, li);
12871 if (what == 0)
12873 /* keys() */
12874 li->li_tv.v_type = VAR_STRING;
12875 li->li_tv.v_lock = 0;
12876 li->li_tv.vval.v_string = vim_strsave(di->di_key);
12878 else if (what == 1)
12880 /* values() */
12881 copy_tv(&di->di_tv, &li->li_tv);
12883 else
12885 /* items() */
12886 l2 = list_alloc();
12887 li->li_tv.v_type = VAR_LIST;
12888 li->li_tv.v_lock = 0;
12889 li->li_tv.vval.v_list = l2;
12890 if (l2 == NULL)
12891 break;
12892 ++l2->lv_refcount;
12894 li2 = listitem_alloc();
12895 if (li2 == NULL)
12896 break;
12897 list_append(l2, li2);
12898 li2->li_tv.v_type = VAR_STRING;
12899 li2->li_tv.v_lock = 0;
12900 li2->li_tv.vval.v_string = vim_strsave(di->di_key);
12902 li2 = listitem_alloc();
12903 if (li2 == NULL)
12904 break;
12905 list_append(l2, li2);
12906 copy_tv(&di->di_tv, &li2->li_tv);
12913 * "items(dict)" function
12915 static void
12916 f_items(argvars, rettv)
12917 typval_T *argvars;
12918 typval_T *rettv;
12920 dict_list(argvars, rettv, 2);
12924 * "join()" function
12926 static void
12927 f_join(argvars, rettv)
12928 typval_T *argvars;
12929 typval_T *rettv;
12931 garray_T ga;
12932 char_u *sep;
12934 if (argvars[0].v_type != VAR_LIST)
12936 EMSG(_(e_listreq));
12937 return;
12939 if (argvars[0].vval.v_list == NULL)
12940 return;
12941 if (argvars[1].v_type == VAR_UNKNOWN)
12942 sep = (char_u *)" ";
12943 else
12944 sep = get_tv_string_chk(&argvars[1]);
12946 rettv->v_type = VAR_STRING;
12948 if (sep != NULL)
12950 ga_init2(&ga, (int)sizeof(char), 80);
12951 list_join(&ga, argvars[0].vval.v_list, sep, TRUE, 0);
12952 ga_append(&ga, NUL);
12953 rettv->vval.v_string = (char_u *)ga.ga_data;
12955 else
12956 rettv->vval.v_string = NULL;
12960 * "keys()" function
12962 static void
12963 f_keys(argvars, rettv)
12964 typval_T *argvars;
12965 typval_T *rettv;
12967 dict_list(argvars, rettv, 0);
12971 * "last_buffer_nr()" function.
12973 static void
12974 f_last_buffer_nr(argvars, rettv)
12975 typval_T *argvars UNUSED;
12976 typval_T *rettv;
12978 int n = 0;
12979 buf_T *buf;
12981 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
12982 if (n < buf->b_fnum)
12983 n = buf->b_fnum;
12985 rettv->vval.v_number = n;
12989 * "len()" function
12991 static void
12992 f_len(argvars, rettv)
12993 typval_T *argvars;
12994 typval_T *rettv;
12996 switch (argvars[0].v_type)
12998 case VAR_STRING:
12999 case VAR_NUMBER:
13000 rettv->vval.v_number = (varnumber_T)STRLEN(
13001 get_tv_string(&argvars[0]));
13002 break;
13003 case VAR_LIST:
13004 rettv->vval.v_number = list_len(argvars[0].vval.v_list);
13005 break;
13006 case VAR_DICT:
13007 rettv->vval.v_number = dict_len(argvars[0].vval.v_dict);
13008 break;
13009 default:
13010 EMSG(_("E701: Invalid type for len()"));
13011 break;
13015 static void libcall_common __ARGS((typval_T *argvars, typval_T *rettv, int type));
13017 static void
13018 libcall_common(argvars, rettv, type)
13019 typval_T *argvars;
13020 typval_T *rettv;
13021 int type;
13023 #ifdef FEAT_LIBCALL
13024 char_u *string_in;
13025 char_u **string_result;
13026 int nr_result;
13027 #endif
13029 rettv->v_type = type;
13030 if (type != VAR_NUMBER)
13031 rettv->vval.v_string = NULL;
13033 if (check_restricted() || check_secure())
13034 return;
13036 #ifdef FEAT_LIBCALL
13037 /* The first two args must be strings, otherwise its meaningless */
13038 if (argvars[0].v_type == VAR_STRING && argvars[1].v_type == VAR_STRING)
13040 string_in = NULL;
13041 if (argvars[2].v_type == VAR_STRING)
13042 string_in = argvars[2].vval.v_string;
13043 if (type == VAR_NUMBER)
13044 string_result = NULL;
13045 else
13046 string_result = &rettv->vval.v_string;
13047 if (mch_libcall(argvars[0].vval.v_string,
13048 argvars[1].vval.v_string,
13049 string_in,
13050 argvars[2].vval.v_number,
13051 string_result,
13052 &nr_result) == OK
13053 && type == VAR_NUMBER)
13054 rettv->vval.v_number = nr_result;
13056 #endif
13060 * "libcall()" function
13062 static void
13063 f_libcall(argvars, rettv)
13064 typval_T *argvars;
13065 typval_T *rettv;
13067 libcall_common(argvars, rettv, VAR_STRING);
13071 * "libcallnr()" function
13073 static void
13074 f_libcallnr(argvars, rettv)
13075 typval_T *argvars;
13076 typval_T *rettv;
13078 libcall_common(argvars, rettv, VAR_NUMBER);
13082 * "line(string)" function
13084 static void
13085 f_line(argvars, rettv)
13086 typval_T *argvars;
13087 typval_T *rettv;
13089 linenr_T lnum = 0;
13090 pos_T *fp;
13091 int fnum;
13093 fp = var2fpos(&argvars[0], TRUE, &fnum);
13094 if (fp != NULL)
13095 lnum = fp->lnum;
13096 rettv->vval.v_number = lnum;
13100 * "line2byte(lnum)" function
13102 static void
13103 f_line2byte(argvars, rettv)
13104 typval_T *argvars UNUSED;
13105 typval_T *rettv;
13107 #ifndef FEAT_BYTEOFF
13108 rettv->vval.v_number = -1;
13109 #else
13110 linenr_T lnum;
13112 lnum = get_tv_lnum(argvars);
13113 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
13114 rettv->vval.v_number = -1;
13115 else
13116 rettv->vval.v_number = ml_find_line_or_offset(curbuf, lnum, NULL);
13117 if (rettv->vval.v_number >= 0)
13118 ++rettv->vval.v_number;
13119 #endif
13123 * "lispindent(lnum)" function
13125 static void
13126 f_lispindent(argvars, rettv)
13127 typval_T *argvars;
13128 typval_T *rettv;
13130 #ifdef FEAT_LISP
13131 pos_T pos;
13132 linenr_T lnum;
13134 pos = curwin->w_cursor;
13135 lnum = get_tv_lnum(argvars);
13136 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
13138 curwin->w_cursor.lnum = lnum;
13139 rettv->vval.v_number = get_lisp_indent();
13140 curwin->w_cursor = pos;
13142 else
13143 #endif
13144 rettv->vval.v_number = -1;
13148 * "localtime()" function
13150 static void
13151 f_localtime(argvars, rettv)
13152 typval_T *argvars UNUSED;
13153 typval_T *rettv;
13155 rettv->vval.v_number = (varnumber_T)time(NULL);
13158 static void get_maparg __ARGS((typval_T *argvars, typval_T *rettv, int exact));
13160 static void
13161 get_maparg(argvars, rettv, exact)
13162 typval_T *argvars;
13163 typval_T *rettv;
13164 int exact;
13166 char_u *keys;
13167 char_u *which;
13168 char_u buf[NUMBUFLEN];
13169 char_u *keys_buf = NULL;
13170 char_u *rhs;
13171 int mode;
13172 garray_T ga;
13173 int abbr = FALSE;
13175 /* return empty string for failure */
13176 rettv->v_type = VAR_STRING;
13177 rettv->vval.v_string = NULL;
13179 keys = get_tv_string(&argvars[0]);
13180 if (*keys == NUL)
13181 return;
13183 if (argvars[1].v_type != VAR_UNKNOWN)
13185 which = get_tv_string_buf_chk(&argvars[1], buf);
13186 if (argvars[2].v_type != VAR_UNKNOWN)
13187 abbr = get_tv_number(&argvars[2]);
13189 else
13190 which = (char_u *)"";
13191 if (which == NULL)
13192 return;
13194 mode = get_map_mode(&which, 0);
13196 keys = replace_termcodes(keys, &keys_buf, TRUE, TRUE, FALSE);
13197 rhs = check_map(keys, mode, exact, FALSE, abbr);
13198 vim_free(keys_buf);
13199 if (rhs != NULL)
13201 ga_init(&ga);
13202 ga.ga_itemsize = 1;
13203 ga.ga_growsize = 40;
13205 while (*rhs != NUL)
13206 ga_concat(&ga, str2special(&rhs, FALSE));
13208 ga_append(&ga, NUL);
13209 rettv->vval.v_string = (char_u *)ga.ga_data;
13213 #ifdef FEAT_FLOAT
13215 * "log10()" function
13217 static void
13218 f_log10(argvars, rettv)
13219 typval_T *argvars;
13220 typval_T *rettv;
13222 float_T f;
13224 rettv->v_type = VAR_FLOAT;
13225 if (get_float_arg(argvars, &f) == OK)
13226 rettv->vval.v_float = log10(f);
13227 else
13228 rettv->vval.v_float = 0.0;
13230 #endif
13233 * "map()" function
13235 static void
13236 f_map(argvars, rettv)
13237 typval_T *argvars;
13238 typval_T *rettv;
13240 filter_map(argvars, rettv, TRUE);
13244 * "maparg()" function
13246 static void
13247 f_maparg(argvars, rettv)
13248 typval_T *argvars;
13249 typval_T *rettv;
13251 get_maparg(argvars, rettv, TRUE);
13255 * "mapcheck()" function
13257 static void
13258 f_mapcheck(argvars, rettv)
13259 typval_T *argvars;
13260 typval_T *rettv;
13262 get_maparg(argvars, rettv, FALSE);
13265 static void find_some_match __ARGS((typval_T *argvars, typval_T *rettv, int start));
13267 static void
13268 find_some_match(argvars, rettv, type)
13269 typval_T *argvars;
13270 typval_T *rettv;
13271 int type;
13273 char_u *str = NULL;
13274 char_u *expr = NULL;
13275 char_u *pat;
13276 regmatch_T regmatch;
13277 char_u patbuf[NUMBUFLEN];
13278 char_u strbuf[NUMBUFLEN];
13279 char_u *save_cpo;
13280 long start = 0;
13281 long nth = 1;
13282 colnr_T startcol = 0;
13283 int match = 0;
13284 list_T *l = NULL;
13285 listitem_T *li = NULL;
13286 long idx = 0;
13287 char_u *tofree = NULL;
13289 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
13290 save_cpo = p_cpo;
13291 p_cpo = (char_u *)"";
13293 rettv->vval.v_number = -1;
13294 if (type == 3)
13296 /* return empty list when there are no matches */
13297 if (rettv_list_alloc(rettv) == FAIL)
13298 goto theend;
13300 else if (type == 2)
13302 rettv->v_type = VAR_STRING;
13303 rettv->vval.v_string = NULL;
13306 if (argvars[0].v_type == VAR_LIST)
13308 if ((l = argvars[0].vval.v_list) == NULL)
13309 goto theend;
13310 li = l->lv_first;
13312 else
13313 expr = str = get_tv_string(&argvars[0]);
13315 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
13316 if (pat == NULL)
13317 goto theend;
13319 if (argvars[2].v_type != VAR_UNKNOWN)
13321 int error = FALSE;
13323 start = get_tv_number_chk(&argvars[2], &error);
13324 if (error)
13325 goto theend;
13326 if (l != NULL)
13328 li = list_find(l, start);
13329 if (li == NULL)
13330 goto theend;
13331 idx = l->lv_idx; /* use the cached index */
13333 else
13335 if (start < 0)
13336 start = 0;
13337 if (start > (long)STRLEN(str))
13338 goto theend;
13339 /* When "count" argument is there ignore matches before "start",
13340 * otherwise skip part of the string. Differs when pattern is "^"
13341 * or "\<". */
13342 if (argvars[3].v_type != VAR_UNKNOWN)
13343 startcol = start;
13344 else
13345 str += start;
13348 if (argvars[3].v_type != VAR_UNKNOWN)
13349 nth = get_tv_number_chk(&argvars[3], &error);
13350 if (error)
13351 goto theend;
13354 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
13355 if (regmatch.regprog != NULL)
13357 regmatch.rm_ic = p_ic;
13359 for (;;)
13361 if (l != NULL)
13363 if (li == NULL)
13365 match = FALSE;
13366 break;
13368 vim_free(tofree);
13369 str = echo_string(&li->li_tv, &tofree, strbuf, 0);
13370 if (str == NULL)
13371 break;
13374 match = vim_regexec_nl(&regmatch, str, (colnr_T)startcol);
13376 if (match && --nth <= 0)
13377 break;
13378 if (l == NULL && !match)
13379 break;
13381 /* Advance to just after the match. */
13382 if (l != NULL)
13384 li = li->li_next;
13385 ++idx;
13387 else
13389 #ifdef FEAT_MBYTE
13390 startcol = (colnr_T)(regmatch.startp[0]
13391 + (*mb_ptr2len)(regmatch.startp[0]) - str);
13392 #else
13393 startcol = regmatch.startp[0] + 1 - str;
13394 #endif
13398 if (match)
13400 if (type == 3)
13402 int i;
13404 /* return list with matched string and submatches */
13405 for (i = 0; i < NSUBEXP; ++i)
13407 if (regmatch.endp[i] == NULL)
13409 if (list_append_string(rettv->vval.v_list,
13410 (char_u *)"", 0) == FAIL)
13411 break;
13413 else if (list_append_string(rettv->vval.v_list,
13414 regmatch.startp[i],
13415 (int)(regmatch.endp[i] - regmatch.startp[i]))
13416 == FAIL)
13417 break;
13420 else if (type == 2)
13422 /* return matched string */
13423 if (l != NULL)
13424 copy_tv(&li->li_tv, rettv);
13425 else
13426 rettv->vval.v_string = vim_strnsave(regmatch.startp[0],
13427 (int)(regmatch.endp[0] - regmatch.startp[0]));
13429 else if (l != NULL)
13430 rettv->vval.v_number = idx;
13431 else
13433 if (type != 0)
13434 rettv->vval.v_number =
13435 (varnumber_T)(regmatch.startp[0] - str);
13436 else
13437 rettv->vval.v_number =
13438 (varnumber_T)(regmatch.endp[0] - str);
13439 rettv->vval.v_number += (varnumber_T)(str - expr);
13442 vim_free(regmatch.regprog);
13445 theend:
13446 vim_free(tofree);
13447 p_cpo = save_cpo;
13451 * "match()" function
13453 static void
13454 f_match(argvars, rettv)
13455 typval_T *argvars;
13456 typval_T *rettv;
13458 find_some_match(argvars, rettv, 1);
13462 * "matchadd()" function
13464 static void
13465 f_matchadd(argvars, rettv)
13466 typval_T *argvars;
13467 typval_T *rettv;
13469 #ifdef FEAT_SEARCH_EXTRA
13470 char_u buf[NUMBUFLEN];
13471 char_u *grp = get_tv_string_buf_chk(&argvars[0], buf); /* group */
13472 char_u *pat = get_tv_string_buf_chk(&argvars[1], buf); /* pattern */
13473 int prio = 10; /* default priority */
13474 int id = -1;
13475 int error = FALSE;
13477 rettv->vval.v_number = -1;
13479 if (grp == NULL || pat == NULL)
13480 return;
13481 if (argvars[2].v_type != VAR_UNKNOWN)
13483 prio = get_tv_number_chk(&argvars[2], &error);
13484 if (argvars[3].v_type != VAR_UNKNOWN)
13485 id = get_tv_number_chk(&argvars[3], &error);
13487 if (error == TRUE)
13488 return;
13489 if (id >= 1 && id <= 3)
13491 EMSGN("E798: ID is reserved for \":match\": %ld", id);
13492 return;
13495 rettv->vval.v_number = match_add(curwin, grp, pat, prio, id);
13496 #endif
13500 * "matcharg()" function
13502 static void
13503 f_matcharg(argvars, rettv)
13504 typval_T *argvars;
13505 typval_T *rettv;
13507 if (rettv_list_alloc(rettv) == OK)
13509 #ifdef FEAT_SEARCH_EXTRA
13510 int id = get_tv_number(&argvars[0]);
13511 matchitem_T *m;
13513 if (id >= 1 && id <= 3)
13515 if ((m = (matchitem_T *)get_match(curwin, id)) != NULL)
13517 list_append_string(rettv->vval.v_list,
13518 syn_id2name(m->hlg_id), -1);
13519 list_append_string(rettv->vval.v_list, m->pattern, -1);
13521 else
13523 list_append_string(rettv->vval.v_list, NUL, -1);
13524 list_append_string(rettv->vval.v_list, NUL, -1);
13527 #endif
13532 * "matchdelete()" function
13534 static void
13535 f_matchdelete(argvars, rettv)
13536 typval_T *argvars;
13537 typval_T *rettv;
13539 #ifdef FEAT_SEARCH_EXTRA
13540 rettv->vval.v_number = match_delete(curwin,
13541 (int)get_tv_number(&argvars[0]), TRUE);
13542 #endif
13546 * "matchend()" function
13548 static void
13549 f_matchend(argvars, rettv)
13550 typval_T *argvars;
13551 typval_T *rettv;
13553 find_some_match(argvars, rettv, 0);
13557 * "matchlist()" function
13559 static void
13560 f_matchlist(argvars, rettv)
13561 typval_T *argvars;
13562 typval_T *rettv;
13564 find_some_match(argvars, rettv, 3);
13568 * "matchstr()" function
13570 static void
13571 f_matchstr(argvars, rettv)
13572 typval_T *argvars;
13573 typval_T *rettv;
13575 find_some_match(argvars, rettv, 2);
13578 static void max_min __ARGS((typval_T *argvars, typval_T *rettv, int domax));
13580 static void
13581 max_min(argvars, rettv, domax)
13582 typval_T *argvars;
13583 typval_T *rettv;
13584 int domax;
13586 long n = 0;
13587 long i;
13588 int error = FALSE;
13590 if (argvars[0].v_type == VAR_LIST)
13592 list_T *l;
13593 listitem_T *li;
13595 l = argvars[0].vval.v_list;
13596 if (l != NULL)
13598 li = l->lv_first;
13599 if (li != NULL)
13601 n = get_tv_number_chk(&li->li_tv, &error);
13602 for (;;)
13604 li = li->li_next;
13605 if (li == NULL)
13606 break;
13607 i = get_tv_number_chk(&li->li_tv, &error);
13608 if (domax ? i > n : i < n)
13609 n = i;
13614 else if (argvars[0].v_type == VAR_DICT)
13616 dict_T *d;
13617 int first = TRUE;
13618 hashitem_T *hi;
13619 int todo;
13621 d = argvars[0].vval.v_dict;
13622 if (d != NULL)
13624 todo = (int)d->dv_hashtab.ht_used;
13625 for (hi = d->dv_hashtab.ht_array; todo > 0; ++hi)
13627 if (!HASHITEM_EMPTY(hi))
13629 --todo;
13630 i = get_tv_number_chk(&HI2DI(hi)->di_tv, &error);
13631 if (first)
13633 n = i;
13634 first = FALSE;
13636 else if (domax ? i > n : i < n)
13637 n = i;
13642 else
13643 EMSG(_(e_listdictarg));
13644 rettv->vval.v_number = error ? 0 : n;
13648 * "max()" function
13650 static void
13651 f_max(argvars, rettv)
13652 typval_T *argvars;
13653 typval_T *rettv;
13655 max_min(argvars, rettv, TRUE);
13659 * "min()" function
13661 static void
13662 f_min(argvars, rettv)
13663 typval_T *argvars;
13664 typval_T *rettv;
13666 max_min(argvars, rettv, FALSE);
13669 static int mkdir_recurse __ARGS((char_u *dir, int prot));
13672 * Create the directory in which "dir" is located, and higher levels when
13673 * needed.
13675 static int
13676 mkdir_recurse(dir, prot)
13677 char_u *dir;
13678 int prot;
13680 char_u *p;
13681 char_u *updir;
13682 int r = FAIL;
13684 /* Get end of directory name in "dir".
13685 * We're done when it's "/" or "c:/". */
13686 p = gettail_sep(dir);
13687 if (p <= get_past_head(dir))
13688 return OK;
13690 /* If the directory exists we're done. Otherwise: create it.*/
13691 updir = vim_strnsave(dir, (int)(p - dir));
13692 if (updir == NULL)
13693 return FAIL;
13694 if (mch_isdir(updir))
13695 r = OK;
13696 else if (mkdir_recurse(updir, prot) == OK)
13697 r = vim_mkdir_emsg(updir, prot);
13698 vim_free(updir);
13699 return r;
13702 #ifdef vim_mkdir
13704 * "mkdir()" function
13706 static void
13707 f_mkdir(argvars, rettv)
13708 typval_T *argvars;
13709 typval_T *rettv;
13711 char_u *dir;
13712 char_u buf[NUMBUFLEN];
13713 int prot = 0755;
13715 rettv->vval.v_number = FAIL;
13716 if (check_restricted() || check_secure())
13717 return;
13719 dir = get_tv_string_buf(&argvars[0], buf);
13720 if (argvars[1].v_type != VAR_UNKNOWN)
13722 if (argvars[2].v_type != VAR_UNKNOWN)
13723 prot = get_tv_number_chk(&argvars[2], NULL);
13724 if (prot != -1 && STRCMP(get_tv_string(&argvars[1]), "p") == 0)
13725 mkdir_recurse(dir, prot);
13727 rettv->vval.v_number = prot != -1 ? vim_mkdir_emsg(dir, prot) : 0;
13729 #endif
13732 * "mode()" function
13734 static void
13735 f_mode(argvars, rettv)
13736 typval_T *argvars;
13737 typval_T *rettv;
13739 char_u buf[3];
13741 buf[1] = NUL;
13742 buf[2] = NUL;
13744 #ifdef FEAT_VISUAL
13745 if (VIsual_active)
13747 if (VIsual_select)
13748 buf[0] = VIsual_mode + 's' - 'v';
13749 else
13750 buf[0] = VIsual_mode;
13752 else
13753 #endif
13754 if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
13755 || State == CONFIRM)
13757 buf[0] = 'r';
13758 if (State == ASKMORE)
13759 buf[1] = 'm';
13760 else if (State == CONFIRM)
13761 buf[1] = '?';
13763 else if (State == EXTERNCMD)
13764 buf[0] = '!';
13765 else if (State & INSERT)
13767 #ifdef FEAT_VREPLACE
13768 if (State & VREPLACE_FLAG)
13770 buf[0] = 'R';
13771 buf[1] = 'v';
13773 else
13774 #endif
13775 if (State & REPLACE_FLAG)
13776 buf[0] = 'R';
13777 else
13778 buf[0] = 'i';
13780 else if (State & CMDLINE)
13782 buf[0] = 'c';
13783 if (exmode_active)
13784 buf[1] = 'v';
13786 else if (exmode_active)
13788 buf[0] = 'c';
13789 buf[1] = 'e';
13791 else
13793 buf[0] = 'n';
13794 if (finish_op)
13795 buf[1] = 'o';
13798 /* Clear out the minor mode when the argument is not a non-zero number or
13799 * non-empty string. */
13800 if (!non_zero_arg(&argvars[0]))
13801 buf[1] = NUL;
13803 rettv->vval.v_string = vim_strsave(buf);
13804 rettv->v_type = VAR_STRING;
13807 #ifdef FEAT_MZSCHEME
13809 * "mzeval()" function
13811 static void
13812 f_mzeval(argvars, rettv)
13813 typval_T *argvars;
13814 typval_T *rettv;
13816 char_u *str;
13817 char_u buf[NUMBUFLEN];
13819 str = get_tv_string_buf(&argvars[0], buf);
13820 do_mzeval(str, rettv);
13822 #endif
13825 * "nextnonblank()" function
13827 static void
13828 f_nextnonblank(argvars, rettv)
13829 typval_T *argvars;
13830 typval_T *rettv;
13832 linenr_T lnum;
13834 for (lnum = get_tv_lnum(argvars); ; ++lnum)
13836 if (lnum < 0 || lnum > curbuf->b_ml.ml_line_count)
13838 lnum = 0;
13839 break;
13841 if (*skipwhite(ml_get(lnum)) != NUL)
13842 break;
13844 rettv->vval.v_number = lnum;
13848 * "nr2char()" function
13850 static void
13851 f_nr2char(argvars, rettv)
13852 typval_T *argvars;
13853 typval_T *rettv;
13855 char_u buf[NUMBUFLEN];
13857 #ifdef FEAT_MBYTE
13858 if (has_mbyte)
13859 buf[(*mb_char2bytes)((int)get_tv_number(&argvars[0]), buf)] = NUL;
13860 else
13861 #endif
13863 buf[0] = (char_u)get_tv_number(&argvars[0]);
13864 buf[1] = NUL;
13866 rettv->v_type = VAR_STRING;
13867 rettv->vval.v_string = vim_strsave(buf);
13871 * "pathshorten()" function
13873 static void
13874 f_pathshorten(argvars, rettv)
13875 typval_T *argvars;
13876 typval_T *rettv;
13878 char_u *p;
13880 rettv->v_type = VAR_STRING;
13881 p = get_tv_string_chk(&argvars[0]);
13882 if (p == NULL)
13883 rettv->vval.v_string = NULL;
13884 else
13886 p = vim_strsave(p);
13887 rettv->vval.v_string = p;
13888 if (p != NULL)
13889 shorten_dir(p);
13893 #ifdef FEAT_FLOAT
13895 * "pow()" function
13897 static void
13898 f_pow(argvars, rettv)
13899 typval_T *argvars;
13900 typval_T *rettv;
13902 float_T fx, fy;
13904 rettv->v_type = VAR_FLOAT;
13905 if (get_float_arg(argvars, &fx) == OK
13906 && get_float_arg(&argvars[1], &fy) == OK)
13907 rettv->vval.v_float = pow(fx, fy);
13908 else
13909 rettv->vval.v_float = 0.0;
13911 #endif
13914 * "prevnonblank()" function
13916 static void
13917 f_prevnonblank(argvars, rettv)
13918 typval_T *argvars;
13919 typval_T *rettv;
13921 linenr_T lnum;
13923 lnum = get_tv_lnum(argvars);
13924 if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count)
13925 lnum = 0;
13926 else
13927 while (lnum >= 1 && *skipwhite(ml_get(lnum)) == NUL)
13928 --lnum;
13929 rettv->vval.v_number = lnum;
13932 #ifdef HAVE_STDARG_H
13933 /* This dummy va_list is here because:
13934 * - passing a NULL pointer doesn't work when va_list isn't a pointer
13935 * - locally in the function results in a "used before set" warning
13936 * - using va_start() to initialize it gives "function with fixed args" error */
13937 static va_list ap;
13938 #endif
13941 * "printf()" function
13943 static void
13944 f_printf(argvars, rettv)
13945 typval_T *argvars;
13946 typval_T *rettv;
13948 rettv->v_type = VAR_STRING;
13949 rettv->vval.v_string = NULL;
13950 #ifdef HAVE_STDARG_H /* only very old compilers can't do this */
13952 char_u buf[NUMBUFLEN];
13953 int len;
13954 char_u *s;
13955 int saved_did_emsg = did_emsg;
13956 char *fmt;
13958 /* Get the required length, allocate the buffer and do it for real. */
13959 did_emsg = FALSE;
13960 fmt = (char *)get_tv_string_buf(&argvars[0], buf);
13961 len = vim_vsnprintf(NULL, 0, fmt, ap, argvars + 1);
13962 if (!did_emsg)
13964 s = alloc(len + 1);
13965 if (s != NULL)
13967 rettv->vval.v_string = s;
13968 (void)vim_vsnprintf((char *)s, len + 1, fmt, ap, argvars + 1);
13971 did_emsg |= saved_did_emsg;
13973 #endif
13977 * "pumvisible()" function
13979 static void
13980 f_pumvisible(argvars, rettv)
13981 typval_T *argvars UNUSED;
13982 typval_T *rettv UNUSED;
13984 #ifdef FEAT_INS_EXPAND
13985 if (pum_visible())
13986 rettv->vval.v_number = 1;
13987 #endif
13991 * "range()" function
13993 static void
13994 f_range(argvars, rettv)
13995 typval_T *argvars;
13996 typval_T *rettv;
13998 long start;
13999 long end;
14000 long stride = 1;
14001 long i;
14002 int error = FALSE;
14004 start = get_tv_number_chk(&argvars[0], &error);
14005 if (argvars[1].v_type == VAR_UNKNOWN)
14007 end = start - 1;
14008 start = 0;
14010 else
14012 end = get_tv_number_chk(&argvars[1], &error);
14013 if (argvars[2].v_type != VAR_UNKNOWN)
14014 stride = get_tv_number_chk(&argvars[2], &error);
14017 if (error)
14018 return; /* type error; errmsg already given */
14019 if (stride == 0)
14020 EMSG(_("E726: Stride is zero"));
14021 else if (stride > 0 ? end + 1 < start : end - 1 > start)
14022 EMSG(_("E727: Start past end"));
14023 else
14025 if (rettv_list_alloc(rettv) == OK)
14026 for (i = start; stride > 0 ? i <= end : i >= end; i += stride)
14027 if (list_append_number(rettv->vval.v_list,
14028 (varnumber_T)i) == FAIL)
14029 break;
14034 * "readfile()" function
14036 static void
14037 f_readfile(argvars, rettv)
14038 typval_T *argvars;
14039 typval_T *rettv;
14041 int binary = FALSE;
14042 char_u *fname;
14043 FILE *fd;
14044 listitem_T *li;
14045 #define FREAD_SIZE 200 /* optimized for text lines */
14046 char_u buf[FREAD_SIZE];
14047 int readlen; /* size of last fread() */
14048 int buflen; /* nr of valid chars in buf[] */
14049 int filtd; /* how much in buf[] was NUL -> '\n' filtered */
14050 int tolist; /* first byte in buf[] still to be put in list */
14051 int chop; /* how many CR to chop off */
14052 char_u *prev = NULL; /* previously read bytes, if any */
14053 int prevlen = 0; /* length of "prev" if not NULL */
14054 char_u *s;
14055 int len;
14056 long maxline = MAXLNUM;
14057 long cnt = 0;
14059 if (argvars[1].v_type != VAR_UNKNOWN)
14061 if (STRCMP(get_tv_string(&argvars[1]), "b") == 0)
14062 binary = TRUE;
14063 if (argvars[2].v_type != VAR_UNKNOWN)
14064 maxline = get_tv_number(&argvars[2]);
14067 if (rettv_list_alloc(rettv) == FAIL)
14068 return;
14070 /* Always open the file in binary mode, library functions have a mind of
14071 * their own about CR-LF conversion. */
14072 fname = get_tv_string(&argvars[0]);
14073 if (*fname == NUL || (fd = mch_fopen((char *)fname, READBIN)) == NULL)
14075 EMSG2(_(e_notopen), *fname == NUL ? (char_u *)_("<empty>") : fname);
14076 return;
14079 filtd = 0;
14080 while (cnt < maxline || maxline < 0)
14082 readlen = (int)fread(buf + filtd, 1, FREAD_SIZE - filtd, fd);
14083 buflen = filtd + readlen;
14084 tolist = 0;
14085 for ( ; filtd < buflen || readlen <= 0; ++filtd)
14087 if (buf[filtd] == '\n' || readlen <= 0)
14089 /* Only when in binary mode add an empty list item when the
14090 * last line ends in a '\n'. */
14091 if (!binary && readlen == 0 && filtd == 0)
14092 break;
14094 /* Found end-of-line or end-of-file: add a text line to the
14095 * list. */
14096 chop = 0;
14097 if (!binary)
14098 while (filtd - chop - 1 >= tolist
14099 && buf[filtd - chop - 1] == '\r')
14100 ++chop;
14101 len = filtd - tolist - chop;
14102 if (prev == NULL)
14103 s = vim_strnsave(buf + tolist, len);
14104 else
14106 s = alloc((unsigned)(prevlen + len + 1));
14107 if (s != NULL)
14109 mch_memmove(s, prev, prevlen);
14110 vim_free(prev);
14111 prev = NULL;
14112 mch_memmove(s + prevlen, buf + tolist, len);
14113 s[prevlen + len] = NUL;
14116 tolist = filtd + 1;
14118 li = listitem_alloc();
14119 if (li == NULL)
14121 vim_free(s);
14122 break;
14124 li->li_tv.v_type = VAR_STRING;
14125 li->li_tv.v_lock = 0;
14126 li->li_tv.vval.v_string = s;
14127 list_append(rettv->vval.v_list, li);
14129 if (++cnt >= maxline && maxline >= 0)
14130 break;
14131 if (readlen <= 0)
14132 break;
14134 else if (buf[filtd] == NUL)
14135 buf[filtd] = '\n';
14137 if (readlen <= 0)
14138 break;
14140 if (tolist == 0)
14142 /* "buf" is full, need to move text to an allocated buffer */
14143 if (prev == NULL)
14145 prev = vim_strnsave(buf, buflen);
14146 prevlen = buflen;
14148 else
14150 s = alloc((unsigned)(prevlen + buflen));
14151 if (s != NULL)
14153 mch_memmove(s, prev, prevlen);
14154 mch_memmove(s + prevlen, buf, buflen);
14155 vim_free(prev);
14156 prev = s;
14157 prevlen += buflen;
14160 filtd = 0;
14162 else
14164 mch_memmove(buf, buf + tolist, buflen - tolist);
14165 filtd -= tolist;
14170 * For a negative line count use only the lines at the end of the file,
14171 * free the rest.
14173 if (maxline < 0)
14174 while (cnt > -maxline)
14176 listitem_remove(rettv->vval.v_list, rettv->vval.v_list->lv_first);
14177 --cnt;
14180 vim_free(prev);
14181 fclose(fd);
14184 #if defined(FEAT_RELTIME)
14185 static int list2proftime __ARGS((typval_T *arg, proftime_T *tm));
14188 * Convert a List to proftime_T.
14189 * Return FAIL when there is something wrong.
14191 static int
14192 list2proftime(arg, tm)
14193 typval_T *arg;
14194 proftime_T *tm;
14196 long n1, n2;
14197 int error = FALSE;
14199 if (arg->v_type != VAR_LIST || arg->vval.v_list == NULL
14200 || arg->vval.v_list->lv_len != 2)
14201 return FAIL;
14202 n1 = list_find_nr(arg->vval.v_list, 0L, &error);
14203 n2 = list_find_nr(arg->vval.v_list, 1L, &error);
14204 # ifdef WIN3264
14205 tm->HighPart = n1;
14206 tm->LowPart = n2;
14207 # else
14208 tm->tv_sec = n1;
14209 tm->tv_usec = n2;
14210 # endif
14211 return error ? FAIL : OK;
14213 #endif /* FEAT_RELTIME */
14216 * "reltime()" function
14218 static void
14219 f_reltime(argvars, rettv)
14220 typval_T *argvars;
14221 typval_T *rettv;
14223 #ifdef FEAT_RELTIME
14224 proftime_T res;
14225 proftime_T start;
14227 if (argvars[0].v_type == VAR_UNKNOWN)
14229 /* No arguments: get current time. */
14230 profile_start(&res);
14232 else if (argvars[1].v_type == VAR_UNKNOWN)
14234 if (list2proftime(&argvars[0], &res) == FAIL)
14235 return;
14236 profile_end(&res);
14238 else
14240 /* Two arguments: compute the difference. */
14241 if (list2proftime(&argvars[0], &start) == FAIL
14242 || list2proftime(&argvars[1], &res) == FAIL)
14243 return;
14244 profile_sub(&res, &start);
14247 if (rettv_list_alloc(rettv) == OK)
14249 long n1, n2;
14251 # ifdef WIN3264
14252 n1 = res.HighPart;
14253 n2 = res.LowPart;
14254 # else
14255 n1 = res.tv_sec;
14256 n2 = res.tv_usec;
14257 # endif
14258 list_append_number(rettv->vval.v_list, (varnumber_T)n1);
14259 list_append_number(rettv->vval.v_list, (varnumber_T)n2);
14261 #endif
14265 * "reltimestr()" function
14267 static void
14268 f_reltimestr(argvars, rettv)
14269 typval_T *argvars;
14270 typval_T *rettv;
14272 #ifdef FEAT_RELTIME
14273 proftime_T tm;
14274 #endif
14276 rettv->v_type = VAR_STRING;
14277 rettv->vval.v_string = NULL;
14278 #ifdef FEAT_RELTIME
14279 if (list2proftime(&argvars[0], &tm) == OK)
14280 rettv->vval.v_string = vim_strsave((char_u *)profile_msg(&tm));
14281 #endif
14284 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
14285 static void make_connection __ARGS((void));
14286 static int check_connection __ARGS((void));
14288 static void
14289 make_connection()
14291 if (X_DISPLAY == NULL
14292 # ifdef FEAT_GUI
14293 && !gui.in_use
14294 # endif
14297 x_force_connect = TRUE;
14298 setup_term_clip();
14299 x_force_connect = FALSE;
14303 static int
14304 check_connection()
14306 make_connection();
14307 if (X_DISPLAY == NULL)
14309 EMSG(_("E240: No connection to Vim server"));
14310 return FAIL;
14312 return OK;
14314 #endif
14316 #ifdef FEAT_CLIENTSERVER
14317 static void remote_common __ARGS((typval_T *argvars, typval_T *rettv, int expr));
14319 static void
14320 remote_common(argvars, rettv, expr)
14321 typval_T *argvars;
14322 typval_T *rettv;
14323 int expr;
14325 char_u *server_name;
14326 char_u *keys;
14327 char_u *r = NULL;
14328 char_u buf[NUMBUFLEN];
14329 # ifdef WIN32
14330 HWND w;
14331 # else
14332 Window w;
14333 # endif
14335 if (check_restricted() || check_secure())
14336 return;
14338 # ifdef FEAT_X11
14339 if (check_connection() == FAIL)
14340 return;
14341 # endif
14343 server_name = get_tv_string_chk(&argvars[0]);
14344 if (server_name == NULL)
14345 return; /* type error; errmsg already given */
14346 keys = get_tv_string_buf(&argvars[1], buf);
14347 # ifdef WIN32
14348 if (serverSendToVim(server_name, keys, &r, &w, expr, TRUE) < 0)
14349 # else
14350 if (serverSendToVim(X_DISPLAY, server_name, keys, &r, &w, expr, 0, TRUE)
14351 < 0)
14352 # endif
14354 if (r != NULL)
14355 EMSG(r); /* sending worked but evaluation failed */
14356 else
14357 EMSG2(_("E241: Unable to send to %s"), server_name);
14358 return;
14361 rettv->vval.v_string = r;
14363 if (argvars[2].v_type != VAR_UNKNOWN)
14365 dictitem_T v;
14366 char_u str[30];
14367 char_u *idvar;
14369 sprintf((char *)str, PRINTF_HEX_LONG_U, (long_u)w);
14370 v.di_tv.v_type = VAR_STRING;
14371 v.di_tv.vval.v_string = vim_strsave(str);
14372 idvar = get_tv_string_chk(&argvars[2]);
14373 if (idvar != NULL)
14374 set_var(idvar, &v.di_tv, FALSE);
14375 vim_free(v.di_tv.vval.v_string);
14378 #endif
14381 * "remote_expr()" function
14383 static void
14384 f_remote_expr(argvars, rettv)
14385 typval_T *argvars UNUSED;
14386 typval_T *rettv;
14388 rettv->v_type = VAR_STRING;
14389 rettv->vval.v_string = NULL;
14390 #ifdef FEAT_CLIENTSERVER
14391 remote_common(argvars, rettv, TRUE);
14392 #endif
14396 * "remote_foreground()" function
14398 static void
14399 f_remote_foreground(argvars, rettv)
14400 typval_T *argvars UNUSED;
14401 typval_T *rettv UNUSED;
14403 #ifdef FEAT_CLIENTSERVER
14404 # ifdef WIN32
14405 /* On Win32 it's done in this application. */
14407 char_u *server_name = get_tv_string_chk(&argvars[0]);
14409 if (server_name != NULL)
14410 serverForeground(server_name);
14412 # else
14413 /* Send a foreground() expression to the server. */
14414 argvars[1].v_type = VAR_STRING;
14415 argvars[1].vval.v_string = vim_strsave((char_u *)"foreground()");
14416 argvars[2].v_type = VAR_UNKNOWN;
14417 remote_common(argvars, rettv, TRUE);
14418 vim_free(argvars[1].vval.v_string);
14419 # endif
14420 #endif
14423 static void
14424 f_remote_peek(argvars, rettv)
14425 typval_T *argvars UNUSED;
14426 typval_T *rettv;
14428 #ifdef FEAT_CLIENTSERVER
14429 dictitem_T v;
14430 char_u *s = NULL;
14431 # ifdef WIN32
14432 long_u n = 0;
14433 # endif
14434 char_u *serverid;
14436 if (check_restricted() || check_secure())
14438 rettv->vval.v_number = -1;
14439 return;
14441 serverid = get_tv_string_chk(&argvars[0]);
14442 if (serverid == NULL)
14444 rettv->vval.v_number = -1;
14445 return; /* type error; errmsg already given */
14447 # ifdef WIN32
14448 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14449 if (n == 0)
14450 rettv->vval.v_number = -1;
14451 else
14453 s = serverGetReply((HWND)n, FALSE, FALSE, FALSE);
14454 rettv->vval.v_number = (s != NULL);
14456 # else
14457 if (check_connection() == FAIL)
14458 return;
14460 rettv->vval.v_number = serverPeekReply(X_DISPLAY,
14461 serverStrToWin(serverid), &s);
14462 # endif
14464 if (argvars[1].v_type != VAR_UNKNOWN && rettv->vval.v_number > 0)
14466 char_u *retvar;
14468 v.di_tv.v_type = VAR_STRING;
14469 v.di_tv.vval.v_string = vim_strsave(s);
14470 retvar = get_tv_string_chk(&argvars[1]);
14471 if (retvar != NULL)
14472 set_var(retvar, &v.di_tv, FALSE);
14473 vim_free(v.di_tv.vval.v_string);
14475 #else
14476 rettv->vval.v_number = -1;
14477 #endif
14480 static void
14481 f_remote_read(argvars, rettv)
14482 typval_T *argvars UNUSED;
14483 typval_T *rettv;
14485 char_u *r = NULL;
14487 #ifdef FEAT_CLIENTSERVER
14488 char_u *serverid = get_tv_string_chk(&argvars[0]);
14490 if (serverid != NULL && !check_restricted() && !check_secure())
14492 # ifdef WIN32
14493 /* The server's HWND is encoded in the 'id' parameter */
14494 long_u n = 0;
14496 sscanf(serverid, SCANF_HEX_LONG_U, &n);
14497 if (n != 0)
14498 r = serverGetReply((HWND)n, FALSE, TRUE, TRUE);
14499 if (r == NULL)
14500 # else
14501 if (check_connection() == FAIL || serverReadReply(X_DISPLAY,
14502 serverStrToWin(serverid), &r, FALSE) < 0)
14503 # endif
14504 EMSG(_("E277: Unable to read a server reply"));
14506 #endif
14507 rettv->v_type = VAR_STRING;
14508 rettv->vval.v_string = r;
14512 * "remote_send()" function
14514 static void
14515 f_remote_send(argvars, rettv)
14516 typval_T *argvars UNUSED;
14517 typval_T *rettv;
14519 rettv->v_type = VAR_STRING;
14520 rettv->vval.v_string = NULL;
14521 #ifdef FEAT_CLIENTSERVER
14522 remote_common(argvars, rettv, FALSE);
14523 #endif
14527 * "remove()" function
14529 static void
14530 f_remove(argvars, rettv)
14531 typval_T *argvars;
14532 typval_T *rettv;
14534 list_T *l;
14535 listitem_T *item, *item2;
14536 listitem_T *li;
14537 long idx;
14538 long end;
14539 char_u *key;
14540 dict_T *d;
14541 dictitem_T *di;
14543 if (argvars[0].v_type == VAR_DICT)
14545 if (argvars[2].v_type != VAR_UNKNOWN)
14546 EMSG2(_(e_toomanyarg), "remove()");
14547 else if ((d = argvars[0].vval.v_dict) != NULL
14548 && !tv_check_lock(d->dv_lock, (char_u *)"remove() argument"))
14550 key = get_tv_string_chk(&argvars[1]);
14551 if (key != NULL)
14553 di = dict_find(d, key, -1);
14554 if (di == NULL)
14555 EMSG2(_(e_dictkey), key);
14556 else
14558 *rettv = di->di_tv;
14559 init_tv(&di->di_tv);
14560 dictitem_remove(d, di);
14565 else if (argvars[0].v_type != VAR_LIST)
14566 EMSG2(_(e_listdictarg), "remove()");
14567 else if ((l = argvars[0].vval.v_list) != NULL
14568 && !tv_check_lock(l->lv_lock, (char_u *)"remove() argument"))
14570 int error = FALSE;
14572 idx = get_tv_number_chk(&argvars[1], &error);
14573 if (error)
14574 ; /* type error: do nothing, errmsg already given */
14575 else if ((item = list_find(l, idx)) == NULL)
14576 EMSGN(_(e_listidx), idx);
14577 else
14579 if (argvars[2].v_type == VAR_UNKNOWN)
14581 /* Remove one item, return its value. */
14582 list_remove(l, item, item);
14583 *rettv = item->li_tv;
14584 vim_free(item);
14586 else
14588 /* Remove range of items, return list with values. */
14589 end = get_tv_number_chk(&argvars[2], &error);
14590 if (error)
14591 ; /* type error: do nothing */
14592 else if ((item2 = list_find(l, end)) == NULL)
14593 EMSGN(_(e_listidx), end);
14594 else
14596 int cnt = 0;
14598 for (li = item; li != NULL; li = li->li_next)
14600 ++cnt;
14601 if (li == item2)
14602 break;
14604 if (li == NULL) /* didn't find "item2" after "item" */
14605 EMSG(_(e_invrange));
14606 else
14608 list_remove(l, item, item2);
14609 if (rettv_list_alloc(rettv) == OK)
14611 l = rettv->vval.v_list;
14612 l->lv_first = item;
14613 l->lv_last = item2;
14614 item->li_prev = NULL;
14615 item2->li_next = NULL;
14616 l->lv_len = cnt;
14626 * "rename({from}, {to})" function
14628 static void
14629 f_rename(argvars, rettv)
14630 typval_T *argvars;
14631 typval_T *rettv;
14633 char_u buf[NUMBUFLEN];
14635 if (check_restricted() || check_secure())
14636 rettv->vval.v_number = -1;
14637 else
14638 rettv->vval.v_number = vim_rename(get_tv_string(&argvars[0]),
14639 get_tv_string_buf(&argvars[1], buf));
14643 * "repeat()" function
14645 static void
14646 f_repeat(argvars, rettv)
14647 typval_T *argvars;
14648 typval_T *rettv;
14650 char_u *p;
14651 int n;
14652 int slen;
14653 int len;
14654 char_u *r;
14655 int i;
14657 n = get_tv_number(&argvars[1]);
14658 if (argvars[0].v_type == VAR_LIST)
14660 if (rettv_list_alloc(rettv) == OK && argvars[0].vval.v_list != NULL)
14661 while (n-- > 0)
14662 if (list_extend(rettv->vval.v_list,
14663 argvars[0].vval.v_list, NULL) == FAIL)
14664 break;
14666 else
14668 p = get_tv_string(&argvars[0]);
14669 rettv->v_type = VAR_STRING;
14670 rettv->vval.v_string = NULL;
14672 slen = (int)STRLEN(p);
14673 len = slen * n;
14674 if (len <= 0)
14675 return;
14677 r = alloc(len + 1);
14678 if (r != NULL)
14680 for (i = 0; i < n; i++)
14681 mch_memmove(r + i * slen, p, (size_t)slen);
14682 r[len] = NUL;
14685 rettv->vval.v_string = r;
14690 * "resolve()" function
14692 static void
14693 f_resolve(argvars, rettv)
14694 typval_T *argvars;
14695 typval_T *rettv;
14697 char_u *p;
14699 p = get_tv_string(&argvars[0]);
14700 #ifdef FEAT_SHORTCUT
14702 char_u *v = NULL;
14704 v = mch_resolve_shortcut(p);
14705 if (v != NULL)
14706 rettv->vval.v_string = v;
14707 else
14708 rettv->vval.v_string = vim_strsave(p);
14710 #else
14711 # ifdef HAVE_READLINK
14713 char_u buf[MAXPATHL + 1];
14714 char_u *cpy;
14715 int len;
14716 char_u *remain = NULL;
14717 char_u *q;
14718 int is_relative_to_current = FALSE;
14719 int has_trailing_pathsep = FALSE;
14720 int limit = 100;
14722 p = vim_strsave(p);
14724 if (p[0] == '.' && (vim_ispathsep(p[1])
14725 || (p[1] == '.' && (vim_ispathsep(p[2])))))
14726 is_relative_to_current = TRUE;
14728 len = STRLEN(p);
14729 if (len > 0 && after_pathsep(p, p + len))
14730 has_trailing_pathsep = TRUE;
14732 q = getnextcomp(p);
14733 if (*q != NUL)
14735 /* Separate the first path component in "p", and keep the
14736 * remainder (beginning with the path separator). */
14737 remain = vim_strsave(q - 1);
14738 q[-1] = NUL;
14741 for (;;)
14743 for (;;)
14745 len = readlink((char *)p, (char *)buf, MAXPATHL);
14746 if (len <= 0)
14747 break;
14748 buf[len] = NUL;
14750 if (limit-- == 0)
14752 vim_free(p);
14753 vim_free(remain);
14754 EMSG(_("E655: Too many symbolic links (cycle?)"));
14755 rettv->vval.v_string = NULL;
14756 goto fail;
14759 /* Ensure that the result will have a trailing path separator
14760 * if the argument has one. */
14761 if (remain == NULL && has_trailing_pathsep)
14762 add_pathsep(buf);
14764 /* Separate the first path component in the link value and
14765 * concatenate the remainders. */
14766 q = getnextcomp(vim_ispathsep(*buf) ? buf + 1 : buf);
14767 if (*q != NUL)
14769 if (remain == NULL)
14770 remain = vim_strsave(q - 1);
14771 else
14773 cpy = concat_str(q - 1, remain);
14774 if (cpy != NULL)
14776 vim_free(remain);
14777 remain = cpy;
14780 q[-1] = NUL;
14783 q = gettail(p);
14784 if (q > p && *q == NUL)
14786 /* Ignore trailing path separator. */
14787 q[-1] = NUL;
14788 q = gettail(p);
14790 if (q > p && !mch_isFullName(buf))
14792 /* symlink is relative to directory of argument */
14793 cpy = alloc((unsigned)(STRLEN(p) + STRLEN(buf) + 1));
14794 if (cpy != NULL)
14796 STRCPY(cpy, p);
14797 STRCPY(gettail(cpy), buf);
14798 vim_free(p);
14799 p = cpy;
14802 else
14804 vim_free(p);
14805 p = vim_strsave(buf);
14809 if (remain == NULL)
14810 break;
14812 /* Append the first path component of "remain" to "p". */
14813 q = getnextcomp(remain + 1);
14814 len = q - remain - (*q != NUL);
14815 cpy = vim_strnsave(p, STRLEN(p) + len);
14816 if (cpy != NULL)
14818 STRNCAT(cpy, remain, len);
14819 vim_free(p);
14820 p = cpy;
14822 /* Shorten "remain". */
14823 if (*q != NUL)
14824 STRMOVE(remain, q - 1);
14825 else
14827 vim_free(remain);
14828 remain = NULL;
14832 /* If the result is a relative path name, make it explicitly relative to
14833 * the current directory if and only if the argument had this form. */
14834 if (!vim_ispathsep(*p))
14836 if (is_relative_to_current
14837 && *p != NUL
14838 && !(p[0] == '.'
14839 && (p[1] == NUL
14840 || vim_ispathsep(p[1])
14841 || (p[1] == '.'
14842 && (p[2] == NUL
14843 || vim_ispathsep(p[2]))))))
14845 /* Prepend "./". */
14846 cpy = concat_str((char_u *)"./", p);
14847 if (cpy != NULL)
14849 vim_free(p);
14850 p = cpy;
14853 else if (!is_relative_to_current)
14855 /* Strip leading "./". */
14856 q = p;
14857 while (q[0] == '.' && vim_ispathsep(q[1]))
14858 q += 2;
14859 if (q > p)
14860 STRMOVE(p, p + 2);
14864 /* Ensure that the result will have no trailing path separator
14865 * if the argument had none. But keep "/" or "//". */
14866 if (!has_trailing_pathsep)
14868 q = p + STRLEN(p);
14869 if (after_pathsep(p, q))
14870 *gettail_sep(p) = NUL;
14873 rettv->vval.v_string = p;
14875 # else
14876 rettv->vval.v_string = vim_strsave(p);
14877 # endif
14878 #endif
14880 simplify_filename(rettv->vval.v_string);
14882 #ifdef HAVE_READLINK
14883 fail:
14884 #endif
14885 rettv->v_type = VAR_STRING;
14889 * "reverse({list})" function
14891 static void
14892 f_reverse(argvars, rettv)
14893 typval_T *argvars;
14894 typval_T *rettv;
14896 list_T *l;
14897 listitem_T *li, *ni;
14899 if (argvars[0].v_type != VAR_LIST)
14900 EMSG2(_(e_listarg), "reverse()");
14901 else if ((l = argvars[0].vval.v_list) != NULL
14902 && !tv_check_lock(l->lv_lock, (char_u *)"reverse()"))
14904 li = l->lv_last;
14905 l->lv_first = l->lv_last = NULL;
14906 l->lv_len = 0;
14907 while (li != NULL)
14909 ni = li->li_prev;
14910 list_append(l, li);
14911 li = ni;
14913 rettv->vval.v_list = l;
14914 rettv->v_type = VAR_LIST;
14915 ++l->lv_refcount;
14916 l->lv_idx = l->lv_len - l->lv_idx - 1;
14920 #define SP_NOMOVE 0x01 /* don't move cursor */
14921 #define SP_REPEAT 0x02 /* repeat to find outer pair */
14922 #define SP_RETCOUNT 0x04 /* return matchcount */
14923 #define SP_SETPCMARK 0x08 /* set previous context mark */
14924 #define SP_START 0x10 /* accept match at start position */
14925 #define SP_SUBPAT 0x20 /* return nr of matching sub-pattern */
14926 #define SP_END 0x40 /* leave cursor at end of match */
14928 static int get_search_arg __ARGS((typval_T *varp, int *flagsp));
14931 * Get flags for a search function.
14932 * Possibly sets "p_ws".
14933 * Returns BACKWARD, FORWARD or zero (for an error).
14935 static int
14936 get_search_arg(varp, flagsp)
14937 typval_T *varp;
14938 int *flagsp;
14940 int dir = FORWARD;
14941 char_u *flags;
14942 char_u nbuf[NUMBUFLEN];
14943 int mask;
14945 if (varp->v_type != VAR_UNKNOWN)
14947 flags = get_tv_string_buf_chk(varp, nbuf);
14948 if (flags == NULL)
14949 return 0; /* type error; errmsg already given */
14950 while (*flags != NUL)
14952 switch (*flags)
14954 case 'b': dir = BACKWARD; break;
14955 case 'w': p_ws = TRUE; break;
14956 case 'W': p_ws = FALSE; break;
14957 default: mask = 0;
14958 if (flagsp != NULL)
14959 switch (*flags)
14961 case 'c': mask = SP_START; break;
14962 case 'e': mask = SP_END; break;
14963 case 'm': mask = SP_RETCOUNT; break;
14964 case 'n': mask = SP_NOMOVE; break;
14965 case 'p': mask = SP_SUBPAT; break;
14966 case 'r': mask = SP_REPEAT; break;
14967 case 's': mask = SP_SETPCMARK; break;
14969 if (mask == 0)
14971 EMSG2(_(e_invarg2), flags);
14972 dir = 0;
14974 else
14975 *flagsp |= mask;
14977 if (dir == 0)
14978 break;
14979 ++flags;
14982 return dir;
14986 * Shared by search() and searchpos() functions
14988 static int
14989 search_cmn(argvars, match_pos, flagsp)
14990 typval_T *argvars;
14991 pos_T *match_pos;
14992 int *flagsp;
14994 int flags;
14995 char_u *pat;
14996 pos_T pos;
14997 pos_T save_cursor;
14998 int save_p_ws = p_ws;
14999 int dir;
15000 int retval = 0; /* default: FAIL */
15001 long lnum_stop = 0;
15002 proftime_T tm;
15003 #ifdef FEAT_RELTIME
15004 long time_limit = 0;
15005 #endif
15006 int options = SEARCH_KEEP;
15007 int subpatnum;
15009 pat = get_tv_string(&argvars[0]);
15010 dir = get_search_arg(&argvars[1], flagsp); /* may set p_ws */
15011 if (dir == 0)
15012 goto theend;
15013 flags = *flagsp;
15014 if (flags & SP_START)
15015 options |= SEARCH_START;
15016 if (flags & SP_END)
15017 options |= SEARCH_END;
15019 /* Optional arguments: line number to stop searching and timeout. */
15020 if (argvars[1].v_type != VAR_UNKNOWN && argvars[2].v_type != VAR_UNKNOWN)
15022 lnum_stop = get_tv_number_chk(&argvars[2], NULL);
15023 if (lnum_stop < 0)
15024 goto theend;
15025 #ifdef FEAT_RELTIME
15026 if (argvars[3].v_type != VAR_UNKNOWN)
15028 time_limit = get_tv_number_chk(&argvars[3], NULL);
15029 if (time_limit < 0)
15030 goto theend;
15032 #endif
15035 #ifdef FEAT_RELTIME
15036 /* Set the time limit, if there is one. */
15037 profile_setlimit(time_limit, &tm);
15038 #endif
15041 * This function does not accept SP_REPEAT and SP_RETCOUNT flags.
15042 * Check to make sure only those flags are set.
15043 * Also, Only the SP_NOMOVE or the SP_SETPCMARK flag can be set. Both
15044 * flags cannot be set. Check for that condition also.
15046 if (((flags & (SP_REPEAT | SP_RETCOUNT)) != 0)
15047 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15049 EMSG2(_(e_invarg2), get_tv_string(&argvars[1]));
15050 goto theend;
15053 pos = save_cursor = curwin->w_cursor;
15054 subpatnum = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15055 options, RE_SEARCH, (linenr_T)lnum_stop, &tm);
15056 if (subpatnum != FAIL)
15058 if (flags & SP_SUBPAT)
15059 retval = subpatnum;
15060 else
15061 retval = pos.lnum;
15062 if (flags & SP_SETPCMARK)
15063 setpcmark();
15064 curwin->w_cursor = pos;
15065 if (match_pos != NULL)
15067 /* Store the match cursor position */
15068 match_pos->lnum = pos.lnum;
15069 match_pos->col = pos.col + 1;
15071 /* "/$" will put the cursor after the end of the line, may need to
15072 * correct that here */
15073 check_cursor();
15076 /* If 'n' flag is used: restore cursor position. */
15077 if (flags & SP_NOMOVE)
15078 curwin->w_cursor = save_cursor;
15079 else
15080 curwin->w_set_curswant = TRUE;
15081 theend:
15082 p_ws = save_p_ws;
15084 return retval;
15087 #ifdef FEAT_FLOAT
15089 * "round({float})" function
15091 static void
15092 f_round(argvars, rettv)
15093 typval_T *argvars;
15094 typval_T *rettv;
15096 float_T f;
15098 rettv->v_type = VAR_FLOAT;
15099 if (get_float_arg(argvars, &f) == OK)
15100 /* round() is not in C90, use ceil() or floor() instead. */
15101 rettv->vval.v_float = f > 0 ? floor(f + 0.5) : ceil(f - 0.5);
15102 else
15103 rettv->vval.v_float = 0.0;
15105 #endif
15108 * "search()" function
15110 static void
15111 f_search(argvars, rettv)
15112 typval_T *argvars;
15113 typval_T *rettv;
15115 int flags = 0;
15117 rettv->vval.v_number = search_cmn(argvars, NULL, &flags);
15121 * "searchdecl()" function
15123 static void
15124 f_searchdecl(argvars, rettv)
15125 typval_T *argvars;
15126 typval_T *rettv;
15128 int locally = 1;
15129 int thisblock = 0;
15130 int error = FALSE;
15131 char_u *name;
15133 rettv->vval.v_number = 1; /* default: FAIL */
15135 name = get_tv_string_chk(&argvars[0]);
15136 if (argvars[1].v_type != VAR_UNKNOWN)
15138 locally = get_tv_number_chk(&argvars[1], &error) == 0;
15139 if (!error && argvars[2].v_type != VAR_UNKNOWN)
15140 thisblock = get_tv_number_chk(&argvars[2], &error) != 0;
15142 if (!error && name != NULL)
15143 rettv->vval.v_number = find_decl(name, (int)STRLEN(name),
15144 locally, thisblock, SEARCH_KEEP) == FAIL;
15148 * Used by searchpair() and searchpairpos()
15150 static int
15151 searchpair_cmn(argvars, match_pos)
15152 typval_T *argvars;
15153 pos_T *match_pos;
15155 char_u *spat, *mpat, *epat;
15156 char_u *skip;
15157 int save_p_ws = p_ws;
15158 int dir;
15159 int flags = 0;
15160 char_u nbuf1[NUMBUFLEN];
15161 char_u nbuf2[NUMBUFLEN];
15162 char_u nbuf3[NUMBUFLEN];
15163 int retval = 0; /* default: FAIL */
15164 long lnum_stop = 0;
15165 long time_limit = 0;
15167 /* Get the three pattern arguments: start, middle, end. */
15168 spat = get_tv_string_chk(&argvars[0]);
15169 mpat = get_tv_string_buf_chk(&argvars[1], nbuf1);
15170 epat = get_tv_string_buf_chk(&argvars[2], nbuf2);
15171 if (spat == NULL || mpat == NULL || epat == NULL)
15172 goto theend; /* type error */
15174 /* Handle the optional fourth argument: flags */
15175 dir = get_search_arg(&argvars[3], &flags); /* may set p_ws */
15176 if (dir == 0)
15177 goto theend;
15179 /* Don't accept SP_END or SP_SUBPAT.
15180 * Only one of the SP_NOMOVE or SP_SETPCMARK flags can be set.
15182 if ((flags & (SP_END | SP_SUBPAT)) != 0
15183 || ((flags & SP_NOMOVE) && (flags & SP_SETPCMARK)))
15185 EMSG2(_(e_invarg2), get_tv_string(&argvars[3]));
15186 goto theend;
15189 /* Using 'r' implies 'W', otherwise it doesn't work. */
15190 if (flags & SP_REPEAT)
15191 p_ws = FALSE;
15193 /* Optional fifth argument: skip expression */
15194 if (argvars[3].v_type == VAR_UNKNOWN
15195 || argvars[4].v_type == VAR_UNKNOWN)
15196 skip = (char_u *)"";
15197 else
15199 skip = get_tv_string_buf_chk(&argvars[4], nbuf3);
15200 if (argvars[5].v_type != VAR_UNKNOWN)
15202 lnum_stop = get_tv_number_chk(&argvars[5], NULL);
15203 if (lnum_stop < 0)
15204 goto theend;
15205 #ifdef FEAT_RELTIME
15206 if (argvars[6].v_type != VAR_UNKNOWN)
15208 time_limit = get_tv_number_chk(&argvars[6], NULL);
15209 if (time_limit < 0)
15210 goto theend;
15212 #endif
15215 if (skip == NULL)
15216 goto theend; /* type error */
15218 retval = do_searchpair(spat, mpat, epat, dir, skip, flags,
15219 match_pos, lnum_stop, time_limit);
15221 theend:
15222 p_ws = save_p_ws;
15224 return retval;
15228 * "searchpair()" function
15230 static void
15231 f_searchpair(argvars, rettv)
15232 typval_T *argvars;
15233 typval_T *rettv;
15235 rettv->vval.v_number = searchpair_cmn(argvars, NULL);
15239 * "searchpairpos()" function
15241 static void
15242 f_searchpairpos(argvars, rettv)
15243 typval_T *argvars;
15244 typval_T *rettv;
15246 pos_T match_pos;
15247 int lnum = 0;
15248 int col = 0;
15250 if (rettv_list_alloc(rettv) == FAIL)
15251 return;
15253 if (searchpair_cmn(argvars, &match_pos) > 0)
15255 lnum = match_pos.lnum;
15256 col = match_pos.col;
15259 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15260 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15264 * Search for a start/middle/end thing.
15265 * Used by searchpair(), see its documentation for the details.
15266 * Returns 0 or -1 for no match,
15268 long
15269 do_searchpair(spat, mpat, epat, dir, skip, flags, match_pos,
15270 lnum_stop, time_limit)
15271 char_u *spat; /* start pattern */
15272 char_u *mpat; /* middle pattern */
15273 char_u *epat; /* end pattern */
15274 int dir; /* BACKWARD or FORWARD */
15275 char_u *skip; /* skip expression */
15276 int flags; /* SP_SETPCMARK and other SP_ values */
15277 pos_T *match_pos;
15278 linenr_T lnum_stop; /* stop at this line if not zero */
15279 long time_limit; /* stop after this many msec */
15281 char_u *save_cpo;
15282 char_u *pat, *pat2 = NULL, *pat3 = NULL;
15283 long retval = 0;
15284 pos_T pos;
15285 pos_T firstpos;
15286 pos_T foundpos;
15287 pos_T save_cursor;
15288 pos_T save_pos;
15289 int n;
15290 int r;
15291 int nest = 1;
15292 int err;
15293 int options = SEARCH_KEEP;
15294 proftime_T tm;
15296 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
15297 save_cpo = p_cpo;
15298 p_cpo = empty_option;
15300 #ifdef FEAT_RELTIME
15301 /* Set the time limit, if there is one. */
15302 profile_setlimit(time_limit, &tm);
15303 #endif
15305 /* Make two search patterns: start/end (pat2, for in nested pairs) and
15306 * start/middle/end (pat3, for the top pair). */
15307 pat2 = alloc((unsigned)(STRLEN(spat) + STRLEN(epat) + 15));
15308 pat3 = alloc((unsigned)(STRLEN(spat) + STRLEN(mpat) + STRLEN(epat) + 23));
15309 if (pat2 == NULL || pat3 == NULL)
15310 goto theend;
15311 sprintf((char *)pat2, "\\(%s\\m\\)\\|\\(%s\\m\\)", spat, epat);
15312 if (*mpat == NUL)
15313 STRCPY(pat3, pat2);
15314 else
15315 sprintf((char *)pat3, "\\(%s\\m\\)\\|\\(%s\\m\\)\\|\\(%s\\m\\)",
15316 spat, epat, mpat);
15317 if (flags & SP_START)
15318 options |= SEARCH_START;
15320 save_cursor = curwin->w_cursor;
15321 pos = curwin->w_cursor;
15322 clearpos(&firstpos);
15323 clearpos(&foundpos);
15324 pat = pat3;
15325 for (;;)
15327 n = searchit(curwin, curbuf, &pos, dir, pat, 1L,
15328 options, RE_SEARCH, lnum_stop, &tm);
15329 if (n == FAIL || (firstpos.lnum != 0 && equalpos(pos, firstpos)))
15330 /* didn't find it or found the first match again: FAIL */
15331 break;
15333 if (firstpos.lnum == 0)
15334 firstpos = pos;
15335 if (equalpos(pos, foundpos))
15337 /* Found the same position again. Can happen with a pattern that
15338 * has "\zs" at the end and searching backwards. Advance one
15339 * character and try again. */
15340 if (dir == BACKWARD)
15341 decl(&pos);
15342 else
15343 incl(&pos);
15345 foundpos = pos;
15347 /* clear the start flag to avoid getting stuck here */
15348 options &= ~SEARCH_START;
15350 /* If the skip pattern matches, ignore this match. */
15351 if (*skip != NUL)
15353 save_pos = curwin->w_cursor;
15354 curwin->w_cursor = pos;
15355 r = eval_to_bool(skip, &err, NULL, FALSE);
15356 curwin->w_cursor = save_pos;
15357 if (err)
15359 /* Evaluating {skip} caused an error, break here. */
15360 curwin->w_cursor = save_cursor;
15361 retval = -1;
15362 break;
15364 if (r)
15365 continue;
15368 if ((dir == BACKWARD && n == 3) || (dir == FORWARD && n == 2))
15370 /* Found end when searching backwards or start when searching
15371 * forward: nested pair. */
15372 ++nest;
15373 pat = pat2; /* nested, don't search for middle */
15375 else
15377 /* Found end when searching forward or start when searching
15378 * backward: end of (nested) pair; or found middle in outer pair. */
15379 if (--nest == 1)
15380 pat = pat3; /* outer level, search for middle */
15383 if (nest == 0)
15385 /* Found the match: return matchcount or line number. */
15386 if (flags & SP_RETCOUNT)
15387 ++retval;
15388 else
15389 retval = pos.lnum;
15390 if (flags & SP_SETPCMARK)
15391 setpcmark();
15392 curwin->w_cursor = pos;
15393 if (!(flags & SP_REPEAT))
15394 break;
15395 nest = 1; /* search for next unmatched */
15399 if (match_pos != NULL)
15401 /* Store the match cursor position */
15402 match_pos->lnum = curwin->w_cursor.lnum;
15403 match_pos->col = curwin->w_cursor.col + 1;
15406 /* If 'n' flag is used or search failed: restore cursor position. */
15407 if ((flags & SP_NOMOVE) || retval == 0)
15408 curwin->w_cursor = save_cursor;
15410 theend:
15411 vim_free(pat2);
15412 vim_free(pat3);
15413 if (p_cpo == empty_option)
15414 p_cpo = save_cpo;
15415 else
15416 /* Darn, evaluating the {skip} expression changed the value. */
15417 free_string_option(save_cpo);
15419 return retval;
15423 * "searchpos()" function
15425 static void
15426 f_searchpos(argvars, rettv)
15427 typval_T *argvars;
15428 typval_T *rettv;
15430 pos_T match_pos;
15431 int lnum = 0;
15432 int col = 0;
15433 int n;
15434 int flags = 0;
15436 if (rettv_list_alloc(rettv) == FAIL)
15437 return;
15439 n = search_cmn(argvars, &match_pos, &flags);
15440 if (n > 0)
15442 lnum = match_pos.lnum;
15443 col = match_pos.col;
15446 list_append_number(rettv->vval.v_list, (varnumber_T)lnum);
15447 list_append_number(rettv->vval.v_list, (varnumber_T)col);
15448 if (flags & SP_SUBPAT)
15449 list_append_number(rettv->vval.v_list, (varnumber_T)n);
15453 static void
15454 f_server2client(argvars, rettv)
15455 typval_T *argvars UNUSED;
15456 typval_T *rettv;
15458 #ifdef FEAT_CLIENTSERVER
15459 char_u buf[NUMBUFLEN];
15460 char_u *server = get_tv_string_chk(&argvars[0]);
15461 char_u *reply = get_tv_string_buf_chk(&argvars[1], buf);
15463 rettv->vval.v_number = -1;
15464 if (server == NULL || reply == NULL)
15465 return;
15466 if (check_restricted() || check_secure())
15467 return;
15468 # ifdef FEAT_X11
15469 if (check_connection() == FAIL)
15470 return;
15471 # endif
15473 if (serverSendReply(server, reply) < 0)
15475 EMSG(_("E258: Unable to send to client"));
15476 return;
15478 rettv->vval.v_number = 0;
15479 #else
15480 rettv->vval.v_number = -1;
15481 #endif
15484 static void
15485 f_serverlist(argvars, rettv)
15486 typval_T *argvars UNUSED;
15487 typval_T *rettv;
15489 char_u *r = NULL;
15491 #ifdef FEAT_CLIENTSERVER
15492 # ifdef WIN32
15493 r = serverGetVimNames();
15494 # else
15495 make_connection();
15496 if (X_DISPLAY != NULL)
15497 r = serverGetVimNames(X_DISPLAY);
15498 # endif
15499 #endif
15500 rettv->v_type = VAR_STRING;
15501 rettv->vval.v_string = r;
15505 * "setbufvar()" function
15507 static void
15508 f_setbufvar(argvars, rettv)
15509 typval_T *argvars;
15510 typval_T *rettv UNUSED;
15512 buf_T *buf;
15513 aco_save_T aco;
15514 char_u *varname, *bufvarname;
15515 typval_T *varp;
15516 char_u nbuf[NUMBUFLEN];
15518 if (check_restricted() || check_secure())
15519 return;
15520 (void)get_tv_number(&argvars[0]); /* issue errmsg if type error */
15521 varname = get_tv_string_chk(&argvars[1]);
15522 buf = get_buf_tv(&argvars[0]);
15523 varp = &argvars[2];
15525 if (buf != NULL && varname != NULL && varp != NULL)
15527 /* set curbuf to be our buf, temporarily */
15528 aucmd_prepbuf(&aco, buf);
15530 if (*varname == '&')
15532 long numval;
15533 char_u *strval;
15534 int error = FALSE;
15536 ++varname;
15537 numval = get_tv_number_chk(varp, &error);
15538 strval = get_tv_string_buf_chk(varp, nbuf);
15539 if (!error && strval != NULL)
15540 set_option_value(varname, numval, strval, OPT_LOCAL);
15542 else
15544 bufvarname = alloc((unsigned)STRLEN(varname) + 3);
15545 if (bufvarname != NULL)
15547 STRCPY(bufvarname, "b:");
15548 STRCPY(bufvarname + 2, varname);
15549 set_var(bufvarname, varp, TRUE);
15550 vim_free(bufvarname);
15554 /* reset notion of buffer */
15555 aucmd_restbuf(&aco);
15560 * "setcmdpos()" function
15562 static void
15563 f_setcmdpos(argvars, rettv)
15564 typval_T *argvars;
15565 typval_T *rettv;
15567 int pos = (int)get_tv_number(&argvars[0]) - 1;
15569 if (pos >= 0)
15570 rettv->vval.v_number = set_cmdline_pos(pos);
15574 * "setline()" function
15576 static void
15577 f_setline(argvars, rettv)
15578 typval_T *argvars;
15579 typval_T *rettv;
15581 linenr_T lnum;
15582 char_u *line = NULL;
15583 list_T *l = NULL;
15584 listitem_T *li = NULL;
15585 long added = 0;
15586 linenr_T lcount = curbuf->b_ml.ml_line_count;
15588 lnum = get_tv_lnum(&argvars[0]);
15589 if (argvars[1].v_type == VAR_LIST)
15591 l = argvars[1].vval.v_list;
15592 li = l->lv_first;
15594 else
15595 line = get_tv_string_chk(&argvars[1]);
15597 /* default result is zero == OK */
15598 for (;;)
15600 if (l != NULL)
15602 /* list argument, get next string */
15603 if (li == NULL)
15604 break;
15605 line = get_tv_string_chk(&li->li_tv);
15606 li = li->li_next;
15609 rettv->vval.v_number = 1; /* FAIL */
15610 if (line == NULL || lnum < 1 || lnum > curbuf->b_ml.ml_line_count + 1)
15611 break;
15612 if (lnum <= curbuf->b_ml.ml_line_count)
15614 /* existing line, replace it */
15615 if (u_savesub(lnum) == OK && ml_replace(lnum, line, TRUE) == OK)
15617 changed_bytes(lnum, 0);
15618 if (lnum == curwin->w_cursor.lnum)
15619 check_cursor_col();
15620 rettv->vval.v_number = 0; /* OK */
15623 else if (added > 0 || u_save(lnum - 1, lnum) == OK)
15625 /* lnum is one past the last line, append the line */
15626 ++added;
15627 if (ml_append(lnum - 1, line, (colnr_T)0, FALSE) == OK)
15628 rettv->vval.v_number = 0; /* OK */
15631 if (l == NULL) /* only one string argument */
15632 break;
15633 ++lnum;
15636 if (added > 0)
15637 appended_lines_mark(lcount, added);
15640 static void set_qf_ll_list __ARGS((win_T *wp, typval_T *list_arg, typval_T *action_arg, typval_T *rettv));
15643 * Used by "setqflist()" and "setloclist()" functions
15645 static void
15646 set_qf_ll_list(wp, list_arg, action_arg, rettv)
15647 win_T *wp UNUSED;
15648 typval_T *list_arg UNUSED;
15649 typval_T *action_arg UNUSED;
15650 typval_T *rettv;
15652 #ifdef FEAT_QUICKFIX
15653 char_u *act;
15654 int action = ' ';
15655 #endif
15657 rettv->vval.v_number = -1;
15659 #ifdef FEAT_QUICKFIX
15660 if (list_arg->v_type != VAR_LIST)
15661 EMSG(_(e_listreq));
15662 else
15664 list_T *l = list_arg->vval.v_list;
15666 if (action_arg->v_type == VAR_STRING)
15668 act = get_tv_string_chk(action_arg);
15669 if (act == NULL)
15670 return; /* type error; errmsg already given */
15671 if (*act == 'a' || *act == 'r')
15672 action = *act;
15675 if (l != NULL && set_errorlist(wp, l, action) == OK)
15676 rettv->vval.v_number = 0;
15678 #endif
15682 * "setloclist()" function
15684 static void
15685 f_setloclist(argvars, rettv)
15686 typval_T *argvars;
15687 typval_T *rettv;
15689 win_T *win;
15691 rettv->vval.v_number = -1;
15693 win = find_win_by_nr(&argvars[0], NULL);
15694 if (win != NULL)
15695 set_qf_ll_list(win, &argvars[1], &argvars[2], rettv);
15699 * "setmatches()" function
15701 static void
15702 f_setmatches(argvars, rettv)
15703 typval_T *argvars;
15704 typval_T *rettv;
15706 #ifdef FEAT_SEARCH_EXTRA
15707 list_T *l;
15708 listitem_T *li;
15709 dict_T *d;
15711 rettv->vval.v_number = -1;
15712 if (argvars[0].v_type != VAR_LIST)
15714 EMSG(_(e_listreq));
15715 return;
15717 if ((l = argvars[0].vval.v_list) != NULL)
15720 /* To some extent make sure that we are dealing with a list from
15721 * "getmatches()". */
15722 li = l->lv_first;
15723 while (li != NULL)
15725 if (li->li_tv.v_type != VAR_DICT
15726 || (d = li->li_tv.vval.v_dict) == NULL)
15728 EMSG(_(e_invarg));
15729 return;
15731 if (!(dict_find(d, (char_u *)"group", -1) != NULL
15732 && dict_find(d, (char_u *)"pattern", -1) != NULL
15733 && dict_find(d, (char_u *)"priority", -1) != NULL
15734 && dict_find(d, (char_u *)"id", -1) != NULL))
15736 EMSG(_(e_invarg));
15737 return;
15739 li = li->li_next;
15742 clear_matches(curwin);
15743 li = l->lv_first;
15744 while (li != NULL)
15746 d = li->li_tv.vval.v_dict;
15747 match_add(curwin, get_dict_string(d, (char_u *)"group", FALSE),
15748 get_dict_string(d, (char_u *)"pattern", FALSE),
15749 (int)get_dict_number(d, (char_u *)"priority"),
15750 (int)get_dict_number(d, (char_u *)"id"));
15751 li = li->li_next;
15753 rettv->vval.v_number = 0;
15755 #endif
15759 * "setpos()" function
15761 static void
15762 f_setpos(argvars, rettv)
15763 typval_T *argvars;
15764 typval_T *rettv;
15766 pos_T pos;
15767 int fnum;
15768 char_u *name;
15770 rettv->vval.v_number = -1;
15771 name = get_tv_string_chk(argvars);
15772 if (name != NULL)
15774 if (list2fpos(&argvars[1], &pos, &fnum) == OK)
15776 if (--pos.col < 0)
15777 pos.col = 0;
15778 if (name[0] == '.' && name[1] == NUL)
15780 /* set cursor */
15781 if (fnum == curbuf->b_fnum)
15783 curwin->w_cursor = pos;
15784 check_cursor();
15785 rettv->vval.v_number = 0;
15787 else
15788 EMSG(_(e_invarg));
15790 else if (name[0] == '\'' && name[1] != NUL && name[2] == NUL)
15792 /* set mark */
15793 if (setmark_pos(name[1], &pos, fnum) == OK)
15794 rettv->vval.v_number = 0;
15796 else
15797 EMSG(_(e_invarg));
15803 * "setqflist()" function
15805 static void
15806 f_setqflist(argvars, rettv)
15807 typval_T *argvars;
15808 typval_T *rettv;
15810 set_qf_ll_list(NULL, &argvars[0], &argvars[1], rettv);
15814 * "setreg()" function
15816 static void
15817 f_setreg(argvars, rettv)
15818 typval_T *argvars;
15819 typval_T *rettv;
15821 int regname;
15822 char_u *strregname;
15823 char_u *stropt;
15824 char_u *strval;
15825 int append;
15826 char_u yank_type;
15827 long block_len;
15829 block_len = -1;
15830 yank_type = MAUTO;
15831 append = FALSE;
15833 strregname = get_tv_string_chk(argvars);
15834 rettv->vval.v_number = 1; /* FAIL is default */
15836 if (strregname == NULL)
15837 return; /* type error; errmsg already given */
15838 regname = *strregname;
15839 if (regname == 0 || regname == '@')
15840 regname = '"';
15841 else if (regname == '=')
15842 return;
15844 if (argvars[2].v_type != VAR_UNKNOWN)
15846 stropt = get_tv_string_chk(&argvars[2]);
15847 if (stropt == NULL)
15848 return; /* type error */
15849 for (; *stropt != NUL; ++stropt)
15850 switch (*stropt)
15852 case 'a': case 'A': /* append */
15853 append = TRUE;
15854 break;
15855 case 'v': case 'c': /* character-wise selection */
15856 yank_type = MCHAR;
15857 break;
15858 case 'V': case 'l': /* line-wise selection */
15859 yank_type = MLINE;
15860 break;
15861 #ifdef FEAT_VISUAL
15862 case 'b': case Ctrl_V: /* block-wise selection */
15863 yank_type = MBLOCK;
15864 if (VIM_ISDIGIT(stropt[1]))
15866 ++stropt;
15867 block_len = getdigits(&stropt) - 1;
15868 --stropt;
15870 break;
15871 #endif
15875 strval = get_tv_string_chk(&argvars[1]);
15876 if (strval != NULL)
15877 write_reg_contents_ex(regname, strval, -1,
15878 append, yank_type, block_len);
15879 rettv->vval.v_number = 0;
15883 * "settabwinvar()" function
15885 static void
15886 f_settabwinvar(argvars, rettv)
15887 typval_T *argvars;
15888 typval_T *rettv;
15890 setwinvar(argvars, rettv, 1);
15894 * "setwinvar()" function
15896 static void
15897 f_setwinvar(argvars, rettv)
15898 typval_T *argvars;
15899 typval_T *rettv;
15901 setwinvar(argvars, rettv, 0);
15905 * "setwinvar()" and "settabwinvar()" functions
15907 static void
15908 setwinvar(argvars, rettv, off)
15909 typval_T *argvars;
15910 typval_T *rettv UNUSED;
15911 int off;
15913 win_T *win;
15914 #ifdef FEAT_WINDOWS
15915 win_T *save_curwin;
15916 tabpage_T *save_curtab;
15917 #endif
15918 char_u *varname, *winvarname;
15919 typval_T *varp;
15920 char_u nbuf[NUMBUFLEN];
15921 tabpage_T *tp;
15923 if (check_restricted() || check_secure())
15924 return;
15926 #ifdef FEAT_WINDOWS
15927 if (off == 1)
15928 tp = find_tabpage((int)get_tv_number_chk(&argvars[0], NULL));
15929 else
15930 tp = curtab;
15931 #endif
15932 win = find_win_by_nr(&argvars[off], tp);
15933 varname = get_tv_string_chk(&argvars[off + 1]);
15934 varp = &argvars[off + 2];
15936 if (win != NULL && varname != NULL && varp != NULL)
15938 #ifdef FEAT_WINDOWS
15939 /* set curwin to be our win, temporarily */
15940 save_curwin = curwin;
15941 save_curtab = curtab;
15942 goto_tabpage_tp(tp);
15943 if (!win_valid(win))
15944 return;
15945 curwin = win;
15946 curbuf = curwin->w_buffer;
15947 #endif
15949 if (*varname == '&')
15951 long numval;
15952 char_u *strval;
15953 int error = FALSE;
15955 ++varname;
15956 numval = get_tv_number_chk(varp, &error);
15957 strval = get_tv_string_buf_chk(varp, nbuf);
15958 if (!error && strval != NULL)
15959 set_option_value(varname, numval, strval, OPT_LOCAL);
15961 else
15963 winvarname = alloc((unsigned)STRLEN(varname) + 3);
15964 if (winvarname != NULL)
15966 STRCPY(winvarname, "w:");
15967 STRCPY(winvarname + 2, varname);
15968 set_var(winvarname, varp, TRUE);
15969 vim_free(winvarname);
15973 #ifdef FEAT_WINDOWS
15974 /* Restore current tabpage and window, if still valid (autocomands can
15975 * make them invalid). */
15976 if (valid_tabpage(save_curtab))
15977 goto_tabpage_tp(save_curtab);
15978 if (win_valid(save_curwin))
15980 curwin = save_curwin;
15981 curbuf = curwin->w_buffer;
15983 #endif
15988 * "shellescape({string})" function
15990 static void
15991 f_shellescape(argvars, rettv)
15992 typval_T *argvars;
15993 typval_T *rettv;
15995 rettv->vval.v_string = vim_strsave_shellescape(
15996 get_tv_string(&argvars[0]), non_zero_arg(&argvars[1]));
15997 rettv->v_type = VAR_STRING;
16001 * "simplify()" function
16003 static void
16004 f_simplify(argvars, rettv)
16005 typval_T *argvars;
16006 typval_T *rettv;
16008 char_u *p;
16010 p = get_tv_string(&argvars[0]);
16011 rettv->vval.v_string = vim_strsave(p);
16012 simplify_filename(rettv->vval.v_string); /* simplify in place */
16013 rettv->v_type = VAR_STRING;
16016 #ifdef FEAT_FLOAT
16018 * "sin()" function
16020 static void
16021 f_sin(argvars, rettv)
16022 typval_T *argvars;
16023 typval_T *rettv;
16025 float_T f;
16027 rettv->v_type = VAR_FLOAT;
16028 if (get_float_arg(argvars, &f) == OK)
16029 rettv->vval.v_float = sin(f);
16030 else
16031 rettv->vval.v_float = 0.0;
16033 #endif
16035 static int
16036 #ifdef __BORLANDC__
16037 _RTLENTRYF
16038 #endif
16039 item_compare __ARGS((const void *s1, const void *s2));
16040 static int
16041 #ifdef __BORLANDC__
16042 _RTLENTRYF
16043 #endif
16044 item_compare2 __ARGS((const void *s1, const void *s2));
16046 static int item_compare_ic;
16047 static char_u *item_compare_func;
16048 static int item_compare_func_err;
16049 #define ITEM_COMPARE_FAIL 999
16052 * Compare functions for f_sort() below.
16054 static int
16055 #ifdef __BORLANDC__
16056 _RTLENTRYF
16057 #endif
16058 item_compare(s1, s2)
16059 const void *s1;
16060 const void *s2;
16062 char_u *p1, *p2;
16063 char_u *tofree1, *tofree2;
16064 int res;
16065 char_u numbuf1[NUMBUFLEN];
16066 char_u numbuf2[NUMBUFLEN];
16068 p1 = tv2string(&(*(listitem_T **)s1)->li_tv, &tofree1, numbuf1, 0);
16069 p2 = tv2string(&(*(listitem_T **)s2)->li_tv, &tofree2, numbuf2, 0);
16070 if (p1 == NULL)
16071 p1 = (char_u *)"";
16072 if (p2 == NULL)
16073 p2 = (char_u *)"";
16074 if (item_compare_ic)
16075 res = STRICMP(p1, p2);
16076 else
16077 res = STRCMP(p1, p2);
16078 vim_free(tofree1);
16079 vim_free(tofree2);
16080 return res;
16083 static int
16084 #ifdef __BORLANDC__
16085 _RTLENTRYF
16086 #endif
16087 item_compare2(s1, s2)
16088 const void *s1;
16089 const void *s2;
16091 int res;
16092 typval_T rettv;
16093 typval_T argv[3];
16094 int dummy;
16096 /* shortcut after failure in previous call; compare all items equal */
16097 if (item_compare_func_err)
16098 return 0;
16100 /* copy the values. This is needed to be able to set v_lock to VAR_FIXED
16101 * in the copy without changing the original list items. */
16102 copy_tv(&(*(listitem_T **)s1)->li_tv, &argv[0]);
16103 copy_tv(&(*(listitem_T **)s2)->li_tv, &argv[1]);
16105 rettv.v_type = VAR_UNKNOWN; /* clear_tv() uses this */
16106 res = call_func(item_compare_func, (int)STRLEN(item_compare_func),
16107 &rettv, 2, argv, 0L, 0L, &dummy, TRUE, NULL);
16108 clear_tv(&argv[0]);
16109 clear_tv(&argv[1]);
16111 if (res == FAIL)
16112 res = ITEM_COMPARE_FAIL;
16113 else
16114 res = get_tv_number_chk(&rettv, &item_compare_func_err);
16115 if (item_compare_func_err)
16116 res = ITEM_COMPARE_FAIL; /* return value has wrong type */
16117 clear_tv(&rettv);
16118 return res;
16122 * "sort({list})" function
16124 static void
16125 f_sort(argvars, rettv)
16126 typval_T *argvars;
16127 typval_T *rettv;
16129 list_T *l;
16130 listitem_T *li;
16131 listitem_T **ptrs;
16132 long len;
16133 long i;
16135 if (argvars[0].v_type != VAR_LIST)
16136 EMSG2(_(e_listarg), "sort()");
16137 else
16139 l = argvars[0].vval.v_list;
16140 if (l == NULL || tv_check_lock(l->lv_lock, (char_u *)"sort()"))
16141 return;
16142 rettv->vval.v_list = l;
16143 rettv->v_type = VAR_LIST;
16144 ++l->lv_refcount;
16146 len = list_len(l);
16147 if (len <= 1)
16148 return; /* short list sorts pretty quickly */
16150 item_compare_ic = FALSE;
16151 item_compare_func = NULL;
16152 if (argvars[1].v_type != VAR_UNKNOWN)
16154 if (argvars[1].v_type == VAR_FUNC)
16155 item_compare_func = argvars[1].vval.v_string;
16156 else
16158 int error = FALSE;
16160 i = get_tv_number_chk(&argvars[1], &error);
16161 if (error)
16162 return; /* type error; errmsg already given */
16163 if (i == 1)
16164 item_compare_ic = TRUE;
16165 else
16166 item_compare_func = get_tv_string(&argvars[1]);
16170 /* Make an array with each entry pointing to an item in the List. */
16171 ptrs = (listitem_T **)alloc((int)(len * sizeof(listitem_T *)));
16172 if (ptrs == NULL)
16173 return;
16174 i = 0;
16175 for (li = l->lv_first; li != NULL; li = li->li_next)
16176 ptrs[i++] = li;
16178 item_compare_func_err = FALSE;
16179 /* test the compare function */
16180 if (item_compare_func != NULL
16181 && item_compare2((void *)&ptrs[0], (void *)&ptrs[1])
16182 == ITEM_COMPARE_FAIL)
16183 EMSG(_("E702: Sort compare function failed"));
16184 else
16186 /* Sort the array with item pointers. */
16187 qsort((void *)ptrs, (size_t)len, sizeof(listitem_T *),
16188 item_compare_func == NULL ? item_compare : item_compare2);
16190 if (!item_compare_func_err)
16192 /* Clear the List and append the items in the sorted order. */
16193 l->lv_first = l->lv_last = l->lv_idx_item = NULL;
16194 l->lv_len = 0;
16195 for (i = 0; i < len; ++i)
16196 list_append(l, ptrs[i]);
16200 vim_free(ptrs);
16205 * "soundfold({word})" function
16207 static void
16208 f_soundfold(argvars, rettv)
16209 typval_T *argvars;
16210 typval_T *rettv;
16212 char_u *s;
16214 rettv->v_type = VAR_STRING;
16215 s = get_tv_string(&argvars[0]);
16216 #ifdef FEAT_SPELL
16217 rettv->vval.v_string = eval_soundfold(s);
16218 #else
16219 rettv->vval.v_string = vim_strsave(s);
16220 #endif
16224 * "spellbadword()" function
16226 static void
16227 f_spellbadword(argvars, rettv)
16228 typval_T *argvars UNUSED;
16229 typval_T *rettv;
16231 char_u *word = (char_u *)"";
16232 hlf_T attr = HLF_COUNT;
16233 int len = 0;
16235 if (rettv_list_alloc(rettv) == FAIL)
16236 return;
16238 #ifdef FEAT_SPELL
16239 if (argvars[0].v_type == VAR_UNKNOWN)
16241 /* Find the start and length of the badly spelled word. */
16242 len = spell_move_to(curwin, FORWARD, TRUE, TRUE, &attr);
16243 if (len != 0)
16244 word = ml_get_cursor();
16246 else if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16248 char_u *str = get_tv_string_chk(&argvars[0]);
16249 int capcol = -1;
16251 if (str != NULL)
16253 /* Check the argument for spelling. */
16254 while (*str != NUL)
16256 len = spell_check(curwin, str, &attr, &capcol, FALSE);
16257 if (attr != HLF_COUNT)
16259 word = str;
16260 break;
16262 str += len;
16266 #endif
16268 list_append_string(rettv->vval.v_list, word, len);
16269 list_append_string(rettv->vval.v_list, (char_u *)(
16270 attr == HLF_SPB ? "bad" :
16271 attr == HLF_SPR ? "rare" :
16272 attr == HLF_SPL ? "local" :
16273 attr == HLF_SPC ? "caps" :
16274 ""), -1);
16278 * "spellsuggest()" function
16280 static void
16281 f_spellsuggest(argvars, rettv)
16282 typval_T *argvars UNUSED;
16283 typval_T *rettv;
16285 #ifdef FEAT_SPELL
16286 char_u *str;
16287 int typeerr = FALSE;
16288 int maxcount;
16289 garray_T ga;
16290 int i;
16291 listitem_T *li;
16292 int need_capital = FALSE;
16293 #endif
16295 if (rettv_list_alloc(rettv) == FAIL)
16296 return;
16298 #ifdef FEAT_SPELL
16299 if (curwin->w_p_spell && *curbuf->b_p_spl != NUL)
16301 str = get_tv_string(&argvars[0]);
16302 if (argvars[1].v_type != VAR_UNKNOWN)
16304 maxcount = get_tv_number_chk(&argvars[1], &typeerr);
16305 if (maxcount <= 0)
16306 return;
16307 if (argvars[2].v_type != VAR_UNKNOWN)
16309 need_capital = get_tv_number_chk(&argvars[2], &typeerr);
16310 if (typeerr)
16311 return;
16314 else
16315 maxcount = 25;
16317 spell_suggest_list(&ga, str, maxcount, need_capital, FALSE);
16319 for (i = 0; i < ga.ga_len; ++i)
16321 str = ((char_u **)ga.ga_data)[i];
16323 li = listitem_alloc();
16324 if (li == NULL)
16325 vim_free(str);
16326 else
16328 li->li_tv.v_type = VAR_STRING;
16329 li->li_tv.v_lock = 0;
16330 li->li_tv.vval.v_string = str;
16331 list_append(rettv->vval.v_list, li);
16334 ga_clear(&ga);
16336 #endif
16339 static void
16340 f_split(argvars, rettv)
16341 typval_T *argvars;
16342 typval_T *rettv;
16344 char_u *str;
16345 char_u *end;
16346 char_u *pat = NULL;
16347 regmatch_T regmatch;
16348 char_u patbuf[NUMBUFLEN];
16349 char_u *save_cpo;
16350 int match;
16351 colnr_T col = 0;
16352 int keepempty = FALSE;
16353 int typeerr = FALSE;
16355 /* Make 'cpoptions' empty, the 'l' flag should not be used here. */
16356 save_cpo = p_cpo;
16357 p_cpo = (char_u *)"";
16359 str = get_tv_string(&argvars[0]);
16360 if (argvars[1].v_type != VAR_UNKNOWN)
16362 pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16363 if (pat == NULL)
16364 typeerr = TRUE;
16365 if (argvars[2].v_type != VAR_UNKNOWN)
16366 keepempty = get_tv_number_chk(&argvars[2], &typeerr);
16368 if (pat == NULL || *pat == NUL)
16369 pat = (char_u *)"[\\x01- ]\\+";
16371 if (rettv_list_alloc(rettv) == FAIL)
16372 return;
16373 if (typeerr)
16374 return;
16376 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
16377 if (regmatch.regprog != NULL)
16379 regmatch.rm_ic = FALSE;
16380 while (*str != NUL || keepempty)
16382 if (*str == NUL)
16383 match = FALSE; /* empty item at the end */
16384 else
16385 match = vim_regexec_nl(&regmatch, str, col);
16386 if (match)
16387 end = regmatch.startp[0];
16388 else
16389 end = str + STRLEN(str);
16390 if (keepempty || end > str || (rettv->vval.v_list->lv_len > 0
16391 && *str != NUL && match && end < regmatch.endp[0]))
16393 if (list_append_string(rettv->vval.v_list, str,
16394 (int)(end - str)) == FAIL)
16395 break;
16397 if (!match)
16398 break;
16399 /* Advance to just after the match. */
16400 if (regmatch.endp[0] > str)
16401 col = 0;
16402 else
16404 /* Don't get stuck at the same match. */
16405 #ifdef FEAT_MBYTE
16406 col = (*mb_ptr2len)(regmatch.endp[0]);
16407 #else
16408 col = 1;
16409 #endif
16411 str = regmatch.endp[0];
16414 vim_free(regmatch.regprog);
16417 p_cpo = save_cpo;
16420 #ifdef FEAT_FLOAT
16422 * "sqrt()" function
16424 static void
16425 f_sqrt(argvars, rettv)
16426 typval_T *argvars;
16427 typval_T *rettv;
16429 float_T f;
16431 rettv->v_type = VAR_FLOAT;
16432 if (get_float_arg(argvars, &f) == OK)
16433 rettv->vval.v_float = sqrt(f);
16434 else
16435 rettv->vval.v_float = 0.0;
16439 * "str2float()" function
16441 static void
16442 f_str2float(argvars, rettv)
16443 typval_T *argvars;
16444 typval_T *rettv;
16446 char_u *p = skipwhite(get_tv_string(&argvars[0]));
16448 if (*p == '+')
16449 p = skipwhite(p + 1);
16450 (void)string2float(p, &rettv->vval.v_float);
16451 rettv->v_type = VAR_FLOAT;
16453 #endif
16456 * "str2nr()" function
16458 static void
16459 f_str2nr(argvars, rettv)
16460 typval_T *argvars;
16461 typval_T *rettv;
16463 int base = 10;
16464 char_u *p;
16465 long n;
16467 if (argvars[1].v_type != VAR_UNKNOWN)
16469 base = get_tv_number(&argvars[1]);
16470 if (base != 8 && base != 10 && base != 16)
16472 EMSG(_(e_invarg));
16473 return;
16477 p = skipwhite(get_tv_string(&argvars[0]));
16478 if (*p == '+')
16479 p = skipwhite(p + 1);
16480 vim_str2nr(p, NULL, NULL, base == 8 ? 2 : 0, base == 16 ? 2 : 0, &n, NULL);
16481 rettv->vval.v_number = n;
16484 #ifdef HAVE_STRFTIME
16486 * "strftime({format}[, {time}])" function
16488 static void
16489 f_strftime(argvars, rettv)
16490 typval_T *argvars;
16491 typval_T *rettv;
16493 char_u result_buf[256];
16494 struct tm *curtime;
16495 time_t seconds;
16496 char_u *p;
16498 rettv->v_type = VAR_STRING;
16500 p = get_tv_string(&argvars[0]);
16501 if (argvars[1].v_type == VAR_UNKNOWN)
16502 seconds = time(NULL);
16503 else
16504 seconds = (time_t)get_tv_number(&argvars[1]);
16505 curtime = localtime(&seconds);
16506 /* MSVC returns NULL for an invalid value of seconds. */
16507 if (curtime == NULL)
16508 rettv->vval.v_string = vim_strsave((char_u *)_("(Invalid)"));
16509 else
16511 # ifdef FEAT_MBYTE
16512 vimconv_T conv;
16513 char_u *enc;
16515 conv.vc_type = CONV_NONE;
16516 enc = enc_locale();
16517 convert_setup(&conv, p_enc, enc);
16518 if (conv.vc_type != CONV_NONE)
16519 p = string_convert(&conv, p, NULL);
16520 # endif
16521 if (p != NULL)
16522 (void)strftime((char *)result_buf, sizeof(result_buf),
16523 (char *)p, curtime);
16524 else
16525 result_buf[0] = NUL;
16527 # ifdef FEAT_MBYTE
16528 if (conv.vc_type != CONV_NONE)
16529 vim_free(p);
16530 convert_setup(&conv, enc, p_enc);
16531 if (conv.vc_type != CONV_NONE)
16532 rettv->vval.v_string = string_convert(&conv, result_buf, NULL);
16533 else
16534 # endif
16535 rettv->vval.v_string = vim_strsave(result_buf);
16537 # ifdef FEAT_MBYTE
16538 /* Release conversion descriptors */
16539 convert_setup(&conv, NULL, NULL);
16540 vim_free(enc);
16541 # endif
16544 #endif
16547 * "stridx()" function
16549 static void
16550 f_stridx(argvars, rettv)
16551 typval_T *argvars;
16552 typval_T *rettv;
16554 char_u buf[NUMBUFLEN];
16555 char_u *needle;
16556 char_u *haystack;
16557 char_u *save_haystack;
16558 char_u *pos;
16559 int start_idx;
16561 needle = get_tv_string_chk(&argvars[1]);
16562 save_haystack = haystack = get_tv_string_buf_chk(&argvars[0], buf);
16563 rettv->vval.v_number = -1;
16564 if (needle == NULL || haystack == NULL)
16565 return; /* type error; errmsg already given */
16567 if (argvars[2].v_type != VAR_UNKNOWN)
16569 int error = FALSE;
16571 start_idx = get_tv_number_chk(&argvars[2], &error);
16572 if (error || start_idx >= (int)STRLEN(haystack))
16573 return;
16574 if (start_idx >= 0)
16575 haystack += start_idx;
16578 pos = (char_u *)strstr((char *)haystack, (char *)needle);
16579 if (pos != NULL)
16580 rettv->vval.v_number = (varnumber_T)(pos - save_haystack);
16584 * "string()" function
16586 static void
16587 f_string(argvars, rettv)
16588 typval_T *argvars;
16589 typval_T *rettv;
16591 char_u *tofree;
16592 char_u numbuf[NUMBUFLEN];
16594 rettv->v_type = VAR_STRING;
16595 rettv->vval.v_string = tv2string(&argvars[0], &tofree, numbuf, 0);
16596 /* Make a copy if we have a value but it's not in allocated memory. */
16597 if (rettv->vval.v_string != NULL && tofree == NULL)
16598 rettv->vval.v_string = vim_strsave(rettv->vval.v_string);
16602 * "strlen()" function
16604 static void
16605 f_strlen(argvars, rettv)
16606 typval_T *argvars;
16607 typval_T *rettv;
16609 rettv->vval.v_number = (varnumber_T)(STRLEN(
16610 get_tv_string(&argvars[0])));
16614 * "strpart()" function
16616 static void
16617 f_strpart(argvars, rettv)
16618 typval_T *argvars;
16619 typval_T *rettv;
16621 char_u *p;
16622 int n;
16623 int len;
16624 int slen;
16625 int error = FALSE;
16627 p = get_tv_string(&argvars[0]);
16628 slen = (int)STRLEN(p);
16630 n = get_tv_number_chk(&argvars[1], &error);
16631 if (error)
16632 len = 0;
16633 else if (argvars[2].v_type != VAR_UNKNOWN)
16634 len = get_tv_number(&argvars[2]);
16635 else
16636 len = slen - n; /* default len: all bytes that are available. */
16639 * Only return the overlap between the specified part and the actual
16640 * string.
16642 if (n < 0)
16644 len += n;
16645 n = 0;
16647 else if (n > slen)
16648 n = slen;
16649 if (len < 0)
16650 len = 0;
16651 else if (n + len > slen)
16652 len = slen - n;
16654 rettv->v_type = VAR_STRING;
16655 rettv->vval.v_string = vim_strnsave(p + n, len);
16659 * "strridx()" function
16661 static void
16662 f_strridx(argvars, rettv)
16663 typval_T *argvars;
16664 typval_T *rettv;
16666 char_u buf[NUMBUFLEN];
16667 char_u *needle;
16668 char_u *haystack;
16669 char_u *rest;
16670 char_u *lastmatch = NULL;
16671 int haystack_len, end_idx;
16673 needle = get_tv_string_chk(&argvars[1]);
16674 haystack = get_tv_string_buf_chk(&argvars[0], buf);
16676 rettv->vval.v_number = -1;
16677 if (needle == NULL || haystack == NULL)
16678 return; /* type error; errmsg already given */
16680 haystack_len = (int)STRLEN(haystack);
16681 if (argvars[2].v_type != VAR_UNKNOWN)
16683 /* Third argument: upper limit for index */
16684 end_idx = get_tv_number_chk(&argvars[2], NULL);
16685 if (end_idx < 0)
16686 return; /* can never find a match */
16688 else
16689 end_idx = haystack_len;
16691 if (*needle == NUL)
16693 /* Empty string matches past the end. */
16694 lastmatch = haystack + end_idx;
16696 else
16698 for (rest = haystack; *rest != '\0'; ++rest)
16700 rest = (char_u *)strstr((char *)rest, (char *)needle);
16701 if (rest == NULL || rest > haystack + end_idx)
16702 break;
16703 lastmatch = rest;
16707 if (lastmatch == NULL)
16708 rettv->vval.v_number = -1;
16709 else
16710 rettv->vval.v_number = (varnumber_T)(lastmatch - haystack);
16714 * "strtrans()" function
16716 static void
16717 f_strtrans(argvars, rettv)
16718 typval_T *argvars;
16719 typval_T *rettv;
16721 rettv->v_type = VAR_STRING;
16722 rettv->vval.v_string = transstr(get_tv_string(&argvars[0]));
16726 * "submatch()" function
16728 static void
16729 f_submatch(argvars, rettv)
16730 typval_T *argvars;
16731 typval_T *rettv;
16733 rettv->v_type = VAR_STRING;
16734 rettv->vval.v_string =
16735 reg_submatch((int)get_tv_number_chk(&argvars[0], NULL));
16739 * "substitute()" function
16741 static void
16742 f_substitute(argvars, rettv)
16743 typval_T *argvars;
16744 typval_T *rettv;
16746 char_u patbuf[NUMBUFLEN];
16747 char_u subbuf[NUMBUFLEN];
16748 char_u flagsbuf[NUMBUFLEN];
16750 char_u *str = get_tv_string_chk(&argvars[0]);
16751 char_u *pat = get_tv_string_buf_chk(&argvars[1], patbuf);
16752 char_u *sub = get_tv_string_buf_chk(&argvars[2], subbuf);
16753 char_u *flg = get_tv_string_buf_chk(&argvars[3], flagsbuf);
16755 rettv->v_type = VAR_STRING;
16756 if (str == NULL || pat == NULL || sub == NULL || flg == NULL)
16757 rettv->vval.v_string = NULL;
16758 else
16759 rettv->vval.v_string = do_string_sub(str, pat, sub, flg);
16763 * "synID(lnum, col, trans)" function
16765 static void
16766 f_synID(argvars, rettv)
16767 typval_T *argvars UNUSED;
16768 typval_T *rettv;
16770 int id = 0;
16771 #ifdef FEAT_SYN_HL
16772 long lnum;
16773 long col;
16774 int trans;
16775 int transerr = FALSE;
16777 lnum = get_tv_lnum(argvars); /* -1 on type error */
16778 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16779 trans = get_tv_number_chk(&argvars[2], &transerr);
16781 if (!transerr && lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16782 && col >= 0 && col < (long)STRLEN(ml_get(lnum)))
16783 id = syn_get_id(curwin, lnum, (colnr_T)col, trans, NULL, FALSE);
16784 #endif
16786 rettv->vval.v_number = id;
16790 * "synIDattr(id, what [, mode])" function
16792 static void
16793 f_synIDattr(argvars, rettv)
16794 typval_T *argvars UNUSED;
16795 typval_T *rettv;
16797 char_u *p = NULL;
16798 #ifdef FEAT_SYN_HL
16799 int id;
16800 char_u *what;
16801 char_u *mode;
16802 char_u modebuf[NUMBUFLEN];
16803 int modec;
16805 id = get_tv_number(&argvars[0]);
16806 what = get_tv_string(&argvars[1]);
16807 if (argvars[2].v_type != VAR_UNKNOWN)
16809 mode = get_tv_string_buf(&argvars[2], modebuf);
16810 modec = TOLOWER_ASC(mode[0]);
16811 if (modec != 't' && modec != 'c'
16812 #ifdef FEAT_GUI
16813 && modec != 'g'
16814 #endif
16816 modec = 0; /* replace invalid with current */
16818 else
16820 #ifdef FEAT_GUI
16821 if (gui.in_use)
16822 modec = 'g';
16823 else
16824 #endif
16825 if (t_colors > 1)
16826 modec = 'c';
16827 else
16828 modec = 't';
16832 switch (TOLOWER_ASC(what[0]))
16834 case 'b':
16835 if (TOLOWER_ASC(what[1]) == 'g') /* bg[#] */
16836 p = highlight_color(id, what, modec);
16837 else /* bold */
16838 p = highlight_has_attr(id, HL_BOLD, modec);
16839 break;
16841 case 'f': /* fg[#] or font */
16842 p = highlight_color(id, what, modec);
16843 break;
16845 case 'i':
16846 if (TOLOWER_ASC(what[1]) == 'n') /* inverse */
16847 p = highlight_has_attr(id, HL_INVERSE, modec);
16848 else /* italic */
16849 p = highlight_has_attr(id, HL_ITALIC, modec);
16850 break;
16852 case 'n': /* name */
16853 p = get_highlight_name(NULL, id - 1);
16854 break;
16856 case 'r': /* reverse */
16857 p = highlight_has_attr(id, HL_INVERSE, modec);
16858 break;
16860 case 's':
16861 if (TOLOWER_ASC(what[1]) == 'p') /* sp[#] */
16862 p = highlight_color(id, what, modec);
16863 else /* standout */
16864 p = highlight_has_attr(id, HL_STANDOUT, modec);
16865 break;
16867 case 'u':
16868 if (STRLEN(what) <= 5 || TOLOWER_ASC(what[5]) != 'c')
16869 /* underline */
16870 p = highlight_has_attr(id, HL_UNDERLINE, modec);
16871 else
16872 /* undercurl */
16873 p = highlight_has_attr(id, HL_UNDERCURL, modec);
16874 break;
16877 if (p != NULL)
16878 p = vim_strsave(p);
16879 #endif
16880 rettv->v_type = VAR_STRING;
16881 rettv->vval.v_string = p;
16885 * "synIDtrans(id)" function
16887 static void
16888 f_synIDtrans(argvars, rettv)
16889 typval_T *argvars UNUSED;
16890 typval_T *rettv;
16892 int id;
16894 #ifdef FEAT_SYN_HL
16895 id = get_tv_number(&argvars[0]);
16897 if (id > 0)
16898 id = syn_get_final_id(id);
16899 else
16900 #endif
16901 id = 0;
16903 rettv->vval.v_number = id;
16907 * "synstack(lnum, col)" function
16909 static void
16910 f_synstack(argvars, rettv)
16911 typval_T *argvars UNUSED;
16912 typval_T *rettv;
16914 #ifdef FEAT_SYN_HL
16915 long lnum;
16916 long col;
16917 int i;
16918 int id;
16919 #endif
16921 rettv->v_type = VAR_LIST;
16922 rettv->vval.v_list = NULL;
16924 #ifdef FEAT_SYN_HL
16925 lnum = get_tv_lnum(argvars); /* -1 on type error */
16926 col = get_tv_number(&argvars[1]) - 1; /* -1 on type error */
16928 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count
16929 && col >= 0 && (col == 0 || col < (long)STRLEN(ml_get(lnum)))
16930 && rettv_list_alloc(rettv) != FAIL)
16932 (void)syn_get_id(curwin, lnum, (colnr_T)col, FALSE, NULL, TRUE);
16933 for (i = 0; ; ++i)
16935 id = syn_get_stack_item(i);
16936 if (id < 0)
16937 break;
16938 if (list_append_number(rettv->vval.v_list, id) == FAIL)
16939 break;
16942 #endif
16946 * "system()" function
16948 static void
16949 f_system(argvars, rettv)
16950 typval_T *argvars;
16951 typval_T *rettv;
16953 char_u *res = NULL;
16954 char_u *p;
16955 char_u *infile = NULL;
16956 char_u buf[NUMBUFLEN];
16957 int err = FALSE;
16958 FILE *fd;
16960 if (check_restricted() || check_secure())
16961 goto done;
16963 if (argvars[1].v_type != VAR_UNKNOWN)
16966 * Write the string to a temp file, to be used for input of the shell
16967 * command.
16969 if ((infile = vim_tempname('i')) == NULL)
16971 EMSG(_(e_notmp));
16972 goto done;
16975 fd = mch_fopen((char *)infile, WRITEBIN);
16976 if (fd == NULL)
16978 EMSG2(_(e_notopen), infile);
16979 goto done;
16981 p = get_tv_string_buf_chk(&argvars[1], buf);
16982 if (p == NULL)
16984 fclose(fd);
16985 goto done; /* type error; errmsg already given */
16987 if (fwrite(p, STRLEN(p), 1, fd) != 1)
16988 err = TRUE;
16989 if (fclose(fd) != 0)
16990 err = TRUE;
16991 if (err)
16993 EMSG(_("E677: Error writing temp file"));
16994 goto done;
16998 res = get_cmd_output(get_tv_string(&argvars[0]), infile,
16999 SHELL_SILENT | SHELL_COOKED);
17001 #ifdef USE_CR
17002 /* translate <CR> into <NL> */
17003 if (res != NULL)
17005 char_u *s;
17007 for (s = res; *s; ++s)
17009 if (*s == CAR)
17010 *s = NL;
17013 #else
17014 # ifdef USE_CRNL
17015 /* translate <CR><NL> into <NL> */
17016 if (res != NULL)
17018 char_u *s, *d;
17020 d = res;
17021 for (s = res; *s; ++s)
17023 if (s[0] == CAR && s[1] == NL)
17024 ++s;
17025 *d++ = *s;
17027 *d = NUL;
17029 # endif
17030 #endif
17032 done:
17033 if (infile != NULL)
17035 mch_remove(infile);
17036 vim_free(infile);
17038 rettv->v_type = VAR_STRING;
17039 rettv->vval.v_string = res;
17043 * "tabpagebuflist()" function
17045 static void
17046 f_tabpagebuflist(argvars, rettv)
17047 typval_T *argvars UNUSED;
17048 typval_T *rettv UNUSED;
17050 #ifdef FEAT_WINDOWS
17051 tabpage_T *tp;
17052 win_T *wp = NULL;
17054 if (argvars[0].v_type == VAR_UNKNOWN)
17055 wp = firstwin;
17056 else
17058 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17059 if (tp != NULL)
17060 wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17062 if (wp != NULL && rettv_list_alloc(rettv) != FAIL)
17064 for (; wp != NULL; wp = wp->w_next)
17065 if (list_append_number(rettv->vval.v_list,
17066 wp->w_buffer->b_fnum) == FAIL)
17067 break;
17069 #endif
17074 * "tabpagenr()" function
17076 static void
17077 f_tabpagenr(argvars, rettv)
17078 typval_T *argvars UNUSED;
17079 typval_T *rettv;
17081 int nr = 1;
17082 #ifdef FEAT_WINDOWS
17083 char_u *arg;
17085 if (argvars[0].v_type != VAR_UNKNOWN)
17087 arg = get_tv_string_chk(&argvars[0]);
17088 nr = 0;
17089 if (arg != NULL)
17091 if (STRCMP(arg, "$") == 0)
17092 nr = tabpage_index(NULL) - 1;
17093 else
17094 EMSG2(_(e_invexpr2), arg);
17097 else
17098 nr = tabpage_index(curtab);
17099 #endif
17100 rettv->vval.v_number = nr;
17104 #ifdef FEAT_WINDOWS
17105 static int get_winnr __ARGS((tabpage_T *tp, typval_T *argvar));
17108 * Common code for tabpagewinnr() and winnr().
17110 static int
17111 get_winnr(tp, argvar)
17112 tabpage_T *tp;
17113 typval_T *argvar;
17115 win_T *twin;
17116 int nr = 1;
17117 win_T *wp;
17118 char_u *arg;
17120 twin = (tp == curtab) ? curwin : tp->tp_curwin;
17121 if (argvar->v_type != VAR_UNKNOWN)
17123 arg = get_tv_string_chk(argvar);
17124 if (arg == NULL)
17125 nr = 0; /* type error; errmsg already given */
17126 else if (STRCMP(arg, "$") == 0)
17127 twin = (tp == curtab) ? lastwin : tp->tp_lastwin;
17128 else if (STRCMP(arg, "#") == 0)
17130 twin = (tp == curtab) ? prevwin : tp->tp_prevwin;
17131 if (twin == NULL)
17132 nr = 0;
17134 else
17136 EMSG2(_(e_invexpr2), arg);
17137 nr = 0;
17141 if (nr > 0)
17142 for (wp = (tp == curtab) ? firstwin : tp->tp_firstwin;
17143 wp != twin; wp = wp->w_next)
17145 if (wp == NULL)
17147 /* didn't find it in this tabpage */
17148 nr = 0;
17149 break;
17151 ++nr;
17153 return nr;
17155 #endif
17158 * "tabpagewinnr()" function
17160 static void
17161 f_tabpagewinnr(argvars, rettv)
17162 typval_T *argvars UNUSED;
17163 typval_T *rettv;
17165 int nr = 1;
17166 #ifdef FEAT_WINDOWS
17167 tabpage_T *tp;
17169 tp = find_tabpage((int)get_tv_number(&argvars[0]));
17170 if (tp == NULL)
17171 nr = 0;
17172 else
17173 nr = get_winnr(tp, &argvars[1]);
17174 #endif
17175 rettv->vval.v_number = nr;
17180 * "tagfiles()" function
17182 static void
17183 f_tagfiles(argvars, rettv)
17184 typval_T *argvars UNUSED;
17185 typval_T *rettv;
17187 char_u fname[MAXPATHL + 1];
17188 tagname_T tn;
17189 int first;
17191 if (rettv_list_alloc(rettv) == FAIL)
17192 return;
17194 for (first = TRUE; ; first = FALSE)
17195 if (get_tagfname(&tn, first, fname) == FAIL
17196 || list_append_string(rettv->vval.v_list, fname, -1) == FAIL)
17197 break;
17198 tagname_free(&tn);
17202 * "taglist()" function
17204 static void
17205 f_taglist(argvars, rettv)
17206 typval_T *argvars;
17207 typval_T *rettv;
17209 char_u *tag_pattern;
17211 tag_pattern = get_tv_string(&argvars[0]);
17213 rettv->vval.v_number = FALSE;
17214 if (*tag_pattern == NUL)
17215 return;
17217 if (rettv_list_alloc(rettv) == OK)
17218 (void)get_tags(rettv->vval.v_list, tag_pattern);
17222 * "tempname()" function
17224 static void
17225 f_tempname(argvars, rettv)
17226 typval_T *argvars UNUSED;
17227 typval_T *rettv;
17229 static int x = 'A';
17231 rettv->v_type = VAR_STRING;
17232 rettv->vval.v_string = vim_tempname(x);
17234 /* Advance 'x' to use A-Z and 0-9, so that there are at least 34 different
17235 * names. Skip 'I' and 'O', they are used for shell redirection. */
17238 if (x == 'Z')
17239 x = '0';
17240 else if (x == '9')
17241 x = 'A';
17242 else
17244 #ifdef EBCDIC
17245 if (x == 'I')
17246 x = 'J';
17247 else if (x == 'R')
17248 x = 'S';
17249 else
17250 #endif
17251 ++x;
17253 } while (x == 'I' || x == 'O');
17257 * "test(list)" function: Just checking the walls...
17259 static void
17260 f_test(argvars, rettv)
17261 typval_T *argvars UNUSED;
17262 typval_T *rettv UNUSED;
17264 /* Used for unit testing. Change the code below to your liking. */
17265 #if 0
17266 listitem_T *li;
17267 list_T *l;
17268 char_u *bad, *good;
17270 if (argvars[0].v_type != VAR_LIST)
17271 return;
17272 l = argvars[0].vval.v_list;
17273 if (l == NULL)
17274 return;
17275 li = l->lv_first;
17276 if (li == NULL)
17277 return;
17278 bad = get_tv_string(&li->li_tv);
17279 li = li->li_next;
17280 if (li == NULL)
17281 return;
17282 good = get_tv_string(&li->li_tv);
17283 rettv->vval.v_number = test_edit_score(bad, good);
17284 #endif
17288 * "tolower(string)" function
17290 static void
17291 f_tolower(argvars, rettv)
17292 typval_T *argvars;
17293 typval_T *rettv;
17295 char_u *p;
17297 p = vim_strsave(get_tv_string(&argvars[0]));
17298 rettv->v_type = VAR_STRING;
17299 rettv->vval.v_string = p;
17301 if (p != NULL)
17302 while (*p != NUL)
17304 #ifdef FEAT_MBYTE
17305 int l;
17307 if (enc_utf8)
17309 int c, lc;
17311 c = utf_ptr2char(p);
17312 lc = utf_tolower(c);
17313 l = utf_ptr2len(p);
17314 /* TODO: reallocate string when byte count changes. */
17315 if (utf_char2len(lc) == l)
17316 utf_char2bytes(lc, p);
17317 p += l;
17319 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
17320 p += l; /* skip multi-byte character */
17321 else
17322 #endif
17324 *p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
17325 ++p;
17331 * "toupper(string)" function
17333 static void
17334 f_toupper(argvars, rettv)
17335 typval_T *argvars;
17336 typval_T *rettv;
17338 rettv->v_type = VAR_STRING;
17339 rettv->vval.v_string = strup_save(get_tv_string(&argvars[0]));
17343 * "tr(string, fromstr, tostr)" function
17345 static void
17346 f_tr(argvars, rettv)
17347 typval_T *argvars;
17348 typval_T *rettv;
17350 char_u *instr;
17351 char_u *fromstr;
17352 char_u *tostr;
17353 char_u *p;
17354 #ifdef FEAT_MBYTE
17355 int inlen;
17356 int fromlen;
17357 int tolen;
17358 int idx;
17359 char_u *cpstr;
17360 int cplen;
17361 int first = TRUE;
17362 #endif
17363 char_u buf[NUMBUFLEN];
17364 char_u buf2[NUMBUFLEN];
17365 garray_T ga;
17367 instr = get_tv_string(&argvars[0]);
17368 fromstr = get_tv_string_buf_chk(&argvars[1], buf);
17369 tostr = get_tv_string_buf_chk(&argvars[2], buf2);
17371 /* Default return value: empty string. */
17372 rettv->v_type = VAR_STRING;
17373 rettv->vval.v_string = NULL;
17374 if (fromstr == NULL || tostr == NULL)
17375 return; /* type error; errmsg already given */
17376 ga_init2(&ga, (int)sizeof(char), 80);
17378 #ifdef FEAT_MBYTE
17379 if (!has_mbyte)
17380 #endif
17381 /* not multi-byte: fromstr and tostr must be the same length */
17382 if (STRLEN(fromstr) != STRLEN(tostr))
17384 #ifdef FEAT_MBYTE
17385 error:
17386 #endif
17387 EMSG2(_(e_invarg2), fromstr);
17388 ga_clear(&ga);
17389 return;
17392 /* fromstr and tostr have to contain the same number of chars */
17393 while (*instr != NUL)
17395 #ifdef FEAT_MBYTE
17396 if (has_mbyte)
17398 inlen = (*mb_ptr2len)(instr);
17399 cpstr = instr;
17400 cplen = inlen;
17401 idx = 0;
17402 for (p = fromstr; *p != NUL; p += fromlen)
17404 fromlen = (*mb_ptr2len)(p);
17405 if (fromlen == inlen && STRNCMP(instr, p, inlen) == 0)
17407 for (p = tostr; *p != NUL; p += tolen)
17409 tolen = (*mb_ptr2len)(p);
17410 if (idx-- == 0)
17412 cplen = tolen;
17413 cpstr = p;
17414 break;
17417 if (*p == NUL) /* tostr is shorter than fromstr */
17418 goto error;
17419 break;
17421 ++idx;
17424 if (first && cpstr == instr)
17426 /* Check that fromstr and tostr have the same number of
17427 * (multi-byte) characters. Done only once when a character
17428 * of instr doesn't appear in fromstr. */
17429 first = FALSE;
17430 for (p = tostr; *p != NUL; p += tolen)
17432 tolen = (*mb_ptr2len)(p);
17433 --idx;
17435 if (idx != 0)
17436 goto error;
17439 ga_grow(&ga, cplen);
17440 mch_memmove((char *)ga.ga_data + ga.ga_len, cpstr, (size_t)cplen);
17441 ga.ga_len += cplen;
17443 instr += inlen;
17445 else
17446 #endif
17448 /* When not using multi-byte chars we can do it faster. */
17449 p = vim_strchr(fromstr, *instr);
17450 if (p != NULL)
17451 ga_append(&ga, tostr[p - fromstr]);
17452 else
17453 ga_append(&ga, *instr);
17454 ++instr;
17458 /* add a terminating NUL */
17459 ga_grow(&ga, 1);
17460 ga_append(&ga, NUL);
17462 rettv->vval.v_string = ga.ga_data;
17465 #ifdef FEAT_FLOAT
17467 * "trunc({float})" function
17469 static void
17470 f_trunc(argvars, rettv)
17471 typval_T *argvars;
17472 typval_T *rettv;
17474 float_T f;
17476 rettv->v_type = VAR_FLOAT;
17477 if (get_float_arg(argvars, &f) == OK)
17478 /* trunc() is not in C90, use floor() or ceil() instead. */
17479 rettv->vval.v_float = f > 0 ? floor(f) : ceil(f);
17480 else
17481 rettv->vval.v_float = 0.0;
17483 #endif
17486 * "type(expr)" function
17488 static void
17489 f_type(argvars, rettv)
17490 typval_T *argvars;
17491 typval_T *rettv;
17493 int n;
17495 switch (argvars[0].v_type)
17497 case VAR_NUMBER: n = 0; break;
17498 case VAR_STRING: n = 1; break;
17499 case VAR_FUNC: n = 2; break;
17500 case VAR_LIST: n = 3; break;
17501 case VAR_DICT: n = 4; break;
17502 #ifdef FEAT_FLOAT
17503 case VAR_FLOAT: n = 5; break;
17504 #endif
17505 default: EMSG2(_(e_intern2), "f_type()"); n = 0; break;
17507 rettv->vval.v_number = n;
17511 * "values(dict)" function
17513 static void
17514 f_values(argvars, rettv)
17515 typval_T *argvars;
17516 typval_T *rettv;
17518 dict_list(argvars, rettv, 1);
17522 * "virtcol(string)" function
17524 static void
17525 f_virtcol(argvars, rettv)
17526 typval_T *argvars;
17527 typval_T *rettv;
17529 colnr_T vcol = 0;
17530 pos_T *fp;
17531 int fnum = curbuf->b_fnum;
17533 fp = var2fpos(&argvars[0], FALSE, &fnum);
17534 if (fp != NULL && fp->lnum <= curbuf->b_ml.ml_line_count
17535 && fnum == curbuf->b_fnum)
17537 getvvcol(curwin, fp, NULL, NULL, &vcol);
17538 ++vcol;
17541 rettv->vval.v_number = vcol;
17545 * "visualmode()" function
17547 static void
17548 f_visualmode(argvars, rettv)
17549 typval_T *argvars UNUSED;
17550 typval_T *rettv UNUSED;
17552 #ifdef FEAT_VISUAL
17553 char_u str[2];
17555 rettv->v_type = VAR_STRING;
17556 str[0] = curbuf->b_visual_mode_eval;
17557 str[1] = NUL;
17558 rettv->vval.v_string = vim_strsave(str);
17560 /* A non-zero number or non-empty string argument: reset mode. */
17561 if (non_zero_arg(&argvars[0]))
17562 curbuf->b_visual_mode_eval = NUL;
17563 #endif
17567 * "winbufnr(nr)" function
17569 static void
17570 f_winbufnr(argvars, rettv)
17571 typval_T *argvars;
17572 typval_T *rettv;
17574 win_T *wp;
17576 wp = find_win_by_nr(&argvars[0], NULL);
17577 if (wp == NULL)
17578 rettv->vval.v_number = -1;
17579 else
17580 rettv->vval.v_number = wp->w_buffer->b_fnum;
17584 * "wincol()" function
17586 static void
17587 f_wincol(argvars, rettv)
17588 typval_T *argvars UNUSED;
17589 typval_T *rettv;
17591 validate_cursor();
17592 rettv->vval.v_number = curwin->w_wcol + 1;
17596 * "winheight(nr)" function
17598 static void
17599 f_winheight(argvars, rettv)
17600 typval_T *argvars;
17601 typval_T *rettv;
17603 win_T *wp;
17605 wp = find_win_by_nr(&argvars[0], NULL);
17606 if (wp == NULL)
17607 rettv->vval.v_number = -1;
17608 else
17609 rettv->vval.v_number = wp->w_height;
17613 * "winline()" function
17615 static void
17616 f_winline(argvars, rettv)
17617 typval_T *argvars UNUSED;
17618 typval_T *rettv;
17620 validate_cursor();
17621 rettv->vval.v_number = curwin->w_wrow + 1;
17625 * "winnr()" function
17627 static void
17628 f_winnr(argvars, rettv)
17629 typval_T *argvars UNUSED;
17630 typval_T *rettv;
17632 int nr = 1;
17634 #ifdef FEAT_WINDOWS
17635 nr = get_winnr(curtab, &argvars[0]);
17636 #endif
17637 rettv->vval.v_number = nr;
17641 * "winrestcmd()" function
17643 static void
17644 f_winrestcmd(argvars, rettv)
17645 typval_T *argvars UNUSED;
17646 typval_T *rettv;
17648 #ifdef FEAT_WINDOWS
17649 win_T *wp;
17650 int winnr = 1;
17651 garray_T ga;
17652 char_u buf[50];
17654 ga_init2(&ga, (int)sizeof(char), 70);
17655 for (wp = firstwin; wp != NULL; wp = wp->w_next)
17657 sprintf((char *)buf, "%dresize %d|", winnr, wp->w_height);
17658 ga_concat(&ga, buf);
17659 # ifdef FEAT_VERTSPLIT
17660 sprintf((char *)buf, "vert %dresize %d|", winnr, wp->w_width);
17661 ga_concat(&ga, buf);
17662 # endif
17663 ++winnr;
17665 ga_append(&ga, NUL);
17667 rettv->vval.v_string = ga.ga_data;
17668 #else
17669 rettv->vval.v_string = NULL;
17670 #endif
17671 rettv->v_type = VAR_STRING;
17675 * "winrestview()" function
17677 static void
17678 f_winrestview(argvars, rettv)
17679 typval_T *argvars;
17680 typval_T *rettv UNUSED;
17682 dict_T *dict;
17684 if (argvars[0].v_type != VAR_DICT
17685 || (dict = argvars[0].vval.v_dict) == NULL)
17686 EMSG(_(e_invarg));
17687 else
17689 curwin->w_cursor.lnum = get_dict_number(dict, (char_u *)"lnum");
17690 curwin->w_cursor.col = get_dict_number(dict, (char_u *)"col");
17691 #ifdef FEAT_VIRTUALEDIT
17692 curwin->w_cursor.coladd = get_dict_number(dict, (char_u *)"coladd");
17693 #endif
17694 curwin->w_curswant = get_dict_number(dict, (char_u *)"curswant");
17695 curwin->w_set_curswant = FALSE;
17697 set_topline(curwin, get_dict_number(dict, (char_u *)"topline"));
17698 #ifdef FEAT_DIFF
17699 curwin->w_topfill = get_dict_number(dict, (char_u *)"topfill");
17700 #endif
17701 curwin->w_leftcol = get_dict_number(dict, (char_u *)"leftcol");
17702 curwin->w_skipcol = get_dict_number(dict, (char_u *)"skipcol");
17704 check_cursor();
17705 changed_cline_bef_curs();
17706 invalidate_botline();
17707 redraw_later(VALID);
17709 if (curwin->w_topline == 0)
17710 curwin->w_topline = 1;
17711 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
17712 curwin->w_topline = curbuf->b_ml.ml_line_count;
17713 #ifdef FEAT_DIFF
17714 check_topfill(curwin, TRUE);
17715 #endif
17720 * "winsaveview()" function
17722 static void
17723 f_winsaveview(argvars, rettv)
17724 typval_T *argvars UNUSED;
17725 typval_T *rettv;
17727 dict_T *dict;
17729 dict = dict_alloc();
17730 if (dict == NULL)
17731 return;
17732 rettv->v_type = VAR_DICT;
17733 rettv->vval.v_dict = dict;
17734 ++dict->dv_refcount;
17736 dict_add_nr_str(dict, "lnum", (long)curwin->w_cursor.lnum, NULL);
17737 dict_add_nr_str(dict, "col", (long)curwin->w_cursor.col, NULL);
17738 #ifdef FEAT_VIRTUALEDIT
17739 dict_add_nr_str(dict, "coladd", (long)curwin->w_cursor.coladd, NULL);
17740 #endif
17741 update_curswant();
17742 dict_add_nr_str(dict, "curswant", (long)curwin->w_curswant, NULL);
17744 dict_add_nr_str(dict, "topline", (long)curwin->w_topline, NULL);
17745 #ifdef FEAT_DIFF
17746 dict_add_nr_str(dict, "topfill", (long)curwin->w_topfill, NULL);
17747 #endif
17748 dict_add_nr_str(dict, "leftcol", (long)curwin->w_leftcol, NULL);
17749 dict_add_nr_str(dict, "skipcol", (long)curwin->w_skipcol, NULL);
17753 * "winwidth(nr)" function
17755 static void
17756 f_winwidth(argvars, rettv)
17757 typval_T *argvars;
17758 typval_T *rettv;
17760 win_T *wp;
17762 wp = find_win_by_nr(&argvars[0], NULL);
17763 if (wp == NULL)
17764 rettv->vval.v_number = -1;
17765 else
17766 #ifdef FEAT_VERTSPLIT
17767 rettv->vval.v_number = wp->w_width;
17768 #else
17769 rettv->vval.v_number = Columns;
17770 #endif
17774 * "writefile()" function
17776 static void
17777 f_writefile(argvars, rettv)
17778 typval_T *argvars;
17779 typval_T *rettv;
17781 int binary = FALSE;
17782 char_u *fname;
17783 FILE *fd;
17784 listitem_T *li;
17785 char_u *s;
17786 int ret = 0;
17787 int c;
17789 if (check_restricted() || check_secure())
17790 return;
17792 if (argvars[0].v_type != VAR_LIST)
17794 EMSG2(_(e_listarg), "writefile()");
17795 return;
17797 if (argvars[0].vval.v_list == NULL)
17798 return;
17800 if (argvars[2].v_type != VAR_UNKNOWN
17801 && STRCMP(get_tv_string(&argvars[2]), "b") == 0)
17802 binary = TRUE;
17804 /* Always open the file in binary mode, library functions have a mind of
17805 * their own about CR-LF conversion. */
17806 fname = get_tv_string(&argvars[1]);
17807 if (*fname == NUL || (fd = mch_fopen((char *)fname, WRITEBIN)) == NULL)
17809 EMSG2(_(e_notcreate), *fname == NUL ? (char_u *)_("<empty>") : fname);
17810 ret = -1;
17812 else
17814 for (li = argvars[0].vval.v_list->lv_first; li != NULL;
17815 li = li->li_next)
17817 for (s = get_tv_string(&li->li_tv); *s != NUL; ++s)
17819 if (*s == '\n')
17820 c = putc(NUL, fd);
17821 else
17822 c = putc(*s, fd);
17823 if (c == EOF)
17825 ret = -1;
17826 break;
17829 if (!binary || li->li_next != NULL)
17830 if (putc('\n', fd) == EOF)
17832 ret = -1;
17833 break;
17835 if (ret < 0)
17837 EMSG(_(e_write));
17838 break;
17841 fclose(fd);
17844 rettv->vval.v_number = ret;
17848 * Translate a String variable into a position.
17849 * Returns NULL when there is an error.
17851 static pos_T *
17852 var2fpos(varp, dollar_lnum, fnum)
17853 typval_T *varp;
17854 int dollar_lnum; /* TRUE when $ is last line */
17855 int *fnum; /* set to fnum for '0, 'A, etc. */
17857 char_u *name;
17858 static pos_T pos;
17859 pos_T *pp;
17861 /* Argument can be [lnum, col, coladd]. */
17862 if (varp->v_type == VAR_LIST)
17864 list_T *l;
17865 int len;
17866 int error = FALSE;
17867 listitem_T *li;
17869 l = varp->vval.v_list;
17870 if (l == NULL)
17871 return NULL;
17873 /* Get the line number */
17874 pos.lnum = list_find_nr(l, 0L, &error);
17875 if (error || pos.lnum <= 0 || pos.lnum > curbuf->b_ml.ml_line_count)
17876 return NULL; /* invalid line number */
17878 /* Get the column number */
17879 pos.col = list_find_nr(l, 1L, &error);
17880 if (error)
17881 return NULL;
17882 len = (long)STRLEN(ml_get(pos.lnum));
17884 /* We accept "$" for the column number: last column. */
17885 li = list_find(l, 1L);
17886 if (li != NULL && li->li_tv.v_type == VAR_STRING
17887 && li->li_tv.vval.v_string != NULL
17888 && STRCMP(li->li_tv.vval.v_string, "$") == 0)
17889 pos.col = len + 1;
17891 /* Accept a position up to the NUL after the line. */
17892 if (pos.col == 0 || (int)pos.col > len + 1)
17893 return NULL; /* invalid column number */
17894 --pos.col;
17896 #ifdef FEAT_VIRTUALEDIT
17897 /* Get the virtual offset. Defaults to zero. */
17898 pos.coladd = list_find_nr(l, 2L, &error);
17899 if (error)
17900 pos.coladd = 0;
17901 #endif
17903 return &pos;
17906 name = get_tv_string_chk(varp);
17907 if (name == NULL)
17908 return NULL;
17909 if (name[0] == '.') /* cursor */
17910 return &curwin->w_cursor;
17911 #ifdef FEAT_VISUAL
17912 if (name[0] == 'v' && name[1] == NUL) /* Visual start */
17914 if (VIsual_active)
17915 return &VIsual;
17916 return &curwin->w_cursor;
17918 #endif
17919 if (name[0] == '\'') /* mark */
17921 pp = getmark_fnum(name[1], FALSE, fnum);
17922 if (pp == NULL || pp == (pos_T *)-1 || pp->lnum <= 0)
17923 return NULL;
17924 return pp;
17927 #ifdef FEAT_VIRTUALEDIT
17928 pos.coladd = 0;
17929 #endif
17931 if (name[0] == 'w' && dollar_lnum)
17933 pos.col = 0;
17934 if (name[1] == '0') /* "w0": first visible line */
17936 update_topline();
17937 pos.lnum = curwin->w_topline;
17938 return &pos;
17940 else if (name[1] == '$') /* "w$": last visible line */
17942 validate_botline();
17943 pos.lnum = curwin->w_botline - 1;
17944 return &pos;
17947 else if (name[0] == '$') /* last column or line */
17949 if (dollar_lnum)
17951 pos.lnum = curbuf->b_ml.ml_line_count;
17952 pos.col = 0;
17954 else
17956 pos.lnum = curwin->w_cursor.lnum;
17957 pos.col = (colnr_T)STRLEN(ml_get_curline());
17959 return &pos;
17961 return NULL;
17965 * Convert list in "arg" into a position and optional file number.
17966 * When "fnump" is NULL there is no file number, only 3 items.
17967 * Note that the column is passed on as-is, the caller may want to decrement
17968 * it to use 1 for the first column.
17969 * Return FAIL when conversion is not possible, doesn't check the position for
17970 * validity.
17972 static int
17973 list2fpos(arg, posp, fnump)
17974 typval_T *arg;
17975 pos_T *posp;
17976 int *fnump;
17978 list_T *l = arg->vval.v_list;
17979 long i = 0;
17980 long n;
17982 /* List must be: [fnum, lnum, col, coladd], where "fnum" is only there
17983 * when "fnump" isn't NULL and "coladd" is optional. */
17984 if (arg->v_type != VAR_LIST
17985 || l == NULL
17986 || l->lv_len < (fnump == NULL ? 2 : 3)
17987 || l->lv_len > (fnump == NULL ? 3 : 4))
17988 return FAIL;
17990 if (fnump != NULL)
17992 n = list_find_nr(l, i++, NULL); /* fnum */
17993 if (n < 0)
17994 return FAIL;
17995 if (n == 0)
17996 n = curbuf->b_fnum; /* current buffer */
17997 *fnump = n;
18000 n = list_find_nr(l, i++, NULL); /* lnum */
18001 if (n < 0)
18002 return FAIL;
18003 posp->lnum = n;
18005 n = list_find_nr(l, i++, NULL); /* col */
18006 if (n < 0)
18007 return FAIL;
18008 posp->col = n;
18010 #ifdef FEAT_VIRTUALEDIT
18011 n = list_find_nr(l, i, NULL);
18012 if (n < 0)
18013 posp->coladd = 0;
18014 else
18015 posp->coladd = n;
18016 #endif
18018 return OK;
18022 * Get the length of an environment variable name.
18023 * Advance "arg" to the first character after the name.
18024 * Return 0 for error.
18026 static int
18027 get_env_len(arg)
18028 char_u **arg;
18030 char_u *p;
18031 int len;
18033 for (p = *arg; vim_isIDc(*p); ++p)
18035 if (p == *arg) /* no name found */
18036 return 0;
18038 len = (int)(p - *arg);
18039 *arg = p;
18040 return len;
18044 * Get the length of the name of a function or internal variable.
18045 * "arg" is advanced to the first non-white character after the name.
18046 * Return 0 if something is wrong.
18048 static int
18049 get_id_len(arg)
18050 char_u **arg;
18052 char_u *p;
18053 int len;
18055 /* Find the end of the name. */
18056 for (p = *arg; eval_isnamec(*p); ++p)
18058 if (p == *arg) /* no name found */
18059 return 0;
18061 len = (int)(p - *arg);
18062 *arg = skipwhite(p);
18064 return len;
18068 * Get the length of the name of a variable or function.
18069 * Only the name is recognized, does not handle ".key" or "[idx]".
18070 * "arg" is advanced to the first non-white character after the name.
18071 * Return -1 if curly braces expansion failed.
18072 * Return 0 if something else is wrong.
18073 * If the name contains 'magic' {}'s, expand them and return the
18074 * expanded name in an allocated string via 'alias' - caller must free.
18076 static int
18077 get_name_len(arg, alias, evaluate, verbose)
18078 char_u **arg;
18079 char_u **alias;
18080 int evaluate;
18081 int verbose;
18083 int len;
18084 char_u *p;
18085 char_u *expr_start;
18086 char_u *expr_end;
18088 *alias = NULL; /* default to no alias */
18090 if ((*arg)[0] == K_SPECIAL && (*arg)[1] == KS_EXTRA
18091 && (*arg)[2] == (int)KE_SNR)
18093 /* hard coded <SNR>, already translated */
18094 *arg += 3;
18095 return get_id_len(arg) + 3;
18097 len = eval_fname_script(*arg);
18098 if (len > 0)
18100 /* literal "<SID>", "s:" or "<SNR>" */
18101 *arg += len;
18105 * Find the end of the name; check for {} construction.
18107 p = find_name_end(*arg, &expr_start, &expr_end,
18108 len > 0 ? 0 : FNE_CHECK_START);
18109 if (expr_start != NULL)
18111 char_u *temp_string;
18113 if (!evaluate)
18115 len += (int)(p - *arg);
18116 *arg = skipwhite(p);
18117 return len;
18121 * Include any <SID> etc in the expanded string:
18122 * Thus the -len here.
18124 temp_string = make_expanded_name(*arg - len, expr_start, expr_end, p);
18125 if (temp_string == NULL)
18126 return -1;
18127 *alias = temp_string;
18128 *arg = skipwhite(p);
18129 return (int)STRLEN(temp_string);
18132 len += get_id_len(arg);
18133 if (len == 0 && verbose)
18134 EMSG2(_(e_invexpr2), *arg);
18136 return len;
18140 * Find the end of a variable or function name, taking care of magic braces.
18141 * If "expr_start" is not NULL then "expr_start" and "expr_end" are set to the
18142 * start and end of the first magic braces item.
18143 * "flags" can have FNE_INCL_BR and FNE_CHECK_START.
18144 * Return a pointer to just after the name. Equal to "arg" if there is no
18145 * valid name.
18147 static char_u *
18148 find_name_end(arg, expr_start, expr_end, flags)
18149 char_u *arg;
18150 char_u **expr_start;
18151 char_u **expr_end;
18152 int flags;
18154 int mb_nest = 0;
18155 int br_nest = 0;
18156 char_u *p;
18158 if (expr_start != NULL)
18160 *expr_start = NULL;
18161 *expr_end = NULL;
18164 /* Quick check for valid starting character. */
18165 if ((flags & FNE_CHECK_START) && !eval_isnamec1(*arg) && *arg != '{')
18166 return arg;
18168 for (p = arg; *p != NUL
18169 && (eval_isnamec(*p)
18170 || *p == '{'
18171 || ((flags & FNE_INCL_BR) && (*p == '[' || *p == '.'))
18172 || mb_nest != 0
18173 || br_nest != 0); mb_ptr_adv(p))
18175 if (*p == '\'')
18177 /* skip over 'string' to avoid counting [ and ] inside it. */
18178 for (p = p + 1; *p != NUL && *p != '\''; mb_ptr_adv(p))
18180 if (*p == NUL)
18181 break;
18183 else if (*p == '"')
18185 /* skip over "str\"ing" to avoid counting [ and ] inside it. */
18186 for (p = p + 1; *p != NUL && *p != '"'; mb_ptr_adv(p))
18187 if (*p == '\\' && p[1] != NUL)
18188 ++p;
18189 if (*p == NUL)
18190 break;
18193 if (mb_nest == 0)
18195 if (*p == '[')
18196 ++br_nest;
18197 else if (*p == ']')
18198 --br_nest;
18201 if (br_nest == 0)
18203 if (*p == '{')
18205 mb_nest++;
18206 if (expr_start != NULL && *expr_start == NULL)
18207 *expr_start = p;
18209 else if (*p == '}')
18211 mb_nest--;
18212 if (expr_start != NULL && mb_nest == 0 && *expr_end == NULL)
18213 *expr_end = p;
18218 return p;
18222 * Expands out the 'magic' {}'s in a variable/function name.
18223 * Note that this can call itself recursively, to deal with
18224 * constructs like foo{bar}{baz}{bam}
18225 * The four pointer arguments point to "foo{expre}ss{ion}bar"
18226 * "in_start" ^
18227 * "expr_start" ^
18228 * "expr_end" ^
18229 * "in_end" ^
18231 * Returns a new allocated string, which the caller must free.
18232 * Returns NULL for failure.
18234 static char_u *
18235 make_expanded_name(in_start, expr_start, expr_end, in_end)
18236 char_u *in_start;
18237 char_u *expr_start;
18238 char_u *expr_end;
18239 char_u *in_end;
18241 char_u c1;
18242 char_u *retval = NULL;
18243 char_u *temp_result;
18244 char_u *nextcmd = NULL;
18246 if (expr_end == NULL || in_end == NULL)
18247 return NULL;
18248 *expr_start = NUL;
18249 *expr_end = NUL;
18250 c1 = *in_end;
18251 *in_end = NUL;
18253 temp_result = eval_to_string(expr_start + 1, &nextcmd, FALSE);
18254 if (temp_result != NULL && nextcmd == NULL)
18256 retval = alloc((unsigned)(STRLEN(temp_result) + (expr_start - in_start)
18257 + (in_end - expr_end) + 1));
18258 if (retval != NULL)
18260 STRCPY(retval, in_start);
18261 STRCAT(retval, temp_result);
18262 STRCAT(retval, expr_end + 1);
18265 vim_free(temp_result);
18267 *in_end = c1; /* put char back for error messages */
18268 *expr_start = '{';
18269 *expr_end = '}';
18271 if (retval != NULL)
18273 temp_result = find_name_end(retval, &expr_start, &expr_end, 0);
18274 if (expr_start != NULL)
18276 /* Further expansion! */
18277 temp_result = make_expanded_name(retval, expr_start,
18278 expr_end, temp_result);
18279 vim_free(retval);
18280 retval = temp_result;
18284 return retval;
18288 * Return TRUE if character "c" can be used in a variable or function name.
18289 * Does not include '{' or '}' for magic braces.
18291 static int
18292 eval_isnamec(c)
18293 int c;
18295 return (ASCII_ISALNUM(c) || c == '_' || c == ':' || c == AUTOLOAD_CHAR);
18299 * Return TRUE if character "c" can be used as the first character in a
18300 * variable or function name (excluding '{' and '}').
18302 static int
18303 eval_isnamec1(c)
18304 int c;
18306 return (ASCII_ISALPHA(c) || c == '_');
18310 * Set number v: variable to "val".
18312 void
18313 set_vim_var_nr(idx, val)
18314 int idx;
18315 long val;
18317 vimvars[idx].vv_nr = val;
18321 * Get number v: variable value.
18323 long
18324 get_vim_var_nr(idx)
18325 int idx;
18327 return vimvars[idx].vv_nr;
18331 * Get string v: variable value. Uses a static buffer, can only be used once.
18333 char_u *
18334 get_vim_var_str(idx)
18335 int idx;
18337 return get_tv_string(&vimvars[idx].vv_tv);
18341 * Get List v: variable value. Caller must take care of reference count when
18342 * needed.
18344 list_T *
18345 get_vim_var_list(idx)
18346 int idx;
18348 return vimvars[idx].vv_list;
18352 * Set v:char to character "c".
18354 void
18355 set_vim_var_char(c)
18356 int c;
18358 #ifdef FEAT_MBYTE
18359 char_u buf[MB_MAXBYTES];
18360 #else
18361 char_u buf[2];
18362 #endif
18364 #ifdef FEAT_MBYTE
18365 if (has_mbyte)
18366 buf[(*mb_char2bytes)(c, buf)] = NUL;
18367 else
18368 #endif
18370 buf[0] = c;
18371 buf[1] = NUL;
18373 set_vim_var_string(VV_CHAR, buf, -1);
18377 * Set v:count to "count" and v:count1 to "count1".
18378 * When "set_prevcount" is TRUE first set v:prevcount from v:count.
18380 void
18381 set_vcount(count, count1, set_prevcount)
18382 long count;
18383 long count1;
18384 int set_prevcount;
18386 if (set_prevcount)
18387 vimvars[VV_PREVCOUNT].vv_nr = vimvars[VV_COUNT].vv_nr;
18388 vimvars[VV_COUNT].vv_nr = count;
18389 vimvars[VV_COUNT1].vv_nr = count1;
18393 * Set string v: variable to a copy of "val".
18395 void
18396 set_vim_var_string(idx, val, len)
18397 int idx;
18398 char_u *val;
18399 int len; /* length of "val" to use or -1 (whole string) */
18401 /* Need to do this (at least) once, since we can't initialize a union.
18402 * Will always be invoked when "v:progname" is set. */
18403 vimvars[VV_VERSION].vv_nr = VIM_VERSION_100;
18405 vim_free(vimvars[idx].vv_str);
18406 if (val == NULL)
18407 vimvars[idx].vv_str = NULL;
18408 else if (len == -1)
18409 vimvars[idx].vv_str = vim_strsave(val);
18410 else
18411 vimvars[idx].vv_str = vim_strnsave(val, len);
18415 * Set List v: variable to "val".
18417 void
18418 set_vim_var_list(idx, val)
18419 int idx;
18420 list_T *val;
18422 list_unref(vimvars[idx].vv_list);
18423 vimvars[idx].vv_list = val;
18424 if (val != NULL)
18425 ++val->lv_refcount;
18429 * Set v:register if needed.
18431 void
18432 set_reg_var(c)
18433 int c;
18435 char_u regname;
18437 if (c == 0 || c == ' ')
18438 regname = '"';
18439 else
18440 regname = c;
18441 /* Avoid free/alloc when the value is already right. */
18442 if (vimvars[VV_REG].vv_str == NULL || vimvars[VV_REG].vv_str[0] != c)
18443 set_vim_var_string(VV_REG, &regname, 1);
18447 * Get or set v:exception. If "oldval" == NULL, return the current value.
18448 * Otherwise, restore the value to "oldval" and return NULL.
18449 * Must always be called in pairs to save and restore v:exception! Does not
18450 * take care of memory allocations.
18452 char_u *
18453 v_exception(oldval)
18454 char_u *oldval;
18456 if (oldval == NULL)
18457 return vimvars[VV_EXCEPTION].vv_str;
18459 vimvars[VV_EXCEPTION].vv_str = oldval;
18460 return NULL;
18464 * Get or set v:throwpoint. If "oldval" == NULL, return the current value.
18465 * Otherwise, restore the value to "oldval" and return NULL.
18466 * Must always be called in pairs to save and restore v:throwpoint! Does not
18467 * take care of memory allocations.
18469 char_u *
18470 v_throwpoint(oldval)
18471 char_u *oldval;
18473 if (oldval == NULL)
18474 return vimvars[VV_THROWPOINT].vv_str;
18476 vimvars[VV_THROWPOINT].vv_str = oldval;
18477 return NULL;
18480 #if defined(FEAT_AUTOCMD) || defined(PROTO)
18482 * Set v:cmdarg.
18483 * If "eap" != NULL, use "eap" to generate the value and return the old value.
18484 * If "oldarg" != NULL, restore the value to "oldarg" and return NULL.
18485 * Must always be called in pairs!
18487 char_u *
18488 set_cmdarg(eap, oldarg)
18489 exarg_T *eap;
18490 char_u *oldarg;
18492 char_u *oldval;
18493 char_u *newval;
18494 unsigned len;
18496 oldval = vimvars[VV_CMDARG].vv_str;
18497 if (eap == NULL)
18499 vim_free(oldval);
18500 vimvars[VV_CMDARG].vv_str = oldarg;
18501 return NULL;
18504 if (eap->force_bin == FORCE_BIN)
18505 len = 6;
18506 else if (eap->force_bin == FORCE_NOBIN)
18507 len = 8;
18508 else
18509 len = 0;
18511 if (eap->read_edit)
18512 len += 7;
18514 if (eap->force_ff != 0)
18515 len += (unsigned)STRLEN(eap->cmd + eap->force_ff) + 6;
18516 # ifdef FEAT_MBYTE
18517 if (eap->force_enc != 0)
18518 len += (unsigned)STRLEN(eap->cmd + eap->force_enc) + 7;
18519 if (eap->bad_char != 0)
18520 len += 7 + 4; /* " ++bad=" + "keep" or "drop" */
18521 # endif
18523 newval = alloc(len + 1);
18524 if (newval == NULL)
18525 return NULL;
18527 if (eap->force_bin == FORCE_BIN)
18528 sprintf((char *)newval, " ++bin");
18529 else if (eap->force_bin == FORCE_NOBIN)
18530 sprintf((char *)newval, " ++nobin");
18531 else
18532 *newval = NUL;
18534 if (eap->read_edit)
18535 STRCAT(newval, " ++edit");
18537 if (eap->force_ff != 0)
18538 sprintf((char *)newval + STRLEN(newval), " ++ff=%s",
18539 eap->cmd + eap->force_ff);
18540 # ifdef FEAT_MBYTE
18541 if (eap->force_enc != 0)
18542 sprintf((char *)newval + STRLEN(newval), " ++enc=%s",
18543 eap->cmd + eap->force_enc);
18544 if (eap->bad_char == BAD_KEEP)
18545 STRCPY(newval + STRLEN(newval), " ++bad=keep");
18546 else if (eap->bad_char == BAD_DROP)
18547 STRCPY(newval + STRLEN(newval), " ++bad=drop");
18548 else if (eap->bad_char != 0)
18549 sprintf((char *)newval + STRLEN(newval), " ++bad=%c", eap->bad_char);
18550 # endif
18551 vimvars[VV_CMDARG].vv_str = newval;
18552 return oldval;
18554 #endif
18557 * Get the value of internal variable "name".
18558 * Return OK or FAIL.
18560 static int
18561 get_var_tv(name, len, rettv, verbose)
18562 char_u *name;
18563 int len; /* length of "name" */
18564 typval_T *rettv; /* NULL when only checking existence */
18565 int verbose; /* may give error message */
18567 int ret = OK;
18568 typval_T *tv = NULL;
18569 typval_T atv;
18570 dictitem_T *v;
18571 int cc;
18573 /* truncate the name, so that we can use strcmp() */
18574 cc = name[len];
18575 name[len] = NUL;
18578 * Check for "b:changedtick".
18580 if (STRCMP(name, "b:changedtick") == 0)
18582 atv.v_type = VAR_NUMBER;
18583 atv.vval.v_number = curbuf->b_changedtick;
18584 tv = &atv;
18588 * Check for user-defined variables.
18590 else
18592 v = find_var(name, NULL);
18593 if (v != NULL)
18594 tv = &v->di_tv;
18597 if (tv == NULL)
18599 if (rettv != NULL && verbose)
18600 EMSG2(_(e_undefvar), name);
18601 ret = FAIL;
18603 else if (rettv != NULL)
18604 copy_tv(tv, rettv);
18606 name[len] = cc;
18608 return ret;
18612 * Handle expr[expr], expr[expr:expr] subscript and .name lookup.
18613 * Also handle function call with Funcref variable: func(expr)
18614 * Can all be combined: dict.func(expr)[idx]['func'](expr)
18616 static int
18617 handle_subscript(arg, rettv, evaluate, verbose)
18618 char_u **arg;
18619 typval_T *rettv;
18620 int evaluate; /* do more than finding the end */
18621 int verbose; /* give error messages */
18623 int ret = OK;
18624 dict_T *selfdict = NULL;
18625 char_u *s;
18626 int len;
18627 typval_T functv;
18629 while (ret == OK
18630 && (**arg == '['
18631 || (**arg == '.' && rettv->v_type == VAR_DICT)
18632 || (**arg == '(' && rettv->v_type == VAR_FUNC))
18633 && !vim_iswhite(*(*arg - 1)))
18635 if (**arg == '(')
18637 /* need to copy the funcref so that we can clear rettv */
18638 functv = *rettv;
18639 rettv->v_type = VAR_UNKNOWN;
18641 /* Invoke the function. Recursive! */
18642 s = functv.vval.v_string;
18643 ret = get_func_tv(s, (int)STRLEN(s), rettv, arg,
18644 curwin->w_cursor.lnum, curwin->w_cursor.lnum,
18645 &len, evaluate, selfdict);
18647 /* Clear the funcref afterwards, so that deleting it while
18648 * evaluating the arguments is possible (see test55). */
18649 clear_tv(&functv);
18651 /* Stop the expression evaluation when immediately aborting on
18652 * error, or when an interrupt occurred or an exception was thrown
18653 * but not caught. */
18654 if (aborting())
18656 if (ret == OK)
18657 clear_tv(rettv);
18658 ret = FAIL;
18660 dict_unref(selfdict);
18661 selfdict = NULL;
18663 else /* **arg == '[' || **arg == '.' */
18665 dict_unref(selfdict);
18666 if (rettv->v_type == VAR_DICT)
18668 selfdict = rettv->vval.v_dict;
18669 if (selfdict != NULL)
18670 ++selfdict->dv_refcount;
18672 else
18673 selfdict = NULL;
18674 if (eval_index(arg, rettv, evaluate, verbose) == FAIL)
18676 clear_tv(rettv);
18677 ret = FAIL;
18681 dict_unref(selfdict);
18682 return ret;
18686 * Allocate memory for a variable type-value, and make it empty (0 or NULL
18687 * value).
18689 static typval_T *
18690 alloc_tv()
18692 return (typval_T *)alloc_clear((unsigned)sizeof(typval_T));
18696 * Allocate memory for a variable type-value, and assign a string to it.
18697 * The string "s" must have been allocated, it is consumed.
18698 * Return NULL for out of memory, the variable otherwise.
18700 static typval_T *
18701 alloc_string_tv(s)
18702 char_u *s;
18704 typval_T *rettv;
18706 rettv = alloc_tv();
18707 if (rettv != NULL)
18709 rettv->v_type = VAR_STRING;
18710 rettv->vval.v_string = s;
18712 else
18713 vim_free(s);
18714 return rettv;
18718 * Free the memory for a variable type-value.
18720 void
18721 free_tv(varp)
18722 typval_T *varp;
18724 if (varp != NULL)
18726 switch (varp->v_type)
18728 case VAR_FUNC:
18729 func_unref(varp->vval.v_string);
18730 /*FALLTHROUGH*/
18731 case VAR_STRING:
18732 vim_free(varp->vval.v_string);
18733 break;
18734 case VAR_LIST:
18735 list_unref(varp->vval.v_list);
18736 break;
18737 case VAR_DICT:
18738 dict_unref(varp->vval.v_dict);
18739 break;
18740 case VAR_NUMBER:
18741 #ifdef FEAT_FLOAT
18742 case VAR_FLOAT:
18743 #endif
18744 case VAR_UNKNOWN:
18745 break;
18746 default:
18747 EMSG2(_(e_intern2), "free_tv()");
18748 break;
18750 vim_free(varp);
18755 * Free the memory for a variable value and set the value to NULL or 0.
18757 void
18758 clear_tv(varp)
18759 typval_T *varp;
18761 if (varp != NULL)
18763 switch (varp->v_type)
18765 case VAR_FUNC:
18766 func_unref(varp->vval.v_string);
18767 /*FALLTHROUGH*/
18768 case VAR_STRING:
18769 vim_free(varp->vval.v_string);
18770 varp->vval.v_string = NULL;
18771 break;
18772 case VAR_LIST:
18773 list_unref(varp->vval.v_list);
18774 varp->vval.v_list = NULL;
18775 break;
18776 case VAR_DICT:
18777 dict_unref(varp->vval.v_dict);
18778 varp->vval.v_dict = NULL;
18779 break;
18780 case VAR_NUMBER:
18781 varp->vval.v_number = 0;
18782 break;
18783 #ifdef FEAT_FLOAT
18784 case VAR_FLOAT:
18785 varp->vval.v_float = 0.0;
18786 break;
18787 #endif
18788 case VAR_UNKNOWN:
18789 break;
18790 default:
18791 EMSG2(_(e_intern2), "clear_tv()");
18793 varp->v_lock = 0;
18798 * Set the value of a variable to NULL without freeing items.
18800 static void
18801 init_tv(varp)
18802 typval_T *varp;
18804 if (varp != NULL)
18805 vim_memset(varp, 0, sizeof(typval_T));
18809 * Get the number value of a variable.
18810 * If it is a String variable, uses vim_str2nr().
18811 * For incompatible types, return 0.
18812 * get_tv_number_chk() is similar to get_tv_number(), but informs the
18813 * caller of incompatible types: it sets *denote to TRUE if "denote"
18814 * is not NULL or returns -1 otherwise.
18816 static long
18817 get_tv_number(varp)
18818 typval_T *varp;
18820 int error = FALSE;
18822 return get_tv_number_chk(varp, &error); /* return 0L on error */
18825 long
18826 get_tv_number_chk(varp, denote)
18827 typval_T *varp;
18828 int *denote;
18830 long n = 0L;
18832 switch (varp->v_type)
18834 case VAR_NUMBER:
18835 return (long)(varp->vval.v_number);
18836 #ifdef FEAT_FLOAT
18837 case VAR_FLOAT:
18838 EMSG(_("E805: Using a Float as a Number"));
18839 break;
18840 #endif
18841 case VAR_FUNC:
18842 EMSG(_("E703: Using a Funcref as a Number"));
18843 break;
18844 case VAR_STRING:
18845 if (varp->vval.v_string != NULL)
18846 vim_str2nr(varp->vval.v_string, NULL, NULL,
18847 TRUE, TRUE, &n, NULL);
18848 return n;
18849 case VAR_LIST:
18850 EMSG(_("E745: Using a List as a Number"));
18851 break;
18852 case VAR_DICT:
18853 EMSG(_("E728: Using a Dictionary as a Number"));
18854 break;
18855 default:
18856 EMSG2(_(e_intern2), "get_tv_number()");
18857 break;
18859 if (denote == NULL) /* useful for values that must be unsigned */
18860 n = -1;
18861 else
18862 *denote = TRUE;
18863 return n;
18867 * Get the lnum from the first argument.
18868 * Also accepts ".", "$", etc., but that only works for the current buffer.
18869 * Returns -1 on error.
18871 static linenr_T
18872 get_tv_lnum(argvars)
18873 typval_T *argvars;
18875 typval_T rettv;
18876 linenr_T lnum;
18878 lnum = get_tv_number_chk(&argvars[0], NULL);
18879 if (lnum == 0) /* no valid number, try using line() */
18881 rettv.v_type = VAR_NUMBER;
18882 f_line(argvars, &rettv);
18883 lnum = rettv.vval.v_number;
18884 clear_tv(&rettv);
18886 return lnum;
18890 * Get the lnum from the first argument.
18891 * Also accepts "$", then "buf" is used.
18892 * Returns 0 on error.
18894 static linenr_T
18895 get_tv_lnum_buf(argvars, buf)
18896 typval_T *argvars;
18897 buf_T *buf;
18899 if (argvars[0].v_type == VAR_STRING
18900 && argvars[0].vval.v_string != NULL
18901 && argvars[0].vval.v_string[0] == '$'
18902 && buf != NULL)
18903 return buf->b_ml.ml_line_count;
18904 return get_tv_number_chk(&argvars[0], NULL);
18908 * Get the string value of a variable.
18909 * If it is a Number variable, the number is converted into a string.
18910 * get_tv_string() uses a single, static buffer. YOU CAN ONLY USE IT ONCE!
18911 * get_tv_string_buf() uses a given buffer.
18912 * If the String variable has never been set, return an empty string.
18913 * Never returns NULL;
18914 * get_tv_string_chk() and get_tv_string_buf_chk() are similar, but return
18915 * NULL on error.
18917 static char_u *
18918 get_tv_string(varp)
18919 typval_T *varp;
18921 static char_u mybuf[NUMBUFLEN];
18923 return get_tv_string_buf(varp, mybuf);
18926 static char_u *
18927 get_tv_string_buf(varp, buf)
18928 typval_T *varp;
18929 char_u *buf;
18931 char_u *res = get_tv_string_buf_chk(varp, buf);
18933 return res != NULL ? res : (char_u *)"";
18936 char_u *
18937 get_tv_string_chk(varp)
18938 typval_T *varp;
18940 static char_u mybuf[NUMBUFLEN];
18942 return get_tv_string_buf_chk(varp, mybuf);
18945 static char_u *
18946 get_tv_string_buf_chk(varp, buf)
18947 typval_T *varp;
18948 char_u *buf;
18950 switch (varp->v_type)
18952 case VAR_NUMBER:
18953 sprintf((char *)buf, "%ld", (long)varp->vval.v_number);
18954 return buf;
18955 case VAR_FUNC:
18956 EMSG(_("E729: using Funcref as a String"));
18957 break;
18958 case VAR_LIST:
18959 EMSG(_("E730: using List as a String"));
18960 break;
18961 case VAR_DICT:
18962 EMSG(_("E731: using Dictionary as a String"));
18963 break;
18964 #ifdef FEAT_FLOAT
18965 case VAR_FLOAT:
18966 EMSG(_("E806: using Float as a String"));
18967 break;
18968 #endif
18969 case VAR_STRING:
18970 if (varp->vval.v_string != NULL)
18971 return varp->vval.v_string;
18972 return (char_u *)"";
18973 default:
18974 EMSG2(_(e_intern2), "get_tv_string_buf()");
18975 break;
18977 return NULL;
18981 * Find variable "name" in the list of variables.
18982 * Return a pointer to it if found, NULL if not found.
18983 * Careful: "a:0" variables don't have a name.
18984 * When "htp" is not NULL we are writing to the variable, set "htp" to the
18985 * hashtab_T used.
18987 static dictitem_T *
18988 find_var(name, htp)
18989 char_u *name;
18990 hashtab_T **htp;
18992 char_u *varname;
18993 hashtab_T *ht;
18995 ht = find_var_ht(name, &varname);
18996 if (htp != NULL)
18997 *htp = ht;
18998 if (ht == NULL)
18999 return NULL;
19000 return find_var_in_ht(ht, varname, htp != NULL);
19004 * Find variable "varname" in hashtab "ht".
19005 * Returns NULL if not found.
19007 static dictitem_T *
19008 find_var_in_ht(ht, varname, writing)
19009 hashtab_T *ht;
19010 char_u *varname;
19011 int writing;
19013 hashitem_T *hi;
19015 if (*varname == NUL)
19017 /* Must be something like "s:", otherwise "ht" would be NULL. */
19018 switch (varname[-2])
19020 case 's': return &SCRIPT_SV(current_SID)->sv_var;
19021 case 'g': return &globvars_var;
19022 case 'v': return &vimvars_var;
19023 case 'b': return &curbuf->b_bufvar;
19024 case 'w': return &curwin->w_winvar;
19025 #ifdef FEAT_WINDOWS
19026 case 't': return &curtab->tp_winvar;
19027 #endif
19028 case 'l': return current_funccal == NULL
19029 ? NULL : &current_funccal->l_vars_var;
19030 case 'a': return current_funccal == NULL
19031 ? NULL : &current_funccal->l_avars_var;
19033 return NULL;
19036 hi = hash_find(ht, varname);
19037 if (HASHITEM_EMPTY(hi))
19039 /* For global variables we may try auto-loading the script. If it
19040 * worked find the variable again. Don't auto-load a script if it was
19041 * loaded already, otherwise it would be loaded every time when
19042 * checking if a function name is a Funcref variable. */
19043 if (ht == &globvarht && !writing
19044 && script_autoload(varname, FALSE) && !aborting())
19045 hi = hash_find(ht, varname);
19046 if (HASHITEM_EMPTY(hi))
19047 return NULL;
19049 return HI2DI(hi);
19053 * Find the hashtab used for a variable name.
19054 * Set "varname" to the start of name without ':'.
19056 static hashtab_T *
19057 find_var_ht(name, varname)
19058 char_u *name;
19059 char_u **varname;
19061 hashitem_T *hi;
19063 if (name[1] != ':')
19065 /* The name must not start with a colon or #. */
19066 if (name[0] == ':' || name[0] == AUTOLOAD_CHAR)
19067 return NULL;
19068 *varname = name;
19070 /* "version" is "v:version" in all scopes */
19071 hi = hash_find(&compat_hashtab, name);
19072 if (!HASHITEM_EMPTY(hi))
19073 return &compat_hashtab;
19075 if (current_funccal == NULL)
19076 return &globvarht; /* global variable */
19077 return &current_funccal->l_vars.dv_hashtab; /* l: variable */
19079 *varname = name + 2;
19080 if (*name == 'g') /* global variable */
19081 return &globvarht;
19082 /* There must be no ':' or '#' in the rest of the name, unless g: is used
19084 if (vim_strchr(name + 2, ':') != NULL
19085 || vim_strchr(name + 2, AUTOLOAD_CHAR) != NULL)
19086 return NULL;
19087 if (*name == 'b') /* buffer variable */
19088 return &curbuf->b_vars.dv_hashtab;
19089 if (*name == 'w') /* window variable */
19090 return &curwin->w_vars.dv_hashtab;
19091 #ifdef FEAT_WINDOWS
19092 if (*name == 't') /* tab page variable */
19093 return &curtab->tp_vars.dv_hashtab;
19094 #endif
19095 if (*name == 'v') /* v: variable */
19096 return &vimvarht;
19097 if (*name == 'a' && current_funccal != NULL) /* function argument */
19098 return &current_funccal->l_avars.dv_hashtab;
19099 if (*name == 'l' && current_funccal != NULL) /* local function variable */
19100 return &current_funccal->l_vars.dv_hashtab;
19101 if (*name == 's' /* script variable */
19102 && current_SID > 0 && current_SID <= ga_scripts.ga_len)
19103 return &SCRIPT_VARS(current_SID);
19104 return NULL;
19108 * Get the string value of a (global/local) variable.
19109 * Returns NULL when it doesn't exist.
19111 char_u *
19112 get_var_value(name)
19113 char_u *name;
19115 dictitem_T *v;
19117 v = find_var(name, NULL);
19118 if (v == NULL)
19119 return NULL;
19120 return get_tv_string(&v->di_tv);
19124 * Allocate a new hashtab for a sourced script. It will be used while
19125 * sourcing this script and when executing functions defined in the script.
19127 void
19128 new_script_vars(id)
19129 scid_T id;
19131 int i;
19132 hashtab_T *ht;
19133 scriptvar_T *sv;
19135 if (ga_grow(&ga_scripts, (int)(id - ga_scripts.ga_len)) == OK)
19137 /* Re-allocating ga_data means that an ht_array pointing to
19138 * ht_smallarray becomes invalid. We can recognize this: ht_mask is
19139 * at its init value. Also reset "v_dict", it's always the same. */
19140 for (i = 1; i <= ga_scripts.ga_len; ++i)
19142 ht = &SCRIPT_VARS(i);
19143 if (ht->ht_mask == HT_INIT_SIZE - 1)
19144 ht->ht_array = ht->ht_smallarray;
19145 sv = SCRIPT_SV(i);
19146 sv->sv_var.di_tv.vval.v_dict = &sv->sv_dict;
19149 while (ga_scripts.ga_len < id)
19151 sv = SCRIPT_SV(ga_scripts.ga_len + 1) =
19152 (scriptvar_T *)alloc_clear(sizeof(scriptvar_T));
19153 init_var_dict(&sv->sv_dict, &sv->sv_var);
19154 ++ga_scripts.ga_len;
19160 * Initialize dictionary "dict" as a scope and set variable "dict_var" to
19161 * point to it.
19163 void
19164 init_var_dict(dict, dict_var)
19165 dict_T *dict;
19166 dictitem_T *dict_var;
19168 hash_init(&dict->dv_hashtab);
19169 dict->dv_refcount = DO_NOT_FREE_CNT;
19170 dict->dv_copyID = 0;
19171 dict_var->di_tv.vval.v_dict = dict;
19172 dict_var->di_tv.v_type = VAR_DICT;
19173 dict_var->di_tv.v_lock = VAR_FIXED;
19174 dict_var->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
19175 dict_var->di_key[0] = NUL;
19179 * Clean up a list of internal variables.
19180 * Frees all allocated variables and the value they contain.
19181 * Clears hashtab "ht", does not free it.
19183 void
19184 vars_clear(ht)
19185 hashtab_T *ht;
19187 vars_clear_ext(ht, TRUE);
19191 * Like vars_clear(), but only free the value if "free_val" is TRUE.
19193 static void
19194 vars_clear_ext(ht, free_val)
19195 hashtab_T *ht;
19196 int free_val;
19198 int todo;
19199 hashitem_T *hi;
19200 dictitem_T *v;
19202 hash_lock(ht);
19203 todo = (int)ht->ht_used;
19204 for (hi = ht->ht_array; todo > 0; ++hi)
19206 if (!HASHITEM_EMPTY(hi))
19208 --todo;
19210 /* Free the variable. Don't remove it from the hashtab,
19211 * ht_array might change then. hash_clear() takes care of it
19212 * later. */
19213 v = HI2DI(hi);
19214 if (free_val)
19215 clear_tv(&v->di_tv);
19216 if ((v->di_flags & DI_FLAGS_FIX) == 0)
19217 vim_free(v);
19220 hash_clear(ht);
19221 ht->ht_used = 0;
19225 * Delete a variable from hashtab "ht" at item "hi".
19226 * Clear the variable value and free the dictitem.
19228 static void
19229 delete_var(ht, hi)
19230 hashtab_T *ht;
19231 hashitem_T *hi;
19233 dictitem_T *di = HI2DI(hi);
19235 hash_remove(ht, hi);
19236 clear_tv(&di->di_tv);
19237 vim_free(di);
19241 * List the value of one internal variable.
19243 static void
19244 list_one_var(v, prefix, first)
19245 dictitem_T *v;
19246 char_u *prefix;
19247 int *first;
19249 char_u *tofree;
19250 char_u *s;
19251 char_u numbuf[NUMBUFLEN];
19253 current_copyID += COPYID_INC;
19254 s = echo_string(&v->di_tv, &tofree, numbuf, current_copyID);
19255 list_one_var_a(prefix, v->di_key, v->di_tv.v_type,
19256 s == NULL ? (char_u *)"" : s, first);
19257 vim_free(tofree);
19260 static void
19261 list_one_var_a(prefix, name, type, string, first)
19262 char_u *prefix;
19263 char_u *name;
19264 int type;
19265 char_u *string;
19266 int *first; /* when TRUE clear rest of screen and set to FALSE */
19268 /* don't use msg() or msg_attr() to avoid overwriting "v:statusmsg" */
19269 msg_start();
19270 msg_puts(prefix);
19271 if (name != NULL) /* "a:" vars don't have a name stored */
19272 msg_puts(name);
19273 msg_putchar(' ');
19274 msg_advance(22);
19275 if (type == VAR_NUMBER)
19276 msg_putchar('#');
19277 else if (type == VAR_FUNC)
19278 msg_putchar('*');
19279 else if (type == VAR_LIST)
19281 msg_putchar('[');
19282 if (*string == '[')
19283 ++string;
19285 else if (type == VAR_DICT)
19287 msg_putchar('{');
19288 if (*string == '{')
19289 ++string;
19291 else
19292 msg_putchar(' ');
19294 msg_outtrans(string);
19296 if (type == VAR_FUNC)
19297 msg_puts((char_u *)"()");
19298 if (*first)
19300 msg_clr_eos();
19301 *first = FALSE;
19306 * Set variable "name" to value in "tv".
19307 * If the variable already exists, the value is updated.
19308 * Otherwise the variable is created.
19310 static void
19311 set_var(name, tv, copy)
19312 char_u *name;
19313 typval_T *tv;
19314 int copy; /* make copy of value in "tv" */
19316 dictitem_T *v;
19317 char_u *varname;
19318 hashtab_T *ht;
19319 char_u *p;
19321 ht = find_var_ht(name, &varname);
19322 if (ht == NULL || *varname == NUL)
19324 EMSG2(_(e_illvar), name);
19325 return;
19327 v = find_var_in_ht(ht, varname, TRUE);
19329 if (tv->v_type == VAR_FUNC)
19331 if (!(vim_strchr((char_u *)"wbs", name[0]) != NULL && name[1] == ':')
19332 && !ASCII_ISUPPER((name[0] != NUL && name[1] == ':')
19333 ? name[2] : name[0]))
19335 EMSG2(_("E704: Funcref variable name must start with a capital: %s"), name);
19336 return;
19338 /* Don't allow hiding a function. When "v" is not NULL we migth be
19339 * assigning another function to the same var, the type is checked
19340 * below. */
19341 if (v == NULL && function_exists(name))
19343 EMSG2(_("E705: Variable name conflicts with existing function: %s"),
19344 name);
19345 return;
19349 if (v != NULL)
19351 /* existing variable, need to clear the value */
19352 if (var_check_ro(v->di_flags, name)
19353 || tv_check_lock(v->di_tv.v_lock, name))
19354 return;
19355 if (v->di_tv.v_type != tv->v_type
19356 && !((v->di_tv.v_type == VAR_STRING
19357 || v->di_tv.v_type == VAR_NUMBER)
19358 && (tv->v_type == VAR_STRING
19359 || tv->v_type == VAR_NUMBER))
19360 #ifdef FEAT_FLOAT
19361 && !((v->di_tv.v_type == VAR_NUMBER
19362 || v->di_tv.v_type == VAR_FLOAT)
19363 && (tv->v_type == VAR_NUMBER
19364 || tv->v_type == VAR_FLOAT))
19365 #endif
19368 EMSG2(_("E706: Variable type mismatch for: %s"), name);
19369 return;
19373 * Handle setting internal v: variables separately: we don't change
19374 * the type.
19376 if (ht == &vimvarht)
19378 if (v->di_tv.v_type == VAR_STRING)
19380 vim_free(v->di_tv.vval.v_string);
19381 if (copy || tv->v_type != VAR_STRING)
19382 v->di_tv.vval.v_string = vim_strsave(get_tv_string(tv));
19383 else
19385 /* Take over the string to avoid an extra alloc/free. */
19386 v->di_tv.vval.v_string = tv->vval.v_string;
19387 tv->vval.v_string = NULL;
19390 else if (v->di_tv.v_type != VAR_NUMBER)
19391 EMSG2(_(e_intern2), "set_var()");
19392 else
19394 v->di_tv.vval.v_number = get_tv_number(tv);
19395 if (STRCMP(varname, "searchforward") == 0)
19396 set_search_direction(v->di_tv.vval.v_number ? '/' : '?');
19398 return;
19401 clear_tv(&v->di_tv);
19403 else /* add a new variable */
19405 /* Can't add "v:" variable. */
19406 if (ht == &vimvarht)
19408 EMSG2(_(e_illvar), name);
19409 return;
19412 /* Make sure the variable name is valid. */
19413 for (p = varname; *p != NUL; ++p)
19414 if (!eval_isnamec1(*p) && (p == varname || !VIM_ISDIGIT(*p))
19415 && *p != AUTOLOAD_CHAR)
19417 EMSG2(_(e_illvar), varname);
19418 return;
19421 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
19422 + STRLEN(varname)));
19423 if (v == NULL)
19424 return;
19425 STRCPY(v->di_key, varname);
19426 if (hash_add(ht, DI2HIKEY(v)) == FAIL)
19428 vim_free(v);
19429 return;
19431 v->di_flags = 0;
19434 if (copy || tv->v_type == VAR_NUMBER || tv->v_type == VAR_FLOAT)
19435 copy_tv(tv, &v->di_tv);
19436 else
19438 v->di_tv = *tv;
19439 v->di_tv.v_lock = 0;
19440 init_tv(tv);
19445 * Return TRUE if di_flags "flags" indicates variable "name" is read-only.
19446 * Also give an error message.
19448 static int
19449 var_check_ro(flags, name)
19450 int flags;
19451 char_u *name;
19453 if (flags & DI_FLAGS_RO)
19455 EMSG2(_(e_readonlyvar), name);
19456 return TRUE;
19458 if ((flags & DI_FLAGS_RO_SBX) && sandbox)
19460 EMSG2(_(e_readonlysbx), name);
19461 return TRUE;
19463 return FALSE;
19467 * Return TRUE if di_flags "flags" indicates variable "name" is fixed.
19468 * Also give an error message.
19470 static int
19471 var_check_fixed(flags, name)
19472 int flags;
19473 char_u *name;
19475 if (flags & DI_FLAGS_FIX)
19477 EMSG2(_("E795: Cannot delete variable %s"), name);
19478 return TRUE;
19480 return FALSE;
19484 * Return TRUE if typeval "tv" is set to be locked (immutable).
19485 * Also give an error message, using "name".
19487 static int
19488 tv_check_lock(lock, name)
19489 int lock;
19490 char_u *name;
19492 if (lock & VAR_LOCKED)
19494 EMSG2(_("E741: Value is locked: %s"),
19495 name == NULL ? (char_u *)_("Unknown") : name);
19496 return TRUE;
19498 if (lock & VAR_FIXED)
19500 EMSG2(_("E742: Cannot change value of %s"),
19501 name == NULL ? (char_u *)_("Unknown") : name);
19502 return TRUE;
19504 return FALSE;
19508 * Copy the values from typval_T "from" to typval_T "to".
19509 * When needed allocates string or increases reference count.
19510 * Does not make a copy of a list or dict but copies the reference!
19511 * It is OK for "from" and "to" to point to the same item. This is used to
19512 * make a copy later.
19514 void
19515 copy_tv(from, to)
19516 typval_T *from;
19517 typval_T *to;
19519 to->v_type = from->v_type;
19520 to->v_lock = 0;
19521 switch (from->v_type)
19523 case VAR_NUMBER:
19524 to->vval.v_number = from->vval.v_number;
19525 break;
19526 #ifdef FEAT_FLOAT
19527 case VAR_FLOAT:
19528 to->vval.v_float = from->vval.v_float;
19529 break;
19530 #endif
19531 case VAR_STRING:
19532 case VAR_FUNC:
19533 if (from->vval.v_string == NULL)
19534 to->vval.v_string = NULL;
19535 else
19537 to->vval.v_string = vim_strsave(from->vval.v_string);
19538 if (from->v_type == VAR_FUNC)
19539 func_ref(to->vval.v_string);
19541 break;
19542 case VAR_LIST:
19543 if (from->vval.v_list == NULL)
19544 to->vval.v_list = NULL;
19545 else
19547 to->vval.v_list = from->vval.v_list;
19548 ++to->vval.v_list->lv_refcount;
19550 break;
19551 case VAR_DICT:
19552 if (from->vval.v_dict == NULL)
19553 to->vval.v_dict = NULL;
19554 else
19556 to->vval.v_dict = from->vval.v_dict;
19557 ++to->vval.v_dict->dv_refcount;
19559 break;
19560 default:
19561 EMSG2(_(e_intern2), "copy_tv()");
19562 break;
19567 * Make a copy of an item.
19568 * Lists and Dictionaries are also copied. A deep copy if "deep" is set.
19569 * For deepcopy() "copyID" is zero for a full copy or the ID for when a
19570 * reference to an already copied list/dict can be used.
19571 * Returns FAIL or OK.
19573 static int
19574 item_copy(from, to, deep, copyID)
19575 typval_T *from;
19576 typval_T *to;
19577 int deep;
19578 int copyID;
19580 static int recurse = 0;
19581 int ret = OK;
19583 if (recurse >= DICT_MAXNEST)
19585 EMSG(_("E698: variable nested too deep for making a copy"));
19586 return FAIL;
19588 ++recurse;
19590 switch (from->v_type)
19592 case VAR_NUMBER:
19593 #ifdef FEAT_FLOAT
19594 case VAR_FLOAT:
19595 #endif
19596 case VAR_STRING:
19597 case VAR_FUNC:
19598 copy_tv(from, to);
19599 break;
19600 case VAR_LIST:
19601 to->v_type = VAR_LIST;
19602 to->v_lock = 0;
19603 if (from->vval.v_list == NULL)
19604 to->vval.v_list = NULL;
19605 else if (copyID != 0 && from->vval.v_list->lv_copyID == copyID)
19607 /* use the copy made earlier */
19608 to->vval.v_list = from->vval.v_list->lv_copylist;
19609 ++to->vval.v_list->lv_refcount;
19611 else
19612 to->vval.v_list = list_copy(from->vval.v_list, deep, copyID);
19613 if (to->vval.v_list == NULL)
19614 ret = FAIL;
19615 break;
19616 case VAR_DICT:
19617 to->v_type = VAR_DICT;
19618 to->v_lock = 0;
19619 if (from->vval.v_dict == NULL)
19620 to->vval.v_dict = NULL;
19621 else if (copyID != 0 && from->vval.v_dict->dv_copyID == copyID)
19623 /* use the copy made earlier */
19624 to->vval.v_dict = from->vval.v_dict->dv_copydict;
19625 ++to->vval.v_dict->dv_refcount;
19627 else
19628 to->vval.v_dict = dict_copy(from->vval.v_dict, deep, copyID);
19629 if (to->vval.v_dict == NULL)
19630 ret = FAIL;
19631 break;
19632 default:
19633 EMSG2(_(e_intern2), "item_copy()");
19634 ret = FAIL;
19636 --recurse;
19637 return ret;
19641 * ":echo expr1 ..." print each argument separated with a space, add a
19642 * newline at the end.
19643 * ":echon expr1 ..." print each argument plain.
19645 void
19646 ex_echo(eap)
19647 exarg_T *eap;
19649 char_u *arg = eap->arg;
19650 typval_T rettv;
19651 char_u *tofree;
19652 char_u *p;
19653 int needclr = TRUE;
19654 int atstart = TRUE;
19655 char_u numbuf[NUMBUFLEN];
19657 if (eap->skip)
19658 ++emsg_skip;
19659 while (*arg != NUL && *arg != '|' && *arg != '\n' && !got_int)
19661 /* If eval1() causes an error message the text from the command may
19662 * still need to be cleared. E.g., "echo 22,44". */
19663 need_clr_eos = needclr;
19665 p = arg;
19666 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19669 * Report the invalid expression unless the expression evaluation
19670 * has been cancelled due to an aborting error, an interrupt, or an
19671 * exception.
19673 if (!aborting())
19674 EMSG2(_(e_invexpr2), p);
19675 need_clr_eos = FALSE;
19676 break;
19678 need_clr_eos = FALSE;
19680 if (!eap->skip)
19682 if (atstart)
19684 atstart = FALSE;
19685 /* Call msg_start() after eval1(), evaluating the expression
19686 * may cause a message to appear. */
19687 if (eap->cmdidx == CMD_echo)
19688 msg_start();
19690 else if (eap->cmdidx == CMD_echo)
19691 msg_puts_attr((char_u *)" ", echo_attr);
19692 current_copyID += COPYID_INC;
19693 p = echo_string(&rettv, &tofree, numbuf, current_copyID);
19694 if (p != NULL)
19695 for ( ; *p != NUL && !got_int; ++p)
19697 if (*p == '\n' || *p == '\r' || *p == TAB)
19699 if (*p != TAB && needclr)
19701 /* remove any text still there from the command */
19702 msg_clr_eos();
19703 needclr = FALSE;
19705 msg_putchar_attr(*p, echo_attr);
19707 else
19709 #ifdef FEAT_MBYTE
19710 if (has_mbyte)
19712 int i = (*mb_ptr2len)(p);
19714 (void)msg_outtrans_len_attr(p, i, echo_attr);
19715 p += i - 1;
19717 else
19718 #endif
19719 (void)msg_outtrans_len_attr(p, 1, echo_attr);
19722 vim_free(tofree);
19724 clear_tv(&rettv);
19725 arg = skipwhite(arg);
19727 eap->nextcmd = check_nextcmd(arg);
19729 if (eap->skip)
19730 --emsg_skip;
19731 else
19733 /* remove text that may still be there from the command */
19734 if (needclr)
19735 msg_clr_eos();
19736 if (eap->cmdidx == CMD_echo)
19737 msg_end();
19742 * ":echohl {name}".
19744 void
19745 ex_echohl(eap)
19746 exarg_T *eap;
19748 int id;
19750 id = syn_name2id(eap->arg);
19751 if (id == 0)
19752 echo_attr = 0;
19753 else
19754 echo_attr = syn_id2attr(id);
19758 * ":execute expr1 ..." execute the result of an expression.
19759 * ":echomsg expr1 ..." Print a message
19760 * ":echoerr expr1 ..." Print an error
19761 * Each gets spaces around each argument and a newline at the end for
19762 * echo commands
19764 void
19765 ex_execute(eap)
19766 exarg_T *eap;
19768 char_u *arg = eap->arg;
19769 typval_T rettv;
19770 int ret = OK;
19771 char_u *p;
19772 garray_T ga;
19773 int len;
19774 int save_did_emsg;
19776 ga_init2(&ga, 1, 80);
19778 if (eap->skip)
19779 ++emsg_skip;
19780 while (*arg != NUL && *arg != '|' && *arg != '\n')
19782 p = arg;
19783 if (eval1(&arg, &rettv, !eap->skip) == FAIL)
19786 * Report the invalid expression unless the expression evaluation
19787 * has been cancelled due to an aborting error, an interrupt, or an
19788 * exception.
19790 if (!aborting())
19791 EMSG2(_(e_invexpr2), p);
19792 ret = FAIL;
19793 break;
19796 if (!eap->skip)
19798 p = get_tv_string(&rettv);
19799 len = (int)STRLEN(p);
19800 if (ga_grow(&ga, len + 2) == FAIL)
19802 clear_tv(&rettv);
19803 ret = FAIL;
19804 break;
19806 if (ga.ga_len)
19807 ((char_u *)(ga.ga_data))[ga.ga_len++] = ' ';
19808 STRCPY((char_u *)(ga.ga_data) + ga.ga_len, p);
19809 ga.ga_len += len;
19812 clear_tv(&rettv);
19813 arg = skipwhite(arg);
19816 if (ret != FAIL && ga.ga_data != NULL)
19818 if (eap->cmdidx == CMD_echomsg)
19820 MSG_ATTR(ga.ga_data, echo_attr);
19821 out_flush();
19823 else if (eap->cmdidx == CMD_echoerr)
19825 /* We don't want to abort following commands, restore did_emsg. */
19826 save_did_emsg = did_emsg;
19827 EMSG((char_u *)ga.ga_data);
19828 if (!force_abort)
19829 did_emsg = save_did_emsg;
19831 else if (eap->cmdidx == CMD_execute)
19832 do_cmdline((char_u *)ga.ga_data,
19833 eap->getline, eap->cookie, DOCMD_NOWAIT|DOCMD_VERBOSE);
19836 ga_clear(&ga);
19838 if (eap->skip)
19839 --emsg_skip;
19841 eap->nextcmd = check_nextcmd(arg);
19845 * Skip over the name of an option: "&option", "&g:option" or "&l:option".
19846 * "arg" points to the "&" or '+' when called, to "option" when returning.
19847 * Returns NULL when no option name found. Otherwise pointer to the char
19848 * after the option name.
19850 static char_u *
19851 find_option_end(arg, opt_flags)
19852 char_u **arg;
19853 int *opt_flags;
19855 char_u *p = *arg;
19857 ++p;
19858 if (*p == 'g' && p[1] == ':')
19860 *opt_flags = OPT_GLOBAL;
19861 p += 2;
19863 else if (*p == 'l' && p[1] == ':')
19865 *opt_flags = OPT_LOCAL;
19866 p += 2;
19868 else
19869 *opt_flags = 0;
19871 if (!ASCII_ISALPHA(*p))
19872 return NULL;
19873 *arg = p;
19875 if (p[0] == 't' && p[1] == '_' && p[2] != NUL && p[3] != NUL)
19876 p += 4; /* termcap option */
19877 else
19878 while (ASCII_ISALPHA(*p))
19879 ++p;
19880 return p;
19884 * ":function"
19886 void
19887 ex_function(eap)
19888 exarg_T *eap;
19890 char_u *theline;
19891 int j;
19892 int c;
19893 int saved_did_emsg;
19894 char_u *name = NULL;
19895 char_u *p;
19896 char_u *arg;
19897 char_u *line_arg = NULL;
19898 garray_T newargs;
19899 garray_T newlines;
19900 int varargs = FALSE;
19901 int mustend = FALSE;
19902 int flags = 0;
19903 ufunc_T *fp;
19904 int indent;
19905 int nesting;
19906 char_u *skip_until = NULL;
19907 dictitem_T *v;
19908 funcdict_T fudi;
19909 static int func_nr = 0; /* number for nameless function */
19910 int paren;
19911 hashtab_T *ht;
19912 int todo;
19913 hashitem_T *hi;
19914 int sourcing_lnum_off;
19917 * ":function" without argument: list functions.
19919 if (ends_excmd(*eap->arg))
19921 if (!eap->skip)
19923 todo = (int)func_hashtab.ht_used;
19924 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19926 if (!HASHITEM_EMPTY(hi))
19928 --todo;
19929 fp = HI2UF(hi);
19930 if (!isdigit(*fp->uf_name))
19931 list_func_head(fp, FALSE);
19935 eap->nextcmd = check_nextcmd(eap->arg);
19936 return;
19940 * ":function /pat": list functions matching pattern.
19942 if (*eap->arg == '/')
19944 p = skip_regexp(eap->arg + 1, '/', TRUE, NULL);
19945 if (!eap->skip)
19947 regmatch_T regmatch;
19949 c = *p;
19950 *p = NUL;
19951 regmatch.regprog = vim_regcomp(eap->arg + 1, RE_MAGIC);
19952 *p = c;
19953 if (regmatch.regprog != NULL)
19955 regmatch.rm_ic = p_ic;
19957 todo = (int)func_hashtab.ht_used;
19958 for (hi = func_hashtab.ht_array; todo > 0 && !got_int; ++hi)
19960 if (!HASHITEM_EMPTY(hi))
19962 --todo;
19963 fp = HI2UF(hi);
19964 if (!isdigit(*fp->uf_name)
19965 && vim_regexec(&regmatch, fp->uf_name, 0))
19966 list_func_head(fp, FALSE);
19969 vim_free(regmatch.regprog);
19972 if (*p == '/')
19973 ++p;
19974 eap->nextcmd = check_nextcmd(p);
19975 return;
19979 * Get the function name. There are these situations:
19980 * func normal function name
19981 * "name" == func, "fudi.fd_dict" == NULL
19982 * dict.func new dictionary entry
19983 * "name" == NULL, "fudi.fd_dict" set,
19984 * "fudi.fd_di" == NULL, "fudi.fd_newkey" == func
19985 * dict.func existing dict entry with a Funcref
19986 * "name" == func, "fudi.fd_dict" set,
19987 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19988 * dict.func existing dict entry that's not a Funcref
19989 * "name" == NULL, "fudi.fd_dict" set,
19990 * "fudi.fd_di" set, "fudi.fd_newkey" == NULL
19992 p = eap->arg;
19993 name = trans_function_name(&p, eap->skip, 0, &fudi);
19994 paren = (vim_strchr(p, '(') != NULL);
19995 if (name == NULL && (fudi.fd_dict == NULL || !paren) && !eap->skip)
19998 * Return on an invalid expression in braces, unless the expression
19999 * evaluation has been cancelled due to an aborting error, an
20000 * interrupt, or an exception.
20002 if (!aborting())
20004 if (!eap->skip && fudi.fd_newkey != NULL)
20005 EMSG2(_(e_dictkey), fudi.fd_newkey);
20006 vim_free(fudi.fd_newkey);
20007 return;
20009 else
20010 eap->skip = TRUE;
20013 /* An error in a function call during evaluation of an expression in magic
20014 * braces should not cause the function not to be defined. */
20015 saved_did_emsg = did_emsg;
20016 did_emsg = FALSE;
20019 * ":function func" with only function name: list function.
20021 if (!paren)
20023 if (!ends_excmd(*skipwhite(p)))
20025 EMSG(_(e_trailing));
20026 goto ret_free;
20028 eap->nextcmd = check_nextcmd(p);
20029 if (eap->nextcmd != NULL)
20030 *p = NUL;
20031 if (!eap->skip && !got_int)
20033 fp = find_func(name);
20034 if (fp != NULL)
20036 list_func_head(fp, TRUE);
20037 for (j = 0; j < fp->uf_lines.ga_len && !got_int; ++j)
20039 if (FUNCLINE(fp, j) == NULL)
20040 continue;
20041 msg_putchar('\n');
20042 msg_outnum((long)(j + 1));
20043 if (j < 9)
20044 msg_putchar(' ');
20045 if (j < 99)
20046 msg_putchar(' ');
20047 msg_prt_line(FUNCLINE(fp, j), FALSE);
20048 out_flush(); /* show a line at a time */
20049 ui_breakcheck();
20051 if (!got_int)
20053 msg_putchar('\n');
20054 msg_puts((char_u *)" endfunction");
20057 else
20058 emsg_funcname(N_("E123: Undefined function: %s"), name);
20060 goto ret_free;
20064 * ":function name(arg1, arg2)" Define function.
20066 p = skipwhite(p);
20067 if (*p != '(')
20069 if (!eap->skip)
20071 EMSG2(_("E124: Missing '(': %s"), eap->arg);
20072 goto ret_free;
20074 /* attempt to continue by skipping some text */
20075 if (vim_strchr(p, '(') != NULL)
20076 p = vim_strchr(p, '(');
20078 p = skipwhite(p + 1);
20080 ga_init2(&newargs, (int)sizeof(char_u *), 3);
20081 ga_init2(&newlines, (int)sizeof(char_u *), 3);
20083 if (!eap->skip)
20085 /* Check the name of the function. Unless it's a dictionary function
20086 * (that we are overwriting). */
20087 if (name != NULL)
20088 arg = name;
20089 else
20090 arg = fudi.fd_newkey;
20091 if (arg != NULL && (fudi.fd_di == NULL
20092 || fudi.fd_di->di_tv.v_type != VAR_FUNC))
20094 if (*arg == K_SPECIAL)
20095 j = 3;
20096 else
20097 j = 0;
20098 while (arg[j] != NUL && (j == 0 ? eval_isnamec1(arg[j])
20099 : eval_isnamec(arg[j])))
20100 ++j;
20101 if (arg[j] != NUL)
20102 emsg_funcname((char *)e_invarg2, arg);
20107 * Isolate the arguments: "arg1, arg2, ...)"
20109 while (*p != ')')
20111 if (p[0] == '.' && p[1] == '.' && p[2] == '.')
20113 varargs = TRUE;
20114 p += 3;
20115 mustend = TRUE;
20117 else
20119 arg = p;
20120 while (ASCII_ISALNUM(*p) || *p == '_')
20121 ++p;
20122 if (arg == p || isdigit(*arg)
20123 || (p - arg == 9 && STRNCMP(arg, "firstline", 9) == 0)
20124 || (p - arg == 8 && STRNCMP(arg, "lastline", 8) == 0))
20126 if (!eap->skip)
20127 EMSG2(_("E125: Illegal argument: %s"), arg);
20128 break;
20130 if (ga_grow(&newargs, 1) == FAIL)
20131 goto erret;
20132 c = *p;
20133 *p = NUL;
20134 arg = vim_strsave(arg);
20135 if (arg == NULL)
20136 goto erret;
20137 ((char_u **)(newargs.ga_data))[newargs.ga_len] = arg;
20138 *p = c;
20139 newargs.ga_len++;
20140 if (*p == ',')
20141 ++p;
20142 else
20143 mustend = TRUE;
20145 p = skipwhite(p);
20146 if (mustend && *p != ')')
20148 if (!eap->skip)
20149 EMSG2(_(e_invarg2), eap->arg);
20150 break;
20153 ++p; /* skip the ')' */
20155 /* find extra arguments "range", "dict" and "abort" */
20156 for (;;)
20158 p = skipwhite(p);
20159 if (STRNCMP(p, "range", 5) == 0)
20161 flags |= FC_RANGE;
20162 p += 5;
20164 else if (STRNCMP(p, "dict", 4) == 0)
20166 flags |= FC_DICT;
20167 p += 4;
20169 else if (STRNCMP(p, "abort", 5) == 0)
20171 flags |= FC_ABORT;
20172 p += 5;
20174 else
20175 break;
20178 /* When there is a line break use what follows for the function body.
20179 * Makes 'exe "func Test()\n...\nendfunc"' work. */
20180 if (*p == '\n')
20181 line_arg = p + 1;
20182 else if (*p != NUL && *p != '"' && !eap->skip && !did_emsg)
20183 EMSG(_(e_trailing));
20186 * Read the body of the function, until ":endfunction" is found.
20188 if (KeyTyped)
20190 /* Check if the function already exists, don't let the user type the
20191 * whole function before telling him it doesn't work! For a script we
20192 * need to skip the body to be able to find what follows. */
20193 if (!eap->skip && !eap->forceit)
20195 if (fudi.fd_dict != NULL && fudi.fd_newkey == NULL)
20196 EMSG(_(e_funcdict));
20197 else if (name != NULL && find_func(name) != NULL)
20198 emsg_funcname(e_funcexts, name);
20201 if (!eap->skip && did_emsg)
20202 goto erret;
20204 msg_putchar('\n'); /* don't overwrite the function name */
20205 cmdline_row = msg_row;
20208 indent = 2;
20209 nesting = 0;
20210 for (;;)
20212 msg_scroll = TRUE;
20213 need_wait_return = FALSE;
20214 sourcing_lnum_off = sourcing_lnum;
20216 if (line_arg != NULL)
20218 /* Use eap->arg, split up in parts by line breaks. */
20219 theline = line_arg;
20220 p = vim_strchr(theline, '\n');
20221 if (p == NULL)
20222 line_arg += STRLEN(line_arg);
20223 else
20225 *p = NUL;
20226 line_arg = p + 1;
20229 else if (eap->getline == NULL)
20230 theline = getcmdline(':', 0L, indent);
20231 else
20232 theline = eap->getline(':', eap->cookie, indent);
20233 if (KeyTyped)
20234 lines_left = Rows - 1;
20235 if (theline == NULL)
20237 EMSG(_("E126: Missing :endfunction"));
20238 goto erret;
20241 /* Detect line continuation: sourcing_lnum increased more than one. */
20242 if (sourcing_lnum > sourcing_lnum_off + 1)
20243 sourcing_lnum_off = sourcing_lnum - sourcing_lnum_off - 1;
20244 else
20245 sourcing_lnum_off = 0;
20247 if (skip_until != NULL)
20249 /* between ":append" and "." and between ":python <<EOF" and "EOF"
20250 * don't check for ":endfunc". */
20251 if (STRCMP(theline, skip_until) == 0)
20253 vim_free(skip_until);
20254 skip_until = NULL;
20257 else
20259 /* skip ':' and blanks*/
20260 for (p = theline; vim_iswhite(*p) || *p == ':'; ++p)
20263 /* Check for "endfunction". */
20264 if (checkforcmd(&p, "endfunction", 4) && nesting-- == 0)
20266 if (line_arg == NULL)
20267 vim_free(theline);
20268 break;
20271 /* Increase indent inside "if", "while", "for" and "try", decrease
20272 * at "end". */
20273 if (indent > 2 && STRNCMP(p, "end", 3) == 0)
20274 indent -= 2;
20275 else if (STRNCMP(p, "if", 2) == 0
20276 || STRNCMP(p, "wh", 2) == 0
20277 || STRNCMP(p, "for", 3) == 0
20278 || STRNCMP(p, "try", 3) == 0)
20279 indent += 2;
20281 /* Check for defining a function inside this function. */
20282 if (checkforcmd(&p, "function", 2))
20284 if (*p == '!')
20285 p = skipwhite(p + 1);
20286 p += eval_fname_script(p);
20287 if (ASCII_ISALPHA(*p))
20289 vim_free(trans_function_name(&p, TRUE, 0, NULL));
20290 if (*skipwhite(p) == '(')
20292 ++nesting;
20293 indent += 2;
20298 /* Check for ":append" or ":insert". */
20299 p = skip_range(p, NULL);
20300 if ((p[0] == 'a' && (!ASCII_ISALPHA(p[1]) || p[1] == 'p'))
20301 || (p[0] == 'i'
20302 && (!ASCII_ISALPHA(p[1]) || (p[1] == 'n'
20303 && (!ASCII_ISALPHA(p[2]) || (p[2] == 's'))))))
20304 skip_until = vim_strsave((char_u *)".");
20306 /* Check for ":python <<EOF", ":tcl <<EOF", etc. */
20307 arg = skipwhite(skiptowhite(p));
20308 if (arg[0] == '<' && arg[1] =='<'
20309 && ((p[0] == 'p' && p[1] == 'y'
20310 && (!ASCII_ISALPHA(p[2]) || p[2] == 't'))
20311 || (p[0] == 'p' && p[1] == 'e'
20312 && (!ASCII_ISALPHA(p[2]) || p[2] == 'r'))
20313 || (p[0] == 't' && p[1] == 'c'
20314 && (!ASCII_ISALPHA(p[2]) || p[2] == 'l'))
20315 || (p[0] == 'r' && p[1] == 'u' && p[2] == 'b'
20316 && (!ASCII_ISALPHA(p[3]) || p[3] == 'y'))
20317 || (p[0] == 'm' && p[1] == 'z'
20318 && (!ASCII_ISALPHA(p[2]) || p[2] == 's'))
20321 /* ":python <<" continues until a dot, like ":append" */
20322 p = skipwhite(arg + 2);
20323 if (*p == NUL)
20324 skip_until = vim_strsave((char_u *)".");
20325 else
20326 skip_until = vim_strsave(p);
20330 /* Add the line to the function. */
20331 if (ga_grow(&newlines, 1 + sourcing_lnum_off) == FAIL)
20333 if (line_arg == NULL)
20334 vim_free(theline);
20335 goto erret;
20338 /* Copy the line to newly allocated memory. get_one_sourceline()
20339 * allocates 250 bytes per line, this saves 80% on average. The cost
20340 * is an extra alloc/free. */
20341 p = vim_strsave(theline);
20342 if (p != NULL)
20344 if (line_arg == NULL)
20345 vim_free(theline);
20346 theline = p;
20349 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = theline;
20351 /* Add NULL lines for continuation lines, so that the line count is
20352 * equal to the index in the growarray. */
20353 while (sourcing_lnum_off-- > 0)
20354 ((char_u **)(newlines.ga_data))[newlines.ga_len++] = NULL;
20356 /* Check for end of eap->arg. */
20357 if (line_arg != NULL && *line_arg == NUL)
20358 line_arg = NULL;
20361 /* Don't define the function when skipping commands or when an error was
20362 * detected. */
20363 if (eap->skip || did_emsg)
20364 goto erret;
20367 * If there are no errors, add the function
20369 if (fudi.fd_dict == NULL)
20371 v = find_var(name, &ht);
20372 if (v != NULL && v->di_tv.v_type == VAR_FUNC)
20374 emsg_funcname(N_("E707: Function name conflicts with variable: %s"),
20375 name);
20376 goto erret;
20379 fp = find_func(name);
20380 if (fp != NULL)
20382 if (!eap->forceit)
20384 emsg_funcname(e_funcexts, name);
20385 goto erret;
20387 if (fp->uf_calls > 0)
20389 emsg_funcname(N_("E127: Cannot redefine function %s: It is in use"),
20390 name);
20391 goto erret;
20393 /* redefine existing function */
20394 ga_clear_strings(&(fp->uf_args));
20395 ga_clear_strings(&(fp->uf_lines));
20396 vim_free(name);
20397 name = NULL;
20400 else
20402 char numbuf[20];
20404 fp = NULL;
20405 if (fudi.fd_newkey == NULL && !eap->forceit)
20407 EMSG(_(e_funcdict));
20408 goto erret;
20410 if (fudi.fd_di == NULL)
20412 /* Can't add a function to a locked dictionary */
20413 if (tv_check_lock(fudi.fd_dict->dv_lock, eap->arg))
20414 goto erret;
20416 /* Can't change an existing function if it is locked */
20417 else if (tv_check_lock(fudi.fd_di->di_tv.v_lock, eap->arg))
20418 goto erret;
20420 /* Give the function a sequential number. Can only be used with a
20421 * Funcref! */
20422 vim_free(name);
20423 sprintf(numbuf, "%d", ++func_nr);
20424 name = vim_strsave((char_u *)numbuf);
20425 if (name == NULL)
20426 goto erret;
20429 if (fp == NULL)
20431 if (fudi.fd_dict == NULL && vim_strchr(name, AUTOLOAD_CHAR) != NULL)
20433 int slen, plen;
20434 char_u *scriptname;
20436 /* Check that the autoload name matches the script name. */
20437 j = FAIL;
20438 if (sourcing_name != NULL)
20440 scriptname = autoload_name(name);
20441 if (scriptname != NULL)
20443 p = vim_strchr(scriptname, '/');
20444 plen = (int)STRLEN(p);
20445 slen = (int)STRLEN(sourcing_name);
20446 if (slen > plen && fnamecmp(p,
20447 sourcing_name + slen - plen) == 0)
20448 j = OK;
20449 vim_free(scriptname);
20452 if (j == FAIL)
20454 EMSG2(_("E746: Function name does not match script file name: %s"), name);
20455 goto erret;
20459 fp = (ufunc_T *)alloc((unsigned)(sizeof(ufunc_T) + STRLEN(name)));
20460 if (fp == NULL)
20461 goto erret;
20463 if (fudi.fd_dict != NULL)
20465 if (fudi.fd_di == NULL)
20467 /* add new dict entry */
20468 fudi.fd_di = dictitem_alloc(fudi.fd_newkey);
20469 if (fudi.fd_di == NULL)
20471 vim_free(fp);
20472 goto erret;
20474 if (dict_add(fudi.fd_dict, fudi.fd_di) == FAIL)
20476 vim_free(fudi.fd_di);
20477 vim_free(fp);
20478 goto erret;
20481 else
20482 /* overwrite existing dict entry */
20483 clear_tv(&fudi.fd_di->di_tv);
20484 fudi.fd_di->di_tv.v_type = VAR_FUNC;
20485 fudi.fd_di->di_tv.v_lock = 0;
20486 fudi.fd_di->di_tv.vval.v_string = vim_strsave(name);
20487 fp->uf_refcount = 1;
20489 /* behave like "dict" was used */
20490 flags |= FC_DICT;
20493 /* insert the new function in the function list */
20494 STRCPY(fp->uf_name, name);
20495 hash_add(&func_hashtab, UF2HIKEY(fp));
20497 fp->uf_args = newargs;
20498 fp->uf_lines = newlines;
20499 #ifdef FEAT_PROFILE
20500 fp->uf_tml_count = NULL;
20501 fp->uf_tml_total = NULL;
20502 fp->uf_tml_self = NULL;
20503 fp->uf_profiling = FALSE;
20504 if (prof_def_func())
20505 func_do_profile(fp);
20506 #endif
20507 fp->uf_varargs = varargs;
20508 fp->uf_flags = flags;
20509 fp->uf_calls = 0;
20510 fp->uf_script_ID = current_SID;
20511 goto ret_free;
20513 erret:
20514 ga_clear_strings(&newargs);
20515 ga_clear_strings(&newlines);
20516 ret_free:
20517 vim_free(skip_until);
20518 vim_free(fudi.fd_newkey);
20519 vim_free(name);
20520 did_emsg |= saved_did_emsg;
20524 * Get a function name, translating "<SID>" and "<SNR>".
20525 * Also handles a Funcref in a List or Dictionary.
20526 * Returns the function name in allocated memory, or NULL for failure.
20527 * flags:
20528 * TFN_INT: internal function name OK
20529 * TFN_QUIET: be quiet
20530 * Advances "pp" to just after the function name (if no error).
20532 static char_u *
20533 trans_function_name(pp, skip, flags, fdp)
20534 char_u **pp;
20535 int skip; /* only find the end, don't evaluate */
20536 int flags;
20537 funcdict_T *fdp; /* return: info about dictionary used */
20539 char_u *name = NULL;
20540 char_u *start;
20541 char_u *end;
20542 int lead;
20543 char_u sid_buf[20];
20544 int len;
20545 lval_T lv;
20547 if (fdp != NULL)
20548 vim_memset(fdp, 0, sizeof(funcdict_T));
20549 start = *pp;
20551 /* Check for hard coded <SNR>: already translated function ID (from a user
20552 * command). */
20553 if ((*pp)[0] == K_SPECIAL && (*pp)[1] == KS_EXTRA
20554 && (*pp)[2] == (int)KE_SNR)
20556 *pp += 3;
20557 len = get_id_len(pp) + 3;
20558 return vim_strnsave(start, len);
20561 /* A name starting with "<SID>" or "<SNR>" is local to a script. But
20562 * don't skip over "s:", get_lval() needs it for "s:dict.func". */
20563 lead = eval_fname_script(start);
20564 if (lead > 2)
20565 start += lead;
20567 end = get_lval(start, NULL, &lv, FALSE, skip, flags & TFN_QUIET,
20568 lead > 2 ? 0 : FNE_CHECK_START);
20569 if (end == start)
20571 if (!skip)
20572 EMSG(_("E129: Function name required"));
20573 goto theend;
20575 if (end == NULL || (lv.ll_tv != NULL && (lead > 2 || lv.ll_range)))
20578 * Report an invalid expression in braces, unless the expression
20579 * evaluation has been cancelled due to an aborting error, an
20580 * interrupt, or an exception.
20582 if (!aborting())
20584 if (end != NULL)
20585 EMSG2(_(e_invarg2), start);
20587 else
20588 *pp = find_name_end(start, NULL, NULL, FNE_INCL_BR);
20589 goto theend;
20592 if (lv.ll_tv != NULL)
20594 if (fdp != NULL)
20596 fdp->fd_dict = lv.ll_dict;
20597 fdp->fd_newkey = lv.ll_newkey;
20598 lv.ll_newkey = NULL;
20599 fdp->fd_di = lv.ll_di;
20601 if (lv.ll_tv->v_type == VAR_FUNC && lv.ll_tv->vval.v_string != NULL)
20603 name = vim_strsave(lv.ll_tv->vval.v_string);
20604 *pp = end;
20606 else
20608 if (!skip && !(flags & TFN_QUIET) && (fdp == NULL
20609 || lv.ll_dict == NULL || fdp->fd_newkey == NULL))
20610 EMSG(_(e_funcref));
20611 else
20612 *pp = end;
20613 name = NULL;
20615 goto theend;
20618 if (lv.ll_name == NULL)
20620 /* Error found, but continue after the function name. */
20621 *pp = end;
20622 goto theend;
20625 /* Check if the name is a Funcref. If so, use the value. */
20626 if (lv.ll_exp_name != NULL)
20628 len = (int)STRLEN(lv.ll_exp_name);
20629 name = deref_func_name(lv.ll_exp_name, &len);
20630 if (name == lv.ll_exp_name)
20631 name = NULL;
20633 else
20635 len = (int)(end - *pp);
20636 name = deref_func_name(*pp, &len);
20637 if (name == *pp)
20638 name = NULL;
20640 if (name != NULL)
20642 name = vim_strsave(name);
20643 *pp = end;
20644 goto theend;
20647 if (lv.ll_exp_name != NULL)
20649 len = (int)STRLEN(lv.ll_exp_name);
20650 if (lead <= 2 && lv.ll_name == lv.ll_exp_name
20651 && STRNCMP(lv.ll_name, "s:", 2) == 0)
20653 /* When there was "s:" already or the name expanded to get a
20654 * leading "s:" then remove it. */
20655 lv.ll_name += 2;
20656 len -= 2;
20657 lead = 2;
20660 else
20662 if (lead == 2) /* skip over "s:" */
20663 lv.ll_name += 2;
20664 len = (int)(end - lv.ll_name);
20668 * Copy the function name to allocated memory.
20669 * Accept <SID>name() inside a script, translate into <SNR>123_name().
20670 * Accept <SNR>123_name() outside a script.
20672 if (skip)
20673 lead = 0; /* do nothing */
20674 else if (lead > 0)
20676 lead = 3;
20677 if ((lv.ll_exp_name != NULL && eval_fname_sid(lv.ll_exp_name))
20678 || eval_fname_sid(*pp))
20680 /* It's "s:" or "<SID>" */
20681 if (current_SID <= 0)
20683 EMSG(_(e_usingsid));
20684 goto theend;
20686 sprintf((char *)sid_buf, "%ld_", (long)current_SID);
20687 lead += (int)STRLEN(sid_buf);
20690 else if (!(flags & TFN_INT) && builtin_function(lv.ll_name))
20692 EMSG2(_("E128: Function name must start with a capital or contain a colon: %s"), lv.ll_name);
20693 goto theend;
20695 name = alloc((unsigned)(len + lead + 1));
20696 if (name != NULL)
20698 if (lead > 0)
20700 name[0] = K_SPECIAL;
20701 name[1] = KS_EXTRA;
20702 name[2] = (int)KE_SNR;
20703 if (lead > 3) /* If it's "<SID>" */
20704 STRCPY(name + 3, sid_buf);
20706 mch_memmove(name + lead, lv.ll_name, (size_t)len);
20707 name[len + lead] = NUL;
20709 *pp = end;
20711 theend:
20712 clear_lval(&lv);
20713 return name;
20717 * Return 5 if "p" starts with "<SID>" or "<SNR>" (ignoring case).
20718 * Return 2 if "p" starts with "s:".
20719 * Return 0 otherwise.
20721 static int
20722 eval_fname_script(p)
20723 char_u *p;
20725 if (p[0] == '<' && (STRNICMP(p + 1, "SID>", 4) == 0
20726 || STRNICMP(p + 1, "SNR>", 4) == 0))
20727 return 5;
20728 if (p[0] == 's' && p[1] == ':')
20729 return 2;
20730 return 0;
20734 * Return TRUE if "p" starts with "<SID>" or "s:".
20735 * Only works if eval_fname_script() returned non-zero for "p"!
20737 static int
20738 eval_fname_sid(p)
20739 char_u *p;
20741 return (*p == 's' || TOUPPER_ASC(p[2]) == 'I');
20745 * List the head of the function: "name(arg1, arg2)".
20747 static void
20748 list_func_head(fp, indent)
20749 ufunc_T *fp;
20750 int indent;
20752 int j;
20754 msg_start();
20755 if (indent)
20756 MSG_PUTS(" ");
20757 MSG_PUTS("function ");
20758 if (fp->uf_name[0] == K_SPECIAL)
20760 MSG_PUTS_ATTR("<SNR>", hl_attr(HLF_8));
20761 msg_puts(fp->uf_name + 3);
20763 else
20764 msg_puts(fp->uf_name);
20765 msg_putchar('(');
20766 for (j = 0; j < fp->uf_args.ga_len; ++j)
20768 if (j)
20769 MSG_PUTS(", ");
20770 msg_puts(FUNCARG(fp, j));
20772 if (fp->uf_varargs)
20774 if (j)
20775 MSG_PUTS(", ");
20776 MSG_PUTS("...");
20778 msg_putchar(')');
20779 msg_clr_eos();
20780 if (p_verbose > 0)
20781 last_set_msg(fp->uf_script_ID);
20785 * Find a function by name, return pointer to it in ufuncs.
20786 * Return NULL for unknown function.
20788 static ufunc_T *
20789 find_func(name)
20790 char_u *name;
20792 hashitem_T *hi;
20794 hi = hash_find(&func_hashtab, name);
20795 if (!HASHITEM_EMPTY(hi))
20796 return HI2UF(hi);
20797 return NULL;
20800 #if defined(EXITFREE) || defined(PROTO)
20801 void
20802 free_all_functions()
20804 hashitem_T *hi;
20806 /* Need to start all over every time, because func_free() may change the
20807 * hash table. */
20808 while (func_hashtab.ht_used > 0)
20809 for (hi = func_hashtab.ht_array; ; ++hi)
20810 if (!HASHITEM_EMPTY(hi))
20812 func_free(HI2UF(hi));
20813 break;
20816 #endif
20819 * Return TRUE if a function "name" exists.
20821 static int
20822 function_exists(name)
20823 char_u *name;
20825 char_u *nm = name;
20826 char_u *p;
20827 int n = FALSE;
20829 p = trans_function_name(&nm, FALSE, TFN_INT|TFN_QUIET, NULL);
20830 nm = skipwhite(nm);
20832 /* Only accept "funcname", "funcname ", "funcname (..." and
20833 * "funcname(...", not "funcname!...". */
20834 if (p != NULL && (*nm == NUL || *nm == '('))
20836 if (builtin_function(p))
20837 n = (find_internal_func(p) >= 0);
20838 else
20839 n = (find_func(p) != NULL);
20841 vim_free(p);
20842 return n;
20846 * Return TRUE if "name" looks like a builtin function name: starts with a
20847 * lower case letter and doesn't contain a ':' or AUTOLOAD_CHAR.
20849 static int
20850 builtin_function(name)
20851 char_u *name;
20853 return ASCII_ISLOWER(name[0]) && vim_strchr(name, ':') == NULL
20854 && vim_strchr(name, AUTOLOAD_CHAR) == NULL;
20857 #if defined(FEAT_PROFILE) || defined(PROTO)
20859 * Start profiling function "fp".
20861 static void
20862 func_do_profile(fp)
20863 ufunc_T *fp;
20865 fp->uf_tm_count = 0;
20866 profile_zero(&fp->uf_tm_self);
20867 profile_zero(&fp->uf_tm_total);
20868 if (fp->uf_tml_count == NULL)
20869 fp->uf_tml_count = (int *)alloc_clear((unsigned)
20870 (sizeof(int) * fp->uf_lines.ga_len));
20871 if (fp->uf_tml_total == NULL)
20872 fp->uf_tml_total = (proftime_T *)alloc_clear((unsigned)
20873 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20874 if (fp->uf_tml_self == NULL)
20875 fp->uf_tml_self = (proftime_T *)alloc_clear((unsigned)
20876 (sizeof(proftime_T) * fp->uf_lines.ga_len));
20877 fp->uf_tml_idx = -1;
20878 if (fp->uf_tml_count == NULL || fp->uf_tml_total == NULL
20879 || fp->uf_tml_self == NULL)
20880 return; /* out of memory */
20882 fp->uf_profiling = TRUE;
20886 * Dump the profiling results for all functions in file "fd".
20888 void
20889 func_dump_profile(fd)
20890 FILE *fd;
20892 hashitem_T *hi;
20893 int todo;
20894 ufunc_T *fp;
20895 int i;
20896 ufunc_T **sorttab;
20897 int st_len = 0;
20899 todo = (int)func_hashtab.ht_used;
20900 if (todo == 0)
20901 return; /* nothing to dump */
20903 sorttab = (ufunc_T **)alloc((unsigned)(sizeof(ufunc_T) * todo));
20905 for (hi = func_hashtab.ht_array; todo > 0; ++hi)
20907 if (!HASHITEM_EMPTY(hi))
20909 --todo;
20910 fp = HI2UF(hi);
20911 if (fp->uf_profiling)
20913 if (sorttab != NULL)
20914 sorttab[st_len++] = fp;
20916 if (fp->uf_name[0] == K_SPECIAL)
20917 fprintf(fd, "FUNCTION <SNR>%s()\n", fp->uf_name + 3);
20918 else
20919 fprintf(fd, "FUNCTION %s()\n", fp->uf_name);
20920 if (fp->uf_tm_count == 1)
20921 fprintf(fd, "Called 1 time\n");
20922 else
20923 fprintf(fd, "Called %d times\n", fp->uf_tm_count);
20924 fprintf(fd, "Total time: %s\n", profile_msg(&fp->uf_tm_total));
20925 fprintf(fd, " Self time: %s\n", profile_msg(&fp->uf_tm_self));
20926 fprintf(fd, "\n");
20927 fprintf(fd, "count total (s) self (s)\n");
20929 for (i = 0; i < fp->uf_lines.ga_len; ++i)
20931 if (FUNCLINE(fp, i) == NULL)
20932 continue;
20933 prof_func_line(fd, fp->uf_tml_count[i],
20934 &fp->uf_tml_total[i], &fp->uf_tml_self[i], TRUE);
20935 fprintf(fd, "%s\n", FUNCLINE(fp, i));
20937 fprintf(fd, "\n");
20942 if (sorttab != NULL && st_len > 0)
20944 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20945 prof_total_cmp);
20946 prof_sort_list(fd, sorttab, st_len, "TOTAL", FALSE);
20947 qsort((void *)sorttab, (size_t)st_len, sizeof(ufunc_T *),
20948 prof_self_cmp);
20949 prof_sort_list(fd, sorttab, st_len, "SELF", TRUE);
20952 vim_free(sorttab);
20955 static void
20956 prof_sort_list(fd, sorttab, st_len, title, prefer_self)
20957 FILE *fd;
20958 ufunc_T **sorttab;
20959 int st_len;
20960 char *title;
20961 int prefer_self; /* when equal print only self time */
20963 int i;
20964 ufunc_T *fp;
20966 fprintf(fd, "FUNCTIONS SORTED ON %s TIME\n", title);
20967 fprintf(fd, "count total (s) self (s) function\n");
20968 for (i = 0; i < 20 && i < st_len; ++i)
20970 fp = sorttab[i];
20971 prof_func_line(fd, fp->uf_tm_count, &fp->uf_tm_total, &fp->uf_tm_self,
20972 prefer_self);
20973 if (fp->uf_name[0] == K_SPECIAL)
20974 fprintf(fd, " <SNR>%s()\n", fp->uf_name + 3);
20975 else
20976 fprintf(fd, " %s()\n", fp->uf_name);
20978 fprintf(fd, "\n");
20982 * Print the count and times for one function or function line.
20984 static void
20985 prof_func_line(fd, count, total, self, prefer_self)
20986 FILE *fd;
20987 int count;
20988 proftime_T *total;
20989 proftime_T *self;
20990 int prefer_self; /* when equal print only self time */
20992 if (count > 0)
20994 fprintf(fd, "%5d ", count);
20995 if (prefer_self && profile_equal(total, self))
20996 fprintf(fd, " ");
20997 else
20998 fprintf(fd, "%s ", profile_msg(total));
20999 if (!prefer_self && profile_equal(total, self))
21000 fprintf(fd, " ");
21001 else
21002 fprintf(fd, "%s ", profile_msg(self));
21004 else
21005 fprintf(fd, " ");
21009 * Compare function for total time sorting.
21011 static int
21012 #ifdef __BORLANDC__
21013 _RTLENTRYF
21014 #endif
21015 prof_total_cmp(s1, s2)
21016 const void *s1;
21017 const void *s2;
21019 ufunc_T *p1, *p2;
21021 p1 = *(ufunc_T **)s1;
21022 p2 = *(ufunc_T **)s2;
21023 return profile_cmp(&p1->uf_tm_total, &p2->uf_tm_total);
21027 * Compare function for self time sorting.
21029 static int
21030 #ifdef __BORLANDC__
21031 _RTLENTRYF
21032 #endif
21033 prof_self_cmp(s1, s2)
21034 const void *s1;
21035 const void *s2;
21037 ufunc_T *p1, *p2;
21039 p1 = *(ufunc_T **)s1;
21040 p2 = *(ufunc_T **)s2;
21041 return profile_cmp(&p1->uf_tm_self, &p2->uf_tm_self);
21044 #endif
21047 * If "name" has a package name try autoloading the script for it.
21048 * Return TRUE if a package was loaded.
21050 static int
21051 script_autoload(name, reload)
21052 char_u *name;
21053 int reload; /* load script again when already loaded */
21055 char_u *p;
21056 char_u *scriptname, *tofree;
21057 int ret = FALSE;
21058 int i;
21060 /* If there is no '#' after name[0] there is no package name. */
21061 p = vim_strchr(name, AUTOLOAD_CHAR);
21062 if (p == NULL || p == name)
21063 return FALSE;
21065 tofree = scriptname = autoload_name(name);
21067 /* Find the name in the list of previously loaded package names. Skip
21068 * "autoload/", it's always the same. */
21069 for (i = 0; i < ga_loaded.ga_len; ++i)
21070 if (STRCMP(((char_u **)ga_loaded.ga_data)[i] + 9, scriptname + 9) == 0)
21071 break;
21072 if (!reload && i < ga_loaded.ga_len)
21073 ret = FALSE; /* was loaded already */
21074 else
21076 /* Remember the name if it wasn't loaded already. */
21077 if (i == ga_loaded.ga_len && ga_grow(&ga_loaded, 1) == OK)
21079 ((char_u **)ga_loaded.ga_data)[ga_loaded.ga_len++] = scriptname;
21080 tofree = NULL;
21083 /* Try loading the package from $VIMRUNTIME/autoload/<name>.vim */
21084 if (source_runtime(scriptname, FALSE) == OK)
21085 ret = TRUE;
21088 vim_free(tofree);
21089 return ret;
21093 * Return the autoload script name for a function or variable name.
21094 * Returns NULL when out of memory.
21096 static char_u *
21097 autoload_name(name)
21098 char_u *name;
21100 char_u *p;
21101 char_u *scriptname;
21103 /* Get the script file name: replace '#' with '/', append ".vim". */
21104 scriptname = alloc((unsigned)(STRLEN(name) + 14));
21105 if (scriptname == NULL)
21106 return FALSE;
21107 STRCPY(scriptname, "autoload/");
21108 STRCAT(scriptname, name);
21109 *vim_strrchr(scriptname, AUTOLOAD_CHAR) = NUL;
21110 STRCAT(scriptname, ".vim");
21111 while ((p = vim_strchr(scriptname, AUTOLOAD_CHAR)) != NULL)
21112 *p = '/';
21113 return scriptname;
21116 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
21119 * Function given to ExpandGeneric() to obtain the list of user defined
21120 * function names.
21122 char_u *
21123 get_user_func_name(xp, idx)
21124 expand_T *xp;
21125 int idx;
21127 static long_u done;
21128 static hashitem_T *hi;
21129 ufunc_T *fp;
21131 if (idx == 0)
21133 done = 0;
21134 hi = func_hashtab.ht_array;
21136 if (done < func_hashtab.ht_used)
21138 if (done++ > 0)
21139 ++hi;
21140 while (HASHITEM_EMPTY(hi))
21141 ++hi;
21142 fp = HI2UF(hi);
21144 if (STRLEN(fp->uf_name) + 4 >= IOSIZE)
21145 return fp->uf_name; /* prevents overflow */
21147 cat_func_name(IObuff, fp);
21148 if (xp->xp_context != EXPAND_USER_FUNC)
21150 STRCAT(IObuff, "(");
21151 if (!fp->uf_varargs && fp->uf_args.ga_len == 0)
21152 STRCAT(IObuff, ")");
21154 return IObuff;
21156 return NULL;
21159 #endif /* FEAT_CMDL_COMPL */
21162 * Copy the function name of "fp" to buffer "buf".
21163 * "buf" must be able to hold the function name plus three bytes.
21164 * Takes care of script-local function names.
21166 static void
21167 cat_func_name(buf, fp)
21168 char_u *buf;
21169 ufunc_T *fp;
21171 if (fp->uf_name[0] == K_SPECIAL)
21173 STRCPY(buf, "<SNR>");
21174 STRCAT(buf, fp->uf_name + 3);
21176 else
21177 STRCPY(buf, fp->uf_name);
21181 * ":delfunction {name}"
21183 void
21184 ex_delfunction(eap)
21185 exarg_T *eap;
21187 ufunc_T *fp = NULL;
21188 char_u *p;
21189 char_u *name;
21190 funcdict_T fudi;
21192 p = eap->arg;
21193 name = trans_function_name(&p, eap->skip, 0, &fudi);
21194 vim_free(fudi.fd_newkey);
21195 if (name == NULL)
21197 if (fudi.fd_dict != NULL && !eap->skip)
21198 EMSG(_(e_funcref));
21199 return;
21201 if (!ends_excmd(*skipwhite(p)))
21203 vim_free(name);
21204 EMSG(_(e_trailing));
21205 return;
21207 eap->nextcmd = check_nextcmd(p);
21208 if (eap->nextcmd != NULL)
21209 *p = NUL;
21211 if (!eap->skip)
21212 fp = find_func(name);
21213 vim_free(name);
21215 if (!eap->skip)
21217 if (fp == NULL)
21219 EMSG2(_(e_nofunc), eap->arg);
21220 return;
21222 if (fp->uf_calls > 0)
21224 EMSG2(_("E131: Cannot delete function %s: It is in use"), eap->arg);
21225 return;
21228 if (fudi.fd_dict != NULL)
21230 /* Delete the dict item that refers to the function, it will
21231 * invoke func_unref() and possibly delete the function. */
21232 dictitem_remove(fudi.fd_dict, fudi.fd_di);
21234 else
21235 func_free(fp);
21240 * Free a function and remove it from the list of functions.
21242 static void
21243 func_free(fp)
21244 ufunc_T *fp;
21246 hashitem_T *hi;
21248 /* clear this function */
21249 ga_clear_strings(&(fp->uf_args));
21250 ga_clear_strings(&(fp->uf_lines));
21251 #ifdef FEAT_PROFILE
21252 vim_free(fp->uf_tml_count);
21253 vim_free(fp->uf_tml_total);
21254 vim_free(fp->uf_tml_self);
21255 #endif
21257 /* remove the function from the function hashtable */
21258 hi = hash_find(&func_hashtab, UF2HIKEY(fp));
21259 if (HASHITEM_EMPTY(hi))
21260 EMSG2(_(e_intern2), "func_free()");
21261 else
21262 hash_remove(&func_hashtab, hi);
21264 vim_free(fp);
21268 * Unreference a Function: decrement the reference count and free it when it
21269 * becomes zero. Only for numbered functions.
21271 static void
21272 func_unref(name)
21273 char_u *name;
21275 ufunc_T *fp;
21277 if (name != NULL && isdigit(*name))
21279 fp = find_func(name);
21280 if (fp == NULL)
21281 EMSG2(_(e_intern2), "func_unref()");
21282 else if (--fp->uf_refcount <= 0)
21284 /* Only delete it when it's not being used. Otherwise it's done
21285 * when "uf_calls" becomes zero. */
21286 if (fp->uf_calls == 0)
21287 func_free(fp);
21293 * Count a reference to a Function.
21295 static void
21296 func_ref(name)
21297 char_u *name;
21299 ufunc_T *fp;
21301 if (name != NULL && isdigit(*name))
21303 fp = find_func(name);
21304 if (fp == NULL)
21305 EMSG2(_(e_intern2), "func_ref()");
21306 else
21307 ++fp->uf_refcount;
21312 * Call a user function.
21314 static void
21315 call_user_func(fp, argcount, argvars, rettv, firstline, lastline, selfdict)
21316 ufunc_T *fp; /* pointer to function */
21317 int argcount; /* nr of args */
21318 typval_T *argvars; /* arguments */
21319 typval_T *rettv; /* return value */
21320 linenr_T firstline; /* first line of range */
21321 linenr_T lastline; /* last line of range */
21322 dict_T *selfdict; /* Dictionary for "self" */
21324 char_u *save_sourcing_name;
21325 linenr_T save_sourcing_lnum;
21326 scid_T save_current_SID;
21327 funccall_T *fc;
21328 int save_did_emsg;
21329 static int depth = 0;
21330 dictitem_T *v;
21331 int fixvar_idx = 0; /* index in fixvar[] */
21332 int i;
21333 int ai;
21334 char_u numbuf[NUMBUFLEN];
21335 char_u *name;
21336 #ifdef FEAT_PROFILE
21337 proftime_T wait_start;
21338 proftime_T call_start;
21339 #endif
21341 /* If depth of calling is getting too high, don't execute the function */
21342 if (depth >= p_mfd)
21344 EMSG(_("E132: Function call depth is higher than 'maxfuncdepth'"));
21345 rettv->v_type = VAR_NUMBER;
21346 rettv->vval.v_number = -1;
21347 return;
21349 ++depth;
21351 line_breakcheck(); /* check for CTRL-C hit */
21353 fc = (funccall_T *)alloc(sizeof(funccall_T));
21354 fc->caller = current_funccal;
21355 current_funccal = fc;
21356 fc->func = fp;
21357 fc->rettv = rettv;
21358 rettv->vval.v_number = 0;
21359 fc->linenr = 0;
21360 fc->returned = FALSE;
21361 fc->level = ex_nesting_level;
21362 /* Check if this function has a breakpoint. */
21363 fc->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name, (linenr_T)0);
21364 fc->dbg_tick = debug_tick;
21367 * Note about using fc->fixvar[]: This is an array of FIXVAR_CNT variables
21368 * with names up to VAR_SHORT_LEN long. This avoids having to alloc/free
21369 * each argument variable and saves a lot of time.
21372 * Init l: variables.
21374 init_var_dict(&fc->l_vars, &fc->l_vars_var);
21375 if (selfdict != NULL)
21377 /* Set l:self to "selfdict". Use "name" to avoid a warning from
21378 * some compiler that checks the destination size. */
21379 v = &fc->fixvar[fixvar_idx++].var;
21380 name = v->di_key;
21381 STRCPY(name, "self");
21382 v->di_flags = DI_FLAGS_RO + DI_FLAGS_FIX;
21383 hash_add(&fc->l_vars.dv_hashtab, DI2HIKEY(v));
21384 v->di_tv.v_type = VAR_DICT;
21385 v->di_tv.v_lock = 0;
21386 v->di_tv.vval.v_dict = selfdict;
21387 ++selfdict->dv_refcount;
21391 * Init a: variables.
21392 * Set a:0 to "argcount".
21393 * Set a:000 to a list with room for the "..." arguments.
21395 init_var_dict(&fc->l_avars, &fc->l_avars_var);
21396 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "0",
21397 (varnumber_T)(argcount - fp->uf_args.ga_len));
21398 /* Use "name" to avoid a warning from some compiler that checks the
21399 * destination size. */
21400 v = &fc->fixvar[fixvar_idx++].var;
21401 name = v->di_key;
21402 STRCPY(name, "000");
21403 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21404 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21405 v->di_tv.v_type = VAR_LIST;
21406 v->di_tv.v_lock = VAR_FIXED;
21407 v->di_tv.vval.v_list = &fc->l_varlist;
21408 vim_memset(&fc->l_varlist, 0, sizeof(list_T));
21409 fc->l_varlist.lv_refcount = DO_NOT_FREE_CNT;
21410 fc->l_varlist.lv_lock = VAR_FIXED;
21413 * Set a:firstline to "firstline" and a:lastline to "lastline".
21414 * Set a:name to named arguments.
21415 * Set a:N to the "..." arguments.
21417 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "firstline",
21418 (varnumber_T)firstline);
21419 add_nr_var(&fc->l_avars, &fc->fixvar[fixvar_idx++].var, "lastline",
21420 (varnumber_T)lastline);
21421 for (i = 0; i < argcount; ++i)
21423 ai = i - fp->uf_args.ga_len;
21424 if (ai < 0)
21425 /* named argument a:name */
21426 name = FUNCARG(fp, i);
21427 else
21429 /* "..." argument a:1, a:2, etc. */
21430 sprintf((char *)numbuf, "%d", ai + 1);
21431 name = numbuf;
21433 if (fixvar_idx < FIXVAR_CNT && STRLEN(name) <= VAR_SHORT_LEN)
21435 v = &fc->fixvar[fixvar_idx++].var;
21436 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21438 else
21440 v = (dictitem_T *)alloc((unsigned)(sizeof(dictitem_T)
21441 + STRLEN(name)));
21442 if (v == NULL)
21443 break;
21444 v->di_flags = DI_FLAGS_RO;
21446 STRCPY(v->di_key, name);
21447 hash_add(&fc->l_avars.dv_hashtab, DI2HIKEY(v));
21449 /* Note: the values are copied directly to avoid alloc/free.
21450 * "argvars" must have VAR_FIXED for v_lock. */
21451 v->di_tv = argvars[i];
21452 v->di_tv.v_lock = VAR_FIXED;
21454 if (ai >= 0 && ai < MAX_FUNC_ARGS)
21456 list_append(&fc->l_varlist, &fc->l_listitems[ai]);
21457 fc->l_listitems[ai].li_tv = argvars[i];
21458 fc->l_listitems[ai].li_tv.v_lock = VAR_FIXED;
21462 /* Don't redraw while executing the function. */
21463 ++RedrawingDisabled;
21464 save_sourcing_name = sourcing_name;
21465 save_sourcing_lnum = sourcing_lnum;
21466 sourcing_lnum = 1;
21467 sourcing_name = alloc((unsigned)((save_sourcing_name == NULL ? 0
21468 : STRLEN(save_sourcing_name)) + STRLEN(fp->uf_name) + 13));
21469 if (sourcing_name != NULL)
21471 if (save_sourcing_name != NULL
21472 && STRNCMP(save_sourcing_name, "function ", 9) == 0)
21473 sprintf((char *)sourcing_name, "%s..", save_sourcing_name);
21474 else
21475 STRCPY(sourcing_name, "function ");
21476 cat_func_name(sourcing_name + STRLEN(sourcing_name), fp);
21478 if (p_verbose >= 12)
21480 ++no_wait_return;
21481 verbose_enter_scroll();
21483 smsg((char_u *)_("calling %s"), sourcing_name);
21484 if (p_verbose >= 14)
21486 char_u buf[MSG_BUF_LEN];
21487 char_u numbuf2[NUMBUFLEN];
21488 char_u *tofree;
21489 char_u *s;
21491 msg_puts((char_u *)"(");
21492 for (i = 0; i < argcount; ++i)
21494 if (i > 0)
21495 msg_puts((char_u *)", ");
21496 if (argvars[i].v_type == VAR_NUMBER)
21497 msg_outnum((long)argvars[i].vval.v_number);
21498 else
21500 s = tv2string(&argvars[i], &tofree, numbuf2, 0);
21501 if (s != NULL)
21503 trunc_string(s, buf, MSG_BUF_CLEN);
21504 msg_puts(buf);
21505 vim_free(tofree);
21509 msg_puts((char_u *)")");
21511 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21513 verbose_leave_scroll();
21514 --no_wait_return;
21517 #ifdef FEAT_PROFILE
21518 if (do_profiling == PROF_YES)
21520 if (!fp->uf_profiling && has_profiling(FALSE, fp->uf_name, NULL))
21521 func_do_profile(fp);
21522 if (fp->uf_profiling
21523 || (fc->caller != NULL && fc->caller->func->uf_profiling))
21525 ++fp->uf_tm_count;
21526 profile_start(&call_start);
21527 profile_zero(&fp->uf_tm_children);
21529 script_prof_save(&wait_start);
21531 #endif
21533 save_current_SID = current_SID;
21534 current_SID = fp->uf_script_ID;
21535 save_did_emsg = did_emsg;
21536 did_emsg = FALSE;
21538 /* call do_cmdline() to execute the lines */
21539 do_cmdline(NULL, get_func_line, (void *)fc,
21540 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
21542 --RedrawingDisabled;
21544 /* when the function was aborted because of an error, return -1 */
21545 if ((did_emsg && (fp->uf_flags & FC_ABORT)) || rettv->v_type == VAR_UNKNOWN)
21547 clear_tv(rettv);
21548 rettv->v_type = VAR_NUMBER;
21549 rettv->vval.v_number = -1;
21552 #ifdef FEAT_PROFILE
21553 if (do_profiling == PROF_YES && (fp->uf_profiling
21554 || (fc->caller != NULL && fc->caller->func->uf_profiling)))
21556 profile_end(&call_start);
21557 profile_sub_wait(&wait_start, &call_start);
21558 profile_add(&fp->uf_tm_total, &call_start);
21559 profile_self(&fp->uf_tm_self, &call_start, &fp->uf_tm_children);
21560 if (fc->caller != NULL && fc->caller->func->uf_profiling)
21562 profile_add(&fc->caller->func->uf_tm_children, &call_start);
21563 profile_add(&fc->caller->func->uf_tml_children, &call_start);
21566 #endif
21568 /* when being verbose, mention the return value */
21569 if (p_verbose >= 12)
21571 ++no_wait_return;
21572 verbose_enter_scroll();
21574 if (aborting())
21575 smsg((char_u *)_("%s aborted"), sourcing_name);
21576 else if (fc->rettv->v_type == VAR_NUMBER)
21577 smsg((char_u *)_("%s returning #%ld"), sourcing_name,
21578 (long)fc->rettv->vval.v_number);
21579 else
21581 char_u buf[MSG_BUF_LEN];
21582 char_u numbuf2[NUMBUFLEN];
21583 char_u *tofree;
21584 char_u *s;
21586 /* The value may be very long. Skip the middle part, so that we
21587 * have some idea how it starts and ends. smsg() would always
21588 * truncate it at the end. */
21589 s = tv2string(fc->rettv, &tofree, numbuf2, 0);
21590 if (s != NULL)
21592 trunc_string(s, buf, MSG_BUF_CLEN);
21593 smsg((char_u *)_("%s returning %s"), sourcing_name, buf);
21594 vim_free(tofree);
21597 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21599 verbose_leave_scroll();
21600 --no_wait_return;
21603 vim_free(sourcing_name);
21604 sourcing_name = save_sourcing_name;
21605 sourcing_lnum = save_sourcing_lnum;
21606 current_SID = save_current_SID;
21607 #ifdef FEAT_PROFILE
21608 if (do_profiling == PROF_YES)
21609 script_prof_restore(&wait_start);
21610 #endif
21612 if (p_verbose >= 12 && sourcing_name != NULL)
21614 ++no_wait_return;
21615 verbose_enter_scroll();
21617 smsg((char_u *)_("continuing in %s"), sourcing_name);
21618 msg_puts((char_u *)"\n"); /* don't overwrite this either */
21620 verbose_leave_scroll();
21621 --no_wait_return;
21624 did_emsg |= save_did_emsg;
21625 current_funccal = fc->caller;
21626 --depth;
21628 /* If the a:000 list and the l: and a: dicts are not referenced we can
21629 * free the funccall_T and what's in it. */
21630 if (fc->l_varlist.lv_refcount == DO_NOT_FREE_CNT
21631 && fc->l_vars.dv_refcount == DO_NOT_FREE_CNT
21632 && fc->l_avars.dv_refcount == DO_NOT_FREE_CNT)
21634 free_funccal(fc, FALSE);
21636 else
21638 hashitem_T *hi;
21639 listitem_T *li;
21640 int todo;
21642 /* "fc" is still in use. This can happen when returning "a:000" or
21643 * assigning "l:" to a global variable.
21644 * Link "fc" in the list for garbage collection later. */
21645 fc->caller = previous_funccal;
21646 previous_funccal = fc;
21648 /* Make a copy of the a: variables, since we didn't do that above. */
21649 todo = (int)fc->l_avars.dv_hashtab.ht_used;
21650 for (hi = fc->l_avars.dv_hashtab.ht_array; todo > 0; ++hi)
21652 if (!HASHITEM_EMPTY(hi))
21654 --todo;
21655 v = HI2DI(hi);
21656 copy_tv(&v->di_tv, &v->di_tv);
21660 /* Make a copy of the a:000 items, since we didn't do that above. */
21661 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21662 copy_tv(&li->li_tv, &li->li_tv);
21667 * Return TRUE if items in "fc" do not have "copyID". That means they are not
21668 * referenced from anywhere that is in use.
21670 static int
21671 can_free_funccal(fc, copyID)
21672 funccall_T *fc;
21673 int copyID;
21675 return (fc->l_varlist.lv_copyID != copyID
21676 && fc->l_vars.dv_copyID != copyID
21677 && fc->l_avars.dv_copyID != copyID);
21681 * Free "fc" and what it contains.
21683 static void
21684 free_funccal(fc, free_val)
21685 funccall_T *fc;
21686 int free_val; /* a: vars were allocated */
21688 listitem_T *li;
21690 /* The a: variables typevals may not have been allocated, only free the
21691 * allocated variables. */
21692 vars_clear_ext(&fc->l_avars.dv_hashtab, free_val);
21694 /* free all l: variables */
21695 vars_clear(&fc->l_vars.dv_hashtab);
21697 /* Free the a:000 variables if they were allocated. */
21698 if (free_val)
21699 for (li = fc->l_varlist.lv_first; li != NULL; li = li->li_next)
21700 clear_tv(&li->li_tv);
21702 vim_free(fc);
21706 * Add a number variable "name" to dict "dp" with value "nr".
21708 static void
21709 add_nr_var(dp, v, name, nr)
21710 dict_T *dp;
21711 dictitem_T *v;
21712 char *name;
21713 varnumber_T nr;
21715 STRCPY(v->di_key, name);
21716 v->di_flags = DI_FLAGS_RO | DI_FLAGS_FIX;
21717 hash_add(&dp->dv_hashtab, DI2HIKEY(v));
21718 v->di_tv.v_type = VAR_NUMBER;
21719 v->di_tv.v_lock = VAR_FIXED;
21720 v->di_tv.vval.v_number = nr;
21724 * ":return [expr]"
21726 void
21727 ex_return(eap)
21728 exarg_T *eap;
21730 char_u *arg = eap->arg;
21731 typval_T rettv;
21732 int returning = FALSE;
21734 if (current_funccal == NULL)
21736 EMSG(_("E133: :return not inside a function"));
21737 return;
21740 if (eap->skip)
21741 ++emsg_skip;
21743 eap->nextcmd = NULL;
21744 if ((*arg != NUL && *arg != '|' && *arg != '\n')
21745 && eval0(arg, &rettv, &eap->nextcmd, !eap->skip) != FAIL)
21747 if (!eap->skip)
21748 returning = do_return(eap, FALSE, TRUE, &rettv);
21749 else
21750 clear_tv(&rettv);
21752 /* It's safer to return also on error. */
21753 else if (!eap->skip)
21756 * Return unless the expression evaluation has been cancelled due to an
21757 * aborting error, an interrupt, or an exception.
21759 if (!aborting())
21760 returning = do_return(eap, FALSE, TRUE, NULL);
21763 /* When skipping or the return gets pending, advance to the next command
21764 * in this line (!returning). Otherwise, ignore the rest of the line.
21765 * Following lines will be ignored by get_func_line(). */
21766 if (returning)
21767 eap->nextcmd = NULL;
21768 else if (eap->nextcmd == NULL) /* no argument */
21769 eap->nextcmd = check_nextcmd(arg);
21771 if (eap->skip)
21772 --emsg_skip;
21776 * Return from a function. Possibly makes the return pending. Also called
21777 * for a pending return at the ":endtry" or after returning from an extra
21778 * do_cmdline(). "reanimate" is used in the latter case. "is_cmd" is set
21779 * when called due to a ":return" command. "rettv" may point to a typval_T
21780 * with the return rettv. Returns TRUE when the return can be carried out,
21781 * FALSE when the return gets pending.
21784 do_return(eap, reanimate, is_cmd, rettv)
21785 exarg_T *eap;
21786 int reanimate;
21787 int is_cmd;
21788 void *rettv;
21790 int idx;
21791 struct condstack *cstack = eap->cstack;
21793 if (reanimate)
21794 /* Undo the return. */
21795 current_funccal->returned = FALSE;
21798 * Cleanup (and inactivate) conditionals, but stop when a try conditional
21799 * not in its finally clause (which then is to be executed next) is found.
21800 * In this case, make the ":return" pending for execution at the ":endtry".
21801 * Otherwise, return normally.
21803 idx = cleanup_conditionals(eap->cstack, 0, TRUE);
21804 if (idx >= 0)
21806 cstack->cs_pending[idx] = CSTP_RETURN;
21808 if (!is_cmd && !reanimate)
21809 /* A pending return again gets pending. "rettv" points to an
21810 * allocated variable with the rettv of the original ":return"'s
21811 * argument if present or is NULL else. */
21812 cstack->cs_rettv[idx] = rettv;
21813 else
21815 /* When undoing a return in order to make it pending, get the stored
21816 * return rettv. */
21817 if (reanimate)
21818 rettv = current_funccal->rettv;
21820 if (rettv != NULL)
21822 /* Store the value of the pending return. */
21823 if ((cstack->cs_rettv[idx] = alloc_tv()) != NULL)
21824 *(typval_T *)cstack->cs_rettv[idx] = *(typval_T *)rettv;
21825 else
21826 EMSG(_(e_outofmem));
21828 else
21829 cstack->cs_rettv[idx] = NULL;
21831 if (reanimate)
21833 /* The pending return value could be overwritten by a ":return"
21834 * without argument in a finally clause; reset the default
21835 * return value. */
21836 current_funccal->rettv->v_type = VAR_NUMBER;
21837 current_funccal->rettv->vval.v_number = 0;
21840 report_make_pending(CSTP_RETURN, rettv);
21842 else
21844 current_funccal->returned = TRUE;
21846 /* If the return is carried out now, store the return value. For
21847 * a return immediately after reanimation, the value is already
21848 * there. */
21849 if (!reanimate && rettv != NULL)
21851 clear_tv(current_funccal->rettv);
21852 *current_funccal->rettv = *(typval_T *)rettv;
21853 if (!is_cmd)
21854 vim_free(rettv);
21858 return idx < 0;
21862 * Free the variable with a pending return value.
21864 void
21865 discard_pending_return(rettv)
21866 void *rettv;
21868 free_tv((typval_T *)rettv);
21872 * Generate a return command for producing the value of "rettv". The result
21873 * is an allocated string. Used by report_pending() for verbose messages.
21875 char_u *
21876 get_return_cmd(rettv)
21877 void *rettv;
21879 char_u *s = NULL;
21880 char_u *tofree = NULL;
21881 char_u numbuf[NUMBUFLEN];
21883 if (rettv != NULL)
21884 s = echo_string((typval_T *)rettv, &tofree, numbuf, 0);
21885 if (s == NULL)
21886 s = (char_u *)"";
21888 STRCPY(IObuff, ":return ");
21889 STRNCPY(IObuff + 8, s, IOSIZE - 8);
21890 if (STRLEN(s) + 8 >= IOSIZE)
21891 STRCPY(IObuff + IOSIZE - 4, "...");
21892 vim_free(tofree);
21893 return vim_strsave(IObuff);
21897 * Get next function line.
21898 * Called by do_cmdline() to get the next line.
21899 * Returns allocated string, or NULL for end of function.
21901 char_u *
21902 get_func_line(c, cookie, indent)
21903 int c UNUSED;
21904 void *cookie;
21905 int indent UNUSED;
21907 funccall_T *fcp = (funccall_T *)cookie;
21908 ufunc_T *fp = fcp->func;
21909 char_u *retval;
21910 garray_T *gap; /* growarray with function lines */
21912 /* If breakpoints have been added/deleted need to check for it. */
21913 if (fcp->dbg_tick != debug_tick)
21915 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21916 sourcing_lnum);
21917 fcp->dbg_tick = debug_tick;
21919 #ifdef FEAT_PROFILE
21920 if (do_profiling == PROF_YES)
21921 func_line_end(cookie);
21922 #endif
21924 gap = &fp->uf_lines;
21925 if (((fp->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
21926 || fcp->returned)
21927 retval = NULL;
21928 else
21930 /* Skip NULL lines (continuation lines). */
21931 while (fcp->linenr < gap->ga_len
21932 && ((char_u **)(gap->ga_data))[fcp->linenr] == NULL)
21933 ++fcp->linenr;
21934 if (fcp->linenr >= gap->ga_len)
21935 retval = NULL;
21936 else
21938 retval = vim_strsave(((char_u **)(gap->ga_data))[fcp->linenr++]);
21939 sourcing_lnum = fcp->linenr;
21940 #ifdef FEAT_PROFILE
21941 if (do_profiling == PROF_YES)
21942 func_line_start(cookie);
21943 #endif
21947 /* Did we encounter a breakpoint? */
21948 if (fcp->breakpoint != 0 && fcp->breakpoint <= sourcing_lnum)
21950 dbg_breakpoint(fp->uf_name, sourcing_lnum);
21951 /* Find next breakpoint. */
21952 fcp->breakpoint = dbg_find_breakpoint(FALSE, fp->uf_name,
21953 sourcing_lnum);
21954 fcp->dbg_tick = debug_tick;
21957 return retval;
21960 #if defined(FEAT_PROFILE) || defined(PROTO)
21962 * Called when starting to read a function line.
21963 * "sourcing_lnum" must be correct!
21964 * When skipping lines it may not actually be executed, but we won't find out
21965 * until later and we need to store the time now.
21967 void
21968 func_line_start(cookie)
21969 void *cookie;
21971 funccall_T *fcp = (funccall_T *)cookie;
21972 ufunc_T *fp = fcp->func;
21974 if (fp->uf_profiling && sourcing_lnum >= 1
21975 && sourcing_lnum <= fp->uf_lines.ga_len)
21977 fp->uf_tml_idx = sourcing_lnum - 1;
21978 /* Skip continuation lines. */
21979 while (fp->uf_tml_idx > 0 && FUNCLINE(fp, fp->uf_tml_idx) == NULL)
21980 --fp->uf_tml_idx;
21981 fp->uf_tml_execed = FALSE;
21982 profile_start(&fp->uf_tml_start);
21983 profile_zero(&fp->uf_tml_children);
21984 profile_get_wait(&fp->uf_tml_wait);
21989 * Called when actually executing a function line.
21991 void
21992 func_line_exec(cookie)
21993 void *cookie;
21995 funccall_T *fcp = (funccall_T *)cookie;
21996 ufunc_T *fp = fcp->func;
21998 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
21999 fp->uf_tml_execed = TRUE;
22003 * Called when done with a function line.
22005 void
22006 func_line_end(cookie)
22007 void *cookie;
22009 funccall_T *fcp = (funccall_T *)cookie;
22010 ufunc_T *fp = fcp->func;
22012 if (fp->uf_profiling && fp->uf_tml_idx >= 0)
22014 if (fp->uf_tml_execed)
22016 ++fp->uf_tml_count[fp->uf_tml_idx];
22017 profile_end(&fp->uf_tml_start);
22018 profile_sub_wait(&fp->uf_tml_wait, &fp->uf_tml_start);
22019 profile_add(&fp->uf_tml_total[fp->uf_tml_idx], &fp->uf_tml_start);
22020 profile_self(&fp->uf_tml_self[fp->uf_tml_idx], &fp->uf_tml_start,
22021 &fp->uf_tml_children);
22023 fp->uf_tml_idx = -1;
22026 #endif
22029 * Return TRUE if the currently active function should be ended, because a
22030 * return was encountered or an error occurred. Used inside a ":while".
22033 func_has_ended(cookie)
22034 void *cookie;
22036 funccall_T *fcp = (funccall_T *)cookie;
22038 /* Ignore the "abort" flag if the abortion behavior has been changed due to
22039 * an error inside a try conditional. */
22040 return (((fcp->func->uf_flags & FC_ABORT) && did_emsg && !aborted_in_try())
22041 || fcp->returned);
22045 * return TRUE if cookie indicates a function which "abort"s on errors.
22048 func_has_abort(cookie)
22049 void *cookie;
22051 return ((funccall_T *)cookie)->func->uf_flags & FC_ABORT;
22054 #if defined(FEAT_VIMINFO) || defined(FEAT_SESSION)
22055 typedef enum
22057 VAR_FLAVOUR_DEFAULT, /* doesn't start with uppercase */
22058 VAR_FLAVOUR_SESSION, /* starts with uppercase, some lower */
22059 VAR_FLAVOUR_VIMINFO /* all uppercase */
22060 } var_flavour_T;
22062 static var_flavour_T var_flavour __ARGS((char_u *varname));
22064 static var_flavour_T
22065 var_flavour(varname)
22066 char_u *varname;
22068 char_u *p = varname;
22070 if (ASCII_ISUPPER(*p))
22072 while (*(++p))
22073 if (ASCII_ISLOWER(*p))
22074 return VAR_FLAVOUR_SESSION;
22075 return VAR_FLAVOUR_VIMINFO;
22077 else
22078 return VAR_FLAVOUR_DEFAULT;
22080 #endif
22082 #if defined(FEAT_VIMINFO) || defined(PROTO)
22084 * Restore global vars that start with a capital from the viminfo file
22087 read_viminfo_varlist(virp, writing)
22088 vir_T *virp;
22089 int writing;
22091 char_u *tab;
22092 int type = VAR_NUMBER;
22093 typval_T tv;
22095 if (!writing && (find_viminfo_parameter('!') != NULL))
22097 tab = vim_strchr(virp->vir_line + 1, '\t');
22098 if (tab != NULL)
22100 *tab++ = '\0'; /* isolate the variable name */
22101 if (*tab == 'S') /* string var */
22102 type = VAR_STRING;
22103 #ifdef FEAT_FLOAT
22104 else if (*tab == 'F')
22105 type = VAR_FLOAT;
22106 #endif
22108 tab = vim_strchr(tab, '\t');
22109 if (tab != NULL)
22111 tv.v_type = type;
22112 if (type == VAR_STRING)
22113 tv.vval.v_string = viminfo_readstring(virp,
22114 (int)(tab - virp->vir_line + 1), TRUE);
22115 #ifdef FEAT_FLOAT
22116 else if (type == VAR_FLOAT)
22117 (void)string2float(tab + 1, &tv.vval.v_float);
22118 #endif
22119 else
22120 tv.vval.v_number = atol((char *)tab + 1);
22121 set_var(virp->vir_line + 1, &tv, FALSE);
22122 if (type == VAR_STRING)
22123 vim_free(tv.vval.v_string);
22128 return viminfo_readline(virp);
22132 * Write global vars that start with a capital to the viminfo file
22134 void
22135 write_viminfo_varlist(fp)
22136 FILE *fp;
22138 hashitem_T *hi;
22139 dictitem_T *this_var;
22140 int todo;
22141 char *s;
22142 char_u *p;
22143 char_u *tofree;
22144 char_u numbuf[NUMBUFLEN];
22146 if (find_viminfo_parameter('!') == NULL)
22147 return;
22149 fputs(_("\n# global variables:\n"), fp);
22151 todo = (int)globvarht.ht_used;
22152 for (hi = globvarht.ht_array; todo > 0; ++hi)
22154 if (!HASHITEM_EMPTY(hi))
22156 --todo;
22157 this_var = HI2DI(hi);
22158 if (var_flavour(this_var->di_key) == VAR_FLAVOUR_VIMINFO)
22160 switch (this_var->di_tv.v_type)
22162 case VAR_STRING: s = "STR"; break;
22163 case VAR_NUMBER: s = "NUM"; break;
22164 #ifdef FEAT_FLOAT
22165 case VAR_FLOAT: s = "FLO"; break;
22166 #endif
22167 default: continue;
22169 fprintf(fp, "!%s\t%s\t", this_var->di_key, s);
22170 p = echo_string(&this_var->di_tv, &tofree, numbuf, 0);
22171 if (p != NULL)
22172 viminfo_writestring(fp, p);
22173 vim_free(tofree);
22178 #endif
22180 #if defined(FEAT_SESSION) || defined(PROTO)
22182 store_session_globals(fd)
22183 FILE *fd;
22185 hashitem_T *hi;
22186 dictitem_T *this_var;
22187 int todo;
22188 char_u *p, *t;
22190 todo = (int)globvarht.ht_used;
22191 for (hi = globvarht.ht_array; todo > 0; ++hi)
22193 if (!HASHITEM_EMPTY(hi))
22195 --todo;
22196 this_var = HI2DI(hi);
22197 if ((this_var->di_tv.v_type == VAR_NUMBER
22198 || this_var->di_tv.v_type == VAR_STRING)
22199 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22201 /* Escape special characters with a backslash. Turn a LF and
22202 * CR into \n and \r. */
22203 p = vim_strsave_escaped(get_tv_string(&this_var->di_tv),
22204 (char_u *)"\\\"\n\r");
22205 if (p == NULL) /* out of memory */
22206 break;
22207 for (t = p; *t != NUL; ++t)
22208 if (*t == '\n')
22209 *t = 'n';
22210 else if (*t == '\r')
22211 *t = 'r';
22212 if ((fprintf(fd, "let %s = %c%s%c",
22213 this_var->di_key,
22214 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22215 : ' ',
22217 (this_var->di_tv.v_type == VAR_STRING) ? '"'
22218 : ' ') < 0)
22219 || put_eol(fd) == FAIL)
22221 vim_free(p);
22222 return FAIL;
22224 vim_free(p);
22226 #ifdef FEAT_FLOAT
22227 else if (this_var->di_tv.v_type == VAR_FLOAT
22228 && var_flavour(this_var->di_key) == VAR_FLAVOUR_SESSION)
22230 float_T f = this_var->di_tv.vval.v_float;
22231 int sign = ' ';
22233 if (f < 0)
22235 f = -f;
22236 sign = '-';
22238 if ((fprintf(fd, "let %s = %c&%f",
22239 this_var->di_key, sign, f) < 0)
22240 || put_eol(fd) == FAIL)
22241 return FAIL;
22243 #endif
22246 return OK;
22248 #endif
22251 * Display script name where an item was last set.
22252 * Should only be invoked when 'verbose' is non-zero.
22254 void
22255 last_set_msg(scriptID)
22256 scid_T scriptID;
22258 char_u *p;
22260 if (scriptID != 0)
22262 p = home_replace_save(NULL, get_scriptname(scriptID));
22263 if (p != NULL)
22265 verbose_enter();
22266 MSG_PUTS(_("\n\tLast set from "));
22267 MSG_PUTS(p);
22268 vim_free(p);
22269 verbose_leave();
22275 * List v:oldfiles in a nice way.
22277 void
22278 ex_oldfiles(eap)
22279 exarg_T *eap UNUSED;
22281 list_T *l = vimvars[VV_OLDFILES].vv_list;
22282 listitem_T *li;
22283 int nr = 0;
22285 if (l == NULL)
22286 msg((char_u *)_("No old files"));
22287 else
22289 msg_start();
22290 msg_scroll = TRUE;
22291 for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
22293 msg_outnum((long)++nr);
22294 MSG_PUTS(": ");
22295 msg_outtrans(get_tv_string(&li->li_tv));
22296 msg_putchar('\n');
22297 out_flush(); /* output one line at a time */
22298 ui_breakcheck();
22300 /* Assume "got_int" was set to truncate the listing. */
22301 got_int = FALSE;
22303 #ifdef FEAT_BROWSE_CMD
22304 if (cmdmod.browse)
22306 quit_more = FALSE;
22307 nr = prompt_for_number(FALSE);
22308 msg_starthere();
22309 if (nr > 0)
22311 char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
22312 (long)nr);
22314 if (p != NULL)
22316 p = expand_env_save(p);
22317 eap->arg = p;
22318 eap->cmdidx = CMD_edit;
22319 cmdmod.browse = FALSE;
22320 do_exedit(eap, NULL);
22321 vim_free(p);
22325 #endif
22329 #endif /* FEAT_EVAL */
22332 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) || defined(PROTO)
22334 #ifdef WIN3264
22336 * Functions for ":8" filename modifier: get 8.3 version of a filename.
22338 static int get_short_pathname __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22339 static int shortpath_for_invalid_fname __ARGS((char_u **fname, char_u **bufp, int *fnamelen));
22340 static int shortpath_for_partial __ARGS((char_u **fnamep, char_u **bufp, int *fnamelen));
22343 * Get the short path (8.3) for the filename in "fnamep".
22344 * Only works for a valid file name.
22345 * When the path gets longer "fnamep" is changed and the allocated buffer
22346 * is put in "bufp".
22347 * *fnamelen is the length of "fnamep" and set to 0 for a nonexistent path.
22348 * Returns OK on success, FAIL on failure.
22350 static int
22351 get_short_pathname(fnamep, bufp, fnamelen)
22352 char_u **fnamep;
22353 char_u **bufp;
22354 int *fnamelen;
22356 int l, len;
22357 char_u *newbuf;
22359 len = *fnamelen;
22360 l = GetShortPathName(*fnamep, *fnamep, len);
22361 if (l > len - 1)
22363 /* If that doesn't work (not enough space), then save the string
22364 * and try again with a new buffer big enough. */
22365 newbuf = vim_strnsave(*fnamep, l);
22366 if (newbuf == NULL)
22367 return FAIL;
22369 vim_free(*bufp);
22370 *fnamep = *bufp = newbuf;
22372 /* Really should always succeed, as the buffer is big enough. */
22373 l = GetShortPathName(*fnamep, *fnamep, l+1);
22376 *fnamelen = l;
22377 return OK;
22381 * Get the short path (8.3) for the filename in "fname". The converted
22382 * path is returned in "bufp".
22384 * Some of the directories specified in "fname" may not exist. This function
22385 * will shorten the existing directories at the beginning of the path and then
22386 * append the remaining non-existing path.
22388 * fname - Pointer to the filename to shorten. On return, contains the
22389 * pointer to the shortened pathname
22390 * bufp - Pointer to an allocated buffer for the filename.
22391 * fnamelen - Length of the filename pointed to by fname
22393 * Returns OK on success (or nothing done) and FAIL on failure (out of memory).
22395 static int
22396 shortpath_for_invalid_fname(fname, bufp, fnamelen)
22397 char_u **fname;
22398 char_u **bufp;
22399 int *fnamelen;
22401 char_u *short_fname, *save_fname, *pbuf_unused;
22402 char_u *endp, *save_endp;
22403 char_u ch;
22404 int old_len, len;
22405 int new_len, sfx_len;
22406 int retval = OK;
22408 /* Make a copy */
22409 old_len = *fnamelen;
22410 save_fname = vim_strnsave(*fname, old_len);
22411 pbuf_unused = NULL;
22412 short_fname = NULL;
22414 endp = save_fname + old_len - 1; /* Find the end of the copy */
22415 save_endp = endp;
22418 * Try shortening the supplied path till it succeeds by removing one
22419 * directory at a time from the tail of the path.
22421 len = 0;
22422 for (;;)
22424 /* go back one path-separator */
22425 while (endp > save_fname && !after_pathsep(save_fname, endp + 1))
22426 --endp;
22427 if (endp <= save_fname)
22428 break; /* processed the complete path */
22431 * Replace the path separator with a NUL and try to shorten the
22432 * resulting path.
22434 ch = *endp;
22435 *endp = 0;
22436 short_fname = save_fname;
22437 len = (int)STRLEN(short_fname) + 1;
22438 if (get_short_pathname(&short_fname, &pbuf_unused, &len) == FAIL)
22440 retval = FAIL;
22441 goto theend;
22443 *endp = ch; /* preserve the string */
22445 if (len > 0)
22446 break; /* successfully shortened the path */
22448 /* failed to shorten the path. Skip the path separator */
22449 --endp;
22452 if (len > 0)
22455 * Succeeded in shortening the path. Now concatenate the shortened
22456 * path with the remaining path at the tail.
22459 /* Compute the length of the new path. */
22460 sfx_len = (int)(save_endp - endp) + 1;
22461 new_len = len + sfx_len;
22463 *fnamelen = new_len;
22464 vim_free(*bufp);
22465 if (new_len > old_len)
22467 /* There is not enough space in the currently allocated string,
22468 * copy it to a buffer big enough. */
22469 *fname = *bufp = vim_strnsave(short_fname, new_len);
22470 if (*fname == NULL)
22472 retval = FAIL;
22473 goto theend;
22476 else
22478 /* Transfer short_fname to the main buffer (it's big enough),
22479 * unless get_short_pathname() did its work in-place. */
22480 *fname = *bufp = save_fname;
22481 if (short_fname != save_fname)
22482 vim_strncpy(save_fname, short_fname, len);
22483 save_fname = NULL;
22486 /* concat the not-shortened part of the path */
22487 vim_strncpy(*fname + len, endp, sfx_len);
22488 (*fname)[new_len] = NUL;
22491 theend:
22492 vim_free(pbuf_unused);
22493 vim_free(save_fname);
22495 return retval;
22499 * Get a pathname for a partial path.
22500 * Returns OK for success, FAIL for failure.
22502 static int
22503 shortpath_for_partial(fnamep, bufp, fnamelen)
22504 char_u **fnamep;
22505 char_u **bufp;
22506 int *fnamelen;
22508 int sepcount, len, tflen;
22509 char_u *p;
22510 char_u *pbuf, *tfname;
22511 int hasTilde;
22513 /* Count up the path separators from the RHS.. so we know which part
22514 * of the path to return. */
22515 sepcount = 0;
22516 for (p = *fnamep; p < *fnamep + *fnamelen; mb_ptr_adv(p))
22517 if (vim_ispathsep(*p))
22518 ++sepcount;
22520 /* Need full path first (use expand_env() to remove a "~/") */
22521 hasTilde = (**fnamep == '~');
22522 if (hasTilde)
22523 pbuf = tfname = expand_env_save(*fnamep);
22524 else
22525 pbuf = tfname = FullName_save(*fnamep, FALSE);
22527 len = tflen = (int)STRLEN(tfname);
22529 if (get_short_pathname(&tfname, &pbuf, &len) == FAIL)
22530 return FAIL;
22532 if (len == 0)
22534 /* Don't have a valid filename, so shorten the rest of the
22535 * path if we can. This CAN give us invalid 8.3 filenames, but
22536 * there's not a lot of point in guessing what it might be.
22538 len = tflen;
22539 if (shortpath_for_invalid_fname(&tfname, &pbuf, &len) == FAIL)
22540 return FAIL;
22543 /* Count the paths backward to find the beginning of the desired string. */
22544 for (p = tfname + len - 1; p >= tfname; --p)
22546 #ifdef FEAT_MBYTE
22547 if (has_mbyte)
22548 p -= mb_head_off(tfname, p);
22549 #endif
22550 if (vim_ispathsep(*p))
22552 if (sepcount == 0 || (hasTilde && sepcount == 1))
22553 break;
22554 else
22555 sepcount --;
22558 if (hasTilde)
22560 --p;
22561 if (p >= tfname)
22562 *p = '~';
22563 else
22564 return FAIL;
22566 else
22567 ++p;
22569 /* Copy in the string - p indexes into tfname - allocated at pbuf */
22570 vim_free(*bufp);
22571 *fnamelen = (int)STRLEN(p);
22572 *bufp = pbuf;
22573 *fnamep = p;
22575 return OK;
22577 #endif /* WIN3264 */
22580 * Adjust a filename, according to a string of modifiers.
22581 * *fnamep must be NUL terminated when called. When returning, the length is
22582 * determined by *fnamelen.
22583 * Returns VALID_ flags or -1 for failure.
22584 * When there is an error, *fnamep is set to NULL.
22587 modify_fname(src, usedlen, fnamep, bufp, fnamelen)
22588 char_u *src; /* string with modifiers */
22589 int *usedlen; /* characters after src that are used */
22590 char_u **fnamep; /* file name so far */
22591 char_u **bufp; /* buffer for allocated file name or NULL */
22592 int *fnamelen; /* length of fnamep */
22594 int valid = 0;
22595 char_u *tail;
22596 char_u *s, *p, *pbuf;
22597 char_u dirname[MAXPATHL];
22598 int c;
22599 int has_fullname = 0;
22600 #ifdef WIN3264
22601 int has_shortname = 0;
22602 #endif
22604 repeat:
22605 /* ":p" - full path/file_name */
22606 if (src[*usedlen] == ':' && src[*usedlen + 1] == 'p')
22608 has_fullname = 1;
22610 valid |= VALID_PATH;
22611 *usedlen += 2;
22613 /* Expand "~/path" for all systems and "~user/path" for Unix and VMS */
22614 if ((*fnamep)[0] == '~'
22615 #if !defined(UNIX) && !(defined(VMS) && defined(USER_HOME))
22616 && ((*fnamep)[1] == '/'
22617 # ifdef BACKSLASH_IN_FILENAME
22618 || (*fnamep)[1] == '\\'
22619 # endif
22620 || (*fnamep)[1] == NUL)
22622 #endif
22625 *fnamep = expand_env_save(*fnamep);
22626 vim_free(*bufp); /* free any allocated file name */
22627 *bufp = *fnamep;
22628 if (*fnamep == NULL)
22629 return -1;
22632 /* When "/." or "/.." is used: force expansion to get rid of it. */
22633 for (p = *fnamep; *p != NUL; mb_ptr_adv(p))
22635 if (vim_ispathsep(*p)
22636 && p[1] == '.'
22637 && (p[2] == NUL
22638 || vim_ispathsep(p[2])
22639 || (p[2] == '.'
22640 && (p[3] == NUL || vim_ispathsep(p[3])))))
22641 break;
22644 /* FullName_save() is slow, don't use it when not needed. */
22645 if (*p != NUL || !vim_isAbsName(*fnamep))
22647 *fnamep = FullName_save(*fnamep, *p != NUL);
22648 vim_free(*bufp); /* free any allocated file name */
22649 *bufp = *fnamep;
22650 if (*fnamep == NULL)
22651 return -1;
22654 /* Append a path separator to a directory. */
22655 if (mch_isdir(*fnamep))
22657 /* Make room for one or two extra characters. */
22658 *fnamep = vim_strnsave(*fnamep, (int)STRLEN(*fnamep) + 2);
22659 vim_free(*bufp); /* free any allocated file name */
22660 *bufp = *fnamep;
22661 if (*fnamep == NULL)
22662 return -1;
22663 add_pathsep(*fnamep);
22667 /* ":." - path relative to the current directory */
22668 /* ":~" - path relative to the home directory */
22669 /* ":8" - shortname path - postponed till after */
22670 while (src[*usedlen] == ':'
22671 && ((c = src[*usedlen + 1]) == '.' || c == '~' || c == '8'))
22673 *usedlen += 2;
22674 if (c == '8')
22676 #ifdef WIN3264
22677 has_shortname = 1; /* Postpone this. */
22678 #endif
22679 continue;
22681 pbuf = NULL;
22682 /* Need full path first (use expand_env() to remove a "~/") */
22683 if (!has_fullname)
22685 if (c == '.' && **fnamep == '~')
22686 p = pbuf = expand_env_save(*fnamep);
22687 else
22688 p = pbuf = FullName_save(*fnamep, FALSE);
22690 else
22691 p = *fnamep;
22693 has_fullname = 0;
22695 if (p != NULL)
22697 if (c == '.')
22699 mch_dirname(dirname, MAXPATHL);
22700 s = shorten_fname(p, dirname);
22701 if (s != NULL)
22703 *fnamep = s;
22704 if (pbuf != NULL)
22706 vim_free(*bufp); /* free any allocated file name */
22707 *bufp = pbuf;
22708 pbuf = NULL;
22712 else
22714 home_replace(NULL, p, dirname, MAXPATHL, TRUE);
22715 /* Only replace it when it starts with '~' */
22716 if (*dirname == '~')
22718 s = vim_strsave(dirname);
22719 if (s != NULL)
22721 *fnamep = s;
22722 vim_free(*bufp);
22723 *bufp = s;
22727 vim_free(pbuf);
22731 tail = gettail(*fnamep);
22732 *fnamelen = (int)STRLEN(*fnamep);
22734 /* ":h" - head, remove "/file_name", can be repeated */
22735 /* Don't remove the first "/" or "c:\" */
22736 while (src[*usedlen] == ':' && src[*usedlen + 1] == 'h')
22738 valid |= VALID_HEAD;
22739 *usedlen += 2;
22740 s = get_past_head(*fnamep);
22741 while (tail > s && after_pathsep(s, tail))
22742 mb_ptr_back(*fnamep, tail);
22743 *fnamelen = (int)(tail - *fnamep);
22744 #ifdef VMS
22745 if (*fnamelen > 0)
22746 *fnamelen += 1; /* the path separator is part of the path */
22747 #endif
22748 if (*fnamelen == 0)
22750 /* Result is empty. Turn it into "." to make ":cd %:h" work. */
22751 p = vim_strsave((char_u *)".");
22752 if (p == NULL)
22753 return -1;
22754 vim_free(*bufp);
22755 *bufp = *fnamep = tail = p;
22756 *fnamelen = 1;
22758 else
22760 while (tail > s && !after_pathsep(s, tail))
22761 mb_ptr_back(*fnamep, tail);
22765 /* ":8" - shortname */
22766 if (src[*usedlen] == ':' && src[*usedlen + 1] == '8')
22768 *usedlen += 2;
22769 #ifdef WIN3264
22770 has_shortname = 1;
22771 #endif
22774 #ifdef WIN3264
22775 /* Check shortname after we have done 'heads' and before we do 'tails'
22777 if (has_shortname)
22779 pbuf = NULL;
22780 /* Copy the string if it is shortened by :h */
22781 if (*fnamelen < (int)STRLEN(*fnamep))
22783 p = vim_strnsave(*fnamep, *fnamelen);
22784 if (p == 0)
22785 return -1;
22786 vim_free(*bufp);
22787 *bufp = *fnamep = p;
22790 /* Split into two implementations - makes it easier. First is where
22791 * there isn't a full name already, second is where there is.
22793 if (!has_fullname && !vim_isAbsName(*fnamep))
22795 if (shortpath_for_partial(fnamep, bufp, fnamelen) == FAIL)
22796 return -1;
22798 else
22800 int l;
22802 /* Simple case, already have the full-name
22803 * Nearly always shorter, so try first time. */
22804 l = *fnamelen;
22805 if (get_short_pathname(fnamep, bufp, &l) == FAIL)
22806 return -1;
22808 if (l == 0)
22810 /* Couldn't find the filename.. search the paths.
22812 l = *fnamelen;
22813 if (shortpath_for_invalid_fname(fnamep, bufp, &l) == FAIL)
22814 return -1;
22816 *fnamelen = l;
22819 #endif /* WIN3264 */
22821 /* ":t" - tail, just the basename */
22822 if (src[*usedlen] == ':' && src[*usedlen + 1] == 't')
22824 *usedlen += 2;
22825 *fnamelen -= (int)(tail - *fnamep);
22826 *fnamep = tail;
22829 /* ":e" - extension, can be repeated */
22830 /* ":r" - root, without extension, can be repeated */
22831 while (src[*usedlen] == ':'
22832 && (src[*usedlen + 1] == 'e' || src[*usedlen + 1] == 'r'))
22834 /* find a '.' in the tail:
22835 * - for second :e: before the current fname
22836 * - otherwise: The last '.'
22838 if (src[*usedlen + 1] == 'e' && *fnamep > tail)
22839 s = *fnamep - 2;
22840 else
22841 s = *fnamep + *fnamelen - 1;
22842 for ( ; s > tail; --s)
22843 if (s[0] == '.')
22844 break;
22845 if (src[*usedlen + 1] == 'e') /* :e */
22847 if (s > tail)
22849 *fnamelen += (int)(*fnamep - (s + 1));
22850 *fnamep = s + 1;
22851 #ifdef VMS
22852 /* cut version from the extension */
22853 s = *fnamep + *fnamelen - 1;
22854 for ( ; s > *fnamep; --s)
22855 if (s[0] == ';')
22856 break;
22857 if (s > *fnamep)
22858 *fnamelen = s - *fnamep;
22859 #endif
22861 else if (*fnamep <= tail)
22862 *fnamelen = 0;
22864 else /* :r */
22866 if (s > tail) /* remove one extension */
22867 *fnamelen = (int)(s - *fnamep);
22869 *usedlen += 2;
22872 /* ":s?pat?foo?" - substitute */
22873 /* ":gs?pat?foo?" - global substitute */
22874 if (src[*usedlen] == ':'
22875 && (src[*usedlen + 1] == 's'
22876 || (src[*usedlen + 1] == 'g' && src[*usedlen + 2] == 's')))
22878 char_u *str;
22879 char_u *pat;
22880 char_u *sub;
22881 int sep;
22882 char_u *flags;
22883 int didit = FALSE;
22885 flags = (char_u *)"";
22886 s = src + *usedlen + 2;
22887 if (src[*usedlen + 1] == 'g')
22889 flags = (char_u *)"g";
22890 ++s;
22893 sep = *s++;
22894 if (sep)
22896 /* find end of pattern */
22897 p = vim_strchr(s, sep);
22898 if (p != NULL)
22900 pat = vim_strnsave(s, (int)(p - s));
22901 if (pat != NULL)
22903 s = p + 1;
22904 /* find end of substitution */
22905 p = vim_strchr(s, sep);
22906 if (p != NULL)
22908 sub = vim_strnsave(s, (int)(p - s));
22909 str = vim_strnsave(*fnamep, *fnamelen);
22910 if (sub != NULL && str != NULL)
22912 *usedlen = (int)(p + 1 - src);
22913 s = do_string_sub(str, pat, sub, flags);
22914 if (s != NULL)
22916 *fnamep = s;
22917 *fnamelen = (int)STRLEN(s);
22918 vim_free(*bufp);
22919 *bufp = s;
22920 didit = TRUE;
22923 vim_free(sub);
22924 vim_free(str);
22926 vim_free(pat);
22929 /* after using ":s", repeat all the modifiers */
22930 if (didit)
22931 goto repeat;
22935 return valid;
22939 * Perform a substitution on "str" with pattern "pat" and substitute "sub".
22940 * "flags" can be "g" to do a global substitute.
22941 * Returns an allocated string, NULL for error.
22943 char_u *
22944 do_string_sub(str, pat, sub, flags)
22945 char_u *str;
22946 char_u *pat;
22947 char_u *sub;
22948 char_u *flags;
22950 int sublen;
22951 regmatch_T regmatch;
22952 int i;
22953 int do_all;
22954 char_u *tail;
22955 garray_T ga;
22956 char_u *ret;
22957 char_u *save_cpo;
22959 /* Make 'cpoptions' empty, so that the 'l' flag doesn't work here */
22960 save_cpo = p_cpo;
22961 p_cpo = empty_option;
22963 ga_init2(&ga, 1, 200);
22965 do_all = (flags[0] == 'g');
22967 regmatch.rm_ic = p_ic;
22968 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
22969 if (regmatch.regprog != NULL)
22971 tail = str;
22972 while (vim_regexec_nl(&regmatch, str, (colnr_T)(tail - str)))
22975 * Get some space for a temporary buffer to do the substitution
22976 * into. It will contain:
22977 * - The text up to where the match is.
22978 * - The substituted text.
22979 * - The text after the match.
22981 sublen = vim_regsub(&regmatch, sub, tail, FALSE, TRUE, FALSE);
22982 if (ga_grow(&ga, (int)(STRLEN(tail) + sublen -
22983 (regmatch.endp[0] - regmatch.startp[0]))) == FAIL)
22985 ga_clear(&ga);
22986 break;
22989 /* copy the text up to where the match is */
22990 i = (int)(regmatch.startp[0] - tail);
22991 mch_memmove((char_u *)ga.ga_data + ga.ga_len, tail, (size_t)i);
22992 /* add the substituted text */
22993 (void)vim_regsub(&regmatch, sub, (char_u *)ga.ga_data
22994 + ga.ga_len + i, TRUE, TRUE, FALSE);
22995 ga.ga_len += i + sublen - 1;
22996 /* avoid getting stuck on a match with an empty string */
22997 if (tail == regmatch.endp[0])
22999 if (*tail == NUL)
23000 break;
23001 *((char_u *)ga.ga_data + ga.ga_len) = *tail++;
23002 ++ga.ga_len;
23004 else
23006 tail = regmatch.endp[0];
23007 if (*tail == NUL)
23008 break;
23010 if (!do_all)
23011 break;
23014 if (ga.ga_data != NULL)
23015 STRCPY((char *)ga.ga_data + ga.ga_len, tail);
23017 vim_free(regmatch.regprog);
23020 ret = vim_strsave(ga.ga_data == NULL ? str : (char_u *)ga.ga_data);
23021 ga_clear(&ga);
23022 if (p_cpo == empty_option)
23023 p_cpo = save_cpo;
23024 else
23025 /* Darn, evaluating {sub} expression changed the value. */
23026 free_string_option(save_cpo);
23028 return ret;
23031 #endif /* defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL) */