blob: bc9091f089df73878dbc487a6f60d5dba283ef2f [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
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 */
9
10/*
11 * misc2.c: Various functions.
12 */
13#include "vim.h"
14
Bram Moolenaarf461c8e2005-06-25 23:04:51 +000015static char_u *username = NULL; /* cached result of mch_get_user_name() */
16
17static char_u *ff_expand_buffer = NULL; /* used for expanding filenames */
18
Bram Moolenaar071d4272004-06-13 20:20:40 +000019#if defined(FEAT_VIRTUALEDIT) || defined(PROTO)
20static int coladvance2 __ARGS((pos_T *pos, int addspaces, int finetune, colnr_T wcol));
21
22/*
23 * Return TRUE if in the current mode we need to use virtual.
24 */
25 int
26virtual_active()
27{
28 /* While an operator is being executed we return "virtual_op", because
29 * VIsual_active has already been reset, thus we can't check for "block"
30 * being used. */
31 if (virtual_op != MAYBE)
32 return virtual_op;
33 return (ve_flags == VE_ALL
34# ifdef FEAT_VISUAL
35 || ((ve_flags & VE_BLOCK) && VIsual_active && VIsual_mode == Ctrl_V)
36# endif
37 || ((ve_flags & VE_INSERT) && (State & INSERT)));
38}
39
40/*
41 * Get the screen position of the cursor.
42 */
43 int
44getviscol()
45{
46 colnr_T x;
47
48 getvvcol(curwin, &curwin->w_cursor, &x, NULL, NULL);
49 return (int)x;
50}
51
52/*
53 * Get the screen position of character col with a coladd in the cursor line.
54 */
55 int
56getviscol2(col, coladd)
57 colnr_T col;
58 colnr_T coladd;
59{
60 colnr_T x;
61 pos_T pos;
62
63 pos.lnum = curwin->w_cursor.lnum;
64 pos.col = col;
65 pos.coladd = coladd;
66 getvvcol(curwin, &pos, &x, NULL, NULL);
67 return (int)x;
68}
69
70/*
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +000071 * Go to column "wcol", and add/insert white space as necessary to get the
Bram Moolenaar071d4272004-06-13 20:20:40 +000072 * cursor in that column.
73 * The caller must have saved the cursor line for undo!
74 */
75 int
76coladvance_force(wcol)
77 colnr_T wcol;
78{
79 int rc = coladvance2(&curwin->w_cursor, TRUE, FALSE, wcol);
80
81 if (wcol == MAXCOL)
82 curwin->w_valid &= ~VALID_VIRTCOL;
83 else
84 {
85 /* Virtcol is valid */
86 curwin->w_valid |= VALID_VIRTCOL;
87 curwin->w_virtcol = wcol;
88 }
89 return rc;
90}
91#endif
92
93/*
94 * Try to advance the Cursor to the specified screen column.
95 * If virtual editing: fine tune the cursor position.
96 * Note that all virtual positions off the end of a line should share
97 * a curwin->w_cursor.col value (n.b. this is equal to STRLEN(line)),
98 * beginning at coladd 0.
99 *
100 * return OK if desired column is reached, FAIL if not
101 */
102 int
103coladvance(wcol)
104 colnr_T wcol;
105{
106 int rc = getvpos(&curwin->w_cursor, wcol);
107
108 if (wcol == MAXCOL || rc == FAIL)
109 curwin->w_valid &= ~VALID_VIRTCOL;
Bram Moolenaardfccaf02004-12-31 20:56:11 +0000110 else if (*ml_get_cursor() != TAB)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000111 {
Bram Moolenaardfccaf02004-12-31 20:56:11 +0000112 /* Virtcol is valid when not on a TAB */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000113 curwin->w_valid |= VALID_VIRTCOL;
114 curwin->w_virtcol = wcol;
115 }
116 return rc;
117}
118
119/*
120 * Return in "pos" the position of the cursor advanced to screen column "wcol".
121 * return OK if desired column is reached, FAIL if not
122 */
123 int
124getvpos(pos, wcol)
125 pos_T *pos;
126 colnr_T wcol;
127{
128#ifdef FEAT_VIRTUALEDIT
129 return coladvance2(pos, FALSE, virtual_active(), wcol);
130}
131
132 static int
133coladvance2(pos, addspaces, finetune, wcol)
134 pos_T *pos;
135 int addspaces; /* change the text to achieve our goal? */
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +0000136 int finetune; /* change char offset for the exact column */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000137 colnr_T wcol; /* column to move to */
138{
139#endif
140 int idx;
141 char_u *ptr;
142 char_u *line;
143 colnr_T col = 0;
144 int csize = 0;
145 int one_more;
146#ifdef FEAT_LINEBREAK
147 int head = 0;
148#endif
149
Bram Moolenaarefd2bf12006-03-16 21:41:35 +0000150 one_more = (State & INSERT)
151 || restart_edit != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152#ifdef FEAT_VISUAL
Bram Moolenaarefd2bf12006-03-16 21:41:35 +0000153 || (VIsual_active && *p_sel != 'o')
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154#endif
Bram Moolenaarefd2bf12006-03-16 21:41:35 +0000155#ifdef FEAT_VIRTUALEDIT
Bram Moolenaar97b2ad32006-03-18 21:40:56 +0000156 || ((ve_flags & VE_ONEMORE) && wcol < MAXCOL)
Bram Moolenaarefd2bf12006-03-16 21:41:35 +0000157#endif
158 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000159 line = ml_get_curline();
160
161 if (wcol >= MAXCOL)
162 {
163 idx = (int)STRLEN(line) - 1 + one_more;
164 col = wcol;
165
166#ifdef FEAT_VIRTUALEDIT
167 if ((addspaces || finetune) && !VIsual_active)
168 {
169 curwin->w_curswant = linetabsize(line) + one_more;
170 if (curwin->w_curswant > 0)
171 --curwin->w_curswant;
172 }
173#endif
174 }
175 else
176 {
177#ifdef FEAT_VIRTUALEDIT
178 int width = W_WIDTH(curwin) - win_col_off(curwin);
179
Bram Moolenaarebefac62005-12-28 22:39:57 +0000180 if (finetune
Bram Moolenaar071d4272004-06-13 20:20:40 +0000181 && curwin->w_p_wrap
182# ifdef FEAT_VERTSPLIT
183 && curwin->w_width != 0
184# endif
185 && wcol >= (colnr_T)width)
186 {
187 csize = linetabsize(line);
188 if (csize > 0)
189 csize--;
190
Bram Moolenaarebefac62005-12-28 22:39:57 +0000191 if (wcol / width > (colnr_T)csize / width
192 && ((State & INSERT) == 0 || (int)wcol > csize + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000193 {
194 /* In case of line wrapping don't move the cursor beyond the
Bram Moolenaarebefac62005-12-28 22:39:57 +0000195 * right screen edge. In Insert mode allow going just beyond
196 * the last character (like what happens when typing and
197 * reaching the right window edge). */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000198 wcol = (csize / width + 1) * width - 1;
199 }
200 }
201#endif
202
203 idx = -1;
204 ptr = line;
205 while (col <= wcol && *ptr != NUL)
206 {
207 /* Count a tab for what it's worth (if list mode not on) */
208#ifdef FEAT_LINEBREAK
209 csize = win_lbr_chartabsize(curwin, ptr, col, &head);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000210 mb_ptr_adv(ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000211#else
212 csize = lbr_chartabsize_adv(&ptr, col);
213#endif
214 col += csize;
215 }
216 idx = (int)(ptr - line);
217 /*
218 * Handle all the special cases. The virtual_active() check
219 * is needed to ensure that a virtual position off the end of
220 * a line has the correct indexing. The one_more comparison
221 * replaces an explicit add of one_more later on.
222 */
223 if (col > wcol || (!virtual_active() && one_more == 0))
224 {
225 idx -= 1;
226# ifdef FEAT_LINEBREAK
227 /* Don't count the chars from 'showbreak'. */
228 csize -= head;
229# endif
230 col -= csize;
231 }
232
233#ifdef FEAT_VIRTUALEDIT
234 if (virtual_active()
235 && addspaces
236 && ((col != wcol && col != wcol + 1) || csize > 1))
237 {
238 /* 'virtualedit' is set: The difference between wcol and col is
239 * filled with spaces. */
240
241 if (line[idx] == NUL)
242 {
243 /* Append spaces */
244 int correct = wcol - col;
245 char_u *newline = alloc(idx + correct + 1);
246 int t;
247
248 if (newline == NULL)
249 return FAIL;
250
251 for (t = 0; t < idx; ++t)
252 newline[t] = line[t];
253
254 for (t = 0; t < correct; ++t)
255 newline[t + idx] = ' ';
256
257 newline[idx + correct] = NUL;
258
259 ml_replace(pos->lnum, newline, FALSE);
260 changed_bytes(pos->lnum, (colnr_T)idx);
261 idx += correct;
262 col = wcol;
263 }
264 else
265 {
266 /* Break a tab */
267 int linelen = (int)STRLEN(line);
268 int correct = wcol - col - csize + 1; /* negative!! */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000269 char_u *newline;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000270 int t, s = 0;
271 int v;
272
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000273 if (-correct > csize)
274 return FAIL;
275
276 newline = alloc(linelen + csize);
277 if (newline == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000278 return FAIL;
279
280 for (t = 0; t < linelen; t++)
281 {
282 if (t != idx)
283 newline[s++] = line[t];
284 else
285 for (v = 0; v < csize; v++)
286 newline[s++] = ' ';
287 }
288
289 newline[linelen + csize - 1] = NUL;
290
291 ml_replace(pos->lnum, newline, FALSE);
292 changed_bytes(pos->lnum, idx);
293 idx += (csize - 1 + correct);
294 col += correct;
295 }
296 }
297#endif
298 }
299
300 if (idx < 0)
301 pos->col = 0;
302 else
303 pos->col = idx;
304
305#ifdef FEAT_VIRTUALEDIT
306 pos->coladd = 0;
307
308 if (finetune)
309 {
310 if (wcol == MAXCOL)
311 {
312 /* The width of the last character is used to set coladd. */
313 if (!one_more)
314 {
315 colnr_T scol, ecol;
316
317 getvcol(curwin, pos, &scol, NULL, &ecol);
318 pos->coladd = ecol - scol;
319 }
320 }
321 else
322 {
323 int b = (int)wcol - (int)col;
324
325 /* The difference between wcol and col is used to set coladd. */
326 if (b > 0 && b < (MAXCOL - 2 * W_WIDTH(curwin)))
327 pos->coladd = b;
328
329 col += b;
330 }
331 }
332#endif
333
334#ifdef FEAT_MBYTE
335 /* prevent cursor from moving on the trail byte */
336 if (has_mbyte)
337 mb_adjust_cursor();
338#endif
339
340 if (col < wcol)
341 return FAIL;
342 return OK;
343}
344
345/*
Bram Moolenaar446cb832008-06-24 21:56:24 +0000346 * Increment the cursor position. See inc() for return values.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000347 */
348 int
349inc_cursor()
350{
351 return inc(&curwin->w_cursor);
352}
353
Bram Moolenaar446cb832008-06-24 21:56:24 +0000354/*
355 * Increment the line pointer "lp" crossing line boundaries as necessary.
356 * Return 1 when going to the next line.
357 * Return 2 when moving forward onto a NUL at the end of the line).
358 * Return -1 when at the end of file.
359 * Return 0 otherwise.
360 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000361 int
362inc(lp)
363 pos_T *lp;
364{
365 char_u *p = ml_get_pos(lp);
366
367 if (*p != NUL) /* still within line, move to next char (may be NUL) */
368 {
369#ifdef FEAT_MBYTE
370 if (has_mbyte)
371 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +0000372 int l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373
374 lp->col += l;
375 return ((p[l] != NUL) ? 0 : 2);
376 }
377#endif
378 lp->col++;
379#ifdef FEAT_VIRTUALEDIT
380 lp->coladd = 0;
381#endif
382 return ((p[1] != NUL) ? 0 : 2);
383 }
384 if (lp->lnum != curbuf->b_ml.ml_line_count) /* there is a next line */
385 {
386 lp->col = 0;
387 lp->lnum++;
388#ifdef FEAT_VIRTUALEDIT
389 lp->coladd = 0;
390#endif
391 return 1;
392 }
393 return -1;
394}
395
396/*
397 * incl(lp): same as inc(), but skip the NUL at the end of non-empty lines
398 */
399 int
400incl(lp)
401 pos_T *lp;
402{
403 int r;
404
405 if ((r = inc(lp)) >= 1 && lp->col)
406 r = inc(lp);
407 return r;
408}
409
410/*
411 * dec(p)
412 *
413 * Decrement the line pointer 'p' crossing line boundaries as necessary.
414 * Return 1 when crossing a line, -1 when at start of file, 0 otherwise.
415 */
416 int
417dec_cursor()
418{
419 return dec(&curwin->w_cursor);
420}
421
422 int
423dec(lp)
424 pos_T *lp;
425{
426 char_u *p;
427
428#ifdef FEAT_VIRTUALEDIT
429 lp->coladd = 0;
430#endif
431 if (lp->col > 0) /* still within line */
432 {
433 lp->col--;
434#ifdef FEAT_MBYTE
435 if (has_mbyte)
436 {
437 p = ml_get(lp->lnum);
438 lp->col -= (*mb_head_off)(p, p + lp->col);
439 }
440#endif
441 return 0;
442 }
443 if (lp->lnum > 1) /* there is a prior line */
444 {
445 lp->lnum--;
446 p = ml_get(lp->lnum);
447 lp->col = (colnr_T)STRLEN(p);
448#ifdef FEAT_MBYTE
449 if (has_mbyte)
450 lp->col -= (*mb_head_off)(p, p + lp->col);
451#endif
452 return 1;
453 }
454 return -1; /* at start of file */
455}
456
457/*
458 * decl(lp): same as dec(), but skip the NUL at the end of non-empty lines
459 */
460 int
461decl(lp)
462 pos_T *lp;
463{
464 int r;
465
466 if ((r = dec(lp)) == 1 && lp->col)
467 r = dec(lp);
468 return r;
469}
470
471/*
472 * Make sure curwin->w_cursor.lnum is valid.
473 */
474 void
475check_cursor_lnum()
476{
477 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
478 {
479#ifdef FEAT_FOLDING
480 /* If there is a closed fold at the end of the file, put the cursor in
481 * its first line. Otherwise in the last line. */
482 if (!hasFolding(curbuf->b_ml.ml_line_count,
483 &curwin->w_cursor.lnum, NULL))
484#endif
485 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
486 }
487 if (curwin->w_cursor.lnum <= 0)
488 curwin->w_cursor.lnum = 1;
489}
490
491/*
492 * Make sure curwin->w_cursor.col is valid.
493 */
494 void
495check_cursor_col()
496{
497 colnr_T len;
498#ifdef FEAT_VIRTUALEDIT
499 colnr_T oldcol = curwin->w_cursor.col + curwin->w_cursor.coladd;
500#endif
501
502 len = (colnr_T)STRLEN(ml_get_curline());
503 if (len == 0)
504 curwin->w_cursor.col = 0;
505 else if (curwin->w_cursor.col >= len)
506 {
Bram Moolenaar33f54432008-01-04 20:25:44 +0000507 /* Allow cursor past end-of-line when:
508 * - in Insert mode or restarting Insert mode
509 * - in Visual mode and 'selection' isn't "old"
510 * - 'virtualedit' is set */
Bram Moolenaarebefac62005-12-28 22:39:57 +0000511 if ((State & INSERT) || restart_edit
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512#ifdef FEAT_VISUAL
513 || (VIsual_active && *p_sel != 'o')
514#endif
Bram Moolenaar33f54432008-01-04 20:25:44 +0000515#ifdef FEAT_VIRTUALEDIT
516 || (ve_flags & VE_ONEMORE)
517#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000518 || virtual_active())
519 curwin->w_cursor.col = len;
520 else
Bram Moolenaar87c19962007-04-26 08:54:21 +0000521 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 curwin->w_cursor.col = len - 1;
Bram Moolenaar87c19962007-04-26 08:54:21 +0000523#ifdef FEAT_MBYTE
524 /* prevent cursor from moving on the trail byte */
525 if (has_mbyte)
526 mb_adjust_cursor();
527#endif
528 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529 }
530
531#ifdef FEAT_VIRTUALEDIT
532 /* If virtual editing is on, we can leave the cursor on the old position,
533 * only we must set it to virtual. But don't do it when at the end of the
534 * line. */
535 if (oldcol == MAXCOL)
536 curwin->w_cursor.coladd = 0;
537 else if (ve_flags == VE_ALL)
538 curwin->w_cursor.coladd = oldcol - curwin->w_cursor.col;
539#endif
540}
541
542/*
543 * make sure curwin->w_cursor in on a valid character
544 */
545 void
546check_cursor()
547{
548 check_cursor_lnum();
549 check_cursor_col();
550}
551
552#if defined(FEAT_TEXTOBJ) || defined(PROTO)
553/*
554 * Make sure curwin->w_cursor is not on the NUL at the end of the line.
555 * Allow it when in Visual mode and 'selection' is not "old".
556 */
557 void
558adjust_cursor_col()
559{
560 if (curwin->w_cursor.col > 0
561# ifdef FEAT_VISUAL
562 && (!VIsual_active || *p_sel == 'o')
563# endif
564 && gchar_cursor() == NUL)
565 --curwin->w_cursor.col;
566}
567#endif
568
569/*
570 * When curwin->w_leftcol has changed, adjust the cursor position.
571 * Return TRUE if the cursor was moved.
572 */
573 int
574leftcol_changed()
575{
576 long lastcol;
577 colnr_T s, e;
578 int retval = FALSE;
579
580 changed_cline_bef_curs();
581 lastcol = curwin->w_leftcol + W_WIDTH(curwin) - curwin_col_off() - 1;
582 validate_virtcol();
583
584 /*
585 * If the cursor is right or left of the screen, move it to last or first
586 * character.
587 */
588 if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso))
589 {
590 retval = TRUE;
591 coladvance((colnr_T)(lastcol - p_siso));
592 }
593 else if (curwin->w_virtcol < curwin->w_leftcol + p_siso)
594 {
595 retval = TRUE;
596 (void)coladvance((colnr_T)(curwin->w_leftcol + p_siso));
597 }
598
599 /*
600 * If the start of the character under the cursor is not on the screen,
601 * advance the cursor one more char. If this fails (last char of the
602 * line) adjust the scrolling.
603 */
604 getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
605 if (e > (colnr_T)lastcol)
606 {
607 retval = TRUE;
608 coladvance(s - 1);
609 }
610 else if (s < curwin->w_leftcol)
611 {
612 retval = TRUE;
613 if (coladvance(e + 1) == FAIL) /* there isn't another character */
614 {
615 curwin->w_leftcol = s; /* adjust w_leftcol instead */
616 changed_cline_bef_curs();
617 }
618 }
619
620 if (retval)
621 curwin->w_set_curswant = TRUE;
622 redraw_later(NOT_VALID);
623 return retval;
624}
625
626/**********************************************************************
627 * Various routines dealing with allocation and deallocation of memory.
628 */
629
630#if defined(MEM_PROFILE) || defined(PROTO)
631
632# define MEM_SIZES 8200
633static long_u mem_allocs[MEM_SIZES];
634static long_u mem_frees[MEM_SIZES];
635static long_u mem_allocated;
636static long_u mem_freed;
637static long_u mem_peak;
638static long_u num_alloc;
639static long_u num_freed;
640
641static void mem_pre_alloc_s __ARGS((size_t *sizep));
642static void mem_pre_alloc_l __ARGS((long_u *sizep));
643static void mem_post_alloc __ARGS((void **pp, size_t size));
644static void mem_pre_free __ARGS((void **pp));
645
646 static void
647mem_pre_alloc_s(sizep)
648 size_t *sizep;
649{
650 *sizep += sizeof(size_t);
651}
652
653 static void
654mem_pre_alloc_l(sizep)
655 long_u *sizep;
656{
657 *sizep += sizeof(size_t);
658}
659
660 static void
661mem_post_alloc(pp, size)
662 void **pp;
663 size_t size;
664{
665 if (*pp == NULL)
666 return;
667 size -= sizeof(size_t);
668 *(long_u *)*pp = size;
669 if (size <= MEM_SIZES-1)
670 mem_allocs[size-1]++;
671 else
672 mem_allocs[MEM_SIZES-1]++;
673 mem_allocated += size;
674 if (mem_allocated - mem_freed > mem_peak)
675 mem_peak = mem_allocated - mem_freed;
676 num_alloc++;
677 *pp = (void *)((char *)*pp + sizeof(size_t));
678}
679
680 static void
681mem_pre_free(pp)
682 void **pp;
683{
684 long_u size;
685
686 *pp = (void *)((char *)*pp - sizeof(size_t));
687 size = *(size_t *)*pp;
688 if (size <= MEM_SIZES-1)
689 mem_frees[size-1]++;
690 else
691 mem_frees[MEM_SIZES-1]++;
692 mem_freed += size;
693 num_freed++;
694}
695
696/*
697 * called on exit via atexit()
698 */
699 void
700vim_mem_profile_dump()
701{
702 int i, j;
703
704 printf("\r\n");
705 j = 0;
706 for (i = 0; i < MEM_SIZES - 1; i++)
707 {
708 if (mem_allocs[i] || mem_frees[i])
709 {
710 if (mem_frees[i] > mem_allocs[i])
711 printf("\r\n%s", _("ERROR: "));
712 printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
713 j++;
714 if (j > 3)
715 {
716 j = 0;
717 printf("\r\n");
718 }
719 }
720 }
721
722 i = MEM_SIZES - 1;
723 if (mem_allocs[i])
724 {
725 printf("\r\n");
726 if (mem_frees[i] > mem_allocs[i])
727 printf(_("ERROR: "));
728 printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
729 }
730
731 printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
732 mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
733 printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
734 num_alloc, num_freed);
735}
736
737#endif /* MEM_PROFILE */
738
739/*
740 * Some memory is reserved for error messages and for being able to
741 * call mf_release_all(), which needs some memory for mf_trans_add().
742 */
743#if defined(MSDOS) && !defined(DJGPP)
744# define SMALL_MEM
745# define KEEP_ROOM 8192L
746#else
747# define KEEP_ROOM (2 * 8192L)
748#endif
749
750/*
Bram Moolenaar2a329742008-04-01 12:53:43 +0000751 * Note: if unsigned is 16 bits we can only allocate up to 64K with alloc().
Bram Moolenaar071d4272004-06-13 20:20:40 +0000752 * Use lalloc for larger blocks.
753 */
754 char_u *
755alloc(size)
756 unsigned size;
757{
758 return (lalloc((long_u)size, TRUE));
759}
760
761/*
762 * Allocate memory and set all bytes to zero.
763 */
764 char_u *
765alloc_clear(size)
766 unsigned size;
767{
768 char_u *p;
769
770 p = (lalloc((long_u)size, TRUE));
771 if (p != NULL)
772 (void)vim_memset(p, 0, (size_t)size);
773 return p;
774}
775
776/*
777 * alloc() with check for maximum line length
778 */
779 char_u *
780alloc_check(size)
781 unsigned size;
782{
783#if !defined(UNIX) && !defined(__EMX__)
784 if (sizeof(int) == 2 && size > 0x7fff)
785 {
786 /* Don't hide this message */
787 emsg_silent = 0;
788 EMSG(_("E340: Line is becoming too long"));
789 return NULL;
790 }
791#endif
792 return (lalloc((long_u)size, TRUE));
793}
794
795/*
796 * Allocate memory like lalloc() and set all bytes to zero.
797 */
798 char_u *
799lalloc_clear(size, message)
800 long_u size;
801 int message;
802{
803 char_u *p;
804
805 p = (lalloc(size, message));
806 if (p != NULL)
807 (void)vim_memset(p, 0, (size_t)size);
808 return p;
809}
810
811/*
812 * Low level memory allocation function.
813 * This is used often, KEEP IT FAST!
814 */
815 char_u *
816lalloc(size, message)
817 long_u size;
818 int message;
819{
820 char_u *p; /* pointer to new storage space */
821 static int releasing = FALSE; /* don't do mf_release_all() recursive */
822 int try_again;
823#if defined(HAVE_AVAIL_MEM) && !defined(SMALL_MEM)
824 static long_u allocated = 0; /* allocated since last avail check */
825#endif
826
827 /* Safety check for allocating zero bytes */
828 if (size == 0)
829 {
830 /* Don't hide this message */
831 emsg_silent = 0;
832 EMSGN(_("E341: Internal error: lalloc(%ld, )"), size);
833 return NULL;
834 }
835
836#ifdef MEM_PROFILE
837 mem_pre_alloc_l(&size);
838#endif
839
840#if defined(MSDOS) && !defined(DJGPP)
841 if (size >= 0xfff0) /* in MSDOS we can't deal with >64K blocks */
842 p = NULL;
843 else
844#endif
845
846 /*
847 * Loop when out of memory: Try to release some memfile blocks and
848 * if some blocks are released call malloc again.
849 */
850 for (;;)
851 {
852 /*
853 * Handle three kind of systems:
854 * 1. No check for available memory: Just return.
855 * 2. Slow check for available memory: call mch_avail_mem() after
856 * allocating KEEP_ROOM amount of memory.
857 * 3. Strict check for available memory: call mch_avail_mem()
858 */
859 if ((p = (char_u *)malloc((size_t)size)) != NULL)
860 {
861#ifndef HAVE_AVAIL_MEM
862 /* 1. No check for available memory: Just return. */
863 goto theend;
864#else
865# ifndef SMALL_MEM
866 /* 2. Slow check for available memory: call mch_avail_mem() after
867 * allocating (KEEP_ROOM / 2) amount of memory. */
868 allocated += size;
869 if (allocated < KEEP_ROOM / 2)
870 goto theend;
871 allocated = 0;
872# endif
873 /* 3. check for available memory: call mch_avail_mem() */
874 if (mch_avail_mem(TRUE) < KEEP_ROOM && !releasing)
875 {
876 vim_free((char *)p); /* System is low... no go! */
877 p = NULL;
878 }
879 else
880 goto theend;
881#endif
882 }
883 /*
884 * Remember that mf_release_all() is being called to avoid an endless
885 * loop, because mf_release_all() may call alloc() recursively.
886 */
887 if (releasing)
888 break;
889 releasing = TRUE;
Bram Moolenaar661b1822005-07-28 22:36:45 +0000890
891 clear_sb_text(); /* free any scrollback text */
892 try_again = mf_release_all(); /* release as many blocks as possible */
Bram Moolenaar39a58ca2005-06-27 22:42:44 +0000893#ifdef FEAT_EVAL
Bram Moolenaar661b1822005-07-28 22:36:45 +0000894 try_again |= garbage_collect(); /* cleanup recursive lists/dicts */
Bram Moolenaar39a58ca2005-06-27 22:42:44 +0000895#endif
Bram Moolenaar661b1822005-07-28 22:36:45 +0000896
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897 releasing = FALSE;
898 if (!try_again)
899 break;
900 }
901
902 if (message && p == NULL)
903 do_outofmem_msg(size);
904
905theend:
906#ifdef MEM_PROFILE
907 mem_post_alloc((void **)&p, (size_t)size);
908#endif
909 return p;
910}
911
912#if defined(MEM_PROFILE) || defined(PROTO)
913/*
914 * realloc() with memory profiling.
915 */
916 void *
917mem_realloc(ptr, size)
918 void *ptr;
919 size_t size;
920{
921 void *p;
922
923 mem_pre_free(&ptr);
924 mem_pre_alloc_s(&size);
925
926 p = realloc(ptr, size);
927
928 mem_post_alloc(&p, size);
929
930 return p;
931}
932#endif
933
934/*
935* Avoid repeating the error message many times (they take 1 second each).
936* Did_outofmem_msg is reset when a character is read.
937*/
938 void
939do_outofmem_msg(size)
940 long_u size;
941{
942 if (!did_outofmem_msg)
943 {
944 /* Don't hide this message */
945 emsg_silent = 0;
946 EMSGN(_("E342: Out of memory! (allocating %lu bytes)"), size);
947 did_outofmem_msg = TRUE;
948 }
949}
950
Bram Moolenaar1ec484f2005-06-24 23:07:47 +0000951#if defined(EXITFREE) || defined(PROTO)
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000952
953# if defined(FEAT_SEARCHPATH)
954static void free_findfile __ARGS((void));
955# endif
956
Bram Moolenaar1ec484f2005-06-24 23:07:47 +0000957/*
958 * Free everything that we allocated.
959 * Can be used to detect memory leaks, e.g., with ccmalloc.
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000960 * NOTE: This is tricky! Things are freed that functions depend on. Don't be
961 * surprised if Vim crashes...
962 * Some things can't be freed, esp. things local to a library function.
Bram Moolenaar1ec484f2005-06-24 23:07:47 +0000963 */
964 void
965free_all_mem()
966{
967 buf_T *buf, *nextbuf;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000968 static int entered = FALSE;
969
970 /* When we cause a crash here it is caught and Vim tries to exit cleanly.
971 * Don't try freeing everything again. */
972 if (entered)
973 return;
974 entered = TRUE;
Bram Moolenaar1ec484f2005-06-24 23:07:47 +0000975
Bram Moolenaare0ca7b22007-11-24 20:28:24 +0000976# ifdef FEAT_AUTOCMD
Bram Moolenaar78ab3312007-09-29 12:16:41 +0000977 block_autocmds(); /* don't want to trigger autocommands here */
Bram Moolenaare0ca7b22007-11-24 20:28:24 +0000978# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +0000979
Bram Moolenaare0ca7b22007-11-24 20:28:24 +0000980# ifdef FEAT_WINDOWS
Bram Moolenaar997fb4b2006-02-17 21:53:23 +0000981 /* close all tabs and windows */
Bram Moolenaar7d47b6e2006-03-15 22:59:18 +0000982 if (first_tabpage->tp_next != NULL)
983 do_cmdline_cmd((char_u *)"tabonly!");
984 if (firstwin != lastwin)
985 do_cmdline_cmd((char_u *)"only!");
Bram Moolenaare0ca7b22007-11-24 20:28:24 +0000986# endif
Bram Moolenaar997fb4b2006-02-17 21:53:23 +0000987
Bram Moolenaarc4956c82006-03-12 21:58:43 +0000988# if defined(FEAT_SPELL)
Bram Moolenaar1ec484f2005-06-24 23:07:47 +0000989 /* Free all spell info. */
990 spell_free_all();
991# endif
992
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000993# if defined(FEAT_USR_CMDS)
Bram Moolenaar1ec484f2005-06-24 23:07:47 +0000994 /* Clear user commands (before deleting buffers). */
995 ex_comclear(NULL);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +0000996# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +0000997
998# ifdef FEAT_MENU
999 /* Clear menus. */
1000 do_cmdline_cmd((char_u *)"aunmenu *");
1001# endif
1002
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001003 /* Clear mappings, abbreviations, breakpoints. */
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001004 do_cmdline_cmd((char_u *)"mapclear");
1005 do_cmdline_cmd((char_u *)"mapclear!");
1006 do_cmdline_cmd((char_u *)"abclear");
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001007# if defined(FEAT_EVAL)
1008 do_cmdline_cmd((char_u *)"breakdel *");
1009# endif
Bram Moolenaar1e498f52005-06-26 22:29:44 +00001010# if defined(FEAT_PROFILE)
1011 do_cmdline_cmd((char_u *)"profdel *");
1012# endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001013
1014# ifdef FEAT_TITLE
1015 free_titles();
1016# endif
1017# if defined(FEAT_SEARCHPATH)
1018 free_findfile();
1019# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001020
1021 /* Obviously named calls. */
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001022# if defined(FEAT_AUTOCMD)
1023 free_all_autocmds();
1024# endif
1025 clear_termcodes();
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001026 free_all_options();
1027 free_all_marks();
1028 alist_clear(&global_alist);
1029 free_homedir();
1030 free_search_patterns();
1031 free_old_sub();
1032 free_last_insert();
1033 free_prev_shellcmd();
1034 free_regexp_stuff();
1035 free_tag_stuff();
1036 free_cd_dir();
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001037# ifdef FEAT_EVAL
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001038 set_expr_line(NULL);
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001039# endif
1040# ifdef FEAT_DIFF
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00001041 diff_clear(curtab);
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001042# endif
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00001043 clear_sb_text(); /* free any scrollback text */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001044
1045 /* Free some global vars. */
1046 vim_free(username);
Bram Moolenaaraf92ee82007-10-07 13:45:08 +00001047# ifdef FEAT_CLIPBOARD
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001048 vim_free(clip_exclude_prog);
Bram Moolenaaraf92ee82007-10-07 13:45:08 +00001049# endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001050 vim_free(last_cmdline);
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001051# ifdef FEAT_CMDHIST
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001052 vim_free(new_last_cmdline);
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001053# endif
Bram Moolenaar238a5642006-02-21 22:12:05 +00001054 set_keep_msg(NULL, 0);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001055 vim_free(ff_expand_buffer);
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001056
1057 /* Clear cmdline history. */
1058 p_hi = 0;
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001059# ifdef FEAT_CMDHIST
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001060 init_history();
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001061# endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001062
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001063#ifdef FEAT_QUICKFIX
Bram Moolenaare0ca7b22007-11-24 20:28:24 +00001064 {
1065 win_T *win;
1066
1067 qf_free_all(NULL);
1068 /* Free all location lists */
1069 FOR_ALL_WINDOWS(win)
1070 qf_free_all(win);
1071 }
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001072#endif
1073
1074 /* Close all script inputs. */
1075 close_all_scripts();
1076
1077#if defined(FEAT_WINDOWS)
1078 /* Destroy all windows. Must come before freeing buffers. */
1079 win_free_all();
1080#endif
1081
Bram Moolenaar2a329742008-04-01 12:53:43 +00001082 /* Free all buffers. Reset 'autochdir' to avoid accessing things that
1083 * were freed already. */
1084#ifdef FEAT_AUTOCHDIR
1085 p_acd = FALSE;
1086#endif
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001087 for (buf = firstbuf; buf != NULL; )
1088 {
1089 nextbuf = buf->b_next;
1090 close_buffer(NULL, buf, DOBUF_WIPE);
1091 if (buf_valid(buf))
1092 buf = nextbuf; /* didn't work, try next one */
1093 else
1094 buf = firstbuf;
1095 }
1096
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001097#ifdef FEAT_ARABIC
1098 free_cmdline_buf();
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001099#endif
1100
1101 /* Clear registers. */
1102 clear_registers();
1103 ResetRedobuff();
1104 ResetRedobuff();
1105
Bram Moolenaar85c79d32007-02-20 01:59:20 +00001106#if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001107 vim_free(serverDelayedStartName);
1108#endif
1109
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001110 /* highlight info */
1111 free_highlight();
1112
Bram Moolenaar1e498f52005-06-26 22:29:44 +00001113 reset_last_sourcing();
1114
Bram Moolenaar7d47b6e2006-03-15 22:59:18 +00001115#ifdef FEAT_WINDOWS
Bram Moolenaar06a89a52006-04-29 22:01:03 +00001116 free_tabpage(first_tabpage);
1117 first_tabpage = NULL;
Bram Moolenaar7d47b6e2006-03-15 22:59:18 +00001118#endif
1119
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001120# ifdef UNIX
1121 /* Machine-specific free. */
1122 mch_free_mem();
1123# endif
1124
1125 /* message history */
1126 for (;;)
1127 if (delete_first_msg() == FAIL)
1128 break;
1129
1130# ifdef FEAT_EVAL
1131 eval_clear();
1132# endif
1133
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001134 free_termoptions();
1135
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001136 /* screenlines (can't display anything now!) */
1137 free_screenlines();
1138
1139#if defined(USE_XSMP)
1140 xsmp_close();
1141#endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00001142#ifdef FEAT_GUI_GTK
1143 gui_mch_free_all();
1144#endif
1145 clear_hl_tables();
Bram Moolenaar1ec484f2005-06-24 23:07:47 +00001146
1147 vim_free(IObuff);
1148 vim_free(NameBuff);
1149}
1150#endif
1151
Bram Moolenaar071d4272004-06-13 20:20:40 +00001152/*
1153 * copy a string into newly allocated memory
1154 */
1155 char_u *
1156vim_strsave(string)
1157 char_u *string;
1158{
1159 char_u *p;
1160 unsigned len;
1161
1162 len = (unsigned)STRLEN(string) + 1;
1163 p = alloc(len);
1164 if (p != NULL)
1165 mch_memmove(p, string, (size_t)len);
1166 return p;
1167}
1168
1169 char_u *
1170vim_strnsave(string, len)
1171 char_u *string;
1172 int len;
1173{
1174 char_u *p;
1175
1176 p = alloc((unsigned)(len + 1));
1177 if (p != NULL)
1178 {
1179 STRNCPY(p, string, len);
1180 p[len] = NUL;
1181 }
1182 return p;
1183}
1184
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185/*
1186 * Same as vim_strsave(), but any characters found in esc_chars are preceded
1187 * by a backslash.
1188 */
1189 char_u *
1190vim_strsave_escaped(string, esc_chars)
1191 char_u *string;
1192 char_u *esc_chars;
1193{
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001194 return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001195}
1196
1197/*
1198 * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape
1199 * characters where rem_backslash() would remove the backslash.
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001200 * Escape the characters with "cc".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001201 */
1202 char_u *
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001203vim_strsave_escaped_ext(string, esc_chars, cc, bsl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001204 char_u *string;
1205 char_u *esc_chars;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001206 int cc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207 int bsl;
1208{
1209 char_u *p;
1210 char_u *p2;
1211 char_u *escaped_string;
1212 unsigned length;
1213#ifdef FEAT_MBYTE
1214 int l;
1215#endif
1216
1217 /*
1218 * First count the number of backslashes required.
1219 * Then allocate the memory and insert them.
1220 */
1221 length = 1; /* count the trailing NUL */
1222 for (p = string; *p; p++)
1223 {
1224#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001225 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001226 {
1227 length += l; /* count a multibyte char */
1228 p += l - 1;
1229 continue;
1230 }
1231#endif
1232 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1233 ++length; /* count a backslash */
1234 ++length; /* count an ordinary char */
1235 }
1236 escaped_string = alloc(length);
1237 if (escaped_string != NULL)
1238 {
1239 p2 = escaped_string;
1240 for (p = string; *p; p++)
1241 {
1242#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001243 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001244 {
1245 mch_memmove(p2, p, (size_t)l);
1246 p2 += l;
1247 p += l - 1; /* skip multibyte char */
1248 continue;
1249 }
1250#endif
1251 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00001252 *p2++ = cc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001253 *p2++ = *p;
1254 }
1255 *p2 = NUL;
1256 }
1257 return escaped_string;
1258}
1259
Bram Moolenaar7693ec62008-07-24 18:29:37 +00001260#if !defined(BACKSLASH_IN_FILENAME) || defined(FEAT_EVAL) || defined(PROTO)
1261/*
1262 * Return TRUE when 'shell' has "csh" in the tail.
1263 */
1264 int
1265csh_like_shell()
1266{
1267 return (strstr((char *)gettail(p_sh), "csh") != NULL);
1268}
1269#endif
1270
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001271#if defined(FEAT_EVAL) || defined(PROTO)
1272/*
1273 * Escape "string" for use as a shell argument with system().
1274 * This uses single quotes, except when we know we need to use double qoutes
1275 * (MS-DOS and MS-Windows without 'shellslash' set).
Bram Moolenaarffd66c42008-07-16 20:43:37 +00001276 * Escape a newline, depending on the 'shell' option.
1277 * When "do_special" is TRUE also replace "!", "%", "#" and things starting
1278 * with "<" like "<cfile>".
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001279 * Returns the result in allocated memory, NULL if we have run out.
1280 */
1281 char_u *
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001282vim_strsave_shellescape(string, do_special)
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001283 char_u *string;
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001284 int do_special;
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001285{
1286 unsigned length;
1287 char_u *p;
1288 char_u *d;
1289 char_u *escaped_string;
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001290 int l;
Bram Moolenaarffd66c42008-07-16 20:43:37 +00001291 int csh_like;
1292
1293 /* Only csh and similar shells expand '!' within single quotes. For sh and
1294 * the like we must not put a backslash before it, it will be taken
1295 * literally. If do_special is set the '!' will be escaped twice.
1296 * Csh also needs to have "\n" escaped twice when do_special is set. */
Bram Moolenaar7693ec62008-07-24 18:29:37 +00001297 csh_like = csh_like_shell();
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001298
1299 /* First count the number of extra bytes required. */
Bram Moolenaar77f66d62007-02-20 02:16:18 +00001300 length = (unsigned)STRLEN(string) + 3; /* two quotes and a trailing NUL */
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001301 for (p = string; *p != NUL; mb_ptr_adv(p))
1302 {
1303# if defined(WIN32) || defined(WIN16) || defined(DOS)
1304 if (!p_ssl)
1305 {
1306 if (*p == '"')
1307 ++length; /* " -> "" */
1308 }
1309 else
1310# endif
1311 if (*p == '\'')
1312 length += 3; /* ' => '\'' */
Bram Moolenaarffd66c42008-07-16 20:43:37 +00001313 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1314 {
1315 ++length; /* insert backslash */
1316 if (csh_like && do_special)
1317 ++length; /* insert backslash */
1318 }
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001319 if (do_special && find_cmdline_var(p, &l) >= 0)
1320 {
1321 ++length; /* insert backslash */
1322 p += l - 1;
1323 }
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001324 }
1325
1326 /* Allocate memory for the result and fill it. */
1327 escaped_string = alloc(length);
1328 if (escaped_string != NULL)
1329 {
1330 d = escaped_string;
1331
1332 /* add opening quote */
1333# if defined(WIN32) || defined(WIN16) || defined(DOS)
1334 if (!p_ssl)
1335 *d++ = '"';
1336 else
1337# endif
1338 *d++ = '\'';
1339
1340 for (p = string; *p != NUL; )
1341 {
1342# if defined(WIN32) || defined(WIN16) || defined(DOS)
1343 if (!p_ssl)
1344 {
1345 if (*p == '"')
1346 {
1347 *d++ = '"';
1348 *d++ = '"';
1349 ++p;
1350 continue;
1351 }
1352 }
1353 else
1354# endif
1355 if (*p == '\'')
1356 {
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001357 *d++ = '\'';
1358 *d++ = '\\';
1359 *d++ = '\'';
1360 *d++ = '\'';
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001361 ++p;
1362 continue;
1363 }
Bram Moolenaarffd66c42008-07-16 20:43:37 +00001364 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1365 {
1366 *d++ = '\\';
1367 if (csh_like && do_special)
1368 *d++ = '\\';
1369 *d++ = *p++;
1370 continue;
1371 }
Bram Moolenaar05bb9532008-07-04 09:44:11 +00001372 if (do_special && find_cmdline_var(p, &l) >= 0)
1373 {
1374 *d++ = '\\'; /* insert backslash */
1375 while (--l >= 0) /* copy the var */
1376 *d++ = *p++;
1377 }
Bram Moolenaar60a495f2006-10-03 12:44:42 +00001378
1379 MB_COPY_CHAR(p, d);
1380 }
1381
1382 /* add terminating quote and finish with a NUL */
1383# if defined(WIN32) || defined(WIN16) || defined(DOS)
1384 if (!p_ssl)
1385 *d++ = '"';
1386 else
1387# endif
1388 *d++ = '\'';
1389 *d = NUL;
1390 }
1391
1392 return escaped_string;
1393}
1394#endif
1395
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396/*
1397 * Like vim_strsave(), but make all characters uppercase.
1398 * This uses ASCII lower-to-upper case translation, language independent.
1399 */
1400 char_u *
1401vim_strsave_up(string)
1402 char_u *string;
1403{
1404 char_u *p1;
1405
1406 p1 = vim_strsave(string);
1407 vim_strup(p1);
1408 return p1;
1409}
1410
1411/*
1412 * Like vim_strnsave(), but make all characters uppercase.
1413 * This uses ASCII lower-to-upper case translation, language independent.
1414 */
1415 char_u *
1416vim_strnsave_up(string, len)
1417 char_u *string;
1418 int len;
1419{
1420 char_u *p1;
1421
1422 p1 = vim_strnsave(string, len);
1423 vim_strup(p1);
1424 return p1;
1425}
1426
1427/*
1428 * ASCII lower-to-upper case translation, language independent.
1429 */
1430 void
1431vim_strup(p)
1432 char_u *p;
1433{
1434 char_u *p2;
1435 int c;
1436
1437 if (p != NULL)
1438 {
1439 p2 = p;
1440 while ((c = *p2) != NUL)
1441#ifdef EBCDIC
1442 *p2++ = isalpha(c) ? toupper(c) : c;
1443#else
1444 *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20);
1445#endif
1446 }
1447}
1448
Bram Moolenaarc4956c82006-03-12 21:58:43 +00001449#if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001450/*
1451 * Make string "s" all upper-case and return it in allocated memory.
1452 * Handles multi-byte characters as well as possible.
1453 * Returns NULL when out of memory.
1454 */
1455 char_u *
1456strup_save(orig)
1457 char_u *orig;
1458{
1459 char_u *p;
1460 char_u *res;
1461
1462 res = p = vim_strsave(orig);
1463
1464 if (res != NULL)
1465 while (*p != NUL)
1466 {
1467# ifdef FEAT_MBYTE
1468 int l;
1469
1470 if (enc_utf8)
1471 {
1472 int c, uc;
1473 int nl;
1474 char_u *s;
1475
1476 c = utf_ptr2char(p);
1477 uc = utf_toupper(c);
1478
1479 /* Reallocate string when byte count changes. This is rare,
1480 * thus it's OK to do another malloc()/free(). */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001481 l = utf_ptr2len(p);
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001482 nl = utf_char2len(uc);
1483 if (nl != l)
1484 {
1485 s = alloc((unsigned)STRLEN(res) + 1 + nl - l);
1486 if (s == NULL)
1487 break;
1488 mch_memmove(s, res, p - res);
1489 STRCPY(s + (p - res) + nl, p + l);
1490 p = s + (p - res);
1491 vim_free(res);
1492 res = s;
1493 }
1494
1495 utf_char2bytes(uc, p);
1496 p += nl;
1497 }
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001498 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001499 p += l; /* skip multi-byte character */
1500 else
1501# endif
1502 {
1503 *p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */
1504 p++;
1505 }
1506 }
1507
1508 return res;
1509}
1510#endif
1511
Bram Moolenaar071d4272004-06-13 20:20:40 +00001512/*
1513 * copy a space a number of times
1514 */
1515 void
1516copy_spaces(ptr, count)
1517 char_u *ptr;
1518 size_t count;
1519{
1520 size_t i = count;
1521 char_u *p = ptr;
1522
1523 while (i--)
1524 *p++ = ' ';
1525}
1526
1527#if defined(FEAT_VISUALEXTRA) || defined(PROTO)
1528/*
1529 * Copy a character a number of times.
1530 * Does not work for multi-byte charactes!
1531 */
1532 void
1533copy_chars(ptr, count, c)
1534 char_u *ptr;
1535 size_t count;
1536 int c;
1537{
1538 size_t i = count;
1539 char_u *p = ptr;
1540
1541 while (i--)
1542 *p++ = c;
1543}
1544#endif
1545
1546/*
1547 * delete spaces at the end of a string
1548 */
1549 void
1550del_trailing_spaces(ptr)
1551 char_u *ptr;
1552{
1553 char_u *q;
1554
1555 q = ptr + STRLEN(ptr);
1556 while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1557 *q = NUL;
1558}
1559
1560/*
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001561 * Like strncpy(), but always terminate the result with one NUL.
Bram Moolenaard042c562005-06-30 22:04:15 +00001562 * "to" must be "len + 1" long!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 */
1564 void
1565vim_strncpy(to, from, len)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001566 char_u *to;
1567 char_u *from;
Bram Moolenaarbbebc852005-07-18 21:47:53 +00001568 size_t len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001569{
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001570 STRNCPY(to, from, len);
1571 to[len] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001572}
1573
1574/*
1575 * Isolate one part of a string option where parts are separated with
1576 * "sep_chars".
Bram Moolenaar83bab712005-08-01 21:58:57 +00001577 * The part is copied into "buf[maxlen]".
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 * "*option" is advanced to the next part.
1579 * The length is returned.
1580 */
1581 int
1582copy_option_part(option, buf, maxlen, sep_chars)
1583 char_u **option;
1584 char_u *buf;
1585 int maxlen;
1586 char *sep_chars;
1587{
1588 int len = 0;
1589 char_u *p = *option;
1590
1591 /* skip '.' at start of option part, for 'suffixes' */
1592 if (*p == '.')
1593 buf[len++] = *p++;
1594 while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1595 {
1596 /*
1597 * Skip backslash before a separator character and space.
1598 */
1599 if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1600 ++p;
1601 if (len < maxlen - 1)
1602 buf[len++] = *p;
1603 ++p;
1604 }
1605 buf[len] = NUL;
1606
1607 if (*p != NUL && *p != ',') /* skip non-standard separator */
1608 ++p;
1609 p = skip_to_option_part(p); /* p points to next file name */
1610
1611 *option = p;
1612 return len;
1613}
1614
1615/*
Bram Moolenaar4770d092006-01-12 23:22:24 +00001616 * Replacement for free() that ignores NULL pointers.
1617 * Also skip free() when exiting for sure, this helps when we caught a deadly
1618 * signal that was caused by a crash in free().
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619 */
1620 void
1621vim_free(x)
1622 void *x;
1623{
Bram Moolenaar4770d092006-01-12 23:22:24 +00001624 if (x != NULL && !really_exiting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 {
1626#ifdef MEM_PROFILE
1627 mem_pre_free(&x);
1628#endif
1629 free(x);
1630 }
1631}
1632
1633#ifndef HAVE_MEMSET
1634 void *
1635vim_memset(ptr, c, size)
1636 void *ptr;
1637 int c;
1638 size_t size;
1639{
1640 char *p = ptr;
1641
1642 while (size-- > 0)
1643 *p++ = c;
1644 return ptr;
1645}
1646#endif
1647
1648#ifdef VIM_MEMCMP
1649/*
1650 * Return zero when "b1" and "b2" are the same for "len" bytes.
1651 * Return non-zero otherwise.
1652 */
1653 int
1654vim_memcmp(b1, b2, len)
1655 void *b1;
1656 void *b2;
1657 size_t len;
1658{
1659 char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1660
1661 for ( ; len > 0; --len)
1662 {
1663 if (*p1 != *p2)
1664 return 1;
1665 ++p1;
1666 ++p2;
1667 }
1668 return 0;
1669}
1670#endif
1671
1672#ifdef VIM_MEMMOVE
1673/*
1674 * Version of memmove() that handles overlapping source and destination.
1675 * For systems that don't have a function that is guaranteed to do that (SYSV).
1676 */
1677 void
1678mch_memmove(dst_arg, src_arg, len)
1679 void *src_arg, *dst_arg;
1680 size_t len;
1681{
1682 /*
1683 * A void doesn't have a size, we use char pointers.
1684 */
1685 char *dst = dst_arg, *src = src_arg;
1686
1687 /* overlap, copy backwards */
1688 if (dst > src && dst < src + len)
1689 {
1690 src += len;
1691 dst += len;
1692 while (len-- > 0)
1693 *--dst = *--src;
1694 }
1695 else /* copy forwards */
1696 while (len-- > 0)
1697 *dst++ = *src++;
1698}
1699#endif
1700
1701#if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1702/*
1703 * Compare two strings, ignoring case, using current locale.
1704 * Doesn't work for multi-byte characters.
1705 * return 0 for match, < 0 for smaller, > 0 for bigger
1706 */
1707 int
1708vim_stricmp(s1, s2)
1709 char *s1;
1710 char *s2;
1711{
1712 int i;
1713
1714 for (;;)
1715 {
1716 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1717 if (i != 0)
1718 return i; /* this character different */
1719 if (*s1 == NUL)
1720 break; /* strings match until NUL */
1721 ++s1;
1722 ++s2;
1723 }
1724 return 0; /* strings match */
1725}
1726#endif
1727
1728#if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1729/*
1730 * Compare two strings, for length "len", ignoring case, using current locale.
1731 * Doesn't work for multi-byte characters.
1732 * return 0 for match, < 0 for smaller, > 0 for bigger
1733 */
1734 int
1735vim_strnicmp(s1, s2, len)
1736 char *s1;
1737 char *s2;
1738 size_t len;
1739{
1740 int i;
1741
1742 while (len > 0)
1743 {
1744 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1745 if (i != 0)
1746 return i; /* this character different */
1747 if (*s1 == NUL)
1748 break; /* strings match until NUL */
1749 ++s1;
1750 ++s2;
1751 --len;
1752 }
1753 return 0; /* strings match */
1754}
1755#endif
1756
1757#if 0 /* currently not used */
1758/*
1759 * Check if string "s2" appears somewhere in "s1" while ignoring case.
1760 * Return NULL if not, a pointer to the first occurrence if it does.
1761 */
1762 char_u *
1763vim_stristr(s1, s2)
1764 char_u *s1;
1765 char_u *s2;
1766{
1767 char_u *p;
1768 int len = STRLEN(s2);
1769 char_u *end = s1 + STRLEN(s1) - len;
1770
1771 for (p = s1; p <= end; ++p)
1772 if (STRNICMP(p, s2, len) == 0)
1773 return p;
1774 return NULL;
1775}
1776#endif
1777
1778/*
1779 * Version of strchr() and strrchr() that handle unsigned char strings
Bram Moolenaar05159a02005-02-26 23:04:13 +00001780 * with characters from 128 to 255 correctly. It also doesn't return a
1781 * pointer to the NUL at the end of the string.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 */
1783 char_u *
1784vim_strchr(string, c)
1785 char_u *string;
1786 int c;
1787{
1788 char_u *p;
1789 int b;
1790
1791 p = string;
1792#ifdef FEAT_MBYTE
1793 if (enc_utf8 && c >= 0x80)
1794 {
1795 while (*p != NUL)
1796 {
1797 if (utf_ptr2char(p) == c)
1798 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001799 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 }
1801 return NULL;
1802 }
1803 if (enc_dbcs != 0 && c > 255)
1804 {
1805 int n2 = c & 0xff;
1806
1807 c = ((unsigned)c >> 8) & 0xff;
1808 while ((b = *p) != NUL)
1809 {
1810 if (b == c && p[1] == n2)
1811 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001812 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 }
1814 return NULL;
1815 }
1816 if (has_mbyte)
1817 {
1818 while ((b = *p) != NUL)
1819 {
1820 if (b == c)
1821 return p;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001822 p += (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823 }
1824 return NULL;
1825 }
1826#endif
1827 while ((b = *p) != NUL)
1828 {
1829 if (b == c)
1830 return p;
1831 ++p;
1832 }
1833 return NULL;
1834}
1835
1836/*
Bram Moolenaar05159a02005-02-26 23:04:13 +00001837 * Version of strchr() that only works for bytes and handles unsigned char
1838 * strings with characters above 128 correctly. It also doesn't return a
1839 * pointer to the NUL at the end of the string.
1840 */
1841 char_u *
1842vim_strbyte(string, c)
1843 char_u *string;
1844 int c;
1845{
1846 char_u *p = string;
1847
1848 while (*p != NUL)
1849 {
1850 if (*p == c)
1851 return p;
1852 ++p;
1853 }
1854 return NULL;
1855}
1856
1857/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 * Search for last occurrence of "c" in "string".
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00001859 * Return NULL if not found.
Bram Moolenaar05159a02005-02-26 23:04:13 +00001860 * Does not handle multi-byte char for "c"!
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 */
1862 char_u *
1863vim_strrchr(string, c)
1864 char_u *string;
1865 int c;
1866{
1867 char_u *retval = NULL;
Bram Moolenaar05159a02005-02-26 23:04:13 +00001868 char_u *p = string;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001869
Bram Moolenaar05159a02005-02-26 23:04:13 +00001870 while (*p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871 {
Bram Moolenaar05159a02005-02-26 23:04:13 +00001872 if (*p == c)
1873 retval = p;
1874 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875 }
1876 return retval;
1877}
1878
1879/*
1880 * Vim's version of strpbrk(), in case it's missing.
1881 * Don't generate a prototype for this, causes problems when it's not used.
1882 */
1883#ifndef PROTO
1884# ifndef HAVE_STRPBRK
1885# ifdef vim_strpbrk
1886# undef vim_strpbrk
1887# endif
1888 char_u *
1889vim_strpbrk(s, charset)
1890 char_u *s;
1891 char_u *charset;
1892{
1893 while (*s)
1894 {
1895 if (vim_strchr(charset, *s) != NULL)
1896 return s;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001897 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001898 }
1899 return NULL;
1900}
1901# endif
1902#endif
1903
1904/*
1905 * Vim has its own isspace() function, because on some machines isspace()
1906 * can't handle characters above 128.
1907 */
1908 int
1909vim_isspace(x)
1910 int x;
1911{
1912 return ((x >= 9 && x <= 13) || x == ' ');
1913}
1914
1915/************************************************************************
Bram Moolenaar383f9bc2005-01-19 22:18:32 +00001916 * Functions for handling growing arrays.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001917 */
1918
1919/*
1920 * Clear an allocated growing array.
1921 */
1922 void
1923ga_clear(gap)
1924 garray_T *gap;
1925{
1926 vim_free(gap->ga_data);
1927 ga_init(gap);
1928}
1929
1930/*
1931 * Clear a growing array that contains a list of strings.
1932 */
1933 void
1934ga_clear_strings(gap)
1935 garray_T *gap;
1936{
1937 int i;
1938
1939 for (i = 0; i < gap->ga_len; ++i)
1940 vim_free(((char_u **)(gap->ga_data))[i]);
1941 ga_clear(gap);
1942}
1943
1944/*
1945 * Initialize a growing array. Don't forget to set ga_itemsize and
1946 * ga_growsize! Or use ga_init2().
1947 */
1948 void
1949ga_init(gap)
1950 garray_T *gap;
1951{
1952 gap->ga_data = NULL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00001953 gap->ga_maxlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 gap->ga_len = 0;
1955}
1956
1957 void
1958ga_init2(gap, itemsize, growsize)
1959 garray_T *gap;
1960 int itemsize;
1961 int growsize;
1962{
1963 ga_init(gap);
1964 gap->ga_itemsize = itemsize;
1965 gap->ga_growsize = growsize;
1966}
1967
1968/*
1969 * Make room in growing array "gap" for at least "n" items.
1970 * Return FAIL for failure, OK otherwise.
1971 */
1972 int
1973ga_grow(gap, n)
1974 garray_T *gap;
1975 int n;
1976{
1977 size_t len;
1978 char_u *pp;
1979
Bram Moolenaar86b68352004-12-27 21:59:20 +00001980 if (gap->ga_maxlen - gap->ga_len < n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 {
1982 if (n < gap->ga_growsize)
1983 n = gap->ga_growsize;
1984 len = gap->ga_itemsize * (gap->ga_len + n);
1985 pp = alloc_clear((unsigned)len);
1986 if (pp == NULL)
1987 return FAIL;
Bram Moolenaar86b68352004-12-27 21:59:20 +00001988 gap->ga_maxlen = gap->ga_len + n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 if (gap->ga_data != NULL)
1990 {
1991 mch_memmove(pp, gap->ga_data,
1992 (size_t)(gap->ga_itemsize * gap->ga_len));
1993 vim_free(gap->ga_data);
1994 }
1995 gap->ga_data = pp;
1996 }
1997 return OK;
1998}
1999
2000/*
2001 * Concatenate a string to a growarray which contains characters.
2002 * Note: Does NOT copy the NUL at the end!
2003 */
2004 void
2005ga_concat(gap, s)
2006 garray_T *gap;
2007 char_u *s;
2008{
2009 int len = (int)STRLEN(s);
2010
2011 if (ga_grow(gap, len) == OK)
2012 {
2013 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
2014 gap->ga_len += len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015 }
2016}
2017
2018/*
2019 * Append one byte to a growarray which contains bytes.
2020 */
2021 void
2022ga_append(gap, c)
2023 garray_T *gap;
2024 int c;
2025{
2026 if (ga_grow(gap, 1) == OK)
2027 {
2028 *((char *)gap->ga_data + gap->ga_len) = c;
2029 ++gap->ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 }
2031}
2032
2033/************************************************************************
2034 * functions that use lookup tables for various things, generally to do with
2035 * special key codes.
2036 */
2037
2038/*
2039 * Some useful tables.
2040 */
2041
2042static struct modmasktable
2043{
2044 short mod_mask; /* Bit-mask for particular key modifier */
2045 short mod_flag; /* Bit(s) for particular key modifier */
2046 char_u name; /* Single letter name of modifier */
2047} mod_mask_table[] =
2048{
2049 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'},
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002050 {MOD_MASK_META, MOD_MASK_META, (char_u)'T'},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002051 {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'},
2052 {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'},
2053 {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'},
2054 {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'},
2055 {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'},
2056#ifdef MACOS
2057 {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'},
2058#endif
2059 /* 'A' must be the last one */
2060 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'},
2061 {0, 0, NUL}
2062};
2063
2064/*
2065 * Shifted key terminal codes and their unshifted equivalent.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00002066 * Don't add mouse codes here, they are handled separately!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 */
2068#define MOD_KEYS_ENTRY_SIZE 5
2069
2070static char_u modifier_keys_table[] =
2071{
2072/* mod mask with modifier without modifier */
2073 MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */
2074 MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */
2075 MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */
2076 MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */
2077 MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */
2078 MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */
2079 MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */
2080 MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */
2081 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */
2082 MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */
2083 MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */
2084 MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */
2085 MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */
2086 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */
2087 MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */
2088 MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */
2089 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */
2090 MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */
2091 MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */
2092 MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */
2093 MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */
2094 MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */
2095 MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */
2096 MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */
2097 MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */
2098 MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */
2099 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */
2100 MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */
2101 MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */
2102 MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */
2103 MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */
2104 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */
2105 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */
2106
2107 /* vt100 F1 */
2108 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1,
2109 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2,
2110 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3,
2111 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4,
2112
2113 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */
2114 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2',
2115 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3',
2116 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4',
2117 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5',
2118 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6',
2119 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7',
2120 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8',
2121 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9',
2122 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */
2123
2124 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1',
2125 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2',
2126 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3',
2127 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4',
2128 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5',
2129 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6',
2130 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7',
2131 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8',
2132 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9',
2133 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A',
2134
2135 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B',
2136 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C',
2137 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D',
2138 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E',
2139 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F',
2140 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G',
2141 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H',
2142 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I',
2143 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J',
2144 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K',
2145
2146 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L',
2147 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M',
2148 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N',
2149 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O',
2150 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P',
2151 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q',
2152 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R',
2153
2154 /* TAB pseudo code*/
2155 MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB,
2156
2157 NUL
2158};
2159
2160static struct key_name_entry
2161{
2162 int key; /* Special key code or ascii value */
2163 char_u *name; /* Name of key */
2164} key_names_table[] =
2165{
2166 {' ', (char_u *)"Space"},
2167 {TAB, (char_u *)"Tab"},
2168 {K_TAB, (char_u *)"Tab"},
2169 {NL, (char_u *)"NL"},
2170 {NL, (char_u *)"NewLine"}, /* Alternative name */
2171 {NL, (char_u *)"LineFeed"}, /* Alternative name */
2172 {NL, (char_u *)"LF"}, /* Alternative name */
2173 {CAR, (char_u *)"CR"},
2174 {CAR, (char_u *)"Return"}, /* Alternative name */
2175 {CAR, (char_u *)"Enter"}, /* Alternative name */
2176 {K_BS, (char_u *)"BS"},
2177 {K_BS, (char_u *)"BackSpace"}, /* Alternative name */
2178 {ESC, (char_u *)"Esc"},
2179 {CSI, (char_u *)"CSI"},
2180 {K_CSI, (char_u *)"xCSI"},
2181 {'|', (char_u *)"Bar"},
2182 {'\\', (char_u *)"Bslash"},
2183 {K_DEL, (char_u *)"Del"},
2184 {K_DEL, (char_u *)"Delete"}, /* Alternative name */
2185 {K_KDEL, (char_u *)"kDel"},
2186 {K_UP, (char_u *)"Up"},
2187 {K_DOWN, (char_u *)"Down"},
2188 {K_LEFT, (char_u *)"Left"},
2189 {K_RIGHT, (char_u *)"Right"},
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002190 {K_XUP, (char_u *)"xUp"},
2191 {K_XDOWN, (char_u *)"xDown"},
2192 {K_XLEFT, (char_u *)"xLeft"},
2193 {K_XRIGHT, (char_u *)"xRight"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194
2195 {K_F1, (char_u *)"F1"},
2196 {K_F2, (char_u *)"F2"},
2197 {K_F3, (char_u *)"F3"},
2198 {K_F4, (char_u *)"F4"},
2199 {K_F5, (char_u *)"F5"},
2200 {K_F6, (char_u *)"F6"},
2201 {K_F7, (char_u *)"F7"},
2202 {K_F8, (char_u *)"F8"},
2203 {K_F9, (char_u *)"F9"},
2204 {K_F10, (char_u *)"F10"},
2205
2206 {K_F11, (char_u *)"F11"},
2207 {K_F12, (char_u *)"F12"},
2208 {K_F13, (char_u *)"F13"},
2209 {K_F14, (char_u *)"F14"},
2210 {K_F15, (char_u *)"F15"},
2211 {K_F16, (char_u *)"F16"},
2212 {K_F17, (char_u *)"F17"},
2213 {K_F18, (char_u *)"F18"},
2214 {K_F19, (char_u *)"F19"},
2215 {K_F20, (char_u *)"F20"},
2216
2217 {K_F21, (char_u *)"F21"},
2218 {K_F22, (char_u *)"F22"},
2219 {K_F23, (char_u *)"F23"},
2220 {K_F24, (char_u *)"F24"},
2221 {K_F25, (char_u *)"F25"},
2222 {K_F26, (char_u *)"F26"},
2223 {K_F27, (char_u *)"F27"},
2224 {K_F28, (char_u *)"F28"},
2225 {K_F29, (char_u *)"F29"},
2226 {K_F30, (char_u *)"F30"},
2227
2228 {K_F31, (char_u *)"F31"},
2229 {K_F32, (char_u *)"F32"},
2230 {K_F33, (char_u *)"F33"},
2231 {K_F34, (char_u *)"F34"},
2232 {K_F35, (char_u *)"F35"},
2233 {K_F36, (char_u *)"F36"},
2234 {K_F37, (char_u *)"F37"},
2235
2236 {K_XF1, (char_u *)"xF1"},
2237 {K_XF2, (char_u *)"xF2"},
2238 {K_XF3, (char_u *)"xF3"},
2239 {K_XF4, (char_u *)"xF4"},
2240
2241 {K_HELP, (char_u *)"Help"},
2242 {K_UNDO, (char_u *)"Undo"},
2243 {K_INS, (char_u *)"Insert"},
2244 {K_INS, (char_u *)"Ins"}, /* Alternative name */
2245 {K_KINS, (char_u *)"kInsert"},
2246 {K_HOME, (char_u *)"Home"},
2247 {K_KHOME, (char_u *)"kHome"},
2248 {K_XHOME, (char_u *)"xHome"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002249 {K_ZHOME, (char_u *)"zHome"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250 {K_END, (char_u *)"End"},
2251 {K_KEND, (char_u *)"kEnd"},
2252 {K_XEND, (char_u *)"xEnd"},
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002253 {K_ZEND, (char_u *)"zEnd"},
Bram Moolenaar071d4272004-06-13 20:20:40 +00002254 {K_PAGEUP, (char_u *)"PageUp"},
2255 {K_PAGEDOWN, (char_u *)"PageDown"},
2256 {K_KPAGEUP, (char_u *)"kPageUp"},
2257 {K_KPAGEDOWN, (char_u *)"kPageDown"},
2258
2259 {K_KPLUS, (char_u *)"kPlus"},
2260 {K_KMINUS, (char_u *)"kMinus"},
2261 {K_KDIVIDE, (char_u *)"kDivide"},
2262 {K_KMULTIPLY, (char_u *)"kMultiply"},
2263 {K_KENTER, (char_u *)"kEnter"},
2264 {K_KPOINT, (char_u *)"kPoint"},
2265
2266 {K_K0, (char_u *)"k0"},
2267 {K_K1, (char_u *)"k1"},
2268 {K_K2, (char_u *)"k2"},
2269 {K_K3, (char_u *)"k3"},
2270 {K_K4, (char_u *)"k4"},
2271 {K_K5, (char_u *)"k5"},
2272 {K_K6, (char_u *)"k6"},
2273 {K_K7, (char_u *)"k7"},
2274 {K_K8, (char_u *)"k8"},
2275 {K_K9, (char_u *)"k9"},
2276
2277 {'<', (char_u *)"lt"},
2278
2279 {K_MOUSE, (char_u *)"Mouse"},
2280 {K_NETTERM_MOUSE, (char_u *)"NetMouse"},
2281 {K_DEC_MOUSE, (char_u *)"DecMouse"},
2282 {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"},
2283 {K_PTERM_MOUSE, (char_u *)"PtermMouse"},
2284 {K_LEFTMOUSE, (char_u *)"LeftMouse"},
2285 {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"},
2286 {K_LEFTDRAG, (char_u *)"LeftDrag"},
2287 {K_LEFTRELEASE, (char_u *)"LeftRelease"},
2288 {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"},
2289 {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"},
2290 {K_MIDDLEDRAG, (char_u *)"MiddleDrag"},
2291 {K_MIDDLERELEASE, (char_u *)"MiddleRelease"},
2292 {K_RIGHTMOUSE, (char_u *)"RightMouse"},
2293 {K_RIGHTDRAG, (char_u *)"RightDrag"},
2294 {K_RIGHTRELEASE, (char_u *)"RightRelease"},
2295 {K_MOUSEDOWN, (char_u *)"MouseDown"},
2296 {K_MOUSEUP, (char_u *)"MouseUp"},
2297 {K_X1MOUSE, (char_u *)"X1Mouse"},
2298 {K_X1DRAG, (char_u *)"X1Drag"},
2299 {K_X1RELEASE, (char_u *)"X1Release"},
2300 {K_X2MOUSE, (char_u *)"X2Mouse"},
2301 {K_X2DRAG, (char_u *)"X2Drag"},
2302 {K_X2RELEASE, (char_u *)"X2Release"},
2303 {K_DROP, (char_u *)"Drop"},
2304 {K_ZERO, (char_u *)"Nul"},
2305#ifdef FEAT_EVAL
2306 {K_SNR, (char_u *)"SNR"},
2307#endif
2308 {K_PLUG, (char_u *)"Plug"},
2309 {0, NULL}
2310};
2311
2312#define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
2313
2314#ifdef FEAT_MOUSE
2315static struct mousetable
2316{
2317 int pseudo_code; /* Code for pseudo mouse event */
2318 int button; /* Which mouse button is it? */
2319 int is_click; /* Is it a mouse button click event? */
2320 int is_drag; /* Is it a mouse drag event? */
2321} mouse_table[] =
2322{
2323 {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE},
2324#ifdef FEAT_GUI
2325 {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE},
2326#endif
2327 {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE},
2328 {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE},
2329#ifdef FEAT_GUI
2330 {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE},
2331#endif
2332 {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE},
2333 {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE},
2334 {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE},
2335 {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE},
2336 {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE},
2337 {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE},
2338 {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE},
2339 {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE},
2340 {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE},
2341 {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE},
2342 {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE},
2343 {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE},
2344 /* DRAG without CLICK */
2345 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE},
2346 /* RELEASE without CLICK */
2347 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE},
2348 {0, 0, 0, 0},
2349};
2350#endif /* FEAT_MOUSE */
2351
2352/*
2353 * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
2354 * modifier name ('S' for Shift, 'C' for Ctrl etc).
2355 */
2356 int
2357name_to_mod_mask(c)
2358 int c;
2359{
2360 int i;
2361
2362 c = TOUPPER_ASC(c);
2363 for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
2364 if (c == mod_mask_table[i].name)
2365 return mod_mask_table[i].mod_flag;
2366 return 0;
2367}
2368
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369/*
2370 * Check if if there is a special key code for "key" that includes the
2371 * modifiers specified.
2372 */
2373 int
2374simplify_key(key, modifiers)
2375 int key;
2376 int *modifiers;
2377{
2378 int i;
2379 int key0;
2380 int key1;
2381
2382 if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2383 {
2384 /* TAB is a special case */
2385 if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2386 {
2387 *modifiers &= ~MOD_MASK_SHIFT;
2388 return K_S_TAB;
2389 }
2390 key0 = KEY2TERMCAP0(key);
2391 key1 = KEY2TERMCAP1(key);
2392 for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2393 if (key0 == modifier_keys_table[i + 3]
2394 && key1 == modifier_keys_table[i + 4]
2395 && (*modifiers & modifier_keys_table[i]))
2396 {
2397 *modifiers &= ~modifier_keys_table[i];
2398 return TERMCAP2KEY(modifier_keys_table[i + 1],
2399 modifier_keys_table[i + 2]);
2400 }
2401 }
2402 return key;
2403}
2404
2405/*
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002406 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002407 */
2408 int
2409handle_x_keys(key)
2410 int key;
2411{
2412 switch (key)
2413 {
2414 case K_XUP: return K_UP;
2415 case K_XDOWN: return K_DOWN;
2416 case K_XLEFT: return K_LEFT;
2417 case K_XRIGHT: return K_RIGHT;
2418 case K_XHOME: return K_HOME;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002419 case K_ZHOME: return K_HOME;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002420 case K_XEND: return K_END;
Bram Moolenaar68b76a62005-03-25 21:53:48 +00002421 case K_ZEND: return K_END;
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002422 case K_XF1: return K_F1;
2423 case K_XF2: return K_F2;
2424 case K_XF3: return K_F3;
2425 case K_XF4: return K_F4;
2426 case K_S_XF1: return K_S_F1;
2427 case K_S_XF2: return K_S_F2;
2428 case K_S_XF3: return K_S_F3;
2429 case K_S_XF4: return K_S_F4;
2430 }
2431 return key;
2432}
2433
2434/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 * Return a string which contains the name of the given key when the given
2436 * modifiers are down.
2437 */
2438 char_u *
2439get_special_key_name(c, modifiers)
2440 int c;
2441 int modifiers;
2442{
2443 static char_u string[MAX_KEY_NAME_LEN + 1];
2444
2445 int i, idx;
2446 int table_idx;
2447 char_u *s;
2448
2449 string[0] = '<';
2450 idx = 1;
2451
2452 /* Key that stands for a normal character. */
2453 if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2454 c = KEY2TERMCAP1(c);
2455
2456 /*
2457 * Translate shifted special keys into unshifted keys and set modifier.
2458 * Same for CTRL and ALT modifiers.
2459 */
2460 if (IS_SPECIAL(c))
2461 {
2462 for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2463 if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2464 && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2465 {
2466 modifiers |= modifier_keys_table[i];
2467 c = TERMCAP2KEY(modifier_keys_table[i + 3],
2468 modifier_keys_table[i + 4]);
2469 break;
2470 }
2471 }
2472
2473 /* try to find the key in the special key table */
2474 table_idx = find_special_key_in_table(c);
2475
2476 /*
2477 * When not a known special key, and not a printable character, try to
2478 * extract modifiers.
2479 */
2480 if (c > 0
2481#ifdef FEAT_MBYTE
2482 && (*mb_char2len)(c) == 1
2483#endif
2484 )
2485 {
2486 if (table_idx < 0
2487 && (!vim_isprintc(c) || (c & 0x7f) == ' ')
2488 && (c & 0x80))
2489 {
2490 c &= 0x7f;
2491 modifiers |= MOD_MASK_ALT;
2492 /* try again, to find the un-alted key in the special key table */
2493 table_idx = find_special_key_in_table(c);
2494 }
2495 if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2496 {
2497#ifdef EBCDIC
2498 c = CtrlChar(c);
2499#else
2500 c += '@';
2501#endif
2502 modifiers |= MOD_MASK_CTRL;
2503 }
2504 }
2505
2506 /* translate the modifier into a string */
2507 for (i = 0; mod_mask_table[i].name != 'A'; i++)
2508 if ((modifiers & mod_mask_table[i].mod_mask)
2509 == mod_mask_table[i].mod_flag)
2510 {
2511 string[idx++] = mod_mask_table[i].name;
2512 string[idx++] = (char_u)'-';
2513 }
2514
2515 if (table_idx < 0) /* unknown special key, may output t_xx */
2516 {
2517 if (IS_SPECIAL(c))
2518 {
2519 string[idx++] = 't';
2520 string[idx++] = '_';
2521 string[idx++] = KEY2TERMCAP0(c);
2522 string[idx++] = KEY2TERMCAP1(c);
2523 }
2524 /* Not a special key, only modifiers, output directly */
2525 else
2526 {
2527#ifdef FEAT_MBYTE
2528 if (has_mbyte && (*mb_char2len)(c) > 1)
2529 idx += (*mb_char2bytes)(c, string + idx);
2530 else
2531#endif
2532 if (vim_isprintc(c))
2533 string[idx++] = c;
2534 else
2535 {
2536 s = transchar(c);
2537 while (*s)
2538 string[idx++] = *s++;
2539 }
2540 }
2541 }
2542 else /* use name of special key */
2543 {
2544 STRCPY(string + idx, key_names_table[table_idx].name);
2545 idx = (int)STRLEN(string);
2546 }
2547 string[idx++] = '>';
2548 string[idx] = NUL;
2549 return string;
2550}
2551
2552/*
2553 * Try translating a <> name at (*srcp)[] to dst[].
2554 * Return the number of characters added to dst[], zero for no match.
2555 * If there is a match, srcp is advanced to after the <> name.
2556 * dst[] must be big enough to hold the result (up to six characters)!
2557 */
2558 int
2559trans_special(srcp, dst, keycode)
2560 char_u **srcp;
2561 char_u *dst;
2562 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2563{
2564 int modifiers = 0;
2565 int key;
2566 int dlen = 0;
2567
2568 key = find_special_key(srcp, &modifiers, keycode);
2569 if (key == 0)
2570 return 0;
2571
2572 /* Put the appropriate modifier in a string */
2573 if (modifiers != 0)
2574 {
2575 dst[dlen++] = K_SPECIAL;
2576 dst[dlen++] = KS_MODIFIER;
2577 dst[dlen++] = modifiers;
2578 }
2579
2580 if (IS_SPECIAL(key))
2581 {
2582 dst[dlen++] = K_SPECIAL;
2583 dst[dlen++] = KEY2TERMCAP0(key);
2584 dst[dlen++] = KEY2TERMCAP1(key);
2585 }
2586#ifdef FEAT_MBYTE
2587 else if (has_mbyte && !keycode)
2588 dlen += (*mb_char2bytes)(key, dst + dlen);
2589#endif
2590 else if (keycode)
2591 dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2592 else
2593 dst[dlen++] = key;
2594
2595 return dlen;
2596}
2597
2598/*
2599 * Try translating a <> name at (*srcp)[], return the key and modifiers.
2600 * srcp is advanced to after the <> name.
2601 * returns 0 if there is no match.
2602 */
2603 int
2604find_special_key(srcp, modp, keycode)
2605 char_u **srcp;
2606 int *modp;
2607 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2608{
2609 char_u *last_dash;
2610 char_u *end_of_name;
2611 char_u *src;
2612 char_u *bp;
2613 int modifiers;
2614 int bit;
2615 int key;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002616 unsigned long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002617
2618 src = *srcp;
2619 if (src[0] != '<')
2620 return 0;
2621
2622 /* Find end of modifier list */
2623 last_dash = src;
2624 for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2625 {
2626 if (*bp == '-')
2627 {
2628 last_dash = bp;
2629 if (bp[1] != NUL && bp[2] == '>')
2630 ++bp; /* anything accepted, like <C-?> */
2631 }
2632 if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2633 bp += 3; /* skip t_xx, xx may be '-' or '>' */
2634 }
2635
2636 if (*bp == '>') /* found matching '>' */
2637 {
2638 end_of_name = bp + 1;
2639
2640 if (STRNICMP(src + 1, "char-", 5) == 0 && VIM_ISDIGIT(src[6]))
2641 {
2642 /* <Char-123> or <Char-033> or <Char-0x33> */
2643 vim_str2nr(src + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2644 *modp = 0;
2645 *srcp = end_of_name;
2646 return (int)n;
2647 }
2648
2649 /* Which modifiers are given? */
2650 modifiers = 0x0;
2651 for (bp = src + 1; bp < last_dash; bp++)
2652 {
2653 if (*bp != '-')
2654 {
2655 bit = name_to_mod_mask(*bp);
2656 if (bit == 0x0)
2657 break; /* Illegal modifier name */
2658 modifiers |= bit;
2659 }
2660 }
2661
2662 /*
2663 * Legal modifier name.
2664 */
2665 if (bp >= last_dash)
2666 {
2667 /*
2668 * Modifier with single letter, or special key name.
2669 */
2670 if (modifiers != 0 && last_dash[2] == '>')
2671 key = last_dash[1];
2672 else
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002673 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002674 key = get_special_key_code(last_dash + 1);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002675 key = handle_x_keys(key);
2676 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002677
2678 /*
2679 * get_special_key_code() may return NUL for invalid
2680 * special key name.
2681 */
2682 if (key != NUL)
2683 {
2684 /*
2685 * Only use a modifier when there is no special key code that
2686 * includes the modifier.
2687 */
2688 key = simplify_key(key, &modifiers);
2689
2690 if (!keycode)
2691 {
2692 /* don't want keycode, use single byte code */
2693 if (key == K_BS)
2694 key = BS;
2695 else if (key == K_DEL || key == K_KDEL)
2696 key = DEL;
2697 }
2698
2699 /*
2700 * Normal Key with modifier: Try to make a single byte code.
2701 */
2702 if (!IS_SPECIAL(key))
2703 key = extract_modifiers(key, &modifiers);
2704
2705 *modp = modifiers;
2706 *srcp = end_of_name;
2707 return key;
2708 }
2709 }
2710 }
2711 return 0;
2712}
2713
2714/*
2715 * Try to include modifiers in the key.
2716 * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2717 */
2718 int
2719extract_modifiers(key, modp)
2720 int key;
2721 int *modp;
2722{
2723 int modifiers = *modp;
2724
2725#ifdef MACOS
2726 /* Command-key really special, No fancynest */
2727 if (!(modifiers & MOD_MASK_CMD))
2728#endif
2729 if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2730 {
2731 key = TOUPPER_ASC(key);
2732 modifiers &= ~MOD_MASK_SHIFT;
2733 }
2734 if ((modifiers & MOD_MASK_CTRL)
2735#ifdef EBCDIC
2736 /* * TODO: EBCDIC Better use:
2737 * && (Ctrl_chr(key) || key == '?')
2738 * ??? */
2739 && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2740 != NULL
2741#else
2742 && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2743#endif
2744 )
2745 {
2746 key = Ctrl_chr(key);
2747 modifiers &= ~MOD_MASK_CTRL;
2748 /* <C-@> is <Nul> */
2749 if (key == 0)
2750 key = K_ZERO;
2751 }
2752#ifdef MACOS
2753 /* Command-key really special, No fancynest */
2754 if (!(modifiers & MOD_MASK_CMD))
2755#endif
2756 if ((modifiers & MOD_MASK_ALT) && key < 0x80
2757#ifdef FEAT_MBYTE
2758 && !enc_dbcs /* avoid creating a lead byte */
2759#endif
2760 )
2761 {
2762 key |= 0x80;
2763 modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */
2764 }
2765
2766 *modp = modifiers;
2767 return key;
2768}
2769
2770/*
2771 * Try to find key "c" in the special key table.
2772 * Return the index when found, -1 when not found.
2773 */
2774 int
2775find_special_key_in_table(c)
2776 int c;
2777{
2778 int i;
2779
2780 for (i = 0; key_names_table[i].name != NULL; i++)
2781 if (c == key_names_table[i].key)
2782 break;
2783 if (key_names_table[i].name == NULL)
2784 i = -1;
2785 return i;
2786}
2787
2788/*
2789 * Find the special key with the given name (the given string does not have to
2790 * end with NUL, the name is assumed to end before the first non-idchar).
2791 * If the name starts with "t_" the next two characters are interpreted as a
2792 * termcap name.
2793 * Return the key code, or 0 if not found.
2794 */
2795 int
2796get_special_key_code(name)
2797 char_u *name;
2798{
2799 char_u *table_name;
2800 char_u string[3];
2801 int i, j;
2802
2803 /*
2804 * If it's <t_xx> we get the code for xx from the termcap
2805 */
2806 if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2807 {
2808 string[0] = name[2];
2809 string[1] = name[3];
2810 string[2] = NUL;
2811 if (add_termcap_entry(string, FALSE) == OK)
2812 return TERMCAP2KEY(name[2], name[3]);
2813 }
2814 else
2815 for (i = 0; key_names_table[i].name != NULL; i++)
2816 {
2817 table_name = key_names_table[i].name;
2818 for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
2819 if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
2820 break;
2821 if (!vim_isIDc(name[j]) && table_name[j] == NUL)
2822 return key_names_table[i].key;
2823 }
2824 return 0;
2825}
2826
Bram Moolenaar05bb9532008-07-04 09:44:11 +00002827#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828 char_u *
2829get_key_name(i)
2830 int i;
2831{
2832 if (i >= KEY_NAMES_TABLE_LEN)
2833 return NULL;
2834 return key_names_table[i].name;
2835}
2836#endif
2837
Bram Moolenaar05bb9532008-07-04 09:44:11 +00002838#if defined(FEAT_MOUSE) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002839/*
2840 * Look up the given mouse code to return the relevant information in the other
2841 * arguments. Return which button is down or was released.
2842 */
2843 int
2844get_mouse_button(code, is_click, is_drag)
2845 int code;
2846 int *is_click;
2847 int *is_drag;
2848{
2849 int i;
2850
2851 for (i = 0; mouse_table[i].pseudo_code; i++)
2852 if (code == mouse_table[i].pseudo_code)
2853 {
2854 *is_click = mouse_table[i].is_click;
2855 *is_drag = mouse_table[i].is_drag;
2856 return mouse_table[i].button;
2857 }
2858 return 0; /* Shouldn't get here */
2859}
2860
2861/*
2862 * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
2863 * the given information about which mouse button is down, and whether the
2864 * mouse was clicked, dragged or released.
2865 */
2866 int
2867get_pseudo_mouse_code(button, is_click, is_drag)
2868 int button; /* eg MOUSE_LEFT */
2869 int is_click;
2870 int is_drag;
2871{
2872 int i;
2873
2874 for (i = 0; mouse_table[i].pseudo_code; i++)
2875 if (button == mouse_table[i].button
2876 && is_click == mouse_table[i].is_click
2877 && is_drag == mouse_table[i].is_drag)
2878 {
2879#ifdef FEAT_GUI
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002880 /* Trick: a non mappable left click and release has mouse_col -1
2881 * or added MOUSE_COLOFF. Used for 'mousefocus' in
2882 * gui_mouse_moved() */
2883 if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884 {
Bram Moolenaarc91506a2005-04-24 22:04:21 +00002885 if (mouse_col < 0)
2886 mouse_col = 0;
2887 else
2888 mouse_col -= MOUSE_COLOFF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
2890 return (int)KE_LEFTMOUSE_NM;
2891 if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
2892 return (int)KE_LEFTRELEASE_NM;
2893 }
2894#endif
2895 return mouse_table[i].pseudo_code;
2896 }
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00002897 return (int)KE_IGNORE; /* not recognized, ignore it */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898}
2899#endif /* FEAT_MOUSE */
2900
2901/*
2902 * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
2903 */
2904 int
2905get_fileformat(buf)
2906 buf_T *buf;
2907{
2908 int c = *buf->b_p_ff;
2909
2910 if (buf->b_p_bin || c == 'u')
2911 return EOL_UNIX;
2912 if (c == 'm')
2913 return EOL_MAC;
2914 return EOL_DOS;
2915}
2916
2917/*
2918 * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
2919 * argument.
2920 */
2921 int
2922get_fileformat_force(buf, eap)
2923 buf_T *buf;
2924 exarg_T *eap; /* can be NULL! */
2925{
2926 int c;
2927
2928 if (eap != NULL && eap->force_ff != 0)
2929 c = eap->cmd[eap->force_ff];
2930 else
2931 {
2932 if ((eap != NULL && eap->force_bin != 0)
2933 ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
2934 return EOL_UNIX;
2935 c = *buf->b_p_ff;
2936 }
2937 if (c == 'u')
2938 return EOL_UNIX;
2939 if (c == 'm')
2940 return EOL_MAC;
2941 return EOL_DOS;
2942}
2943
2944/*
2945 * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
2946 * Sets both 'textmode' and 'fileformat'.
2947 * Note: Does _not_ set global value of 'textmode'!
2948 */
2949 void
2950set_fileformat(t, opt_flags)
2951 int t;
2952 int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */
2953{
2954 char *p = NULL;
2955
2956 switch (t)
2957 {
2958 case EOL_DOS:
2959 p = FF_DOS;
2960 curbuf->b_p_tx = TRUE;
2961 break;
2962 case EOL_UNIX:
2963 p = FF_UNIX;
2964 curbuf->b_p_tx = FALSE;
2965 break;
2966 case EOL_MAC:
2967 p = FF_MAC;
2968 curbuf->b_p_tx = FALSE;
2969 break;
2970 }
2971 if (p != NULL)
2972 set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002973 OPT_FREE | opt_flags, 0);
2974
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975#ifdef FEAT_WINDOWS
Bram Moolenaarf740b292006-02-16 22:11:02 +00002976 /* This may cause the buffer to become (un)modified. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 check_status(curbuf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002978 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979#endif
2980#ifdef FEAT_TITLE
2981 need_maketitle = TRUE; /* set window title later */
2982#endif
2983}
2984
2985/*
2986 * Return the default fileformat from 'fileformats'.
2987 */
2988 int
2989default_fileformat()
2990{
2991 switch (*p_ffs)
2992 {
2993 case 'm': return EOL_MAC;
2994 case 'd': return EOL_DOS;
2995 }
2996 return EOL_UNIX;
2997}
2998
2999/*
3000 * Call shell. Calls mch_call_shell, with 'shellxquote' added.
3001 */
3002 int
3003call_shell(cmd, opt)
3004 char_u *cmd;
3005 int opt;
3006{
3007 char_u *ncmd;
3008 int retval;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003009#ifdef FEAT_PROFILE
3010 proftime_T wait_time;
3011#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012
3013 if (p_verbose > 3)
3014 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00003015 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00003016 smsg((char_u *)_("Calling shell to execute: \"%s\""),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003017 cmd == NULL ? p_sh : cmd);
3018 out_char('\n');
3019 cursor_on();
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00003020 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021 }
3022
Bram Moolenaar05159a02005-02-26 23:04:13 +00003023#ifdef FEAT_PROFILE
Bram Moolenaar01265852006-03-20 21:50:15 +00003024 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003025 prof_child_enter(&wait_time);
3026#endif
3027
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028 if (*p_sh == NUL)
3029 {
3030 EMSG(_(e_shellempty));
3031 retval = -1;
3032 }
3033 else
3034 {
3035#ifdef FEAT_GUI_MSWIN
3036 /* Don't hide the pointer while executing a shell command. */
3037 gui_mch_mousehide(FALSE);
3038#endif
3039#ifdef FEAT_GUI
3040 ++hold_gui_events;
3041#endif
3042 /* The external command may update a tags file, clear cached tags. */
3043 tag_freematch();
3044
3045 if (cmd == NULL || *p_sxq == NUL)
3046 retval = mch_call_shell(cmd, opt);
3047 else
3048 {
3049 ncmd = alloc((unsigned)(STRLEN(cmd) + STRLEN(p_sxq) * 2 + 1));
3050 if (ncmd != NULL)
3051 {
3052 STRCPY(ncmd, p_sxq);
3053 STRCAT(ncmd, cmd);
3054 STRCAT(ncmd, p_sxq);
3055 retval = mch_call_shell(ncmd, opt);
3056 vim_free(ncmd);
3057 }
3058 else
3059 retval = -1;
3060 }
3061#ifdef FEAT_GUI
3062 --hold_gui_events;
3063#endif
3064 /*
3065 * Check the window size, in case it changed while executing the
3066 * external command.
3067 */
3068 shell_resized_check();
3069 }
3070
3071#ifdef FEAT_EVAL
3072 set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003073# ifdef FEAT_PROFILE
Bram Moolenaar01265852006-03-20 21:50:15 +00003074 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003075 prof_child_exit(&wait_time);
3076# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003077#endif
3078
3079 return retval;
3080}
3081
3082/*
Bram Moolenaar01265852006-03-20 21:50:15 +00003083 * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to
3084 * NORMAL State with a condition. This function returns the real State.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 */
3086 int
3087get_real_state()
3088{
3089 if (State & NORMAL)
3090 {
3091#ifdef FEAT_VISUAL
3092 if (VIsual_active)
Bram Moolenaar01265852006-03-20 21:50:15 +00003093 {
3094 if (VIsual_select)
3095 return SELECTMODE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096 return VISUAL;
Bram Moolenaar01265852006-03-20 21:50:15 +00003097 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 else
3099#endif
3100 if (finish_op)
Bram Moolenaar01265852006-03-20 21:50:15 +00003101 return OP_PENDING;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 }
3103 return State;
3104}
3105
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003106#if defined(FEAT_MBYTE) || defined(PROTO)
3107/*
3108 * Return TRUE if "p" points to just after a path separator.
3109 * Take care of multi-byte characters.
3110 * "b" must point to the start of the file name
3111 */
3112 int
3113after_pathsep(b, p)
3114 char_u *b;
3115 char_u *p;
3116{
3117 return vim_ispathsep(p[-1])
3118 && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
3119}
3120#endif
3121
3122/*
3123 * Return TRUE if file names "f1" and "f2" are in the same directory.
3124 * "f1" may be a short name, "f2" must be a full path.
3125 */
3126 int
3127same_directory(f1, f2)
3128 char_u *f1;
3129 char_u *f2;
3130{
3131 char_u ffname[MAXPATHL];
3132 char_u *t1;
3133 char_u *t2;
3134
3135 /* safety check */
3136 if (f1 == NULL || f2 == NULL)
3137 return FALSE;
3138
3139 (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
3140 t1 = gettail_sep(ffname);
3141 t2 = gettail_sep(f2);
3142 return (t1 - ffname == t2 - f2
3143 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
3144}
3145
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146#if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
Bram Moolenaar9372a112005-12-06 19:59:18 +00003147 || ((defined(FEAT_GUI_GTK)) \
Bram Moolenaar843ee412004-06-30 16:16:41 +00003148 && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
3150 || defined(PROTO)
3151/*
3152 * Change to a file's directory.
3153 * Caller must call shorten_fnames()!
3154 * Return OK or FAIL.
3155 */
3156 int
3157vim_chdirfile(fname)
3158 char_u *fname;
3159{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003160 char_u dir[MAXPATHL];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161
Bram Moolenaarbbebc852005-07-18 21:47:53 +00003162 vim_strncpy(dir, fname, MAXPATHL - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003163 *gettail_sep(dir) = NUL;
3164 return mch_chdir((char *)dir) == 0 ? OK : FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165}
3166#endif
3167
3168#if defined(STAT_IGNORES_SLASH) || defined(PROTO)
3169/*
3170 * Check if "name" ends in a slash and is not a directory.
3171 * Used for systems where stat() ignores a trailing slash on a file name.
3172 * The Vim code assumes a trailing slash is only ignored for a directory.
3173 */
3174 int
3175illegal_slash(name)
3176 char *name;
3177{
3178 if (name[0] == NUL)
3179 return FALSE; /* no file name is not illegal */
3180 if (name[strlen(name) - 1] != '/')
3181 return FALSE; /* no trailing slash */
3182 if (mch_isdir((char_u *)name))
3183 return FALSE; /* trailing slash for a directory */
3184 return TRUE;
3185}
3186#endif
3187
3188#if defined(CURSOR_SHAPE) || defined(PROTO)
3189
3190/*
3191 * Handling of cursor and mouse pointer shapes in various modes.
3192 */
3193
3194cursorentry_T shape_table[SHAPE_IDX_COUNT] =
3195{
3196 /* The values will be filled in from the 'guicursor' and 'mouseshape'
3197 * defaults when Vim starts.
3198 * Adjust the SHAPE_IDX_ defines when making changes! */
3199 {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
3200 {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
3201 {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
3202 {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
3203 {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
3204 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
3205 {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
3206 {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
3207 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
3208 {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE},
3209 {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE},
3210 {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE},
3211 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE},
3212 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE},
3213 {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE},
3214 {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE},
3215 {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
3216};
3217
3218#ifdef FEAT_MOUSESHAPE
3219/*
3220 * Table with names for mouse shapes. Keep in sync with all the tables for
3221 * mch_set_mouse_shape()!.
3222 */
3223static char * mshape_names[] =
3224{
3225 "arrow", /* default, must be the first one */
3226 "blank", /* hidden */
3227 "beam",
3228 "updown",
3229 "udsizing",
3230 "leftright",
3231 "lrsizing",
3232 "busy",
3233 "no",
3234 "crosshair",
3235 "hand1",
3236 "hand2",
3237 "pencil",
3238 "question",
3239 "rightup-arrow",
3240 "up-arrow",
3241 NULL
3242};
3243#endif
3244
3245/*
3246 * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
3247 * ("what" is SHAPE_MOUSE).
3248 * Returns error message for an illegal option, NULL otherwise.
3249 */
3250 char_u *
3251parse_shape_opt(what)
3252 int what;
3253{
3254 char_u *modep;
3255 char_u *colonp;
3256 char_u *commap;
3257 char_u *slashp;
3258 char_u *p, *endp;
3259 int idx = 0; /* init for GCC */
3260 int all_idx;
3261 int len;
3262 int i;
3263 long n;
3264 int found_ve = FALSE; /* found "ve" flag */
3265 int round;
3266
3267 /*
3268 * First round: check for errors; second round: do it for real.
3269 */
3270 for (round = 1; round <= 2; ++round)
3271 {
3272 /*
3273 * Repeat for all comma separated parts.
3274 */
3275#ifdef FEAT_MOUSESHAPE
3276 if (what == SHAPE_MOUSE)
3277 modep = p_mouseshape;
3278 else
3279#endif
3280 modep = p_guicursor;
3281 while (*modep != NUL)
3282 {
3283 colonp = vim_strchr(modep, ':');
3284 if (colonp == NULL)
3285 return (char_u *)N_("E545: Missing colon");
3286 if (colonp == modep)
3287 return (char_u *)N_("E546: Illegal mode");
3288 commap = vim_strchr(modep, ',');
3289
3290 /*
3291 * Repeat for all mode's before the colon.
3292 * For the 'a' mode, we loop to handle all the modes.
3293 */
3294 all_idx = -1;
3295 while (modep < colonp || all_idx >= 0)
3296 {
3297 if (all_idx < 0)
3298 {
3299 /* Find the mode. */
3300 if (modep[1] == '-' || modep[1] == ':')
3301 len = 1;
3302 else
3303 len = 2;
3304 if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
3305 all_idx = SHAPE_IDX_COUNT - 1;
3306 else
3307 {
3308 for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
3309 if (STRNICMP(modep, shape_table[idx].name, len)
3310 == 0)
3311 break;
3312 if (idx == SHAPE_IDX_COUNT
3313 || (shape_table[idx].used_for & what) == 0)
3314 return (char_u *)N_("E546: Illegal mode");
3315 if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
3316 found_ve = TRUE;
3317 }
3318 modep += len + 1;
3319 }
3320
3321 if (all_idx >= 0)
3322 idx = all_idx--;
3323 else if (round == 2)
3324 {
3325#ifdef FEAT_MOUSESHAPE
3326 if (what == SHAPE_MOUSE)
3327 {
3328 /* Set the default, for the missing parts */
3329 shape_table[idx].mshape = 0;
3330 }
3331 else
3332#endif
3333 {
3334 /* Set the defaults, for the missing parts */
3335 shape_table[idx].shape = SHAPE_BLOCK;
3336 shape_table[idx].blinkwait = 700L;
3337 shape_table[idx].blinkon = 400L;
3338 shape_table[idx].blinkoff = 250L;
3339 }
3340 }
3341
3342 /* Parse the part after the colon */
3343 for (p = colonp + 1; *p && *p != ','; )
3344 {
3345#ifdef FEAT_MOUSESHAPE
3346 if (what == SHAPE_MOUSE)
3347 {
3348 for (i = 0; ; ++i)
3349 {
3350 if (mshape_names[i] == NULL)
3351 {
3352 if (!VIM_ISDIGIT(*p))
3353 return (char_u *)N_("E547: Illegal mouseshape");
3354 if (round == 2)
3355 shape_table[idx].mshape =
3356 getdigits(&p) + MSHAPE_NUMBERED;
3357 else
3358 (void)getdigits(&p);
3359 break;
3360 }
3361 len = (int)STRLEN(mshape_names[i]);
3362 if (STRNICMP(p, mshape_names[i], len) == 0)
3363 {
3364 if (round == 2)
3365 shape_table[idx].mshape = i;
3366 p += len;
3367 break;
3368 }
3369 }
3370 }
3371 else /* if (what == SHAPE_MOUSE) */
3372#endif
3373 {
3374 /*
3375 * First handle the ones with a number argument.
3376 */
3377 i = *p;
3378 len = 0;
3379 if (STRNICMP(p, "ver", 3) == 0)
3380 len = 3;
3381 else if (STRNICMP(p, "hor", 3) == 0)
3382 len = 3;
3383 else if (STRNICMP(p, "blinkwait", 9) == 0)
3384 len = 9;
3385 else if (STRNICMP(p, "blinkon", 7) == 0)
3386 len = 7;
3387 else if (STRNICMP(p, "blinkoff", 8) == 0)
3388 len = 8;
3389 if (len != 0)
3390 {
3391 p += len;
3392 if (!VIM_ISDIGIT(*p))
3393 return (char_u *)N_("E548: digit expected");
3394 n = getdigits(&p);
3395 if (len == 3) /* "ver" or "hor" */
3396 {
3397 if (n == 0)
3398 return (char_u *)N_("E549: Illegal percentage");
3399 if (round == 2)
3400 {
3401 if (TOLOWER_ASC(i) == 'v')
3402 shape_table[idx].shape = SHAPE_VER;
3403 else
3404 shape_table[idx].shape = SHAPE_HOR;
3405 shape_table[idx].percentage = n;
3406 }
3407 }
3408 else if (round == 2)
3409 {
3410 if (len == 9)
3411 shape_table[idx].blinkwait = n;
3412 else if (len == 7)
3413 shape_table[idx].blinkon = n;
3414 else
3415 shape_table[idx].blinkoff = n;
3416 }
3417 }
3418 else if (STRNICMP(p, "block", 5) == 0)
3419 {
3420 if (round == 2)
3421 shape_table[idx].shape = SHAPE_BLOCK;
3422 p += 5;
3423 }
3424 else /* must be a highlight group name then */
3425 {
3426 endp = vim_strchr(p, '-');
3427 if (commap == NULL) /* last part */
3428 {
3429 if (endp == NULL)
3430 endp = p + STRLEN(p); /* find end of part */
3431 }
3432 else if (endp > commap || endp == NULL)
3433 endp = commap;
3434 slashp = vim_strchr(p, '/');
3435 if (slashp != NULL && slashp < endp)
3436 {
3437 /* "group/langmap_group" */
3438 i = syn_check_group(p, (int)(slashp - p));
3439 p = slashp + 1;
3440 }
3441 if (round == 2)
3442 {
3443 shape_table[idx].id = syn_check_group(p,
3444 (int)(endp - p));
3445 shape_table[idx].id_lm = shape_table[idx].id;
3446 if (slashp != NULL && slashp < endp)
3447 shape_table[idx].id = i;
3448 }
3449 p = endp;
3450 }
3451 } /* if (what != SHAPE_MOUSE) */
3452
3453 if (*p == '-')
3454 ++p;
3455 }
3456 }
3457 modep = p;
3458 if (*modep == ',')
3459 ++modep;
3460 }
3461 }
3462
3463 /* If the 's' flag is not given, use the 'v' cursor for 's' */
3464 if (!found_ve)
3465 {
3466#ifdef FEAT_MOUSESHAPE
3467 if (what == SHAPE_MOUSE)
3468 {
3469 shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3470 }
3471 else
3472#endif
3473 {
3474 shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3475 shape_table[SHAPE_IDX_VE].percentage =
3476 shape_table[SHAPE_IDX_V].percentage;
3477 shape_table[SHAPE_IDX_VE].blinkwait =
3478 shape_table[SHAPE_IDX_V].blinkwait;
3479 shape_table[SHAPE_IDX_VE].blinkon =
3480 shape_table[SHAPE_IDX_V].blinkon;
3481 shape_table[SHAPE_IDX_VE].blinkoff =
3482 shape_table[SHAPE_IDX_V].blinkoff;
3483 shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3484 shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3485 }
3486 }
3487
3488 return NULL;
3489}
3490
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00003491# if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
3492 || defined(FEAT_MOUSESHAPE) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493/*
3494 * Return the index into shape_table[] for the current mode.
3495 * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3496 */
3497 int
3498get_shape_idx(mouse)
3499 int mouse;
3500{
3501#ifdef FEAT_MOUSESHAPE
3502 if (mouse && (State == HITRETURN || State == ASKMORE))
3503 {
3504# ifdef FEAT_GUI
Bram Moolenaar9588a0f2005-01-08 21:45:39 +00003505 int x, y;
3506 gui_mch_getmouse(&x, &y);
3507 if (Y_2_ROW(y) == Rows - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508 return SHAPE_IDX_MOREL;
3509# endif
3510 return SHAPE_IDX_MORE;
3511 }
3512 if (mouse && drag_status_line)
3513 return SHAPE_IDX_SDRAG;
3514# ifdef FEAT_VERTSPLIT
3515 if (mouse && drag_sep_line)
3516 return SHAPE_IDX_VDRAG;
3517# endif
3518#endif
3519 if (!mouse && State == SHOWMATCH)
3520 return SHAPE_IDX_SM;
3521#ifdef FEAT_VREPLACE
3522 if (State & VREPLACE_FLAG)
3523 return SHAPE_IDX_R;
3524#endif
3525 if (State & REPLACE_FLAG)
3526 return SHAPE_IDX_R;
3527 if (State & INSERT)
3528 return SHAPE_IDX_I;
3529 if (State & CMDLINE)
3530 {
3531 if (cmdline_at_end())
3532 return SHAPE_IDX_C;
3533 if (cmdline_overstrike())
3534 return SHAPE_IDX_CR;
3535 return SHAPE_IDX_CI;
3536 }
3537 if (finish_op)
3538 return SHAPE_IDX_O;
3539#ifdef FEAT_VISUAL
3540 if (VIsual_active)
3541 {
3542 if (*p_sel == 'e')
3543 return SHAPE_IDX_VE;
3544 else
3545 return SHAPE_IDX_V;
3546 }
3547#endif
3548 return SHAPE_IDX_N;
3549}
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00003550#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551
3552# if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3553static int old_mouse_shape = 0;
3554
3555/*
3556 * Set the mouse shape:
3557 * If "shape" is -1, use shape depending on the current mode,
3558 * depending on the current state.
3559 * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3560 * when the mouse moves off the status or command line).
3561 */
3562 void
3563update_mouseshape(shape_idx)
3564 int shape_idx;
3565{
3566 int new_mouse_shape;
3567
3568 /* Only works in GUI mode. */
Bram Moolenaar6bb68362005-03-22 23:03:44 +00003569 if (!gui.in_use || gui.starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570 return;
3571
3572 /* Postpone the updating when more is to come. Speeds up executing of
3573 * mappings. */
3574 if (shape_idx == -1 && char_avail())
3575 {
3576 postponed_mouseshape = TRUE;
3577 return;
3578 }
3579
Bram Moolenaar14716812006-05-04 21:54:08 +00003580 /* When ignoring the mouse don't change shape on the statusline. */
3581 if (*p_mouse == NUL
3582 && (shape_idx == SHAPE_IDX_CLINE
3583 || shape_idx == SHAPE_IDX_STATUS
3584 || shape_idx == SHAPE_IDX_VSEP))
3585 shape_idx = -2;
3586
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587 if (shape_idx == -2
3588 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3589 && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3590 && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3591 return;
3592 if (shape_idx < 0)
3593 new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3594 else
3595 new_mouse_shape = shape_table[shape_idx].mshape;
3596 if (new_mouse_shape != old_mouse_shape)
3597 {
3598 mch_set_mouse_shape(new_mouse_shape);
3599 old_mouse_shape = new_mouse_shape;
3600 }
3601 postponed_mouseshape = FALSE;
3602}
3603# endif
3604
3605#endif /* CURSOR_SHAPE */
3606
3607
3608#ifdef FEAT_CRYPT
3609/*
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00003610 * Optional encryption support.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 * Mohsin Ahmed, mosh@sasi.com, 98-09-24
3612 * Based on zip/crypt sources.
3613 *
3614 * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3615 * most countries. There are a few exceptions, but that still should not be a
3616 * problem since this code was originally created in Europe and India.
3617 */
3618
3619/* from zip.h */
3620
3621typedef unsigned short ush; /* unsigned 16-bit value */
3622typedef unsigned long ulg; /* unsigned 32-bit value */
3623
3624static void make_crc_tab __ARGS((void));
3625
Bram Moolenaard6f676d2005-06-01 21:51:55 +00003626static ulg crc_32_tab[256];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627
3628/*
3629 * Fill the CRC table.
3630 */
3631 static void
3632make_crc_tab()
3633{
3634 ulg s,t,v;
3635 static int done = FALSE;
3636
3637 if (done)
3638 return;
3639 for (t = 0; t < 256; t++)
3640 {
3641 v = t;
3642 for (s = 0; s < 8; s++)
3643 v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3644 crc_32_tab[t] = v;
3645 }
3646 done = TRUE;
3647}
3648
3649#define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3650
3651
3652static ulg keys[3]; /* keys defining the pseudo-random sequence */
3653
3654/*
3655 * Return the next byte in the pseudo-random sequence
3656 */
3657 int
3658decrypt_byte()
3659{
3660 ush temp;
3661
3662 temp = (ush)keys[2] | 2;
3663 return (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff);
3664}
3665
3666/*
3667 * Update the encryption keys with the next byte of plain text
3668 */
3669 int
3670update_keys(c)
3671 int c; /* byte of plain text */
3672{
3673 keys[0] = CRC32(keys[0], c);
3674 keys[1] += keys[0] & 0xff;
3675 keys[1] = keys[1] * 134775813L + 1;
3676 keys[2] = CRC32(keys[2], (int)(keys[1] >> 24));
3677 return c;
3678}
3679
3680/*
3681 * Initialize the encryption keys and the random header according to
3682 * the given password.
3683 * If "passwd" is NULL or empty, don't do anything.
3684 */
3685 void
3686crypt_init_keys(passwd)
3687 char_u *passwd; /* password string with which to modify keys */
3688{
3689 if (passwd != NULL && *passwd != NUL)
3690 {
3691 make_crc_tab();
3692 keys[0] = 305419896L;
3693 keys[1] = 591751049L;
3694 keys[2] = 878082192L;
3695 while (*passwd != '\0')
3696 update_keys((int)*passwd++);
3697 }
3698}
3699
3700/*
3701 * Ask the user for a crypt key.
3702 * When "store" is TRUE, the new key in stored in the 'key' option, and the
3703 * 'key' option value is returned: Don't free it.
3704 * When "store" is FALSE, the typed key is returned in allocated memory.
3705 * Returns NULL on failure.
3706 */
3707 char_u *
3708get_crypt_key(store, twice)
3709 int store;
3710 int twice; /* Ask for the key twice. */
3711{
3712 char_u *p1, *p2 = NULL;
3713 int round;
3714
3715 for (round = 0; ; ++round)
3716 {
3717 cmdline_star = TRUE;
3718 cmdline_row = msg_row;
3719 p1 = getcmdline_prompt(NUL, round == 0
3720 ? (char_u *)_("Enter encryption key: ")
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00003721 : (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING,
3722 NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003723 cmdline_star = FALSE;
3724
3725 if (p1 == NULL)
3726 break;
3727
3728 if (round == twice)
3729 {
3730 if (p2 != NULL && STRCMP(p1, p2) != 0)
3731 {
3732 MSG(_("Keys don't match!"));
3733 vim_free(p1);
3734 vim_free(p2);
3735 p2 = NULL;
3736 round = -1; /* do it again */
3737 continue;
3738 }
3739 if (store)
3740 {
3741 set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
3742 vim_free(p1);
3743 p1 = curbuf->b_p_key;
3744 }
3745 break;
3746 }
3747 p2 = p1;
3748 }
3749
3750 /* since the user typed this, no need to wait for return */
3751 need_wait_return = FALSE;
3752 msg_didout = FALSE;
3753
3754 vim_free(p2);
3755 return p1;
3756}
3757
3758#endif /* FEAT_CRYPT */
3759
3760/* TODO: make some #ifdef for this */
3761/*--------[ file searching ]-------------------------------------------------*/
3762/*
3763 * File searching functions for 'path', 'tags' and 'cdpath' options.
3764 * External visible functions:
3765 * vim_findfile_init() creates/initialises the search context
3766 * vim_findfile_free_visited() free list of visited files/dirs of search
3767 * context
3768 * vim_findfile() find a file in the search context
3769 * vim_findfile_cleanup() cleanup/free search context created by
3770 * vim_findfile_init()
3771 *
3772 * All static functions and variables start with 'ff_'
3773 *
3774 * In general it works like this:
3775 * First you create yourself a search context by calling vim_findfile_init().
3776 * It is possible to give a search context from a previous call to
3777 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
3778 * until you are satisfied with the result or it returns NULL. On every call it
3779 * returns the next file which matches the conditions given to
3780 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
3781 *
3782 * It is possible to call vim_findfile_init() again to reinitialise your search
3783 * with some new parameters. Don't forget to pass your old search context to
3784 * it, so it can reuse it and especially reuse the list of already visited
3785 * directories. If you want to delete the list of already visited directories
3786 * simply call vim_findfile_free_visited().
3787 *
3788 * When you are done call vim_findfile_cleanup() to free the search context.
3789 *
3790 * The function vim_findfile_init() has a long comment, which describes the
3791 * needed parameters.
3792 *
3793 *
3794 *
3795 * ATTENTION:
3796 * ==========
Bram Moolenaar77f66d62007-02-20 02:16:18 +00003797 * Also we use an allocated search context here, this functions are NOT
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798 * thread-safe!!!!!
3799 *
3800 * To minimize parameter passing (or because I'm to lazy), only the
3801 * external visible functions get a search context as a parameter. This is
3802 * then assigned to a static global, which is used throughout the local
3803 * functions.
3804 */
3805
3806/*
3807 * type for the directory search stack
3808 */
3809typedef struct ff_stack
3810{
3811 struct ff_stack *ffs_prev;
3812
3813 /* the fix part (no wildcards) and the part containing the wildcards
3814 * of the search path
3815 */
3816 char_u *ffs_fix_path;
3817#ifdef FEAT_PATH_EXTRA
3818 char_u *ffs_wc_path;
3819#endif
3820
3821 /* files/dirs found in the above directory, matched by the first wildcard
3822 * of wc_part
3823 */
3824 char_u **ffs_filearray;
3825 int ffs_filearray_size;
3826 char_u ffs_filearray_cur; /* needed for partly handled dirs */
3827
3828 /* to store status of partly handled directories
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00003829 * 0: we work on this directory for the first time
Bram Moolenaar071d4272004-06-13 20:20:40 +00003830 * 1: this directory was partly searched in an earlier step
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00003831 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003832 int ffs_stage;
3833
3834 /* How deep are we in the directory tree?
3835 * Counts backward from value of level parameter to vim_findfile_init
3836 */
3837 int ffs_level;
3838
3839 /* Did we already expand '**' to an empty string? */
3840 int ffs_star_star_empty;
3841} ff_stack_T;
3842
3843/*
3844 * type for already visited directories or files.
3845 */
3846typedef struct ff_visited
3847{
3848 struct ff_visited *ffv_next;
3849
3850#ifdef FEAT_PATH_EXTRA
3851 /* Visited directories are different if the wildcard string are
3852 * different. So we have to save it.
3853 */
3854 char_u *ffv_wc_path;
3855#endif
3856 /* for unix use inode etc for comparison (needed because of links), else
3857 * use filename.
3858 */
3859#ifdef UNIX
3860 int ffv_dev; /* device number (-1 if not set) */
3861 ino_t ffv_ino; /* inode number */
3862#endif
3863 /* The memory for this struct is allocated according to the length of
3864 * ffv_fname.
3865 */
3866 char_u ffv_fname[1]; /* actually longer */
3867} ff_visited_T;
3868
3869/*
3870 * We might have to manage several visited lists during a search.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00003871 * This is especially needed for the tags option. If tags is set to:
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
3873 * So we have to do 3 searches:
3874 * 1) search from the current files directory downward for the file "tags"
3875 * 2) search from the current files directory downward for the file "TAGS"
3876 * 3) search from Vims current directory downwards for the file "tags"
3877 * As you can see, the first and the third search are for the same file, so for
3878 * the third search we can use the visited list of the first search. For the
3879 * second search we must start from a empty visited list.
3880 * The struct ff_visited_list_hdr is used to manage a linked list of already
3881 * visited lists.
3882 */
3883typedef struct ff_visited_list_hdr
3884{
3885 struct ff_visited_list_hdr *ffvl_next;
3886
3887 /* the filename the attached visited list is for */
3888 char_u *ffvl_filename;
3889
3890 ff_visited_T *ffvl_visited_list;
3891
3892} ff_visited_list_hdr_T;
3893
3894
3895/*
3896 * '**' can be expanded to several directory levels.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00003897 * Set the default maximum depth.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003898 */
3899#define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00003900
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901/*
3902 * The search context:
3903 * ffsc_stack_ptr: the stack for the dirs to search
3904 * ffsc_visited_list: the currently active visited list
3905 * ffsc_dir_visited_list: the currently active visited list for search dirs
3906 * ffsc_visited_lists_list: the list of all visited lists
3907 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
3908 * ffsc_file_to_search: the file to search for
3909 * ffsc_start_dir: the starting directory, if search path was relative
3910 * ffsc_fix_path: the fix part of the given path (without wildcards)
3911 * Needed for upward search.
3912 * ffsc_wc_path: the part of the given path containing wildcards
3913 * ffsc_level: how many levels of dirs to search downwards
3914 * ffsc_stopdirs_v: array of stop directories for upward search
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00003915 * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916 */
3917typedef struct ff_search_ctx_T
3918{
3919 ff_stack_T *ffsc_stack_ptr;
3920 ff_visited_list_hdr_T *ffsc_visited_list;
3921 ff_visited_list_hdr_T *ffsc_dir_visited_list;
3922 ff_visited_list_hdr_T *ffsc_visited_lists_list;
3923 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
3924 char_u *ffsc_file_to_search;
3925 char_u *ffsc_start_dir;
3926 char_u *ffsc_fix_path;
3927#ifdef FEAT_PATH_EXTRA
3928 char_u *ffsc_wc_path;
3929 int ffsc_level;
3930 char_u **ffsc_stopdirs_v;
3931#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00003932 int ffsc_find_what;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003933} ff_search_ctx_T;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935/* locally needed functions */
3936#ifdef FEAT_PATH_EXTRA
3937static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
3938#else
3939static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
3940#endif
3941static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
3942static void ff_free_visited_list __ARGS((ff_visited_T *vl));
3943static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
3944#ifdef FEAT_PATH_EXTRA
3945static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
3946#endif
3947
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00003948static void ff_push __ARGS((ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr));
3949static ff_stack_T *ff_pop __ARGS((ff_search_ctx_T *search_ctx));
3950static void ff_clear __ARGS((ff_search_ctx_T *search_ctx));
3951static void ff_free_stack_element __ARGS((ff_stack_T *stack_ptr));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952#ifdef FEAT_PATH_EXTRA
3953static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
3954#else
3955static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
3956#endif
3957#ifdef FEAT_PATH_EXTRA
3958static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
3959#endif
3960
Bram Moolenaar071d4272004-06-13 20:20:40 +00003961#if 0
3962/*
3963 * if someone likes findfirst/findnext, here are the functions
3964 * NOT TESTED!!
3965 */
3966
3967static void *ff_fn_search_context = NULL;
3968
3969 char_u *
3970vim_findfirst(path, filename, level)
3971 char_u *path;
3972 char_u *filename;
3973 int level;
3974{
3975 ff_fn_search_context =
3976 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
3977 ff_fn_search_context, rel_fname);
3978 if (NULL == ff_fn_search_context)
3979 return NULL;
3980 else
3981 return vim_findnext()
3982}
3983
3984 char_u *
3985vim_findnext()
3986{
3987 char_u *ret = vim_findfile(ff_fn_search_context);
3988
3989 if (NULL == ret)
3990 {
3991 vim_findfile_cleanup(ff_fn_search_context);
3992 ff_fn_search_context = NULL;
3993 }
3994 return ret;
3995}
3996#endif
3997
3998/*
3999 * Initialization routine for vim_findfile.
4000 *
4001 * Returns the newly allocated search context or NULL if an error occured.
4002 *
4003 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
4004 * with the search context.
4005 *
4006 * Find the file 'filename' in the directory 'path'.
4007 * The parameter 'path' may contain wildcards. If so only search 'level'
4008 * directories deep. The parameter 'level' is the absolute maximum and is
4009 * not related to restricts given to the '**' wildcard. If 'level' is 100
4010 * and you use '**200' vim_findfile() will stop after 100 levels.
4011 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004012 * 'filename' cannot contain wildcards! It is used as-is, no backslashes to
4013 * escape special characters.
4014 *
Bram Moolenaar071d4272004-06-13 20:20:40 +00004015 * If 'stopdirs' is not NULL and nothing is found downward, the search is
4016 * restarted on the next higher directory level. This is repeated until the
4017 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
4018 * format ";*<dirname>*\(;<dirname>\)*;\=$".
4019 *
4020 * If the 'path' is relative, the starting dir for the search is either VIM's
4021 * current dir or if the path starts with "./" the current files dir.
4022 * If the 'path' is absolut, the starting dir is that part of the path before
4023 * the first wildcard.
4024 *
4025 * Upward search is only done on the starting dir.
4026 *
4027 * If 'free_visited' is TRUE the list of already visited files/directories is
4028 * cleared. Set this to FALSE if you just want to search from another
4029 * directory, but want to be sure that no directory from a previous search is
4030 * searched again. This is useful if you search for a file at different places.
4031 * The list of visited files/dirs can also be cleared with the function
4032 * vim_findfile_free_visited().
4033 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004034 * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
4035 * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036 *
4037 * A search context returned by a previous call to vim_findfile_init() can be
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004038 * passed in the parameter "search_ctx_arg". This context is reused and
4039 * reinitialized with the new parameters. The list of already visited
Bram Moolenaar071d4272004-06-13 20:20:40 +00004040 * directories from this context is only deleted if the parameter
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004041 * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed
4042 * if the reinitialization fails.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043 *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004044 * If you don't have a search context from a previous call "search_ctx_arg"
4045 * must be NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046 *
4047 * This function silently ignores a few errors, vim_findfile() will have
4048 * limited functionality then.
4049 */
4050/*ARGSUSED*/
4051 void *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004052vim_findfile_init(path, filename, stopdirs, level, free_visited, find_what,
4053 search_ctx_arg, tagfile, rel_fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 char_u *path;
4055 char_u *filename;
4056 char_u *stopdirs;
4057 int level;
4058 int free_visited;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004059 int find_what;
4060 void *search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061 int tagfile;
4062 char_u *rel_fname; /* file name to use for "." */
4063{
4064#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004065 char_u *wc_part;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004066#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004067 ff_stack_T *sptr;
4068 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069
4070 /* If a search context is given by the caller, reuse it, else allocate a
4071 * new one.
4072 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004073 if (search_ctx_arg != NULL)
4074 search_ctx = search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004075 else
4076 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004077 search_ctx = (ff_search_ctx_T*)alloc((unsigned)sizeof(ff_search_ctx_T));
4078 if (search_ctx == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 goto error_return;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004080 memset(search_ctx, 0, sizeof(ff_search_ctx_T));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004082 search_ctx->ffsc_find_what = find_what;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083
4084 /* clear the search context, but NOT the visited lists */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004085 ff_clear(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086
4087 /* clear visited list if wanted */
4088 if (free_visited == TRUE)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004089 vim_findfile_free_visited(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004090 else
4091 {
4092 /* Reuse old visited lists. Get the visited list for the given
4093 * filename. If no list for the current filename exists, creates a new
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004094 * one. */
4095 search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
4096 &search_ctx->ffsc_visited_lists_list);
4097 if (search_ctx->ffsc_visited_list == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004098 goto error_return;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004099 search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
4100 &search_ctx->ffsc_dir_visited_lists_list);
4101 if (search_ctx->ffsc_dir_visited_list == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 goto error_return;
4103 }
4104
4105 if (ff_expand_buffer == NULL)
4106 {
4107 ff_expand_buffer = (char_u*)alloc(MAXPATHL);
4108 if (ff_expand_buffer == NULL)
4109 goto error_return;
4110 }
4111
4112 /* Store information on starting dir now if path is relative.
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004113 * If path is absolute, we do that later. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004114 if (path[0] == '.'
4115 && (vim_ispathsep(path[1]) || path[1] == NUL)
4116 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
4117 && rel_fname != NULL)
4118 {
4119 int len = (int)(gettail(rel_fname) - rel_fname);
4120
4121 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
4122 {
4123 /* Make the start dir an absolute path name. */
Bram Moolenaarbbebc852005-07-18 21:47:53 +00004124 vim_strncpy(ff_expand_buffer, rel_fname, len);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004125 search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004126 }
4127 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004128 search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
4129 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004130 goto error_return;
4131 if (*++path != NUL)
4132 ++path;
4133 }
4134 else if (*path == NUL || !vim_isAbsName(path))
4135 {
4136#ifdef BACKSLASH_IN_FILENAME
4137 /* "c:dir" needs "c:" to be expanded, otherwise use current dir */
4138 if (*path != NUL && path[1] == ':')
4139 {
4140 char_u drive[3];
4141
4142 drive[0] = path[0];
4143 drive[1] = ':';
4144 drive[2] = NUL;
4145 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4146 goto error_return;
4147 path += 2;
4148 }
4149 else
4150#endif
4151 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
4152 goto error_return;
4153
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004154 search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
4155 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156 goto error_return;
4157
4158#ifdef BACKSLASH_IN_FILENAME
4159 /* A path that starts with "/dir" is relative to the drive, not to the
4160 * directory (but not for "//machine/dir"). Only use the drive name. */
4161 if ((*path == '/' || *path == '\\')
4162 && path[1] != path[0]
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004163 && search_ctx->ffsc_start_dir[1] == ':')
4164 search_ctx->ffsc_start_dir[2] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004165#endif
4166 }
4167
4168#ifdef FEAT_PATH_EXTRA
4169 /*
4170 * If stopdirs are given, split them into an array of pointers.
4171 * If this fails (mem allocation), there is no upward search at all or a
4172 * stop directory is not recognized -> continue silently.
4173 * If stopdirs just contains a ";" or is empty,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004174 * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
Bram Moolenaar071d4272004-06-13 20:20:40 +00004175 * is handled as unlimited upward search. See function
4176 * ff_path_in_stoplist() for details.
4177 */
4178 if (stopdirs != NULL)
4179 {
4180 char_u *walker = stopdirs;
4181 int dircount;
4182
4183 while (*walker == ';')
4184 walker++;
4185
4186 dircount = 1;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004187 search_ctx->ffsc_stopdirs_v =
4188 (char_u **)alloc((unsigned)sizeof(char_u *));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004190 if (search_ctx->ffsc_stopdirs_v != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 {
4192 do
4193 {
4194 char_u *helper;
4195 void *ptr;
4196
4197 helper = walker;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004198 ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 (dircount + 1) * sizeof(char_u *));
4200 if (ptr)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004201 search_ctx->ffsc_stopdirs_v = ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202 else
4203 /* ignore, keep what we have and continue */
4204 break;
4205 walker = vim_strchr(walker, ';');
4206 if (walker)
4207 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004208 search_ctx->ffsc_stopdirs_v[dircount-1] =
4209 vim_strnsave(helper, (int)(walker - helper));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004210 walker++;
4211 }
4212 else
4213 /* this might be "", which means ascent till top
4214 * of directory tree.
4215 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004216 search_ctx->ffsc_stopdirs_v[dircount-1] =
4217 vim_strsave(helper);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004218
4219 dircount++;
4220
4221 } while (walker != NULL);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004222 search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 }
4224 }
4225#endif
4226
4227#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004228 search_ctx->ffsc_level = level;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229
4230 /* split into:
4231 * -fix path
4232 * -wildcard_stuff (might be NULL)
4233 */
4234 wc_part = vim_strchr(path, '*');
4235 if (wc_part != NULL)
4236 {
4237 int llevel;
4238 int len;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004239 char *errpt;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240
4241 /* save the fix part of the path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004242 search_ctx->ffsc_fix_path = vim_strnsave(path, (int)(wc_part - path));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243
4244 /*
4245 * copy wc_path and add restricts to the '**' wildcard.
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004246 * The octet after a '**' is used as a (binary) counter.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
4248 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
4249 * For EBCDIC you get different character values.
4250 * If no restrict is given after '**' the default is used.
4251 * Due to this technic the path looks awful if you print it as a
4252 * string.
4253 */
4254 len = 0;
4255 while (*wc_part != NUL)
4256 {
4257 if (STRNCMP(wc_part, "**", 2) == 0)
4258 {
4259 ff_expand_buffer[len++] = *wc_part++;
4260 ff_expand_buffer[len++] = *wc_part++;
4261
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004262 llevel = strtol((char *)wc_part, &errpt, 10);
4263 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004264 ff_expand_buffer[len++] = llevel;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004265 else if ((char_u *)errpt != wc_part && llevel == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004266 /* restrict is 0 -> remove already added '**' */
4267 len -= 2;
4268 else
4269 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
Bram Moolenaar7b0294c2004-10-11 10:16:09 +00004270 wc_part = (char_u *)errpt;
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00004271 if (*wc_part != NUL && !vim_ispathsep(*wc_part))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 {
4273 EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
4274 goto error_return;
4275 }
4276 }
4277 else
4278 ff_expand_buffer[len++] = *wc_part++;
4279 }
4280 ff_expand_buffer[len] = NUL;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004281 search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004282
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004283 if (search_ctx->ffsc_wc_path == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284 goto error_return;
4285 }
4286 else
4287#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004288 search_ctx->ffsc_fix_path = vim_strsave(path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004290 if (search_ctx->ffsc_start_dir == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004291 {
4292 /* store the fix part as startdir.
4293 * This is needed if the parameter path is fully qualified.
4294 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004295 search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
4296 if (search_ctx->ffsc_start_dir)
4297 search_ctx->ffsc_fix_path[0] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 }
4299
4300 /* create an absolute path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004301 STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302 add_pathsep(ff_expand_buffer);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004303 STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 add_pathsep(ff_expand_buffer);
4305
4306 sptr = ff_create_stack_element(ff_expand_buffer,
4307#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004308 search_ctx->ffsc_wc_path,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309#endif
4310 level, 0);
4311
4312 if (sptr == NULL)
4313 goto error_return;
4314
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004315 ff_push(search_ctx, sptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004317 search_ctx->ffsc_file_to_search = vim_strsave(filename);
4318 if (search_ctx->ffsc_file_to_search == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 goto error_return;
4320
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004321 return search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004322
4323error_return:
4324 /*
4325 * We clear the search context now!
4326 * Even when the caller gave us a (perhaps valid) context we free it here,
4327 * as we might have already destroyed it.
4328 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004329 vim_findfile_cleanup(search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004330 return NULL;
4331}
4332
4333#if defined(FEAT_PATH_EXTRA) || defined(PROTO)
4334/*
4335 * Get the stopdir string. Check that ';' is not escaped.
4336 */
4337 char_u *
4338vim_findfile_stopdir(buf)
4339 char_u *buf;
4340{
4341 char_u *r_ptr = buf;
4342
4343 while (*r_ptr != NUL && *r_ptr != ';')
4344 {
4345 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
4346 {
4347 /* overwrite the escape char,
4348 * use STRLEN(r_ptr) to move the trailing '\0'
4349 */
Bram Moolenaar446cb832008-06-24 21:56:24 +00004350 STRMOVE(r_ptr, r_ptr + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 r_ptr++;
4352 }
4353 r_ptr++;
4354 }
4355 if (*r_ptr == ';')
4356 {
4357 *r_ptr = 0;
4358 r_ptr++;
4359 }
4360 else if (*r_ptr == NUL)
4361 r_ptr = NULL;
4362 return r_ptr;
4363}
4364#endif
4365
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004366/*
4367 * Clean up the given search context. Can handle a NULL pointer.
4368 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004369 void
4370vim_findfile_cleanup(ctx)
4371 void *ctx;
4372{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00004373 if (ctx == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004374 return;
4375
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376 vim_findfile_free_visited(ctx);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004377 ff_clear(ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 vim_free(ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004379}
4380
4381/*
4382 * Find a file in a search context.
4383 * The search context was created with vim_findfile_init() above.
4384 * Return a pointer to an allocated file name or NULL if nothing found.
4385 * To get all matching files call this function until you get NULL.
4386 *
Bram Moolenaar5eb86f92004-07-26 12:53:41 +00004387 * If the passed search_context is NULL, NULL is returned.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004388 *
4389 * The search algorithm is depth first. To change this replace the
4390 * stack with a list (don't forget to leave partly searched directories on the
4391 * top of the list).
4392 */
4393 char_u *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004394vim_findfile(search_ctx_arg)
4395 void *search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396{
4397 char_u *file_path;
4398#ifdef FEAT_PATH_EXTRA
4399 char_u *rest_of_wildcards;
4400 char_u *path_end = NULL;
4401#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004402 ff_stack_T *stackp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004403#if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
4404 int len;
4405#endif
4406 int i;
4407 char_u *p;
4408#ifdef FEAT_SEARCHPATH
4409 char_u *suf;
4410#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004411 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004413 if (search_ctx_arg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004414 return NULL;
4415
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004416 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004417
4418 /*
4419 * filepath is used as buffer for various actions and as the storage to
4420 * return a found filename.
4421 */
4422 if ((file_path = alloc((int)MAXPATHL)) == NULL)
4423 return NULL;
4424
4425#ifdef FEAT_PATH_EXTRA
4426 /* store the end of the start dir -- needed for upward search */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004427 if (search_ctx->ffsc_start_dir != NULL)
4428 path_end = &search_ctx->ffsc_start_dir[
4429 STRLEN(search_ctx->ffsc_start_dir)];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430#endif
4431
4432#ifdef FEAT_PATH_EXTRA
4433 /* upward search loop */
4434 for (;;)
4435 {
4436#endif
4437 /* downward search loop */
4438 for (;;)
4439 {
4440 /* check if user user wants to stop the search*/
4441 ui_breakcheck();
4442 if (got_int)
4443 break;
4444
4445 /* get directory to work on from stack */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004446 stackp = ff_pop(search_ctx);
4447 if (stackp == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 break;
4449
4450 /*
4451 * TODO: decide if we leave this test in
4452 *
4453 * GOOD: don't search a directory(-tree) twice.
4454 * BAD: - check linked list for every new directory entered.
4455 * - check for double files also done below
4456 *
4457 * Here we check if we already searched this directory.
4458 * We already searched a directory if:
4459 * 1) The directory is the same.
4460 * 2) We would use the same wildcard string.
4461 *
4462 * Good if you have links on same directory via several ways
4463 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4464 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4465 *
4466 * This check is only needed for directories we work on for the
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004467 * first time (hence stackp->ff_filearray == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004469 if (stackp->ffs_filearray == NULL
4470 && ff_check_visited(&search_ctx->ffsc_dir_visited_list
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471 ->ffvl_visited_list,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004472 stackp->ffs_fix_path
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004474 , stackp->ffs_wc_path
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475#endif
4476 ) == FAIL)
4477 {
4478#ifdef FF_VERBOSE
4479 if (p_verbose >= 5)
4480 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004481 verbose_enter_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482 smsg((char_u *)"Already Searched: %s (%s)",
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004483 stackp->ffs_fix_path, stackp->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 /* don't overwrite this either */
4485 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004486 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004487 }
4488#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004489 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490 continue;
4491 }
4492#ifdef FF_VERBOSE
4493 else if (p_verbose >= 5)
4494 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004495 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004496 smsg((char_u *)"Searching: %s (%s)",
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004497 stackp->ffs_fix_path, stackp->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498 /* don't overwrite this either */
4499 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004500 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501 }
4502#endif
4503
4504 /* check depth */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004505 if (stackp->ffs_level <= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004507 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508 continue;
4509 }
4510
4511 file_path[0] = NUL;
4512
4513 /*
4514 * If no filearray till now expand wildcards
4515 * The function expand_wildcards() can handle an array of paths
4516 * and all possible expands are returned in one array. We use this
4517 * to handle the expansion of '**' into an empty string.
4518 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004519 if (stackp->ffs_filearray == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 {
4521 char_u *dirptrs[2];
4522
4523 /* we use filepath to build the path expand_wildcards() should
4524 * expand.
4525 */
4526 dirptrs[0] = file_path;
4527 dirptrs[1] = NULL;
4528
4529 /* if we have a start dir copy it in */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004530 if (!vim_isAbsName(stackp->ffs_fix_path)
4531 && search_ctx->ffsc_start_dir)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004533 STRCPY(file_path, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534 add_pathsep(file_path);
4535 }
4536
4537 /* append the fix part of the search path */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004538 STRCAT(file_path, stackp->ffs_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004539 add_pathsep(file_path);
4540
4541#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004542 rest_of_wildcards = stackp->ffs_wc_path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004543 if (*rest_of_wildcards != NUL)
4544 {
4545 len = (int)STRLEN(file_path);
4546 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4547 {
4548 /* pointer to the restrict byte
4549 * The restrict byte is not a character!
4550 */
4551 p = rest_of_wildcards + 2;
4552
4553 if (*p > 0)
4554 {
4555 (*p)--;
4556 file_path[len++] = '*';
4557 }
4558
4559 if (*p == 0)
4560 {
4561 /* remove '**<numb> from wildcards */
Bram Moolenaar446cb832008-06-24 21:56:24 +00004562 STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004563 }
4564 else
4565 rest_of_wildcards += 3;
4566
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004567 if (stackp->ffs_star_star_empty == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004568 {
4569 /* if not done before, expand '**' to empty */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004570 stackp->ffs_star_star_empty = 1;
4571 dirptrs[1] = stackp->ffs_fix_path;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004572 }
4573 }
4574
4575 /*
4576 * Here we copy until the next path separator or the end of
4577 * the path. If we stop at a path separator, there is
Bram Moolenaar7aa9f6a2007-05-10 18:00:30 +00004578 * still something else left. This is handled below by
Bram Moolenaar071d4272004-06-13 20:20:40 +00004579 * pushing every directory returned from expand_wildcards()
4580 * on the stack again for further search.
4581 */
4582 while (*rest_of_wildcards
4583 && !vim_ispathsep(*rest_of_wildcards))
4584 file_path[len++] = *rest_of_wildcards++;
4585
4586 file_path[len] = NUL;
4587 if (vim_ispathsep(*rest_of_wildcards))
4588 rest_of_wildcards++;
4589 }
4590#endif
4591
4592 /*
4593 * Expand wildcards like "*" and "$VAR".
4594 * If the path is a URL don't try this.
4595 */
4596 if (path_with_url(dirptrs[0]))
4597 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004598 stackp->ffs_filearray = (char_u **)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004599 alloc((unsigned)sizeof(char *));
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004600 if (stackp->ffs_filearray != NULL
4601 && (stackp->ffs_filearray[0]
Bram Moolenaar071d4272004-06-13 20:20:40 +00004602 = vim_strsave(dirptrs[0])) != NULL)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004603 stackp->ffs_filearray_size = 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004604 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004605 stackp->ffs_filearray_size = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004606 }
4607 else
4608 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004609 &stackp->ffs_filearray_size,
4610 &stackp->ffs_filearray,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611 EW_DIR|EW_ADDSLASH|EW_SILENT);
4612
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004613 stackp->ffs_filearray_cur = 0;
4614 stackp->ffs_stage = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615 }
4616#ifdef FEAT_PATH_EXTRA
4617 else
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004618 rest_of_wildcards = &stackp->ffs_wc_path[
4619 STRLEN(stackp->ffs_wc_path)];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004620#endif
4621
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004622 if (stackp->ffs_stage == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004623 {
4624 /* this is the first time we work on this directory */
4625#ifdef FEAT_PATH_EXTRA
4626 if (*rest_of_wildcards == NUL)
4627#endif
4628 {
4629 /*
4630 * we don't have further wildcards to expand, so we have to
4631 * check for the final file now
4632 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004633 for (i = stackp->ffs_filearray_cur;
4634 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004636 if (!path_with_url(stackp->ffs_filearray[i])
4637 && !mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 continue; /* not a directory */
4639
4640 /* prepare the filename to be checked for existance
4641 * below */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004642 STRCPY(file_path, stackp->ffs_filearray[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004643 add_pathsep(file_path);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004644 STRCAT(file_path, search_ctx->ffsc_file_to_search);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645
4646 /*
4647 * Try without extra suffix and then with suffixes
4648 * from 'suffixesadd'.
4649 */
4650#ifdef FEAT_SEARCHPATH
4651 len = (int)STRLEN(file_path);
4652 suf = curbuf->b_p_sua;
4653 for (;;)
4654#endif
4655 {
4656 /* if file exists and we didn't already find it */
4657 if ((path_with_url(file_path)
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004658 || (mch_getperm(file_path) >= 0
4659 && (search_ctx->ffsc_find_what
4660 == FINDFILE_BOTH
4661 || ((search_ctx->ffsc_find_what
4662 == FINDFILE_DIR)
4663 == mch_isdir(file_path)))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664#ifndef FF_VERBOSE
4665 && (ff_check_visited(
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004666 &search_ctx->ffsc_visited_list->ffvl_visited_list,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004667 file_path
4668#ifdef FEAT_PATH_EXTRA
4669 , (char_u *)""
4670#endif
4671 ) == OK)
4672#endif
4673 )
4674 {
4675#ifdef FF_VERBOSE
4676 if (ff_check_visited(
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004677 &search_ctx->ffsc_visited_list->ffvl_visited_list,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678 file_path
4679#ifdef FEAT_PATH_EXTRA
4680 , (char_u *)""
4681#endif
4682 ) == FAIL)
4683 {
4684 if (p_verbose >= 5)
4685 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004686 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004687 smsg((char_u *)"Already: %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004688 file_path);
4689 /* don't overwrite this either */
4690 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004691 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692 }
4693 continue;
4694 }
4695#endif
4696
4697 /* push dir to examine rest of subdirs later */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004698 stackp->ffs_filearray_cur = i + 1;
4699 ff_push(search_ctx, stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700
4701 simplify_filename(file_path);
4702 if (mch_dirname(ff_expand_buffer, MAXPATHL)
4703 == OK)
4704 {
4705 p = shorten_fname(file_path,
4706 ff_expand_buffer);
4707 if (p != NULL)
Bram Moolenaar446cb832008-06-24 21:56:24 +00004708 STRMOVE(file_path, p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004709 }
4710#ifdef FF_VERBOSE
4711 if (p_verbose >= 5)
4712 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004713 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004714 smsg((char_u *)"HIT: %s", file_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715 /* don't overwrite this either */
4716 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004717 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718 }
4719#endif
4720 return file_path;
4721 }
4722
4723#ifdef FEAT_SEARCHPATH
4724 /* Not found or found already, try next suffix. */
4725 if (*suf == NUL)
4726 break;
4727 copy_option_part(&suf, file_path + len,
4728 MAXPATHL - len, ",");
4729#endif
4730 }
4731 }
4732 }
4733#ifdef FEAT_PATH_EXTRA
4734 else
4735 {
4736 /*
4737 * still wildcards left, push the directories for further
4738 * search
4739 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004740 for (i = stackp->ffs_filearray_cur;
4741 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004743 if (!mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004744 continue; /* not a directory */
4745
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004746 ff_push(search_ctx,
4747 ff_create_stack_element(
4748 stackp->ffs_filearray[i],
4749 rest_of_wildcards,
4750 stackp->ffs_level - 1, 0));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004751 }
4752 }
4753#endif
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004754 stackp->ffs_filearray_cur = 0;
4755 stackp->ffs_stage = 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756 }
4757
4758#ifdef FEAT_PATH_EXTRA
4759 /*
4760 * if wildcards contains '**' we have to descent till we reach the
4761 * leaves of the directory tree.
4762 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004763 if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004765 for (i = stackp->ffs_filearray_cur;
4766 i < stackp->ffs_filearray_size; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004768 if (fnamecmp(stackp->ffs_filearray[i],
4769 stackp->ffs_fix_path) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770 continue; /* don't repush same directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004771 if (!mch_isdir(stackp->ffs_filearray[i]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004772 continue; /* not a directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004773 ff_push(search_ctx,
4774 ff_create_stack_element(stackp->ffs_filearray[i],
4775 stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776 }
4777 }
4778#endif
4779
4780 /* we are done with the current directory */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004781 ff_free_stack_element(stackp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004782
4783 }
4784
4785#ifdef FEAT_PATH_EXTRA
4786 /* If we reached this, we didn't find anything downwards.
4787 * Let's check if we should do an upward search.
4788 */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004789 if (search_ctx->ffsc_start_dir
4790 && search_ctx->ffsc_stopdirs_v != NULL && !got_int)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791 {
4792 ff_stack_T *sptr;
4793
4794 /* is the last starting directory in the stop list? */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004795 if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
4796 (int)(path_end - search_ctx->ffsc_start_dir),
4797 search_ctx->ffsc_stopdirs_v) == TRUE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004798 break;
4799
4800 /* cut of last dir */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004801 while (path_end > search_ctx->ffsc_start_dir
4802 && vim_ispathsep(*path_end))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803 path_end--;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004804 while (path_end > search_ctx->ffsc_start_dir
4805 && !vim_ispathsep(path_end[-1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806 path_end--;
4807 *path_end = 0;
4808 path_end--;
4809
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004810 if (*search_ctx->ffsc_start_dir == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004811 break;
4812
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004813 STRCPY(file_path, search_ctx->ffsc_start_dir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004814 add_pathsep(file_path);
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004815 STRCAT(file_path, search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004816
4817 /* create a new stack entry */
4818 sptr = ff_create_stack_element(file_path,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004819 search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820 if (sptr == NULL)
4821 break;
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004822 ff_push(search_ctx, sptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004823 }
4824 else
4825 break;
4826 }
4827#endif
4828
4829 vim_free(file_path);
4830 return NULL;
4831}
4832
4833/*
4834 * Free the list of lists of visited files and directories
4835 * Can handle it if the passed search_context is NULL;
4836 */
4837 void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004838vim_findfile_free_visited(search_ctx_arg)
4839 void *search_ctx_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840{
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004841 ff_search_ctx_T *search_ctx;
4842
4843 if (search_ctx_arg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004844 return;
4845
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00004846 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
4847 vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
4848 vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849}
4850
4851 static void
4852vim_findfile_free_visited_list(list_headp)
4853 ff_visited_list_hdr_T **list_headp;
4854{
4855 ff_visited_list_hdr_T *vp;
4856
4857 while (*list_headp != NULL)
4858 {
4859 vp = (*list_headp)->ffvl_next;
4860 ff_free_visited_list((*list_headp)->ffvl_visited_list);
4861
4862 vim_free((*list_headp)->ffvl_filename);
4863 vim_free(*list_headp);
4864 *list_headp = vp;
4865 }
4866 *list_headp = NULL;
4867}
4868
4869 static void
4870ff_free_visited_list(vl)
4871 ff_visited_T *vl;
4872{
4873 ff_visited_T *vp;
4874
4875 while (vl != NULL)
4876 {
4877 vp = vl->ffv_next;
4878#ifdef FEAT_PATH_EXTRA
4879 vim_free(vl->ffv_wc_path);
4880#endif
4881 vim_free(vl);
4882 vl = vp;
4883 }
4884 vl = NULL;
4885}
4886
4887/*
4888 * Returns the already visited list for the given filename. If none is found it
4889 * allocates a new one.
4890 */
4891 static ff_visited_list_hdr_T*
4892ff_get_visited_list(filename, list_headp)
4893 char_u *filename;
4894 ff_visited_list_hdr_T **list_headp;
4895{
4896 ff_visited_list_hdr_T *retptr = NULL;
4897
4898 /* check if a visited list for the given filename exists */
4899 if (*list_headp != NULL)
4900 {
4901 retptr = *list_headp;
4902 while (retptr != NULL)
4903 {
4904 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
4905 {
4906#ifdef FF_VERBOSE
4907 if (p_verbose >= 5)
4908 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004909 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004910 smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004911 filename);
4912 /* don't overwrite this either */
4913 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004914 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004915 }
4916#endif
4917 return retptr;
4918 }
4919 retptr = retptr->ffvl_next;
4920 }
4921 }
4922
4923#ifdef FF_VERBOSE
4924 if (p_verbose >= 5)
4925 {
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004926 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00004927 smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928 /* don't overwrite this either */
4929 msg_puts((char_u *)"\n");
Bram Moolenaar5c06f8b2005-05-31 22:14:58 +00004930 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00004931 }
4932#endif
4933
4934 /*
4935 * if we reach this we didn't find a list and we have to allocate new list
4936 */
4937 retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
4938 if (retptr == NULL)
4939 return NULL;
4940
4941 retptr->ffvl_visited_list = NULL;
4942 retptr->ffvl_filename = vim_strsave(filename);
4943 if (retptr->ffvl_filename == NULL)
4944 {
4945 vim_free(retptr);
4946 return NULL;
4947 }
4948 retptr->ffvl_next = *list_headp;
4949 *list_headp = retptr;
4950
4951 return retptr;
4952}
4953
4954#ifdef FEAT_PATH_EXTRA
4955/*
4956 * check if two wildcard paths are equal. Returns TRUE or FALSE.
4957 * They are equal if:
4958 * - both paths are NULL
4959 * - they have the same length
4960 * - char by char comparison is OK
4961 * - the only differences are in the counters behind a '**', so
4962 * '**\20' is equal to '**\24'
4963 */
4964 static int
4965ff_wc_equal(s1, s2)
4966 char_u *s1;
4967 char_u *s2;
4968{
4969 int i;
4970
4971 if (s1 == s2)
4972 return TRUE;
4973
4974 if (s1 == NULL || s2 == NULL)
4975 return FALSE;
4976
4977 if (STRLEN(s1) != STRLEN(s2))
4978 return FAIL;
4979
4980 for (i = 0; s1[i] != NUL && s2[i] != NUL; i++)
4981 {
4982 if (s1[i] != s2[i]
4983#ifdef CASE_INSENSITIVE_FILENAME
4984 && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i])
4985#endif
4986 )
4987 {
4988 if (i >= 2)
4989 if (s1[i-1] == '*' && s1[i-2] == '*')
4990 continue;
4991 else
4992 return FAIL;
4993 else
4994 return FAIL;
4995 }
4996 }
4997 return TRUE;
4998}
4999#endif
5000
5001/*
5002 * maintains the list of already visited files and dirs
5003 * returns FAIL if the given file/dir is already in the list
5004 * returns OK if it is newly added
5005 *
5006 * TODO: What to do on memory allocation problems?
5007 * -> return TRUE - Better the file is found several times instead of
5008 * never.
5009 */
5010 static int
5011ff_check_visited(visited_list, fname
5012#ifdef FEAT_PATH_EXTRA
5013 , wc_path
5014#endif
5015 )
5016 ff_visited_T **visited_list;
5017 char_u *fname;
5018#ifdef FEAT_PATH_EXTRA
5019 char_u *wc_path;
5020#endif
5021{
5022 ff_visited_T *vp;
5023#ifdef UNIX
5024 struct stat st;
5025 int url = FALSE;
5026#endif
5027
5028 /* For an URL we only compare the name, otherwise we compare the
5029 * device/inode (unix) or the full path name (not Unix). */
5030 if (path_with_url(fname))
5031 {
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005032 vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033#ifdef UNIX
5034 url = TRUE;
5035#endif
5036 }
5037 else
5038 {
5039 ff_expand_buffer[0] = NUL;
5040#ifdef UNIX
5041 if (mch_stat((char *)fname, &st) < 0)
5042#else
5043 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
5044#endif
5045 return FAIL;
5046 }
5047
5048 /* check against list of already visited files */
5049 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
5050 {
5051 if (
5052#ifdef UNIX
5053 !url
5054 ? (vp->ffv_dev == st.st_dev
5055 && vp->ffv_ino == st.st_ino)
5056 :
5057#endif
5058 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
5059 )
5060 {
5061#ifdef FEAT_PATH_EXTRA
5062 /* are the wildcard parts equal */
5063 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
5064#endif
5065 /* already visited */
5066 return FAIL;
5067 }
5068 }
5069
5070 /*
5071 * New file/dir. Add it to the list of visited files/dirs.
5072 */
5073 vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
5074 + STRLEN(ff_expand_buffer)));
5075
5076 if (vp != NULL)
5077 {
5078#ifdef UNIX
5079 if (!url)
5080 {
5081 vp->ffv_ino = st.st_ino;
5082 vp->ffv_dev = st.st_dev;
5083 vp->ffv_fname[0] = NUL;
5084 }
5085 else
5086 {
5087 vp->ffv_ino = 0;
5088 vp->ffv_dev = -1;
5089#endif
5090 STRCPY(vp->ffv_fname, ff_expand_buffer);
5091#ifdef UNIX
5092 }
5093#endif
5094#ifdef FEAT_PATH_EXTRA
5095 if (wc_path != NULL)
5096 vp->ffv_wc_path = vim_strsave(wc_path);
5097 else
5098 vp->ffv_wc_path = NULL;
5099#endif
5100
5101 vp->ffv_next = *visited_list;
5102 *visited_list = vp;
5103 }
5104
5105 return OK;
5106}
5107
5108/*
5109 * create stack element from given path pieces
5110 */
5111 static ff_stack_T *
5112ff_create_stack_element(fix_part,
5113#ifdef FEAT_PATH_EXTRA
5114 wc_part,
5115#endif
5116 level, star_star_empty)
5117 char_u *fix_part;
5118#ifdef FEAT_PATH_EXTRA
5119 char_u *wc_part;
5120#endif
5121 int level;
5122 int star_star_empty;
5123{
5124 ff_stack_T *new;
5125
5126 new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
5127 if (new == NULL)
5128 return NULL;
5129
5130 new->ffs_prev = NULL;
5131 new->ffs_filearray = NULL;
5132 new->ffs_filearray_size = 0;
5133 new->ffs_filearray_cur = 0;
5134 new->ffs_stage = 0;
5135 new->ffs_level = level;
5136 new->ffs_star_star_empty = star_star_empty;;
5137
5138 /* the following saves NULL pointer checks in vim_findfile */
5139 if (fix_part == NULL)
5140 fix_part = (char_u *)"";
5141 new->ffs_fix_path = vim_strsave(fix_part);
5142
5143#ifdef FEAT_PATH_EXTRA
5144 if (wc_part == NULL)
5145 wc_part = (char_u *)"";
5146 new->ffs_wc_path = vim_strsave(wc_part);
5147#endif
5148
5149 if (new->ffs_fix_path == NULL
5150#ifdef FEAT_PATH_EXTRA
5151 || new->ffs_wc_path == NULL
5152#endif
5153 )
5154 {
5155 ff_free_stack_element(new);
5156 new = NULL;
5157 }
5158
5159 return new;
5160}
5161
5162/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005163 * Push a dir on the directory stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005164 */
5165 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005166ff_push(search_ctx, stack_ptr)
5167 ff_search_ctx_T *search_ctx;
5168 ff_stack_T *stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005169{
5170 /* check for NULL pointer, not to return an error to the user, but
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005171 * to prevent a crash */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005172 if (stack_ptr != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005174 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
5175 search_ctx->ffsc_stack_ptr = stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005176 }
5177}
5178
5179/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005180 * Pop a dir from the directory stack.
5181 * Returns NULL if stack is empty.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182 */
5183 static ff_stack_T *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005184ff_pop(search_ctx)
5185 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186{
5187 ff_stack_T *sptr;
5188
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005189 sptr = search_ctx->ffsc_stack_ptr;
5190 if (search_ctx->ffsc_stack_ptr != NULL)
5191 search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005192
5193 return sptr;
5194}
5195
5196/*
5197 * free the given stack element
5198 */
5199 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005200ff_free_stack_element(stack_ptr)
5201 ff_stack_T *stack_ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202{
5203 /* vim_free handles possible NULL pointers */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005204 vim_free(stack_ptr->ffs_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005206 vim_free(stack_ptr->ffs_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207#endif
5208
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005209 if (stack_ptr->ffs_filearray != NULL)
5210 FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005211
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005212 vim_free(stack_ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213}
5214
5215/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005216 * Clear the search context, but NOT the visited list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217 */
5218 static void
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005219ff_clear(search_ctx)
5220 ff_search_ctx_T *search_ctx;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005221{
5222 ff_stack_T *sptr;
5223
5224 /* clear up stack */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005225 while ((sptr = ff_pop(search_ctx)) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005226 ff_free_stack_element(sptr);
5227
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005228 vim_free(search_ctx->ffsc_file_to_search);
5229 vim_free(search_ctx->ffsc_start_dir);
5230 vim_free(search_ctx->ffsc_fix_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005231#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005232 vim_free(search_ctx->ffsc_wc_path);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233#endif
5234
5235#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005236 if (search_ctx->ffsc_stopdirs_v != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237 {
5238 int i = 0;
5239
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005240 while (search_ctx->ffsc_stopdirs_v[i] != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005242 vim_free(search_ctx->ffsc_stopdirs_v[i]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005243 i++;
5244 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005245 vim_free(search_ctx->ffsc_stopdirs_v);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246 }
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005247 search_ctx->ffsc_stopdirs_v = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005248#endif
5249
5250 /* reset everything */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005251 search_ctx->ffsc_file_to_search = NULL;
5252 search_ctx->ffsc_start_dir = NULL;
5253 search_ctx->ffsc_fix_path = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005254#ifdef FEAT_PATH_EXTRA
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005255 search_ctx->ffsc_wc_path = NULL;
5256 search_ctx->ffsc_level = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005257#endif
5258}
5259
5260#ifdef FEAT_PATH_EXTRA
5261/*
5262 * check if the given path is in the stopdirs
5263 * returns TRUE if yes else FALSE
5264 */
5265 static int
5266ff_path_in_stoplist(path, path_len, stopdirs_v)
5267 char_u *path;
5268 int path_len;
5269 char_u **stopdirs_v;
5270{
5271 int i = 0;
5272
5273 /* eat up trailing path separators, except the first */
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00005274 while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005275 path_len--;
5276
5277 /* if no path consider it as match */
5278 if (path_len == 0)
5279 return TRUE;
5280
5281 for (i = 0; stopdirs_v[i] != NULL; i++)
5282 {
5283 if ((int)STRLEN(stopdirs_v[i]) > path_len)
5284 {
5285 /* match for parent directory. So '/home' also matches
5286 * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
5287 * '/home/r' would also match '/home/rks'
5288 */
5289 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00005290 && vim_ispathsep(stopdirs_v[i][path_len]))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291 return TRUE;
5292 }
5293 else
5294 {
5295 if (fnamecmp(stopdirs_v[i], path) == 0)
5296 return TRUE;
5297 }
5298 }
5299 return FALSE;
5300}
5301#endif
5302
5303#if defined(FEAT_SEARCHPATH) || defined(PROTO)
5304/*
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005305 * Find the file name "ptr[len]" in the path. Also finds directory names.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005306 *
5307 * On the first call set the parameter 'first' to TRUE to initialize
5308 * the search. For repeating calls to FALSE.
5309 *
5310 * Repeating calls will return other files called 'ptr[len]' from the path.
5311 *
5312 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
5313 * don't need valid values.
5314 *
5315 * If nothing found on the first call the option FNAME_MESS will issue the
5316 * message:
5317 * 'Can't find file "<file>" in path'
5318 * On repeating calls:
5319 * 'No more file "<file>" found in path'
5320 *
5321 * options:
5322 * FNAME_MESS give error message when not found
5323 *
5324 * Uses NameBuff[]!
5325 *
5326 * Returns an allocated string for the file name. NULL for error.
5327 *
5328 */
5329 char_u *
5330find_file_in_path(ptr, len, options, first, rel_fname)
5331 char_u *ptr; /* file name */
5332 int len; /* length of file name */
5333 int options;
5334 int first; /* use count'th matching file name */
5335 char_u *rel_fname; /* file name searching relative to */
5336{
5337 return find_file_in_path_option(ptr, len, options, first,
5338 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005339 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340}
5341
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005342static char_u *ff_file_to_find = NULL;
5343static void *fdip_search_ctx = NULL;
5344
5345#if defined(EXITFREE)
5346 static void
5347free_findfile()
5348{
5349 vim_free(ff_file_to_find);
5350 vim_findfile_cleanup(fdip_search_ctx);
5351}
5352#endif
5353
Bram Moolenaar071d4272004-06-13 20:20:40 +00005354/*
5355 * Find the directory name "ptr[len]" in the path.
5356 *
5357 * options:
5358 * FNAME_MESS give error message when not found
5359 *
5360 * Uses NameBuff[]!
5361 *
5362 * Returns an allocated string for the file name. NULL for error.
5363 */
5364 char_u *
5365find_directory_in_path(ptr, len, options, rel_fname)
5366 char_u *ptr; /* file name */
5367 int len; /* length of file name */
5368 int options;
5369 char_u *rel_fname; /* file name searching relative to */
5370{
5371 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005372 FINDFILE_DIR, rel_fname, (char_u *)"");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005373}
5374
Bram Moolenaar89cb5e02004-07-19 20:55:54 +00005375 char_u *
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005376find_file_in_path_option(ptr, len, options, first, path_option, find_what, rel_fname, suffixes)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005377 char_u *ptr; /* file name */
5378 int len; /* length of file name */
5379 int options;
5380 int first; /* use count'th matching file name */
5381 char_u *path_option; /* p_path or p_cdpath */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005382 int find_what; /* FINDFILE_FILE, _DIR or _BOTH */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383 char_u *rel_fname; /* file name we are looking relative to. */
Bram Moolenaar433f7c82006-03-21 21:29:36 +00005384 char_u *suffixes; /* list of suffixes, 'suffixesadd' option */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005385{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005386 static char_u *dir;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005387 static int did_findfile_init = FALSE;
5388 char_u save_char;
5389 char_u *file_name = NULL;
5390 char_u *buf = NULL;
5391 int rel_to_curdir;
5392#ifdef AMIGA
5393 struct Process *proc = (struct Process *)FindTask(0L);
5394 APTR save_winptr = proc->pr_WindowPtr;
5395
5396 /* Avoid a requester here for a volume that doesn't exist. */
5397 proc->pr_WindowPtr = (APTR)-1L;
5398#endif
5399
5400 if (first == TRUE)
5401 {
5402 /* copy file name into NameBuff, expanding environment variables */
5403 save_char = ptr[len];
5404 ptr[len] = NUL;
5405 expand_env(ptr, NameBuff, MAXPATHL);
5406 ptr[len] = save_char;
5407
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005408 vim_free(ff_file_to_find);
5409 ff_file_to_find = vim_strsave(NameBuff);
5410 if (ff_file_to_find == NULL) /* out of memory */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411 {
5412 file_name = NULL;
5413 goto theend;
5414 }
5415 }
5416
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005417 rel_to_curdir = (ff_file_to_find[0] == '.'
5418 && (ff_file_to_find[1] == NUL
5419 || vim_ispathsep(ff_file_to_find[1])
5420 || (ff_file_to_find[1] == '.'
5421 && (ff_file_to_find[2] == NUL
5422 || vim_ispathsep(ff_file_to_find[2])))));
5423 if (vim_isAbsName(ff_file_to_find)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005424 /* "..", "../path", "." and "./path": don't use the path_option */
5425 || rel_to_curdir
5426#if defined(MSWIN) || defined(MSDOS) || defined(OS2)
5427 /* handle "\tmp" as absolute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005428 || vim_ispathsep(ff_file_to_find[0])
Bram Moolenaar071d4272004-06-13 20:20:40 +00005429 /* handle "c:name" as absulute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005430 || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005431#endif
5432#ifdef AMIGA
5433 /* handle ":tmp" as absolute path */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005434 || ff_file_to_find[0] == ':'
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435#endif
5436 )
5437 {
5438 /*
5439 * Absolute path, no need to use "path_option".
5440 * If this is not a first call, return NULL. We already returned a
5441 * filename on the first call.
5442 */
5443 if (first == TRUE)
5444 {
5445 int l;
5446 int run;
5447
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005448 if (path_with_url(ff_file_to_find))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005449 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005450 file_name = vim_strsave(ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005451 goto theend;
5452 }
5453
5454 /* When FNAME_REL flag given first use the directory of the file.
5455 * Otherwise or when this fails use the current directory. */
5456 for (run = 1; run <= 2; ++run)
5457 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005458 l = (int)STRLEN(ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005459 if (run == 1
5460 && rel_to_curdir
5461 && (options & FNAME_REL)
5462 && rel_fname != NULL
5463 && STRLEN(rel_fname) + l < MAXPATHL)
5464 {
5465 STRCPY(NameBuff, rel_fname);
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005466 STRCPY(gettail(NameBuff), ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005467 l = (int)STRLEN(NameBuff);
5468 }
5469 else
5470 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005471 STRCPY(NameBuff, ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472 run = 2;
5473 }
5474
5475 /* When the file doesn't exist, try adding parts of
5476 * 'suffixesadd'. */
Bram Moolenaar433f7c82006-03-21 21:29:36 +00005477 buf = suffixes;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005478 for (;;)
5479 {
5480 if (
5481#ifdef DJGPP
5482 /* "C:" by itself will fail for mch_getperm(),
5483 * assume it's always valid. */
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005484 (find_what != FINDFILE_FILE && NameBuff[0] != NUL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005485 && NameBuff[1] == ':'
5486 && NameBuff[2] == NUL) ||
5487#endif
5488 (mch_getperm(NameBuff) >= 0
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005489 && (find_what == FINDFILE_BOTH
5490 || ((find_what == FINDFILE_DIR)
5491 == mch_isdir(NameBuff)))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005492 {
5493 file_name = vim_strsave(NameBuff);
5494 goto theend;
5495 }
5496 if (*buf == NUL)
5497 break;
5498 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5499 }
5500 }
5501 }
5502 }
5503 else
5504 {
5505 /*
5506 * Loop over all paths in the 'path' or 'cdpath' option.
5507 * When "first" is set, first setup to the start of the option.
5508 * Otherwise continue to find the next match.
5509 */
5510 if (first == TRUE)
5511 {
5512 /* vim_findfile_free_visited can handle a possible NULL pointer */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005513 vim_findfile_free_visited(fdip_search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005514 dir = path_option;
5515 did_findfile_init = FALSE;
5516 }
5517
5518 for (;;)
5519 {
5520 if (did_findfile_init)
5521 {
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005522 file_name = vim_findfile(fdip_search_ctx);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 if (file_name != NULL)
5524 break;
5525
5526 did_findfile_init = FALSE;
5527 }
5528 else
5529 {
5530 char_u *r_ptr;
5531
5532 if (dir == NULL || *dir == NUL)
5533 {
5534 /* We searched all paths of the option, now we can
5535 * free the search context. */
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005536 vim_findfile_cleanup(fdip_search_ctx);
5537 fdip_search_ctx = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005538 break;
5539 }
5540
5541 if ((buf = alloc((int)(MAXPATHL))) == NULL)
5542 break;
5543
5544 /* copy next path */
5545 buf[0] = 0;
5546 copy_option_part(&dir, buf, MAXPATHL, " ,");
5547
5548#ifdef FEAT_PATH_EXTRA
5549 /* get the stopdir string */
5550 r_ptr = vim_findfile_stopdir(buf);
5551#else
5552 r_ptr = NULL;
5553#endif
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005554 fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005555 r_ptr, 100, FALSE, find_what,
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005556 fdip_search_ctx, FALSE, rel_fname);
5557 if (fdip_search_ctx != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 did_findfile_init = TRUE;
5559 vim_free(buf);
5560 }
5561 }
5562 }
5563 if (file_name == NULL && (options & FNAME_MESS))
5564 {
5565 if (first == TRUE)
5566 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005567 if (find_what == FINDFILE_DIR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568 EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005569 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005570 else
5571 EMSG2(_("E345: Can't find file \"%s\" in path"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005572 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573 }
5574 else
5575 {
Bram Moolenaar4d0ec162008-02-20 11:24:52 +00005576 if (find_what == FINDFILE_DIR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577 EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005578 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005579 else
5580 EMSG2(_("E347: No more file \"%s\" found in path"),
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005581 ff_file_to_find);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582 }
5583 }
5584
5585theend:
5586#ifdef AMIGA
5587 proc->pr_WindowPtr = save_winptr;
5588#endif
5589 return file_name;
5590}
5591
5592#endif /* FEAT_SEARCHPATH */
5593
5594/*
5595 * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search
5596 * 'cdpath' for relative directory names, otherwise just mch_chdir().
5597 */
5598 int
5599vim_chdir(new_dir)
5600 char_u *new_dir;
5601{
5602#ifndef FEAT_SEARCHPATH
5603 return mch_chdir((char *)new_dir);
5604#else
5605 char_u *dir_name;
5606 int r;
5607
5608 dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
5609 FNAME_MESS, curbuf->b_ffname);
5610 if (dir_name == NULL)
5611 return -1;
5612 r = mch_chdir((char *)dir_name);
5613 vim_free(dir_name);
5614 return r;
5615#endif
5616}
5617
5618/*
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005619 * Get user name from machine-specific function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 * Returns the user name in "buf[len]".
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005621 * Some systems are quite slow in obtaining the user name (Windows NT), thus
5622 * cache the result.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 * Returns OK or FAIL.
5624 */
5625 int
5626get_user_name(buf, len)
5627 char_u *buf;
5628 int len;
5629{
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005630 if (username == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005631 {
5632 if (mch_get_user_name(buf, len) == FAIL)
5633 return FAIL;
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00005634 username = vim_strsave(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005635 }
5636 else
Bram Moolenaarbbebc852005-07-18 21:47:53 +00005637 vim_strncpy(buf, username, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638 return OK;
5639}
5640
5641#ifndef HAVE_QSORT
5642/*
5643 * Our own qsort(), for systems that don't have it.
5644 * It's simple and slow. From the K&R C book.
5645 */
5646 void
5647qsort(base, elm_count, elm_size, cmp)
5648 void *base;
5649 size_t elm_count;
5650 size_t elm_size;
5651 int (*cmp) __ARGS((const void *, const void *));
5652{
5653 char_u *buf;
5654 char_u *p1;
5655 char_u *p2;
5656 int i, j;
5657 int gap;
5658
5659 buf = alloc((unsigned)elm_size);
5660 if (buf == NULL)
5661 return;
5662
5663 for (gap = elm_count / 2; gap > 0; gap /= 2)
5664 for (i = gap; i < elm_count; ++i)
5665 for (j = i - gap; j >= 0; j -= gap)
5666 {
5667 /* Compare the elements. */
5668 p1 = (char_u *)base + j * elm_size;
5669 p2 = (char_u *)base + (j + gap) * elm_size;
5670 if ((*cmp)((void *)p1, (void *)p2) <= 0)
5671 break;
5672 /* Exchange the elemets. */
5673 mch_memmove(buf, p1, elm_size);
5674 mch_memmove(p1, p2, elm_size);
5675 mch_memmove(p2, buf, elm_size);
5676 }
5677
5678 vim_free(buf);
5679}
5680#endif
5681
Bram Moolenaar071d4272004-06-13 20:20:40 +00005682/*
5683 * Sort an array of strings.
5684 */
5685static int
5686#ifdef __BORLANDC__
5687_RTLENTRYF
5688#endif
5689sort_compare __ARGS((const void *s1, const void *s2));
5690
5691 static int
5692#ifdef __BORLANDC__
5693_RTLENTRYF
5694#endif
5695sort_compare(s1, s2)
5696 const void *s1;
5697 const void *s2;
5698{
5699 return STRCMP(*(char **)s1, *(char **)s2);
5700}
5701
5702 void
5703sort_strings(files, count)
5704 char_u **files;
5705 int count;
5706{
5707 qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
5708}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005709
5710#if !defined(NO_EXPANDPATH) || defined(PROTO)
5711/*
5712 * Compare path "p[]" to "q[]".
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005713 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 * Return value like strcmp(p, q), but consider path separators.
5715 */
5716 int
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005717pathcmp(p, q, maxlen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 const char *p, *q;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005719 int maxlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720{
5721 int i;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005722 const char *s = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005723
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005724 for (i = 0; maxlen < 0 || i < maxlen; ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 {
5726 /* End of "p": check if "q" also ends or just has a slash. */
5727 if (p[i] == NUL)
5728 {
5729 if (q[i] == NUL) /* full match */
5730 return 0;
5731 s = q;
5732 break;
5733 }
5734
5735 /* End of "q": check if "p" just has a slash. */
5736 if (q[i] == NUL)
5737 {
5738 s = p;
5739 break;
5740 }
5741
5742 if (
5743#ifdef CASE_INSENSITIVE_FILENAME
5744 TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i])
5745#else
5746 p[i] != q[i]
5747#endif
5748#ifdef BACKSLASH_IN_FILENAME
5749 /* consider '/' and '\\' to be equal */
5750 && !((p[i] == '/' && q[i] == '\\')
5751 || (p[i] == '\\' && q[i] == '/'))
5752#endif
5753 )
5754 {
5755 if (vim_ispathsep(p[i]))
5756 return -1;
5757 if (vim_ispathsep(q[i]))
5758 return 1;
5759 return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */
5760 }
5761 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005762 if (s == NULL) /* "i" ran into "maxlen" */
5763 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005764
5765 /* ignore a trailing slash, but not "//" or ":/" */
Bram Moolenaar86b68352004-12-27 21:59:20 +00005766 if (s[i + 1] == NUL
5767 && i > 0
5768 && !after_pathsep((char_u *)s, (char_u *)s + i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769#ifdef BACKSLASH_IN_FILENAME
Bram Moolenaar86b68352004-12-27 21:59:20 +00005770 && (s[i] == '/' || s[i] == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771#else
Bram Moolenaar86b68352004-12-27 21:59:20 +00005772 && s[i] == '/'
Bram Moolenaar071d4272004-06-13 20:20:40 +00005773#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005774 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 return 0; /* match with trailing slash */
5776 if (s == q)
5777 return -1; /* no match */
5778 return 1;
5779}
5780#endif
5781
Bram Moolenaar071d4272004-06-13 20:20:40 +00005782/*
5783 * The putenv() implementation below comes from the "screen" program.
5784 * Included with permission from Juergen Weigert.
5785 * See pty.c for the copyright notice.
5786 */
5787
5788/*
5789 * putenv -- put value into environment
5790 *
5791 * Usage: i = putenv (string)
5792 * int i;
5793 * char *string;
5794 *
5795 * where string is of the form <name>=<value>.
5796 * Putenv returns 0 normally, -1 on error (not enough core for malloc).
5797 *
5798 * Putenv may need to add a new name into the environment, or to
5799 * associate a value longer than the current value with a particular
5800 * name. So, to make life simpler, putenv() copies your entire
5801 * environment into the heap (i.e. malloc()) from the stack
5802 * (i.e. where it resides when your process is initiated) the first
5803 * time you call it.
5804 *
5805 * (history removed, not very interesting. See the "screen" sources.)
5806 */
5807
5808#if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
5809
5810#define EXTRASIZE 5 /* increment to add to env. size */
5811
5812static int envsize = -1; /* current size of environment */
5813#ifndef MACOS_CLASSIC
5814extern
5815#endif
5816 char **environ; /* the global which is your env. */
5817
5818static int findenv __ARGS((char *name)); /* look for a name in the env. */
5819static int newenv __ARGS((void)); /* copy env. from stack to heap */
5820static int moreenv __ARGS((void)); /* incr. size of env. */
5821
5822 int
5823putenv(string)
5824 const char *string;
5825{
5826 int i;
5827 char *p;
5828
5829 if (envsize < 0)
5830 { /* first time putenv called */
5831 if (newenv() < 0) /* copy env. to heap */
5832 return -1;
5833 }
5834
5835 i = findenv((char *)string); /* look for name in environment */
5836
5837 if (i < 0)
5838 { /* name must be added */
5839 for (i = 0; environ[i]; i++);
5840 if (i >= (envsize - 1))
5841 { /* need new slot */
5842 if (moreenv() < 0)
5843 return -1;
5844 }
5845 p = (char *)alloc((unsigned)(strlen(string) + 1));
5846 if (p == NULL) /* not enough core */
5847 return -1;
5848 environ[i + 1] = 0; /* new end of env. */
5849 }
5850 else
5851 { /* name already in env. */
5852 p = vim_realloc(environ[i], strlen(string) + 1);
5853 if (p == NULL)
5854 return -1;
5855 }
5856 sprintf(p, "%s", string); /* copy into env. */
5857 environ[i] = p;
5858
5859 return 0;
5860}
5861
5862 static int
5863findenv(name)
5864 char *name;
5865{
5866 char *namechar, *envchar;
5867 int i, found;
5868
5869 found = 0;
5870 for (i = 0; environ[i] && !found; i++)
5871 {
5872 envchar = environ[i];
5873 namechar = name;
5874 while (*namechar && *namechar != '=' && (*namechar == *envchar))
5875 {
5876 namechar++;
5877 envchar++;
5878 }
5879 found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
5880 }
5881 return found ? i - 1 : -1;
5882}
5883
5884 static int
5885newenv()
5886{
5887 char **env, *elem;
5888 int i, esize;
5889
5890#ifdef MACOS
5891 /* for Mac a new, empty environment is created */
5892 i = 0;
5893#else
5894 for (i = 0; environ[i]; i++)
5895 ;
5896#endif
5897 esize = i + EXTRASIZE + 1;
5898 env = (char **)alloc((unsigned)(esize * sizeof (elem)));
5899 if (env == NULL)
5900 return -1;
5901
5902#ifndef MACOS
5903 for (i = 0; environ[i]; i++)
5904 {
5905 elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
5906 if (elem == NULL)
5907 return -1;
5908 env[i] = elem;
5909 strcpy(elem, environ[i]);
5910 }
5911#endif
5912
5913 env[i] = 0;
5914 environ = env;
5915 envsize = esize;
5916 return 0;
5917}
5918
5919 static int
5920moreenv()
5921{
5922 int esize;
5923 char **env;
5924
5925 esize = envsize + EXTRASIZE;
5926 env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
5927 if (env == 0)
5928 return -1;
5929 environ = env;
5930 envsize = esize;
5931 return 0;
5932}
5933
5934# ifdef USE_VIMPTY_GETENV
5935 char_u *
5936vimpty_getenv(string)
5937 const char_u *string;
5938{
5939 int i;
5940 char_u *p;
5941
5942 if (envsize < 0)
5943 return NULL;
5944
5945 i = findenv((char *)string);
5946
5947 if (i < 0)
5948 return NULL;
5949
5950 p = vim_strchr((char_u *)environ[i], '=');
5951 return (p + 1);
5952}
5953# endif
5954
5955#endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
Bram Moolenaarc4a06d32005-06-07 21:04:49 +00005956
Bram Moolenaarc4956c82006-03-12 21:58:43 +00005957#if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
Bram Moolenaarc4a06d32005-06-07 21:04:49 +00005958/*
5959 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
5960 * rights to write into.
5961 */
5962 int
5963filewritable(fname)
5964 char_u *fname;
5965{
5966 int retval = 0;
5967#if defined(UNIX) || defined(VMS)
5968 int perm = 0;
5969#endif
5970
5971#if defined(UNIX) || defined(VMS)
5972 perm = mch_getperm(fname);
5973#endif
5974#ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */
5975 if (
5976# ifdef WIN3264
5977 mch_writable(fname) &&
5978# else
5979# if defined(UNIX) || defined(VMS)
5980 (perm & 0222) &&
5981# endif
5982# endif
5983 mch_access((char *)fname, W_OK) == 0
5984 )
5985#endif
5986 {
5987 ++retval;
5988 if (mch_isdir(fname))
5989 ++retval;
5990 }
5991 return retval;
5992}
5993#endif
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00005994
5995/*
5996 * Print an error message with one or two "%s" and one or two string arguments.
5997 * This is not in message.c to avoid a warning for prototypes.
5998 */
5999 int
6000emsg3(s, a1, a2)
6001 char_u *s, *a1, *a2;
6002{
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006003 if (emsg_not_now())
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006004 return TRUE; /* no error messages at the moment */
Bram Moolenaar6f192452007-11-08 19:49:02 +00006005#ifdef HAVE_STDARG_H
6006 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, a1, a2);
6007#else
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006008 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, (long_u)a1, (long_u)a2);
Bram Moolenaar6f192452007-11-08 19:49:02 +00006009#endif
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006010 return emsg(IObuff);
6011}
6012
6013/*
6014 * Print an error message with one "%ld" and one long int argument.
6015 * This is not in message.c to avoid a warning for prototypes.
6016 */
6017 int
6018emsgn(s, n)
6019 char_u *s;
6020 long n;
6021{
Bram Moolenaareb3593b2006-04-22 22:33:57 +00006022 if (emsg_not_now())
Bram Moolenaar6bab4d12005-06-16 21:53:56 +00006023 return TRUE; /* no error messages at the moment */
6024 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, n);
6025 return emsg(IObuff);
6026}