Merge branch 'vim' into feat/rel-line-numbers
[vim_extended.git] / src / misc2.c
blob20e6747d47f6a01e7324fc2200f4937c910f287b
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * misc2.c: Various functions.
13 #include "vim.h"
15 static char_u *username = NULL; /* cached result of mch_get_user_name() */
17 static char_u *ff_expand_buffer = NULL; /* used for expanding filenames */
19 #if defined(FEAT_VIRTUALEDIT) || defined(PROTO)
20 static int coladvance2 __ARGS((pos_T *pos, int addspaces, int finetune, colnr_T wcol));
23 * Return TRUE if in the current mode we need to use virtual.
25 int
26 virtual_active()
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)));
41 * Get the screen position of the cursor.
43 int
44 getviscol()
46 colnr_T x;
48 getvvcol(curwin, &curwin->w_cursor, &x, NULL, NULL);
49 return (int)x;
53 * Get the screen position of character col with a coladd in the cursor line.
55 int
56 getviscol2(col, coladd)
57 colnr_T col;
58 colnr_T coladd;
60 colnr_T x;
61 pos_T pos;
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;
71 * Go to column "wcol", and add/insert white space as necessary to get the
72 * cursor in that column.
73 * The caller must have saved the cursor line for undo!
75 int
76 coladvance_force(wcol)
77 colnr_T wcol;
79 int rc = coladvance2(&curwin->w_cursor, TRUE, FALSE, wcol);
81 if (wcol == MAXCOL)
82 curwin->w_valid &= ~VALID_VIRTCOL;
83 else
85 /* Virtcol is valid */
86 curwin->w_valid |= VALID_VIRTCOL;
87 curwin->w_virtcol = wcol;
89 return rc;
91 #endif
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.
100 * return OK if desired column is reached, FAIL if not
103 coladvance(wcol)
104 colnr_T wcol;
106 int rc = getvpos(&curwin->w_cursor, wcol);
108 if (wcol == MAXCOL || rc == FAIL)
109 curwin->w_valid &= ~VALID_VIRTCOL;
110 else if (*ml_get_cursor() != TAB)
112 /* Virtcol is valid when not on a TAB */
113 curwin->w_valid |= VALID_VIRTCOL;
114 curwin->w_virtcol = wcol;
116 return rc;
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
124 getvpos(pos, wcol)
125 pos_T *pos;
126 colnr_T wcol;
128 #ifdef FEAT_VIRTUALEDIT
129 return coladvance2(pos, FALSE, virtual_active(), wcol);
132 static int
133 coladvance2(pos, addspaces, finetune, wcol)
134 pos_T *pos;
135 int addspaces; /* change the text to achieve our goal? */
136 int finetune; /* change char offset for the exact column */
137 colnr_T wcol; /* column to move to */
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
150 one_more = (State & INSERT)
151 || restart_edit != NUL
152 #ifdef FEAT_VISUAL
153 || (VIsual_active && *p_sel != 'o')
154 #endif
155 #ifdef FEAT_VIRTUALEDIT
156 || ((ve_flags & VE_ONEMORE) && wcol < MAXCOL)
157 #endif
159 line = ml_get_buf(curbuf, pos->lnum, FALSE);
161 if (wcol >= MAXCOL)
163 idx = (int)STRLEN(line) - 1 + one_more;
164 col = wcol;
166 #ifdef FEAT_VIRTUALEDIT
167 if ((addspaces || finetune) && !VIsual_active)
169 curwin->w_curswant = linetabsize(line) + one_more;
170 if (curwin->w_curswant > 0)
171 --curwin->w_curswant;
173 #endif
175 else
177 #ifdef FEAT_VIRTUALEDIT
178 int width = W_WIDTH(curwin) - win_col_off(curwin);
180 if (finetune
181 && curwin->w_p_wrap
182 # ifdef FEAT_VERTSPLIT
183 && curwin->w_width != 0
184 # endif
185 && wcol >= (colnr_T)width)
187 csize = linetabsize(line);
188 if (csize > 0)
189 csize--;
191 if (wcol / width > (colnr_T)csize / width
192 && ((State & INSERT) == 0 || (int)wcol > csize + 1))
194 /* In case of line wrapping don't move the cursor beyond the
195 * 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). */
198 wcol = (csize / width + 1) * width - 1;
201 #endif
203 idx = -1;
204 ptr = line;
205 while (col <= wcol && *ptr != NUL)
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);
210 mb_ptr_adv(ptr);
211 #else
212 csize = lbr_chartabsize_adv(&ptr, col);
213 #endif
214 col += csize;
216 idx = (int)(ptr - line);
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.
223 if (col > wcol || (!virtual_active() && one_more == 0))
225 idx -= 1;
226 # ifdef FEAT_LINEBREAK
227 /* Don't count the chars from 'showbreak'. */
228 csize -= head;
229 # endif
230 col -= csize;
233 #ifdef FEAT_VIRTUALEDIT
234 if (virtual_active()
235 && addspaces
236 && ((col != wcol && col != wcol + 1) || csize > 1))
238 /* 'virtualedit' is set: The difference between wcol and col is
239 * filled with spaces. */
241 if (line[idx] == NUL)
243 /* Append spaces */
244 int correct = wcol - col;
245 char_u *newline = alloc(idx + correct + 1);
246 int t;
248 if (newline == NULL)
249 return FAIL;
251 for (t = 0; t < idx; ++t)
252 newline[t] = line[t];
254 for (t = 0; t < correct; ++t)
255 newline[t + idx] = ' ';
257 newline[idx + correct] = NUL;
259 ml_replace(pos->lnum, newline, FALSE);
260 changed_bytes(pos->lnum, (colnr_T)idx);
261 idx += correct;
262 col = wcol;
264 else
266 /* Break a tab */
267 int linelen = (int)STRLEN(line);
268 int correct = wcol - col - csize + 1; /* negative!! */
269 char_u *newline;
270 int t, s = 0;
271 int v;
273 if (-correct > csize)
274 return FAIL;
276 newline = alloc(linelen + csize);
277 if (newline == NULL)
278 return FAIL;
280 for (t = 0; t < linelen; t++)
282 if (t != idx)
283 newline[s++] = line[t];
284 else
285 for (v = 0; v < csize; v++)
286 newline[s++] = ' ';
289 newline[linelen + csize - 1] = NUL;
291 ml_replace(pos->lnum, newline, FALSE);
292 changed_bytes(pos->lnum, idx);
293 idx += (csize - 1 + correct);
294 col += correct;
297 #endif
300 if (idx < 0)
301 pos->col = 0;
302 else
303 pos->col = idx;
305 #ifdef FEAT_VIRTUALEDIT
306 pos->coladd = 0;
308 if (finetune)
310 if (wcol == MAXCOL)
312 /* The width of the last character is used to set coladd. */
313 if (!one_more)
315 colnr_T scol, ecol;
317 getvcol(curwin, pos, &scol, NULL, &ecol);
318 pos->coladd = ecol - scol;
321 else
323 int b = (int)wcol - (int)col;
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;
329 col += b;
332 #endif
334 #ifdef FEAT_MBYTE
335 /* prevent from moving onto a trail byte */
336 if (has_mbyte)
337 mb_adjustpos(pos);
338 #endif
340 if (col < wcol)
341 return FAIL;
342 return OK;
346 * Increment the cursor position. See inc() for return values.
349 inc_cursor()
351 return inc(&curwin->w_cursor);
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.
362 inc(lp)
363 pos_T *lp;
365 char_u *p = ml_get_pos(lp);
367 if (*p != NUL) /* still within line, move to next char (may be NUL) */
369 #ifdef FEAT_MBYTE
370 if (has_mbyte)
372 int l = (*mb_ptr2len)(p);
374 lp->col += l;
375 return ((p[l] != NUL) ? 0 : 2);
377 #endif
378 lp->col++;
379 #ifdef FEAT_VIRTUALEDIT
380 lp->coladd = 0;
381 #endif
382 return ((p[1] != NUL) ? 0 : 2);
384 if (lp->lnum != curbuf->b_ml.ml_line_count) /* there is a next line */
386 lp->col = 0;
387 lp->lnum++;
388 #ifdef FEAT_VIRTUALEDIT
389 lp->coladd = 0;
390 #endif
391 return 1;
393 return -1;
397 * incl(lp): same as inc(), but skip the NUL at the end of non-empty lines
400 incl(lp)
401 pos_T *lp;
403 int r;
405 if ((r = inc(lp)) >= 1 && lp->col)
406 r = inc(lp);
407 return r;
411 * dec(p)
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.
417 dec_cursor()
419 return dec(&curwin->w_cursor);
423 dec(lp)
424 pos_T *lp;
426 char_u *p;
428 #ifdef FEAT_VIRTUALEDIT
429 lp->coladd = 0;
430 #endif
431 if (lp->col > 0) /* still within line */
433 lp->col--;
434 #ifdef FEAT_MBYTE
435 if (has_mbyte)
437 p = ml_get(lp->lnum);
438 lp->col -= (*mb_head_off)(p, p + lp->col);
440 #endif
441 return 0;
443 if (lp->lnum > 1) /* there is a prior line */
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;
454 return -1; /* at start of file */
458 * decl(lp): same as dec(), but skip the NUL at the end of non-empty lines
461 decl(lp)
462 pos_T *lp;
464 int r;
466 if ((r = dec(lp)) == 1 && lp->col)
467 r = dec(lp);
468 return r;
472 * Get the line number relative to the actual cursor position, i.e. the
473 * difference between line number and cursor position. Only look for lines that
474 * can be visible, folded lines don't count.
476 linenr_T
477 get_cursor_rel_lnum(wp, lnum)
478 win_T *wp;
479 linenr_T lnum; /* line number to get the result for */
481 linenr_T cursor = wp->w_cursor.lnum;
482 linenr_T retval = 0;
484 #ifdef FEAT_FOLDING
485 if (hasAnyFolding(wp))
487 if (lnum > cursor)
489 while (lnum > cursor)
491 (void)hasFolding(lnum, &lnum, NULL);
492 /* if lnum and cursor are in the same fold,
493 * now lnum <= cursor */
494 if (lnum > cursor)
495 retval++;
496 lnum--;
499 else if (lnum < cursor)
501 while (lnum < cursor)
503 (void)hasFolding(lnum, NULL, &lnum);
504 /* if lnum and cursor are in the same fold,
505 * now lnum >= cursor */
506 if (lnum < cursor)
507 retval--;
508 lnum++;
511 /* else if (lnum == cursor)
512 * retval = 0;
515 else
516 #endif
517 retval = lnum - cursor;
519 return retval;
523 * Make sure curwin->w_cursor.lnum is valid.
525 void
526 check_cursor_lnum()
528 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
530 #ifdef FEAT_FOLDING
531 /* If there is a closed fold at the end of the file, put the cursor in
532 * its first line. Otherwise in the last line. */
533 if (!hasFolding(curbuf->b_ml.ml_line_count,
534 &curwin->w_cursor.lnum, NULL))
535 #endif
536 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
538 if (curwin->w_cursor.lnum <= 0)
539 curwin->w_cursor.lnum = 1;
543 * Make sure curwin->w_cursor.col is valid.
545 void
546 check_cursor_col()
548 colnr_T len;
549 #ifdef FEAT_VIRTUALEDIT
550 colnr_T oldcol = curwin->w_cursor.col;
551 colnr_T oldcoladd = curwin->w_cursor.col + curwin->w_cursor.coladd;
552 #endif
554 len = (colnr_T)STRLEN(ml_get_curline());
555 if (len == 0)
556 curwin->w_cursor.col = 0;
557 else if (curwin->w_cursor.col >= len)
559 /* Allow cursor past end-of-line when:
560 * - in Insert mode or restarting Insert mode
561 * - in Visual mode and 'selection' isn't "old"
562 * - 'virtualedit' is set */
563 if ((State & INSERT) || restart_edit
564 #ifdef FEAT_VISUAL
565 || (VIsual_active && *p_sel != 'o')
566 #endif
567 #ifdef FEAT_VIRTUALEDIT
568 || (ve_flags & VE_ONEMORE)
569 #endif
570 || virtual_active())
571 curwin->w_cursor.col = len;
572 else
574 curwin->w_cursor.col = len - 1;
575 #ifdef FEAT_MBYTE
576 /* prevent cursor from moving on the trail byte */
577 if (has_mbyte)
578 mb_adjust_cursor();
579 #endif
583 #ifdef FEAT_VIRTUALEDIT
584 /* If virtual editing is on, we can leave the cursor on the old position,
585 * only we must set it to virtual. But don't do it when at the end of the
586 * line. */
587 if (oldcol == MAXCOL)
588 curwin->w_cursor.coladd = 0;
589 else if (ve_flags == VE_ALL)
591 if (oldcoladd > curwin->w_cursor.col)
592 curwin->w_cursor.coladd = oldcoladd - curwin->w_cursor.col;
593 else
594 /* avoid weird number when there is a miscalculation or overflow */
595 curwin->w_cursor.coladd = 0;
597 #endif
601 * make sure curwin->w_cursor in on a valid character
603 void
604 check_cursor()
606 check_cursor_lnum();
607 check_cursor_col();
610 #if defined(FEAT_TEXTOBJ) || defined(PROTO)
612 * Make sure curwin->w_cursor is not on the NUL at the end of the line.
613 * Allow it when in Visual mode and 'selection' is not "old".
615 void
616 adjust_cursor_col()
618 if (curwin->w_cursor.col > 0
619 # ifdef FEAT_VISUAL
620 && (!VIsual_active || *p_sel == 'o')
621 # endif
622 && gchar_cursor() == NUL)
623 --curwin->w_cursor.col;
625 #endif
628 * When curwin->w_leftcol has changed, adjust the cursor position.
629 * Return TRUE if the cursor was moved.
632 leftcol_changed()
634 long lastcol;
635 colnr_T s, e;
636 int retval = FALSE;
638 changed_cline_bef_curs();
639 lastcol = curwin->w_leftcol + W_WIDTH(curwin) - curwin_col_off() - 1;
640 validate_virtcol();
643 * If the cursor is right or left of the screen, move it to last or first
644 * character.
646 if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso))
648 retval = TRUE;
649 coladvance((colnr_T)(lastcol - p_siso));
651 else if (curwin->w_virtcol < curwin->w_leftcol + p_siso)
653 retval = TRUE;
654 (void)coladvance((colnr_T)(curwin->w_leftcol + p_siso));
658 * If the start of the character under the cursor is not on the screen,
659 * advance the cursor one more char. If this fails (last char of the
660 * line) adjust the scrolling.
662 getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
663 if (e > (colnr_T)lastcol)
665 retval = TRUE;
666 coladvance(s - 1);
668 else if (s < curwin->w_leftcol)
670 retval = TRUE;
671 if (coladvance(e + 1) == FAIL) /* there isn't another character */
673 curwin->w_leftcol = s; /* adjust w_leftcol instead */
674 changed_cline_bef_curs();
678 if (retval)
679 curwin->w_set_curswant = TRUE;
680 redraw_later(NOT_VALID);
681 return retval;
684 /**********************************************************************
685 * Various routines dealing with allocation and deallocation of memory.
688 #if defined(MEM_PROFILE) || defined(PROTO)
690 # define MEM_SIZES 8200
691 static long_u mem_allocs[MEM_SIZES];
692 static long_u mem_frees[MEM_SIZES];
693 static long_u mem_allocated;
694 static long_u mem_freed;
695 static long_u mem_peak;
696 static long_u num_alloc;
697 static long_u num_freed;
699 static void mem_pre_alloc_s __ARGS((size_t *sizep));
700 static void mem_pre_alloc_l __ARGS((long_u *sizep));
701 static void mem_post_alloc __ARGS((void **pp, size_t size));
702 static void mem_pre_free __ARGS((void **pp));
704 static void
705 mem_pre_alloc_s(sizep)
706 size_t *sizep;
708 *sizep += sizeof(size_t);
711 static void
712 mem_pre_alloc_l(sizep)
713 long_u *sizep;
715 *sizep += sizeof(size_t);
718 static void
719 mem_post_alloc(pp, size)
720 void **pp;
721 size_t size;
723 if (*pp == NULL)
724 return;
725 size -= sizeof(size_t);
726 *(long_u *)*pp = size;
727 if (size <= MEM_SIZES-1)
728 mem_allocs[size-1]++;
729 else
730 mem_allocs[MEM_SIZES-1]++;
731 mem_allocated += size;
732 if (mem_allocated - mem_freed > mem_peak)
733 mem_peak = mem_allocated - mem_freed;
734 num_alloc++;
735 *pp = (void *)((char *)*pp + sizeof(size_t));
738 static void
739 mem_pre_free(pp)
740 void **pp;
742 long_u size;
744 *pp = (void *)((char *)*pp - sizeof(size_t));
745 size = *(size_t *)*pp;
746 if (size <= MEM_SIZES-1)
747 mem_frees[size-1]++;
748 else
749 mem_frees[MEM_SIZES-1]++;
750 mem_freed += size;
751 num_freed++;
755 * called on exit via atexit()
757 void
758 vim_mem_profile_dump()
760 int i, j;
762 printf("\r\n");
763 j = 0;
764 for (i = 0; i < MEM_SIZES - 1; i++)
766 if (mem_allocs[i] || mem_frees[i])
768 if (mem_frees[i] > mem_allocs[i])
769 printf("\r\n%s", _("ERROR: "));
770 printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
771 j++;
772 if (j > 3)
774 j = 0;
775 printf("\r\n");
780 i = MEM_SIZES - 1;
781 if (mem_allocs[i])
783 printf("\r\n");
784 if (mem_frees[i] > mem_allocs[i])
785 printf(_("ERROR: "));
786 printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
789 printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
790 mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
791 printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
792 num_alloc, num_freed);
795 #endif /* MEM_PROFILE */
798 * Some memory is reserved for error messages and for being able to
799 * call mf_release_all(), which needs some memory for mf_trans_add().
801 #if defined(MSDOS) && !defined(DJGPP)
802 # define SMALL_MEM
803 # define KEEP_ROOM 8192L
804 #else
805 # define KEEP_ROOM (2 * 8192L)
806 #endif
809 * Note: if unsigned is 16 bits we can only allocate up to 64K with alloc().
810 * Use lalloc for larger blocks.
812 char_u *
813 alloc(size)
814 unsigned size;
816 return (lalloc((long_u)size, TRUE));
820 * Allocate memory and set all bytes to zero.
822 char_u *
823 alloc_clear(size)
824 unsigned size;
826 char_u *p;
828 p = (lalloc((long_u)size, TRUE));
829 if (p != NULL)
830 (void)vim_memset(p, 0, (size_t)size);
831 return p;
835 * alloc() with check for maximum line length
837 char_u *
838 alloc_check(size)
839 unsigned size;
841 #if !defined(UNIX) && !defined(__EMX__)
842 if (sizeof(int) == 2 && size > 0x7fff)
844 /* Don't hide this message */
845 emsg_silent = 0;
846 EMSG(_("E340: Line is becoming too long"));
847 return NULL;
849 #endif
850 return (lalloc((long_u)size, TRUE));
854 * Allocate memory like lalloc() and set all bytes to zero.
856 char_u *
857 lalloc_clear(size, message)
858 long_u size;
859 int message;
861 char_u *p;
863 p = (lalloc(size, message));
864 if (p != NULL)
865 (void)vim_memset(p, 0, (size_t)size);
866 return p;
870 * Low level memory allocation function.
871 * This is used often, KEEP IT FAST!
873 char_u *
874 lalloc(size, message)
875 long_u size;
876 int message;
878 char_u *p; /* pointer to new storage space */
879 static int releasing = FALSE; /* don't do mf_release_all() recursive */
880 int try_again;
881 #if defined(HAVE_AVAIL_MEM) && !defined(SMALL_MEM)
882 static long_u allocated = 0; /* allocated since last avail check */
883 #endif
885 /* Safety check for allocating zero bytes */
886 if (size == 0)
888 /* Don't hide this message */
889 emsg_silent = 0;
890 EMSGN(_("E341: Internal error: lalloc(%ld, )"), size);
891 return NULL;
894 #ifdef MEM_PROFILE
895 mem_pre_alloc_l(&size);
896 #endif
898 #if defined(MSDOS) && !defined(DJGPP)
899 if (size >= 0xfff0) /* in MSDOS we can't deal with >64K blocks */
900 p = NULL;
901 else
902 #endif
905 * Loop when out of memory: Try to release some memfile blocks and
906 * if some blocks are released call malloc again.
908 for (;;)
911 * Handle three kind of systems:
912 * 1. No check for available memory: Just return.
913 * 2. Slow check for available memory: call mch_avail_mem() after
914 * allocating KEEP_ROOM amount of memory.
915 * 3. Strict check for available memory: call mch_avail_mem()
917 if ((p = (char_u *)malloc((size_t)size)) != NULL)
919 #ifndef HAVE_AVAIL_MEM
920 /* 1. No check for available memory: Just return. */
921 goto theend;
922 #else
923 # ifndef SMALL_MEM
924 /* 2. Slow check for available memory: call mch_avail_mem() after
925 * allocating (KEEP_ROOM / 2) amount of memory. */
926 allocated += size;
927 if (allocated < KEEP_ROOM / 2)
928 goto theend;
929 allocated = 0;
930 # endif
931 /* 3. check for available memory: call mch_avail_mem() */
932 if (mch_avail_mem(TRUE) < KEEP_ROOM && !releasing)
934 free((char *)p); /* System is low... no go! */
935 p = NULL;
937 else
938 goto theend;
939 #endif
942 * Remember that mf_release_all() is being called to avoid an endless
943 * loop, because mf_release_all() may call alloc() recursively.
945 if (releasing)
946 break;
947 releasing = TRUE;
949 clear_sb_text(); /* free any scrollback text */
950 try_again = mf_release_all(); /* release as many blocks as possible */
951 #ifdef FEAT_EVAL
952 try_again |= garbage_collect(); /* cleanup recursive lists/dicts */
953 #endif
955 releasing = FALSE;
956 if (!try_again)
957 break;
960 if (message && p == NULL)
961 do_outofmem_msg(size);
963 theend:
964 #ifdef MEM_PROFILE
965 mem_post_alloc((void **)&p, (size_t)size);
966 #endif
967 return p;
970 #if defined(MEM_PROFILE) || defined(PROTO)
972 * realloc() with memory profiling.
974 void *
975 mem_realloc(ptr, size)
976 void *ptr;
977 size_t size;
979 void *p;
981 mem_pre_free(&ptr);
982 mem_pre_alloc_s(&size);
984 p = realloc(ptr, size);
986 mem_post_alloc(&p, size);
988 return p;
990 #endif
993 * Avoid repeating the error message many times (they take 1 second each).
994 * Did_outofmem_msg is reset when a character is read.
996 void
997 do_outofmem_msg(size)
998 long_u size;
1000 if (!did_outofmem_msg)
1002 /* Don't hide this message */
1003 emsg_silent = 0;
1004 EMSGN(_("E342: Out of memory! (allocating %lu bytes)"), size);
1005 did_outofmem_msg = TRUE;
1009 #if defined(EXITFREE) || defined(PROTO)
1011 # if defined(FEAT_SEARCHPATH)
1012 static void free_findfile __ARGS((void));
1013 # endif
1016 * Free everything that we allocated.
1017 * Can be used to detect memory leaks, e.g., with ccmalloc.
1018 * NOTE: This is tricky! Things are freed that functions depend on. Don't be
1019 * surprised if Vim crashes...
1020 * Some things can't be freed, esp. things local to a library function.
1022 void
1023 free_all_mem()
1025 buf_T *buf, *nextbuf;
1026 static int entered = FALSE;
1028 /* When we cause a crash here it is caught and Vim tries to exit cleanly.
1029 * Don't try freeing everything again. */
1030 if (entered)
1031 return;
1032 entered = TRUE;
1034 # ifdef FEAT_AUTOCMD
1035 block_autocmds(); /* don't want to trigger autocommands here */
1036 # endif
1038 # ifdef FEAT_WINDOWS
1039 /* close all tabs and windows */
1040 if (first_tabpage->tp_next != NULL)
1041 do_cmdline_cmd((char_u *)"tabonly!");
1042 if (firstwin != lastwin)
1043 do_cmdline_cmd((char_u *)"only!");
1044 # endif
1046 # if defined(FEAT_SPELL)
1047 /* Free all spell info. */
1048 spell_free_all();
1049 # endif
1051 # if defined(FEAT_USR_CMDS)
1052 /* Clear user commands (before deleting buffers). */
1053 ex_comclear(NULL);
1054 # endif
1056 # ifdef FEAT_MENU
1057 /* Clear menus. */
1058 do_cmdline_cmd((char_u *)"aunmenu *");
1059 # endif
1061 /* Clear mappings, abbreviations, breakpoints. */
1062 do_cmdline_cmd((char_u *)"mapclear");
1063 do_cmdline_cmd((char_u *)"mapclear!");
1064 do_cmdline_cmd((char_u *)"abclear");
1065 # if defined(FEAT_EVAL)
1066 do_cmdline_cmd((char_u *)"breakdel *");
1067 # endif
1068 # if defined(FEAT_PROFILE)
1069 do_cmdline_cmd((char_u *)"profdel *");
1070 # endif
1071 # if defined(FEAT_KEYMAP)
1072 do_cmdline_cmd((char_u *)"set keymap=");
1073 #endif
1075 # ifdef FEAT_TITLE
1076 free_titles();
1077 # endif
1078 # if defined(FEAT_SEARCHPATH)
1079 free_findfile();
1080 # endif
1082 /* Obviously named calls. */
1083 # if defined(FEAT_AUTOCMD)
1084 free_all_autocmds();
1085 # endif
1086 clear_termcodes();
1087 free_all_options();
1088 free_all_marks();
1089 alist_clear(&global_alist);
1090 free_homedir();
1091 free_search_patterns();
1092 free_old_sub();
1093 free_last_insert();
1094 free_prev_shellcmd();
1095 free_regexp_stuff();
1096 free_tag_stuff();
1097 free_cd_dir();
1098 # ifdef FEAT_SIGNS
1099 free_signs();
1100 # endif
1101 # ifdef FEAT_EVAL
1102 set_expr_line(NULL);
1103 # endif
1104 # ifdef FEAT_DIFF
1105 diff_clear(curtab);
1106 # endif
1107 clear_sb_text(); /* free any scrollback text */
1109 /* Free some global vars. */
1110 vim_free(username);
1111 # ifdef FEAT_CLIPBOARD
1112 vim_free(clip_exclude_prog);
1113 # endif
1114 vim_free(last_cmdline);
1115 # ifdef FEAT_CMDHIST
1116 vim_free(new_last_cmdline);
1117 # endif
1118 set_keep_msg(NULL, 0);
1119 vim_free(ff_expand_buffer);
1121 /* Clear cmdline history. */
1122 p_hi = 0;
1123 # ifdef FEAT_CMDHIST
1124 init_history();
1125 # endif
1127 #ifdef FEAT_QUICKFIX
1129 win_T *win;
1130 tabpage_T *tab;
1132 qf_free_all(NULL);
1133 /* Free all location lists */
1134 FOR_ALL_TAB_WINDOWS(tab, win)
1135 qf_free_all(win);
1137 #endif
1139 /* Close all script inputs. */
1140 close_all_scripts();
1142 #if defined(FEAT_WINDOWS)
1143 /* Destroy all windows. Must come before freeing buffers. */
1144 win_free_all();
1145 #endif
1147 /* Free all buffers. Reset 'autochdir' to avoid accessing things that
1148 * were freed already. */
1149 #ifdef FEAT_AUTOCHDIR
1150 p_acd = FALSE;
1151 #endif
1152 for (buf = firstbuf; buf != NULL; )
1154 nextbuf = buf->b_next;
1155 close_buffer(NULL, buf, DOBUF_WIPE);
1156 if (buf_valid(buf))
1157 buf = nextbuf; /* didn't work, try next one */
1158 else
1159 buf = firstbuf;
1162 #ifdef FEAT_ARABIC
1163 free_cmdline_buf();
1164 #endif
1166 /* Clear registers. */
1167 clear_registers();
1168 ResetRedobuff();
1169 ResetRedobuff();
1171 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
1172 vim_free(serverDelayedStartName);
1173 #endif
1175 /* highlight info */
1176 free_highlight();
1178 reset_last_sourcing();
1180 #ifdef FEAT_WINDOWS
1181 free_tabpage(first_tabpage);
1182 first_tabpage = NULL;
1183 #endif
1185 # ifdef UNIX
1186 /* Machine-specific free. */
1187 mch_free_mem();
1188 # endif
1190 /* message history */
1191 for (;;)
1192 if (delete_first_msg() == FAIL)
1193 break;
1195 # ifdef FEAT_EVAL
1196 eval_clear();
1197 # endif
1199 free_termoptions();
1201 /* screenlines (can't display anything now!) */
1202 free_screenlines();
1204 #if defined(USE_XSMP)
1205 xsmp_close();
1206 #endif
1207 #ifdef FEAT_GUI_GTK
1208 gui_mch_free_all();
1209 #endif
1210 clear_hl_tables();
1212 vim_free(IObuff);
1213 vim_free(NameBuff);
1215 #endif
1218 * copy a string into newly allocated memory
1220 char_u *
1221 vim_strsave(string)
1222 char_u *string;
1224 char_u *p;
1225 unsigned len;
1227 len = (unsigned)STRLEN(string) + 1;
1228 p = alloc(len);
1229 if (p != NULL)
1230 mch_memmove(p, string, (size_t)len);
1231 return p;
1234 char_u *
1235 vim_strnsave(string, len)
1236 char_u *string;
1237 int len;
1239 char_u *p;
1241 p = alloc((unsigned)(len + 1));
1242 if (p != NULL)
1244 STRNCPY(p, string, len);
1245 p[len] = NUL;
1247 return p;
1251 * Same as vim_strsave(), but any characters found in esc_chars are preceded
1252 * by a backslash.
1254 char_u *
1255 vim_strsave_escaped(string, esc_chars)
1256 char_u *string;
1257 char_u *esc_chars;
1259 return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE);
1263 * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape
1264 * characters where rem_backslash() would remove the backslash.
1265 * Escape the characters with "cc".
1267 char_u *
1268 vim_strsave_escaped_ext(string, esc_chars, cc, bsl)
1269 char_u *string;
1270 char_u *esc_chars;
1271 int cc;
1272 int bsl;
1274 char_u *p;
1275 char_u *p2;
1276 char_u *escaped_string;
1277 unsigned length;
1278 #ifdef FEAT_MBYTE
1279 int l;
1280 #endif
1283 * First count the number of backslashes required.
1284 * Then allocate the memory and insert them.
1286 length = 1; /* count the trailing NUL */
1287 for (p = string; *p; p++)
1289 #ifdef FEAT_MBYTE
1290 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1292 length += l; /* count a multibyte char */
1293 p += l - 1;
1294 continue;
1296 #endif
1297 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1298 ++length; /* count a backslash */
1299 ++length; /* count an ordinary char */
1301 escaped_string = alloc(length);
1302 if (escaped_string != NULL)
1304 p2 = escaped_string;
1305 for (p = string; *p; p++)
1307 #ifdef FEAT_MBYTE
1308 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1310 mch_memmove(p2, p, (size_t)l);
1311 p2 += l;
1312 p += l - 1; /* skip multibyte char */
1313 continue;
1315 #endif
1316 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1317 *p2++ = cc;
1318 *p2++ = *p;
1320 *p2 = NUL;
1322 return escaped_string;
1326 * Return TRUE when 'shell' has "csh" in the tail.
1329 csh_like_shell()
1331 return (strstr((char *)gettail(p_sh), "csh") != NULL);
1335 * Escape "string" for use as a shell argument with system().
1336 * This uses single quotes, except when we know we need to use double qoutes
1337 * (MS-DOS and MS-Windows without 'shellslash' set).
1338 * Escape a newline, depending on the 'shell' option.
1339 * When "do_special" is TRUE also replace "!", "%", "#" and things starting
1340 * with "<" like "<cfile>".
1341 * Returns the result in allocated memory, NULL if we have run out.
1343 char_u *
1344 vim_strsave_shellescape(string, do_special)
1345 char_u *string;
1346 int do_special;
1348 unsigned length;
1349 char_u *p;
1350 char_u *d;
1351 char_u *escaped_string;
1352 int l;
1353 int csh_like;
1355 /* Only csh and similar shells expand '!' within single quotes. For sh and
1356 * the like we must not put a backslash before it, it will be taken
1357 * literally. If do_special is set the '!' will be escaped twice.
1358 * Csh also needs to have "\n" escaped twice when do_special is set. */
1359 csh_like = csh_like_shell();
1361 /* First count the number of extra bytes required. */
1362 length = (unsigned)STRLEN(string) + 3; /* two quotes and a trailing NUL */
1363 for (p = string; *p != NUL; mb_ptr_adv(p))
1365 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1366 if (!p_ssl)
1368 if (*p == '"')
1369 ++length; /* " -> "" */
1371 else
1372 # endif
1373 if (*p == '\'')
1374 length += 3; /* ' => '\'' */
1375 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1377 ++length; /* insert backslash */
1378 if (csh_like && do_special)
1379 ++length; /* insert backslash */
1381 if (do_special && find_cmdline_var(p, &l) >= 0)
1383 ++length; /* insert backslash */
1384 p += l - 1;
1388 /* Allocate memory for the result and fill it. */
1389 escaped_string = alloc(length);
1390 if (escaped_string != NULL)
1392 d = escaped_string;
1394 /* add opening quote */
1395 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1396 if (!p_ssl)
1397 *d++ = '"';
1398 else
1399 # endif
1400 *d++ = '\'';
1402 for (p = string; *p != NUL; )
1404 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1405 if (!p_ssl)
1407 if (*p == '"')
1409 *d++ = '"';
1410 *d++ = '"';
1411 ++p;
1412 continue;
1415 else
1416 # endif
1417 if (*p == '\'')
1419 *d++ = '\'';
1420 *d++ = '\\';
1421 *d++ = '\'';
1422 *d++ = '\'';
1423 ++p;
1424 continue;
1426 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1428 *d++ = '\\';
1429 if (csh_like && do_special)
1430 *d++ = '\\';
1431 *d++ = *p++;
1432 continue;
1434 if (do_special && find_cmdline_var(p, &l) >= 0)
1436 *d++ = '\\'; /* insert backslash */
1437 while (--l >= 0) /* copy the var */
1438 *d++ = *p++;
1441 MB_COPY_CHAR(p, d);
1444 /* add terminating quote and finish with a NUL */
1445 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1446 if (!p_ssl)
1447 *d++ = '"';
1448 else
1449 # endif
1450 *d++ = '\'';
1451 *d = NUL;
1454 return escaped_string;
1458 * Like vim_strsave(), but make all characters uppercase.
1459 * This uses ASCII lower-to-upper case translation, language independent.
1461 char_u *
1462 vim_strsave_up(string)
1463 char_u *string;
1465 char_u *p1;
1467 p1 = vim_strsave(string);
1468 vim_strup(p1);
1469 return p1;
1473 * Like vim_strnsave(), but make all characters uppercase.
1474 * This uses ASCII lower-to-upper case translation, language independent.
1476 char_u *
1477 vim_strnsave_up(string, len)
1478 char_u *string;
1479 int len;
1481 char_u *p1;
1483 p1 = vim_strnsave(string, len);
1484 vim_strup(p1);
1485 return p1;
1489 * ASCII lower-to-upper case translation, language independent.
1491 void
1492 vim_strup(p)
1493 char_u *p;
1495 char_u *p2;
1496 int c;
1498 if (p != NULL)
1500 p2 = p;
1501 while ((c = *p2) != NUL)
1502 #ifdef EBCDIC
1503 *p2++ = isalpha(c) ? toupper(c) : c;
1504 #else
1505 *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20);
1506 #endif
1510 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
1512 * Make string "s" all upper-case and return it in allocated memory.
1513 * Handles multi-byte characters as well as possible.
1514 * Returns NULL when out of memory.
1516 char_u *
1517 strup_save(orig)
1518 char_u *orig;
1520 char_u *p;
1521 char_u *res;
1523 res = p = vim_strsave(orig);
1525 if (res != NULL)
1526 while (*p != NUL)
1528 # ifdef FEAT_MBYTE
1529 int l;
1531 if (enc_utf8)
1533 int c, uc;
1534 int nl;
1535 char_u *s;
1537 c = utf_ptr2char(p);
1538 uc = utf_toupper(c);
1540 /* Reallocate string when byte count changes. This is rare,
1541 * thus it's OK to do another malloc()/free(). */
1542 l = utf_ptr2len(p);
1543 nl = utf_char2len(uc);
1544 if (nl != l)
1546 s = alloc((unsigned)STRLEN(res) + 1 + nl - l);
1547 if (s == NULL)
1548 break;
1549 mch_memmove(s, res, p - res);
1550 STRCPY(s + (p - res) + nl, p + l);
1551 p = s + (p - res);
1552 vim_free(res);
1553 res = s;
1556 utf_char2bytes(uc, p);
1557 p += nl;
1559 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1560 p += l; /* skip multi-byte character */
1561 else
1562 # endif
1564 *p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */
1565 p++;
1569 return res;
1571 #endif
1574 * copy a space a number of times
1576 void
1577 copy_spaces(ptr, count)
1578 char_u *ptr;
1579 size_t count;
1581 size_t i = count;
1582 char_u *p = ptr;
1584 while (i--)
1585 *p++ = ' ';
1588 #if defined(FEAT_VISUALEXTRA) || defined(PROTO)
1590 * Copy a character a number of times.
1591 * Does not work for multi-byte charactes!
1593 void
1594 copy_chars(ptr, count, c)
1595 char_u *ptr;
1596 size_t count;
1597 int c;
1599 size_t i = count;
1600 char_u *p = ptr;
1602 while (i--)
1603 *p++ = c;
1605 #endif
1608 * delete spaces at the end of a string
1610 void
1611 del_trailing_spaces(ptr)
1612 char_u *ptr;
1614 char_u *q;
1616 q = ptr + STRLEN(ptr);
1617 while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1618 *q = NUL;
1622 * Like strncpy(), but always terminate the result with one NUL.
1623 * "to" must be "len + 1" long!
1625 void
1626 vim_strncpy(to, from, len)
1627 char_u *to;
1628 char_u *from;
1629 size_t len;
1631 STRNCPY(to, from, len);
1632 to[len] = NUL;
1636 * Isolate one part of a string option where parts are separated with
1637 * "sep_chars".
1638 * The part is copied into "buf[maxlen]".
1639 * "*option" is advanced to the next part.
1640 * The length is returned.
1643 copy_option_part(option, buf, maxlen, sep_chars)
1644 char_u **option;
1645 char_u *buf;
1646 int maxlen;
1647 char *sep_chars;
1649 int len = 0;
1650 char_u *p = *option;
1652 /* skip '.' at start of option part, for 'suffixes' */
1653 if (*p == '.')
1654 buf[len++] = *p++;
1655 while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1658 * Skip backslash before a separator character and space.
1660 if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1661 ++p;
1662 if (len < maxlen - 1)
1663 buf[len++] = *p;
1664 ++p;
1666 buf[len] = NUL;
1668 if (*p != NUL && *p != ',') /* skip non-standard separator */
1669 ++p;
1670 p = skip_to_option_part(p); /* p points to next file name */
1672 *option = p;
1673 return len;
1677 * Replacement for free() that ignores NULL pointers.
1678 * Also skip free() when exiting for sure, this helps when we caught a deadly
1679 * signal that was caused by a crash in free().
1681 void
1682 vim_free(x)
1683 void *x;
1685 if (x != NULL && !really_exiting)
1687 #ifdef MEM_PROFILE
1688 mem_pre_free(&x);
1689 #endif
1690 free(x);
1694 #ifndef HAVE_MEMSET
1695 void *
1696 vim_memset(ptr, c, size)
1697 void *ptr;
1698 int c;
1699 size_t size;
1701 char *p = ptr;
1703 while (size-- > 0)
1704 *p++ = c;
1705 return ptr;
1707 #endif
1709 #ifdef VIM_MEMCMP
1711 * Return zero when "b1" and "b2" are the same for "len" bytes.
1712 * Return non-zero otherwise.
1715 vim_memcmp(b1, b2, len)
1716 void *b1;
1717 void *b2;
1718 size_t len;
1720 char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1722 for ( ; len > 0; --len)
1724 if (*p1 != *p2)
1725 return 1;
1726 ++p1;
1727 ++p2;
1729 return 0;
1731 #endif
1733 #ifdef VIM_MEMMOVE
1735 * Version of memmove() that handles overlapping source and destination.
1736 * For systems that don't have a function that is guaranteed to do that (SYSV).
1738 void
1739 mch_memmove(dst_arg, src_arg, len)
1740 void *src_arg, *dst_arg;
1741 size_t len;
1744 * A void doesn't have a size, we use char pointers.
1746 char *dst = dst_arg, *src = src_arg;
1748 /* overlap, copy backwards */
1749 if (dst > src && dst < src + len)
1751 src += len;
1752 dst += len;
1753 while (len-- > 0)
1754 *--dst = *--src;
1756 else /* copy forwards */
1757 while (len-- > 0)
1758 *dst++ = *src++;
1760 #endif
1762 #if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1764 * Compare two strings, ignoring case, using current locale.
1765 * Doesn't work for multi-byte characters.
1766 * return 0 for match, < 0 for smaller, > 0 for bigger
1769 vim_stricmp(s1, s2)
1770 char *s1;
1771 char *s2;
1773 int i;
1775 for (;;)
1777 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1778 if (i != 0)
1779 return i; /* this character different */
1780 if (*s1 == NUL)
1781 break; /* strings match until NUL */
1782 ++s1;
1783 ++s2;
1785 return 0; /* strings match */
1787 #endif
1789 #if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1791 * Compare two strings, for length "len", ignoring case, using current locale.
1792 * Doesn't work for multi-byte characters.
1793 * return 0 for match, < 0 for smaller, > 0 for bigger
1796 vim_strnicmp(s1, s2, len)
1797 char *s1;
1798 char *s2;
1799 size_t len;
1801 int i;
1803 while (len > 0)
1805 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1806 if (i != 0)
1807 return i; /* this character different */
1808 if (*s1 == NUL)
1809 break; /* strings match until NUL */
1810 ++s1;
1811 ++s2;
1812 --len;
1814 return 0; /* strings match */
1816 #endif
1818 #if 0 /* currently not used */
1820 * Check if string "s2" appears somewhere in "s1" while ignoring case.
1821 * Return NULL if not, a pointer to the first occurrence if it does.
1823 char_u *
1824 vim_stristr(s1, s2)
1825 char_u *s1;
1826 char_u *s2;
1828 char_u *p;
1829 int len = STRLEN(s2);
1830 char_u *end = s1 + STRLEN(s1) - len;
1832 for (p = s1; p <= end; ++p)
1833 if (STRNICMP(p, s2, len) == 0)
1834 return p;
1835 return NULL;
1837 #endif
1840 * Version of strchr() and strrchr() that handle unsigned char strings
1841 * with characters from 128 to 255 correctly. It also doesn't return a
1842 * pointer to the NUL at the end of the string.
1844 char_u *
1845 vim_strchr(string, c)
1846 char_u *string;
1847 int c;
1849 char_u *p;
1850 int b;
1852 p = string;
1853 #ifdef FEAT_MBYTE
1854 if (enc_utf8 && c >= 0x80)
1856 while (*p != NUL)
1858 if (utf_ptr2char(p) == c)
1859 return p;
1860 p += (*mb_ptr2len)(p);
1862 return NULL;
1864 if (enc_dbcs != 0 && c > 255)
1866 int n2 = c & 0xff;
1868 c = ((unsigned)c >> 8) & 0xff;
1869 while ((b = *p) != NUL)
1871 if (b == c && p[1] == n2)
1872 return p;
1873 p += (*mb_ptr2len)(p);
1875 return NULL;
1877 if (has_mbyte)
1879 while ((b = *p) != NUL)
1881 if (b == c)
1882 return p;
1883 p += (*mb_ptr2len)(p);
1885 return NULL;
1887 #endif
1888 while ((b = *p) != NUL)
1890 if (b == c)
1891 return p;
1892 ++p;
1894 return NULL;
1898 * Version of strchr() that only works for bytes and handles unsigned char
1899 * strings with characters above 128 correctly. It also doesn't return a
1900 * pointer to the NUL at the end of the string.
1902 char_u *
1903 vim_strbyte(string, c)
1904 char_u *string;
1905 int c;
1907 char_u *p = string;
1909 while (*p != NUL)
1911 if (*p == c)
1912 return p;
1913 ++p;
1915 return NULL;
1919 * Search for last occurrence of "c" in "string".
1920 * Return NULL if not found.
1921 * Does not handle multi-byte char for "c"!
1923 char_u *
1924 vim_strrchr(string, c)
1925 char_u *string;
1926 int c;
1928 char_u *retval = NULL;
1929 char_u *p = string;
1931 while (*p)
1933 if (*p == c)
1934 retval = p;
1935 mb_ptr_adv(p);
1937 return retval;
1941 * Vim's version of strpbrk(), in case it's missing.
1942 * Don't generate a prototype for this, causes problems when it's not used.
1944 #ifndef PROTO
1945 # ifndef HAVE_STRPBRK
1946 # ifdef vim_strpbrk
1947 # undef vim_strpbrk
1948 # endif
1949 char_u *
1950 vim_strpbrk(s, charset)
1951 char_u *s;
1952 char_u *charset;
1954 while (*s)
1956 if (vim_strchr(charset, *s) != NULL)
1957 return s;
1958 mb_ptr_adv(s);
1960 return NULL;
1962 # endif
1963 #endif
1966 * Vim has its own isspace() function, because on some machines isspace()
1967 * can't handle characters above 128.
1970 vim_isspace(x)
1971 int x;
1973 return ((x >= 9 && x <= 13) || x == ' ');
1976 /************************************************************************
1977 * Functions for handling growing arrays.
1981 * Clear an allocated growing array.
1983 void
1984 ga_clear(gap)
1985 garray_T *gap;
1987 vim_free(gap->ga_data);
1988 ga_init(gap);
1992 * Clear a growing array that contains a list of strings.
1994 void
1995 ga_clear_strings(gap)
1996 garray_T *gap;
1998 int i;
2000 for (i = 0; i < gap->ga_len; ++i)
2001 vim_free(((char_u **)(gap->ga_data))[i]);
2002 ga_clear(gap);
2006 * Initialize a growing array. Don't forget to set ga_itemsize and
2007 * ga_growsize! Or use ga_init2().
2009 void
2010 ga_init(gap)
2011 garray_T *gap;
2013 gap->ga_data = NULL;
2014 gap->ga_maxlen = 0;
2015 gap->ga_len = 0;
2018 void
2019 ga_init2(gap, itemsize, growsize)
2020 garray_T *gap;
2021 int itemsize;
2022 int growsize;
2024 ga_init(gap);
2025 gap->ga_itemsize = itemsize;
2026 gap->ga_growsize = growsize;
2030 * Make room in growing array "gap" for at least "n" items.
2031 * Return FAIL for failure, OK otherwise.
2034 ga_grow(gap, n)
2035 garray_T *gap;
2036 int n;
2038 size_t len;
2039 char_u *pp;
2041 if (gap->ga_maxlen - gap->ga_len < n)
2043 if (n < gap->ga_growsize)
2044 n = gap->ga_growsize;
2045 len = gap->ga_itemsize * (gap->ga_len + n);
2046 pp = alloc_clear((unsigned)len);
2047 if (pp == NULL)
2048 return FAIL;
2049 gap->ga_maxlen = gap->ga_len + n;
2050 if (gap->ga_data != NULL)
2052 mch_memmove(pp, gap->ga_data,
2053 (size_t)(gap->ga_itemsize * gap->ga_len));
2054 vim_free(gap->ga_data);
2056 gap->ga_data = pp;
2058 return OK;
2062 * Concatenate a string to a growarray which contains characters.
2063 * Note: Does NOT copy the NUL at the end!
2065 void
2066 ga_concat(gap, s)
2067 garray_T *gap;
2068 char_u *s;
2070 int len = (int)STRLEN(s);
2072 if (ga_grow(gap, len) == OK)
2074 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
2075 gap->ga_len += len;
2080 * Append one byte to a growarray which contains bytes.
2082 void
2083 ga_append(gap, c)
2084 garray_T *gap;
2085 int c;
2087 if (ga_grow(gap, 1) == OK)
2089 *((char *)gap->ga_data + gap->ga_len) = c;
2090 ++gap->ga_len;
2094 /************************************************************************
2095 * functions that use lookup tables for various things, generally to do with
2096 * special key codes.
2100 * Some useful tables.
2103 static struct modmasktable
2105 short mod_mask; /* Bit-mask for particular key modifier */
2106 short mod_flag; /* Bit(s) for particular key modifier */
2107 char_u name; /* Single letter name of modifier */
2108 } mod_mask_table[] =
2110 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'},
2111 {MOD_MASK_META, MOD_MASK_META, (char_u)'T'},
2112 {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'},
2113 {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'},
2114 {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'},
2115 {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'},
2116 {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'},
2117 #ifdef MACOS
2118 {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'},
2119 #endif
2120 /* 'A' must be the last one */
2121 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'},
2122 {0, 0, NUL}
2126 * Shifted key terminal codes and their unshifted equivalent.
2127 * Don't add mouse codes here, they are handled separately!
2129 #define MOD_KEYS_ENTRY_SIZE 5
2131 static char_u modifier_keys_table[] =
2133 /* mod mask with modifier without modifier */
2134 MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */
2135 MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */
2136 MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */
2137 MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */
2138 MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */
2139 MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */
2140 MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */
2141 MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */
2142 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */
2143 MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */
2144 MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */
2145 MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */
2146 MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */
2147 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */
2148 MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */
2149 MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */
2150 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */
2151 MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */
2152 MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */
2153 MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */
2154 MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */
2155 MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */
2156 MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */
2157 MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */
2158 MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */
2159 MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */
2160 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */
2161 MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */
2162 MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */
2163 MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */
2164 MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */
2165 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */
2166 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */
2168 /* vt100 F1 */
2169 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1,
2170 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2,
2171 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3,
2172 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4,
2174 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */
2175 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2',
2176 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3',
2177 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4',
2178 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5',
2179 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6',
2180 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7',
2181 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8',
2182 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9',
2183 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */
2185 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1',
2186 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2',
2187 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3',
2188 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4',
2189 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5',
2190 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6',
2191 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7',
2192 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8',
2193 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9',
2194 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A',
2196 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B',
2197 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C',
2198 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D',
2199 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E',
2200 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F',
2201 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G',
2202 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H',
2203 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I',
2204 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J',
2205 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K',
2207 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L',
2208 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M',
2209 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N',
2210 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O',
2211 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P',
2212 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q',
2213 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R',
2215 /* TAB pseudo code*/
2216 MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB,
2221 static struct key_name_entry
2223 int key; /* Special key code or ascii value */
2224 char_u *name; /* Name of key */
2225 } key_names_table[] =
2227 {' ', (char_u *)"Space"},
2228 {TAB, (char_u *)"Tab"},
2229 {K_TAB, (char_u *)"Tab"},
2230 {NL, (char_u *)"NL"},
2231 {NL, (char_u *)"NewLine"}, /* Alternative name */
2232 {NL, (char_u *)"LineFeed"}, /* Alternative name */
2233 {NL, (char_u *)"LF"}, /* Alternative name */
2234 {CAR, (char_u *)"CR"},
2235 {CAR, (char_u *)"Return"}, /* Alternative name */
2236 {CAR, (char_u *)"Enter"}, /* Alternative name */
2237 {K_BS, (char_u *)"BS"},
2238 {K_BS, (char_u *)"BackSpace"}, /* Alternative name */
2239 {ESC, (char_u *)"Esc"},
2240 {CSI, (char_u *)"CSI"},
2241 {K_CSI, (char_u *)"xCSI"},
2242 {'|', (char_u *)"Bar"},
2243 {'\\', (char_u *)"Bslash"},
2244 {K_DEL, (char_u *)"Del"},
2245 {K_DEL, (char_u *)"Delete"}, /* Alternative name */
2246 {K_KDEL, (char_u *)"kDel"},
2247 {K_UP, (char_u *)"Up"},
2248 {K_DOWN, (char_u *)"Down"},
2249 {K_LEFT, (char_u *)"Left"},
2250 {K_RIGHT, (char_u *)"Right"},
2251 {K_XUP, (char_u *)"xUp"},
2252 {K_XDOWN, (char_u *)"xDown"},
2253 {K_XLEFT, (char_u *)"xLeft"},
2254 {K_XRIGHT, (char_u *)"xRight"},
2256 {K_F1, (char_u *)"F1"},
2257 {K_F2, (char_u *)"F2"},
2258 {K_F3, (char_u *)"F3"},
2259 {K_F4, (char_u *)"F4"},
2260 {K_F5, (char_u *)"F5"},
2261 {K_F6, (char_u *)"F6"},
2262 {K_F7, (char_u *)"F7"},
2263 {K_F8, (char_u *)"F8"},
2264 {K_F9, (char_u *)"F9"},
2265 {K_F10, (char_u *)"F10"},
2267 {K_F11, (char_u *)"F11"},
2268 {K_F12, (char_u *)"F12"},
2269 {K_F13, (char_u *)"F13"},
2270 {K_F14, (char_u *)"F14"},
2271 {K_F15, (char_u *)"F15"},
2272 {K_F16, (char_u *)"F16"},
2273 {K_F17, (char_u *)"F17"},
2274 {K_F18, (char_u *)"F18"},
2275 {K_F19, (char_u *)"F19"},
2276 {K_F20, (char_u *)"F20"},
2278 {K_F21, (char_u *)"F21"},
2279 {K_F22, (char_u *)"F22"},
2280 {K_F23, (char_u *)"F23"},
2281 {K_F24, (char_u *)"F24"},
2282 {K_F25, (char_u *)"F25"},
2283 {K_F26, (char_u *)"F26"},
2284 {K_F27, (char_u *)"F27"},
2285 {K_F28, (char_u *)"F28"},
2286 {K_F29, (char_u *)"F29"},
2287 {K_F30, (char_u *)"F30"},
2289 {K_F31, (char_u *)"F31"},
2290 {K_F32, (char_u *)"F32"},
2291 {K_F33, (char_u *)"F33"},
2292 {K_F34, (char_u *)"F34"},
2293 {K_F35, (char_u *)"F35"},
2294 {K_F36, (char_u *)"F36"},
2295 {K_F37, (char_u *)"F37"},
2297 {K_XF1, (char_u *)"xF1"},
2298 {K_XF2, (char_u *)"xF2"},
2299 {K_XF3, (char_u *)"xF3"},
2300 {K_XF4, (char_u *)"xF4"},
2302 {K_HELP, (char_u *)"Help"},
2303 {K_UNDO, (char_u *)"Undo"},
2304 {K_INS, (char_u *)"Insert"},
2305 {K_INS, (char_u *)"Ins"}, /* Alternative name */
2306 {K_KINS, (char_u *)"kInsert"},
2307 {K_HOME, (char_u *)"Home"},
2308 {K_KHOME, (char_u *)"kHome"},
2309 {K_XHOME, (char_u *)"xHome"},
2310 {K_ZHOME, (char_u *)"zHome"},
2311 {K_END, (char_u *)"End"},
2312 {K_KEND, (char_u *)"kEnd"},
2313 {K_XEND, (char_u *)"xEnd"},
2314 {K_ZEND, (char_u *)"zEnd"},
2315 {K_PAGEUP, (char_u *)"PageUp"},
2316 {K_PAGEDOWN, (char_u *)"PageDown"},
2317 {K_KPAGEUP, (char_u *)"kPageUp"},
2318 {K_KPAGEDOWN, (char_u *)"kPageDown"},
2320 {K_KPLUS, (char_u *)"kPlus"},
2321 {K_KMINUS, (char_u *)"kMinus"},
2322 {K_KDIVIDE, (char_u *)"kDivide"},
2323 {K_KMULTIPLY, (char_u *)"kMultiply"},
2324 {K_KENTER, (char_u *)"kEnter"},
2325 {K_KPOINT, (char_u *)"kPoint"},
2327 {K_K0, (char_u *)"k0"},
2328 {K_K1, (char_u *)"k1"},
2329 {K_K2, (char_u *)"k2"},
2330 {K_K3, (char_u *)"k3"},
2331 {K_K4, (char_u *)"k4"},
2332 {K_K5, (char_u *)"k5"},
2333 {K_K6, (char_u *)"k6"},
2334 {K_K7, (char_u *)"k7"},
2335 {K_K8, (char_u *)"k8"},
2336 {K_K9, (char_u *)"k9"},
2338 {'<', (char_u *)"lt"},
2340 {K_MOUSE, (char_u *)"Mouse"},
2341 {K_NETTERM_MOUSE, (char_u *)"NetMouse"},
2342 {K_DEC_MOUSE, (char_u *)"DecMouse"},
2343 {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"},
2344 {K_PTERM_MOUSE, (char_u *)"PtermMouse"},
2345 {K_LEFTMOUSE, (char_u *)"LeftMouse"},
2346 {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"},
2347 {K_LEFTDRAG, (char_u *)"LeftDrag"},
2348 {K_LEFTRELEASE, (char_u *)"LeftRelease"},
2349 {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"},
2350 {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"},
2351 {K_MIDDLEDRAG, (char_u *)"MiddleDrag"},
2352 {K_MIDDLERELEASE, (char_u *)"MiddleRelease"},
2353 {K_RIGHTMOUSE, (char_u *)"RightMouse"},
2354 {K_RIGHTDRAG, (char_u *)"RightDrag"},
2355 {K_RIGHTRELEASE, (char_u *)"RightRelease"},
2356 {K_MOUSEDOWN, (char_u *)"MouseDown"},
2357 {K_MOUSEUP, (char_u *)"MouseUp"},
2358 {K_X1MOUSE, (char_u *)"X1Mouse"},
2359 {K_X1DRAG, (char_u *)"X1Drag"},
2360 {K_X1RELEASE, (char_u *)"X1Release"},
2361 {K_X2MOUSE, (char_u *)"X2Mouse"},
2362 {K_X2DRAG, (char_u *)"X2Drag"},
2363 {K_X2RELEASE, (char_u *)"X2Release"},
2364 {K_DROP, (char_u *)"Drop"},
2365 {K_ZERO, (char_u *)"Nul"},
2366 #ifdef FEAT_EVAL
2367 {K_SNR, (char_u *)"SNR"},
2368 #endif
2369 {K_PLUG, (char_u *)"Plug"},
2370 {0, NULL}
2373 #define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
2375 #ifdef FEAT_MOUSE
2376 static struct mousetable
2378 int pseudo_code; /* Code for pseudo mouse event */
2379 int button; /* Which mouse button is it? */
2380 int is_click; /* Is it a mouse button click event? */
2381 int is_drag; /* Is it a mouse drag event? */
2382 } mouse_table[] =
2384 {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE},
2385 #ifdef FEAT_GUI
2386 {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE},
2387 #endif
2388 {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE},
2389 {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE},
2390 #ifdef FEAT_GUI
2391 {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE},
2392 #endif
2393 {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE},
2394 {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE},
2395 {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE},
2396 {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE},
2397 {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE},
2398 {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE},
2399 {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE},
2400 {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE},
2401 {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE},
2402 {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE},
2403 {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE},
2404 {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE},
2405 /* DRAG without CLICK */
2406 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE},
2407 /* RELEASE without CLICK */
2408 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE},
2409 {0, 0, 0, 0},
2411 #endif /* FEAT_MOUSE */
2414 * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
2415 * modifier name ('S' for Shift, 'C' for Ctrl etc).
2418 name_to_mod_mask(c)
2419 int c;
2421 int i;
2423 c = TOUPPER_ASC(c);
2424 for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
2425 if (c == mod_mask_table[i].name)
2426 return mod_mask_table[i].mod_flag;
2427 return 0;
2431 * Check if if there is a special key code for "key" that includes the
2432 * modifiers specified.
2435 simplify_key(key, modifiers)
2436 int key;
2437 int *modifiers;
2439 int i;
2440 int key0;
2441 int key1;
2443 if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2445 /* TAB is a special case */
2446 if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2448 *modifiers &= ~MOD_MASK_SHIFT;
2449 return K_S_TAB;
2451 key0 = KEY2TERMCAP0(key);
2452 key1 = KEY2TERMCAP1(key);
2453 for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2454 if (key0 == modifier_keys_table[i + 3]
2455 && key1 == modifier_keys_table[i + 4]
2456 && (*modifiers & modifier_keys_table[i]))
2458 *modifiers &= ~modifier_keys_table[i];
2459 return TERMCAP2KEY(modifier_keys_table[i + 1],
2460 modifier_keys_table[i + 2]);
2463 return key;
2467 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
2470 handle_x_keys(key)
2471 int key;
2473 switch (key)
2475 case K_XUP: return K_UP;
2476 case K_XDOWN: return K_DOWN;
2477 case K_XLEFT: return K_LEFT;
2478 case K_XRIGHT: return K_RIGHT;
2479 case K_XHOME: return K_HOME;
2480 case K_ZHOME: return K_HOME;
2481 case K_XEND: return K_END;
2482 case K_ZEND: return K_END;
2483 case K_XF1: return K_F1;
2484 case K_XF2: return K_F2;
2485 case K_XF3: return K_F3;
2486 case K_XF4: return K_F4;
2487 case K_S_XF1: return K_S_F1;
2488 case K_S_XF2: return K_S_F2;
2489 case K_S_XF3: return K_S_F3;
2490 case K_S_XF4: return K_S_F4;
2492 return key;
2496 * Return a string which contains the name of the given key when the given
2497 * modifiers are down.
2499 char_u *
2500 get_special_key_name(c, modifiers)
2501 int c;
2502 int modifiers;
2504 static char_u string[MAX_KEY_NAME_LEN + 1];
2506 int i, idx;
2507 int table_idx;
2508 char_u *s;
2510 string[0] = '<';
2511 idx = 1;
2513 /* Key that stands for a normal character. */
2514 if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2515 c = KEY2TERMCAP1(c);
2518 * Translate shifted special keys into unshifted keys and set modifier.
2519 * Same for CTRL and ALT modifiers.
2521 if (IS_SPECIAL(c))
2523 for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2524 if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2525 && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2527 modifiers |= modifier_keys_table[i];
2528 c = TERMCAP2KEY(modifier_keys_table[i + 3],
2529 modifier_keys_table[i + 4]);
2530 break;
2534 /* try to find the key in the special key table */
2535 table_idx = find_special_key_in_table(c);
2538 * When not a known special key, and not a printable character, try to
2539 * extract modifiers.
2541 if (c > 0
2542 #ifdef FEAT_MBYTE
2543 && (*mb_char2len)(c) == 1
2544 #endif
2547 if (table_idx < 0
2548 && (!vim_isprintc(c) || (c & 0x7f) == ' ')
2549 && (c & 0x80))
2551 c &= 0x7f;
2552 modifiers |= MOD_MASK_ALT;
2553 /* try again, to find the un-alted key in the special key table */
2554 table_idx = find_special_key_in_table(c);
2556 if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2558 #ifdef EBCDIC
2559 c = CtrlChar(c);
2560 #else
2561 c += '@';
2562 #endif
2563 modifiers |= MOD_MASK_CTRL;
2567 /* translate the modifier into a string */
2568 for (i = 0; mod_mask_table[i].name != 'A'; i++)
2569 if ((modifiers & mod_mask_table[i].mod_mask)
2570 == mod_mask_table[i].mod_flag)
2572 string[idx++] = mod_mask_table[i].name;
2573 string[idx++] = (char_u)'-';
2576 if (table_idx < 0) /* unknown special key, may output t_xx */
2578 if (IS_SPECIAL(c))
2580 string[idx++] = 't';
2581 string[idx++] = '_';
2582 string[idx++] = KEY2TERMCAP0(c);
2583 string[idx++] = KEY2TERMCAP1(c);
2585 /* Not a special key, only modifiers, output directly */
2586 else
2588 #ifdef FEAT_MBYTE
2589 if (has_mbyte && (*mb_char2len)(c) > 1)
2590 idx += (*mb_char2bytes)(c, string + idx);
2591 else
2592 #endif
2593 if (vim_isprintc(c))
2594 string[idx++] = c;
2595 else
2597 s = transchar(c);
2598 while (*s)
2599 string[idx++] = *s++;
2603 else /* use name of special key */
2605 STRCPY(string + idx, key_names_table[table_idx].name);
2606 idx = (int)STRLEN(string);
2608 string[idx++] = '>';
2609 string[idx] = NUL;
2610 return string;
2614 * Try translating a <> name at (*srcp)[] to dst[].
2615 * Return the number of characters added to dst[], zero for no match.
2616 * If there is a match, srcp is advanced to after the <> name.
2617 * dst[] must be big enough to hold the result (up to six characters)!
2620 trans_special(srcp, dst, keycode)
2621 char_u **srcp;
2622 char_u *dst;
2623 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2625 int modifiers = 0;
2626 int key;
2627 int dlen = 0;
2629 key = find_special_key(srcp, &modifiers, keycode, FALSE);
2630 if (key == 0)
2631 return 0;
2633 /* Put the appropriate modifier in a string */
2634 if (modifiers != 0)
2636 dst[dlen++] = K_SPECIAL;
2637 dst[dlen++] = KS_MODIFIER;
2638 dst[dlen++] = modifiers;
2641 if (IS_SPECIAL(key))
2643 dst[dlen++] = K_SPECIAL;
2644 dst[dlen++] = KEY2TERMCAP0(key);
2645 dst[dlen++] = KEY2TERMCAP1(key);
2647 #ifdef FEAT_MBYTE
2648 else if (has_mbyte && !keycode)
2649 dlen += (*mb_char2bytes)(key, dst + dlen);
2650 #endif
2651 else if (keycode)
2652 dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2653 else
2654 dst[dlen++] = key;
2656 return dlen;
2660 * Try translating a <> name at (*srcp)[], return the key and modifiers.
2661 * srcp is advanced to after the <> name.
2662 * returns 0 if there is no match.
2665 find_special_key(srcp, modp, keycode, keep_x_key)
2666 char_u **srcp;
2667 int *modp;
2668 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2669 int keep_x_key; /* don't translate xHome to Home key */
2671 char_u *last_dash;
2672 char_u *end_of_name;
2673 char_u *src;
2674 char_u *bp;
2675 int modifiers;
2676 int bit;
2677 int key;
2678 unsigned long n;
2680 src = *srcp;
2681 if (src[0] != '<')
2682 return 0;
2684 /* Find end of modifier list */
2685 last_dash = src;
2686 for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2688 if (*bp == '-')
2690 last_dash = bp;
2691 if (bp[1] != NUL && bp[2] == '>')
2692 ++bp; /* anything accepted, like <C-?> */
2694 if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2695 bp += 3; /* skip t_xx, xx may be '-' or '>' */
2698 if (*bp == '>') /* found matching '>' */
2700 end_of_name = bp + 1;
2702 if (STRNICMP(src + 1, "char-", 5) == 0 && VIM_ISDIGIT(src[6]))
2704 /* <Char-123> or <Char-033> or <Char-0x33> */
2705 vim_str2nr(src + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2706 *modp = 0;
2707 *srcp = end_of_name;
2708 return (int)n;
2711 /* Which modifiers are given? */
2712 modifiers = 0x0;
2713 for (bp = src + 1; bp < last_dash; bp++)
2715 if (*bp != '-')
2717 bit = name_to_mod_mask(*bp);
2718 if (bit == 0x0)
2719 break; /* Illegal modifier name */
2720 modifiers |= bit;
2725 * Legal modifier name.
2727 if (bp >= last_dash)
2730 * Modifier with single letter, or special key name.
2732 if (modifiers != 0 && last_dash[2] == '>')
2733 key = last_dash[1];
2734 else
2736 key = get_special_key_code(last_dash + 1);
2737 if (!keep_x_key)
2738 key = handle_x_keys(key);
2742 * get_special_key_code() may return NUL for invalid
2743 * special key name.
2745 if (key != NUL)
2748 * Only use a modifier when there is no special key code that
2749 * includes the modifier.
2751 key = simplify_key(key, &modifiers);
2753 if (!keycode)
2755 /* don't want keycode, use single byte code */
2756 if (key == K_BS)
2757 key = BS;
2758 else if (key == K_DEL || key == K_KDEL)
2759 key = DEL;
2763 * Normal Key with modifier: Try to make a single byte code.
2765 if (!IS_SPECIAL(key))
2766 key = extract_modifiers(key, &modifiers);
2768 *modp = modifiers;
2769 *srcp = end_of_name;
2770 return key;
2774 return 0;
2778 * Try to include modifiers in the key.
2779 * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2782 extract_modifiers(key, modp)
2783 int key;
2784 int *modp;
2786 int modifiers = *modp;
2788 #ifdef MACOS
2789 /* Command-key really special, No fancynest */
2790 if (!(modifiers & MOD_MASK_CMD))
2791 #endif
2792 if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2794 key = TOUPPER_ASC(key);
2795 modifiers &= ~MOD_MASK_SHIFT;
2797 if ((modifiers & MOD_MASK_CTRL)
2798 #ifdef EBCDIC
2799 /* * TODO: EBCDIC Better use:
2800 * && (Ctrl_chr(key) || key == '?')
2801 * ??? */
2802 && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2803 != NULL
2804 #else
2805 && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2806 #endif
2809 key = Ctrl_chr(key);
2810 modifiers &= ~MOD_MASK_CTRL;
2811 /* <C-@> is <Nul> */
2812 if (key == 0)
2813 key = K_ZERO;
2815 #ifdef MACOS
2816 /* Command-key really special, No fancynest */
2817 if (!(modifiers & MOD_MASK_CMD))
2818 #endif
2819 if ((modifiers & MOD_MASK_ALT) && key < 0x80
2820 #ifdef FEAT_MBYTE
2821 && !enc_dbcs /* avoid creating a lead byte */
2822 #endif
2825 key |= 0x80;
2826 modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */
2829 *modp = modifiers;
2830 return key;
2834 * Try to find key "c" in the special key table.
2835 * Return the index when found, -1 when not found.
2838 find_special_key_in_table(c)
2839 int c;
2841 int i;
2843 for (i = 0; key_names_table[i].name != NULL; i++)
2844 if (c == key_names_table[i].key)
2845 break;
2846 if (key_names_table[i].name == NULL)
2847 i = -1;
2848 return i;
2852 * Find the special key with the given name (the given string does not have to
2853 * end with NUL, the name is assumed to end before the first non-idchar).
2854 * If the name starts with "t_" the next two characters are interpreted as a
2855 * termcap name.
2856 * Return the key code, or 0 if not found.
2859 get_special_key_code(name)
2860 char_u *name;
2862 char_u *table_name;
2863 char_u string[3];
2864 int i, j;
2867 * If it's <t_xx> we get the code for xx from the termcap
2869 if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2871 string[0] = name[2];
2872 string[1] = name[3];
2873 string[2] = NUL;
2874 if (add_termcap_entry(string, FALSE) == OK)
2875 return TERMCAP2KEY(name[2], name[3]);
2877 else
2878 for (i = 0; key_names_table[i].name != NULL; i++)
2880 table_name = key_names_table[i].name;
2881 for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
2882 if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
2883 break;
2884 if (!vim_isIDc(name[j]) && table_name[j] == NUL)
2885 return key_names_table[i].key;
2887 return 0;
2890 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2891 char_u *
2892 get_key_name(i)
2893 int i;
2895 if (i >= (int)KEY_NAMES_TABLE_LEN)
2896 return NULL;
2897 return key_names_table[i].name;
2899 #endif
2901 #if defined(FEAT_MOUSE) || defined(PROTO)
2903 * Look up the given mouse code to return the relevant information in the other
2904 * arguments. Return which button is down or was released.
2907 get_mouse_button(code, is_click, is_drag)
2908 int code;
2909 int *is_click;
2910 int *is_drag;
2912 int i;
2914 for (i = 0; mouse_table[i].pseudo_code; i++)
2915 if (code == mouse_table[i].pseudo_code)
2917 *is_click = mouse_table[i].is_click;
2918 *is_drag = mouse_table[i].is_drag;
2919 return mouse_table[i].button;
2921 return 0; /* Shouldn't get here */
2925 * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
2926 * the given information about which mouse button is down, and whether the
2927 * mouse was clicked, dragged or released.
2930 get_pseudo_mouse_code(button, is_click, is_drag)
2931 int button; /* eg MOUSE_LEFT */
2932 int is_click;
2933 int is_drag;
2935 int i;
2937 for (i = 0; mouse_table[i].pseudo_code; i++)
2938 if (button == mouse_table[i].button
2939 && is_click == mouse_table[i].is_click
2940 && is_drag == mouse_table[i].is_drag)
2942 #ifdef FEAT_GUI
2943 /* Trick: a non mappable left click and release has mouse_col -1
2944 * or added MOUSE_COLOFF. Used for 'mousefocus' in
2945 * gui_mouse_moved() */
2946 if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
2948 if (mouse_col < 0)
2949 mouse_col = 0;
2950 else
2951 mouse_col -= MOUSE_COLOFF;
2952 if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
2953 return (int)KE_LEFTMOUSE_NM;
2954 if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
2955 return (int)KE_LEFTRELEASE_NM;
2957 #endif
2958 return mouse_table[i].pseudo_code;
2960 return (int)KE_IGNORE; /* not recognized, ignore it */
2962 #endif /* FEAT_MOUSE */
2965 * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
2968 get_fileformat(buf)
2969 buf_T *buf;
2971 int c = *buf->b_p_ff;
2973 if (buf->b_p_bin || c == 'u')
2974 return EOL_UNIX;
2975 if (c == 'm')
2976 return EOL_MAC;
2977 return EOL_DOS;
2981 * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
2982 * argument.
2985 get_fileformat_force(buf, eap)
2986 buf_T *buf;
2987 exarg_T *eap; /* can be NULL! */
2989 int c;
2991 if (eap != NULL && eap->force_ff != 0)
2992 c = eap->cmd[eap->force_ff];
2993 else
2995 if ((eap != NULL && eap->force_bin != 0)
2996 ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
2997 return EOL_UNIX;
2998 c = *buf->b_p_ff;
3000 if (c == 'u')
3001 return EOL_UNIX;
3002 if (c == 'm')
3003 return EOL_MAC;
3004 return EOL_DOS;
3008 * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
3009 * Sets both 'textmode' and 'fileformat'.
3010 * Note: Does _not_ set global value of 'textmode'!
3012 void
3013 set_fileformat(t, opt_flags)
3014 int t;
3015 int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */
3017 char *p = NULL;
3019 switch (t)
3021 case EOL_DOS:
3022 p = FF_DOS;
3023 curbuf->b_p_tx = TRUE;
3024 break;
3025 case EOL_UNIX:
3026 p = FF_UNIX;
3027 curbuf->b_p_tx = FALSE;
3028 break;
3029 case EOL_MAC:
3030 p = FF_MAC;
3031 curbuf->b_p_tx = FALSE;
3032 break;
3034 if (p != NULL)
3035 set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
3036 OPT_FREE | opt_flags, 0);
3038 #ifdef FEAT_WINDOWS
3039 /* This may cause the buffer to become (un)modified. */
3040 check_status(curbuf);
3041 redraw_tabline = TRUE;
3042 #endif
3043 #ifdef FEAT_TITLE
3044 need_maketitle = TRUE; /* set window title later */
3045 #endif
3049 * Return the default fileformat from 'fileformats'.
3052 default_fileformat()
3054 switch (*p_ffs)
3056 case 'm': return EOL_MAC;
3057 case 'd': return EOL_DOS;
3059 return EOL_UNIX;
3063 * Call shell. Calls mch_call_shell, with 'shellxquote' added.
3066 call_shell(cmd, opt)
3067 char_u *cmd;
3068 int opt;
3070 char_u *ncmd;
3071 int retval;
3072 #ifdef FEAT_PROFILE
3073 proftime_T wait_time;
3074 #endif
3076 if (p_verbose > 3)
3078 verbose_enter();
3079 smsg((char_u *)_("Calling shell to execute: \"%s\""),
3080 cmd == NULL ? p_sh : cmd);
3081 out_char('\n');
3082 cursor_on();
3083 verbose_leave();
3086 #ifdef FEAT_PROFILE
3087 if (do_profiling == PROF_YES)
3088 prof_child_enter(&wait_time);
3089 #endif
3091 if (*p_sh == NUL)
3093 EMSG(_(e_shellempty));
3094 retval = -1;
3096 else
3098 #ifdef FEAT_GUI_MSWIN
3099 /* Don't hide the pointer while executing a shell command. */
3100 gui_mch_mousehide(FALSE);
3101 #endif
3102 #ifdef FEAT_GUI
3103 ++hold_gui_events;
3104 #endif
3105 /* The external command may update a tags file, clear cached tags. */
3106 tag_freematch();
3108 if (cmd == NULL || *p_sxq == NUL)
3109 retval = mch_call_shell(cmd, opt);
3110 else
3112 ncmd = alloc((unsigned)(STRLEN(cmd) + STRLEN(p_sxq) * 2 + 1));
3113 if (ncmd != NULL)
3115 STRCPY(ncmd, p_sxq);
3116 STRCAT(ncmd, cmd);
3117 STRCAT(ncmd, p_sxq);
3118 retval = mch_call_shell(ncmd, opt);
3119 vim_free(ncmd);
3121 else
3122 retval = -1;
3124 #ifdef FEAT_GUI
3125 --hold_gui_events;
3126 #endif
3128 * Check the window size, in case it changed while executing the
3129 * external command.
3131 shell_resized_check();
3134 #ifdef FEAT_EVAL
3135 set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
3136 # ifdef FEAT_PROFILE
3137 if (do_profiling == PROF_YES)
3138 prof_child_exit(&wait_time);
3139 # endif
3140 #endif
3142 return retval;
3146 * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to
3147 * NORMAL State with a condition. This function returns the real State.
3150 get_real_state()
3152 if (State & NORMAL)
3154 #ifdef FEAT_VISUAL
3155 if (VIsual_active)
3157 if (VIsual_select)
3158 return SELECTMODE;
3159 return VISUAL;
3161 else
3162 #endif
3163 if (finish_op)
3164 return OP_PENDING;
3166 return State;
3169 #if defined(FEAT_MBYTE) || defined(PROTO)
3171 * Return TRUE if "p" points to just after a path separator.
3172 * Take care of multi-byte characters.
3173 * "b" must point to the start of the file name
3176 after_pathsep(b, p)
3177 char_u *b;
3178 char_u *p;
3180 return vim_ispathsep(p[-1])
3181 && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
3183 #endif
3186 * Return TRUE if file names "f1" and "f2" are in the same directory.
3187 * "f1" may be a short name, "f2" must be a full path.
3190 same_directory(f1, f2)
3191 char_u *f1;
3192 char_u *f2;
3194 char_u ffname[MAXPATHL];
3195 char_u *t1;
3196 char_u *t2;
3198 /* safety check */
3199 if (f1 == NULL || f2 == NULL)
3200 return FALSE;
3202 (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
3203 t1 = gettail_sep(ffname);
3204 t2 = gettail_sep(f2);
3205 return (t1 - ffname == t2 - f2
3206 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
3209 #if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
3210 || ((defined(FEAT_GUI_GTK)) \
3211 && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
3212 || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
3213 || defined(PROTO)
3215 * Change to a file's directory.
3216 * Caller must call shorten_fnames()!
3217 * Return OK or FAIL.
3220 vim_chdirfile(fname)
3221 char_u *fname;
3223 char_u dir[MAXPATHL];
3225 vim_strncpy(dir, fname, MAXPATHL - 1);
3226 *gettail_sep(dir) = NUL;
3227 return mch_chdir((char *)dir) == 0 ? OK : FAIL;
3229 #endif
3231 #if defined(STAT_IGNORES_SLASH) || defined(PROTO)
3233 * Check if "name" ends in a slash and is not a directory.
3234 * Used for systems where stat() ignores a trailing slash on a file name.
3235 * The Vim code assumes a trailing slash is only ignored for a directory.
3238 illegal_slash(name)
3239 char *name;
3241 if (name[0] == NUL)
3242 return FALSE; /* no file name is not illegal */
3243 if (name[strlen(name) - 1] != '/')
3244 return FALSE; /* no trailing slash */
3245 if (mch_isdir((char_u *)name))
3246 return FALSE; /* trailing slash for a directory */
3247 return TRUE;
3249 #endif
3251 #if defined(CURSOR_SHAPE) || defined(PROTO)
3254 * Handling of cursor and mouse pointer shapes in various modes.
3257 cursorentry_T shape_table[SHAPE_IDX_COUNT] =
3259 /* The values will be filled in from the 'guicursor' and 'mouseshape'
3260 * defaults when Vim starts.
3261 * Adjust the SHAPE_IDX_ defines when making changes! */
3262 {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
3263 {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
3264 {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
3265 {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
3266 {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
3267 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
3268 {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
3269 {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
3270 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
3271 {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE},
3272 {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE},
3273 {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE},
3274 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE},
3275 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE},
3276 {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE},
3277 {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE},
3278 {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
3281 #ifdef FEAT_MOUSESHAPE
3283 * Table with names for mouse shapes. Keep in sync with all the tables for
3284 * mch_set_mouse_shape()!.
3286 static char * mshape_names[] =
3288 "arrow", /* default, must be the first one */
3289 "blank", /* hidden */
3290 "beam",
3291 "updown",
3292 "udsizing",
3293 "leftright",
3294 "lrsizing",
3295 "busy",
3296 "no",
3297 "crosshair",
3298 "hand1",
3299 "hand2",
3300 "pencil",
3301 "question",
3302 "rightup-arrow",
3303 "up-arrow",
3304 NULL
3306 #endif
3309 * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
3310 * ("what" is SHAPE_MOUSE).
3311 * Returns error message for an illegal option, NULL otherwise.
3313 char_u *
3314 parse_shape_opt(what)
3315 int what;
3317 char_u *modep;
3318 char_u *colonp;
3319 char_u *commap;
3320 char_u *slashp;
3321 char_u *p, *endp;
3322 int idx = 0; /* init for GCC */
3323 int all_idx;
3324 int len;
3325 int i;
3326 long n;
3327 int found_ve = FALSE; /* found "ve" flag */
3328 int round;
3331 * First round: check for errors; second round: do it for real.
3333 for (round = 1; round <= 2; ++round)
3336 * Repeat for all comma separated parts.
3338 #ifdef FEAT_MOUSESHAPE
3339 if (what == SHAPE_MOUSE)
3340 modep = p_mouseshape;
3341 else
3342 #endif
3343 modep = p_guicursor;
3344 while (*modep != NUL)
3346 colonp = vim_strchr(modep, ':');
3347 if (colonp == NULL)
3348 return (char_u *)N_("E545: Missing colon");
3349 if (colonp == modep)
3350 return (char_u *)N_("E546: Illegal mode");
3351 commap = vim_strchr(modep, ',');
3354 * Repeat for all mode's before the colon.
3355 * For the 'a' mode, we loop to handle all the modes.
3357 all_idx = -1;
3358 while (modep < colonp || all_idx >= 0)
3360 if (all_idx < 0)
3362 /* Find the mode. */
3363 if (modep[1] == '-' || modep[1] == ':')
3364 len = 1;
3365 else
3366 len = 2;
3367 if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
3368 all_idx = SHAPE_IDX_COUNT - 1;
3369 else
3371 for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
3372 if (STRNICMP(modep, shape_table[idx].name, len)
3373 == 0)
3374 break;
3375 if (idx == SHAPE_IDX_COUNT
3376 || (shape_table[idx].used_for & what) == 0)
3377 return (char_u *)N_("E546: Illegal mode");
3378 if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
3379 found_ve = TRUE;
3381 modep += len + 1;
3384 if (all_idx >= 0)
3385 idx = all_idx--;
3386 else if (round == 2)
3388 #ifdef FEAT_MOUSESHAPE
3389 if (what == SHAPE_MOUSE)
3391 /* Set the default, for the missing parts */
3392 shape_table[idx].mshape = 0;
3394 else
3395 #endif
3397 /* Set the defaults, for the missing parts */
3398 shape_table[idx].shape = SHAPE_BLOCK;
3399 shape_table[idx].blinkwait = 700L;
3400 shape_table[idx].blinkon = 400L;
3401 shape_table[idx].blinkoff = 250L;
3405 /* Parse the part after the colon */
3406 for (p = colonp + 1; *p && *p != ','; )
3408 #ifdef FEAT_MOUSESHAPE
3409 if (what == SHAPE_MOUSE)
3411 for (i = 0; ; ++i)
3413 if (mshape_names[i] == NULL)
3415 if (!VIM_ISDIGIT(*p))
3416 return (char_u *)N_("E547: Illegal mouseshape");
3417 if (round == 2)
3418 shape_table[idx].mshape =
3419 getdigits(&p) + MSHAPE_NUMBERED;
3420 else
3421 (void)getdigits(&p);
3422 break;
3424 len = (int)STRLEN(mshape_names[i]);
3425 if (STRNICMP(p, mshape_names[i], len) == 0)
3427 if (round == 2)
3428 shape_table[idx].mshape = i;
3429 p += len;
3430 break;
3434 else /* if (what == SHAPE_MOUSE) */
3435 #endif
3438 * First handle the ones with a number argument.
3440 i = *p;
3441 len = 0;
3442 if (STRNICMP(p, "ver", 3) == 0)
3443 len = 3;
3444 else if (STRNICMP(p, "hor", 3) == 0)
3445 len = 3;
3446 else if (STRNICMP(p, "blinkwait", 9) == 0)
3447 len = 9;
3448 else if (STRNICMP(p, "blinkon", 7) == 0)
3449 len = 7;
3450 else if (STRNICMP(p, "blinkoff", 8) == 0)
3451 len = 8;
3452 if (len != 0)
3454 p += len;
3455 if (!VIM_ISDIGIT(*p))
3456 return (char_u *)N_("E548: digit expected");
3457 n = getdigits(&p);
3458 if (len == 3) /* "ver" or "hor" */
3460 if (n == 0)
3461 return (char_u *)N_("E549: Illegal percentage");
3462 if (round == 2)
3464 if (TOLOWER_ASC(i) == 'v')
3465 shape_table[idx].shape = SHAPE_VER;
3466 else
3467 shape_table[idx].shape = SHAPE_HOR;
3468 shape_table[idx].percentage = n;
3471 else if (round == 2)
3473 if (len == 9)
3474 shape_table[idx].blinkwait = n;
3475 else if (len == 7)
3476 shape_table[idx].blinkon = n;
3477 else
3478 shape_table[idx].blinkoff = n;
3481 else if (STRNICMP(p, "block", 5) == 0)
3483 if (round == 2)
3484 shape_table[idx].shape = SHAPE_BLOCK;
3485 p += 5;
3487 else /* must be a highlight group name then */
3489 endp = vim_strchr(p, '-');
3490 if (commap == NULL) /* last part */
3492 if (endp == NULL)
3493 endp = p + STRLEN(p); /* find end of part */
3495 else if (endp > commap || endp == NULL)
3496 endp = commap;
3497 slashp = vim_strchr(p, '/');
3498 if (slashp != NULL && slashp < endp)
3500 /* "group/langmap_group" */
3501 i = syn_check_group(p, (int)(slashp - p));
3502 p = slashp + 1;
3504 if (round == 2)
3506 shape_table[idx].id = syn_check_group(p,
3507 (int)(endp - p));
3508 shape_table[idx].id_lm = shape_table[idx].id;
3509 if (slashp != NULL && slashp < endp)
3510 shape_table[idx].id = i;
3512 p = endp;
3514 } /* if (what != SHAPE_MOUSE) */
3516 if (*p == '-')
3517 ++p;
3520 modep = p;
3521 if (*modep == ',')
3522 ++modep;
3526 /* If the 's' flag is not given, use the 'v' cursor for 's' */
3527 if (!found_ve)
3529 #ifdef FEAT_MOUSESHAPE
3530 if (what == SHAPE_MOUSE)
3532 shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3534 else
3535 #endif
3537 shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3538 shape_table[SHAPE_IDX_VE].percentage =
3539 shape_table[SHAPE_IDX_V].percentage;
3540 shape_table[SHAPE_IDX_VE].blinkwait =
3541 shape_table[SHAPE_IDX_V].blinkwait;
3542 shape_table[SHAPE_IDX_VE].blinkon =
3543 shape_table[SHAPE_IDX_V].blinkon;
3544 shape_table[SHAPE_IDX_VE].blinkoff =
3545 shape_table[SHAPE_IDX_V].blinkoff;
3546 shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3547 shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3551 return NULL;
3554 # if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
3555 || defined(FEAT_MOUSESHAPE) || defined(PROTO)
3557 * Return the index into shape_table[] for the current mode.
3558 * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3561 get_shape_idx(mouse)
3562 int mouse;
3564 #ifdef FEAT_MOUSESHAPE
3565 if (mouse && (State == HITRETURN || State == ASKMORE))
3567 # ifdef FEAT_GUI
3568 int x, y;
3569 gui_mch_getmouse(&x, &y);
3570 if (Y_2_ROW(y) == Rows - 1)
3571 return SHAPE_IDX_MOREL;
3572 # endif
3573 return SHAPE_IDX_MORE;
3575 if (mouse && drag_status_line)
3576 return SHAPE_IDX_SDRAG;
3577 # ifdef FEAT_VERTSPLIT
3578 if (mouse && drag_sep_line)
3579 return SHAPE_IDX_VDRAG;
3580 # endif
3581 #endif
3582 if (!mouse && State == SHOWMATCH)
3583 return SHAPE_IDX_SM;
3584 #ifdef FEAT_VREPLACE
3585 if (State & VREPLACE_FLAG)
3586 return SHAPE_IDX_R;
3587 #endif
3588 if (State & REPLACE_FLAG)
3589 return SHAPE_IDX_R;
3590 if (State & INSERT)
3591 return SHAPE_IDX_I;
3592 if (State & CMDLINE)
3594 if (cmdline_at_end())
3595 return SHAPE_IDX_C;
3596 if (cmdline_overstrike())
3597 return SHAPE_IDX_CR;
3598 return SHAPE_IDX_CI;
3600 if (finish_op)
3601 return SHAPE_IDX_O;
3602 #ifdef FEAT_VISUAL
3603 if (VIsual_active)
3605 if (*p_sel == 'e')
3606 return SHAPE_IDX_VE;
3607 else
3608 return SHAPE_IDX_V;
3610 #endif
3611 return SHAPE_IDX_N;
3613 #endif
3615 # if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3616 static int old_mouse_shape = 0;
3619 * Set the mouse shape:
3620 * If "shape" is -1, use shape depending on the current mode,
3621 * depending on the current state.
3622 * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3623 * when the mouse moves off the status or command line).
3625 void
3626 update_mouseshape(shape_idx)
3627 int shape_idx;
3629 int new_mouse_shape;
3631 /* Only works in GUI mode. */
3632 if (!gui.in_use || gui.starting)
3633 return;
3635 /* Postpone the updating when more is to come. Speeds up executing of
3636 * mappings. */
3637 if (shape_idx == -1 && char_avail())
3639 postponed_mouseshape = TRUE;
3640 return;
3643 /* When ignoring the mouse don't change shape on the statusline. */
3644 if (*p_mouse == NUL
3645 && (shape_idx == SHAPE_IDX_CLINE
3646 || shape_idx == SHAPE_IDX_STATUS
3647 || shape_idx == SHAPE_IDX_VSEP))
3648 shape_idx = -2;
3650 if (shape_idx == -2
3651 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3652 && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3653 && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3654 return;
3655 if (shape_idx < 0)
3656 new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3657 else
3658 new_mouse_shape = shape_table[shape_idx].mshape;
3659 if (new_mouse_shape != old_mouse_shape)
3661 mch_set_mouse_shape(new_mouse_shape);
3662 old_mouse_shape = new_mouse_shape;
3664 postponed_mouseshape = FALSE;
3666 # endif
3668 #endif /* CURSOR_SHAPE */
3671 #ifdef FEAT_CRYPT
3673 * Optional encryption support.
3674 * Mohsin Ahmed, mosh@sasi.com, 98-09-24
3675 * Based on zip/crypt sources.
3677 * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3678 * most countries. There are a few exceptions, but that still should not be a
3679 * problem since this code was originally created in Europe and India.
3682 /* from zip.h */
3684 typedef unsigned short ush; /* unsigned 16-bit value */
3685 typedef unsigned long ulg; /* unsigned 32-bit value */
3687 static void make_crc_tab __ARGS((void));
3689 static ulg crc_32_tab[256];
3692 * Fill the CRC table.
3694 static void
3695 make_crc_tab()
3697 ulg s,t,v;
3698 static int done = FALSE;
3700 if (done)
3701 return;
3702 for (t = 0; t < 256; t++)
3704 v = t;
3705 for (s = 0; s < 8; s++)
3706 v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3707 crc_32_tab[t] = v;
3709 done = TRUE;
3712 #define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3715 static ulg keys[3]; /* keys defining the pseudo-random sequence */
3718 * Return the next byte in the pseudo-random sequence
3721 decrypt_byte()
3723 ush temp;
3725 temp = (ush)keys[2] | 2;
3726 return (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff);
3730 * Update the encryption keys with the next byte of plain text
3733 update_keys(c)
3734 int c; /* byte of plain text */
3736 keys[0] = CRC32(keys[0], c);
3737 keys[1] += keys[0] & 0xff;
3738 keys[1] = keys[1] * 134775813L + 1;
3739 keys[2] = CRC32(keys[2], (int)(keys[1] >> 24));
3740 return c;
3744 * Initialize the encryption keys and the random header according to
3745 * the given password.
3746 * If "passwd" is NULL or empty, don't do anything.
3748 void
3749 crypt_init_keys(passwd)
3750 char_u *passwd; /* password string with which to modify keys */
3752 if (passwd != NULL && *passwd != NUL)
3754 make_crc_tab();
3755 keys[0] = 305419896L;
3756 keys[1] = 591751049L;
3757 keys[2] = 878082192L;
3758 while (*passwd != '\0')
3759 update_keys((int)*passwd++);
3764 * Ask the user for a crypt key.
3765 * When "store" is TRUE, the new key in stored in the 'key' option, and the
3766 * 'key' option value is returned: Don't free it.
3767 * When "store" is FALSE, the typed key is returned in allocated memory.
3768 * Returns NULL on failure.
3770 char_u *
3771 get_crypt_key(store, twice)
3772 int store;
3773 int twice; /* Ask for the key twice. */
3775 char_u *p1, *p2 = NULL;
3776 int round;
3778 for (round = 0; ; ++round)
3780 cmdline_star = TRUE;
3781 cmdline_row = msg_row;
3782 p1 = getcmdline_prompt(NUL, round == 0
3783 ? (char_u *)_("Enter encryption key: ")
3784 : (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING,
3785 NULL);
3786 cmdline_star = FALSE;
3788 if (p1 == NULL)
3789 break;
3791 if (round == twice)
3793 if (p2 != NULL && STRCMP(p1, p2) != 0)
3795 MSG(_("Keys don't match!"));
3796 vim_free(p1);
3797 vim_free(p2);
3798 p2 = NULL;
3799 round = -1; /* do it again */
3800 continue;
3802 if (store)
3804 set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
3805 vim_free(p1);
3806 p1 = curbuf->b_p_key;
3808 break;
3810 p2 = p1;
3813 /* since the user typed this, no need to wait for return */
3814 need_wait_return = FALSE;
3815 msg_didout = FALSE;
3817 vim_free(p2);
3818 return p1;
3821 #endif /* FEAT_CRYPT */
3823 /* TODO: make some #ifdef for this */
3824 /*--------[ file searching ]-------------------------------------------------*/
3826 * File searching functions for 'path', 'tags' and 'cdpath' options.
3827 * External visible functions:
3828 * vim_findfile_init() creates/initialises the search context
3829 * vim_findfile_free_visited() free list of visited files/dirs of search
3830 * context
3831 * vim_findfile() find a file in the search context
3832 * vim_findfile_cleanup() cleanup/free search context created by
3833 * vim_findfile_init()
3835 * All static functions and variables start with 'ff_'
3837 * In general it works like this:
3838 * First you create yourself a search context by calling vim_findfile_init().
3839 * It is possible to give a search context from a previous call to
3840 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
3841 * until you are satisfied with the result or it returns NULL. On every call it
3842 * returns the next file which matches the conditions given to
3843 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
3845 * It is possible to call vim_findfile_init() again to reinitialise your search
3846 * with some new parameters. Don't forget to pass your old search context to
3847 * it, so it can reuse it and especially reuse the list of already visited
3848 * directories. If you want to delete the list of already visited directories
3849 * simply call vim_findfile_free_visited().
3851 * When you are done call vim_findfile_cleanup() to free the search context.
3853 * The function vim_findfile_init() has a long comment, which describes the
3854 * needed parameters.
3858 * ATTENTION:
3859 * ==========
3860 * Also we use an allocated search context here, this functions are NOT
3861 * thread-safe!!!!!
3863 * To minimize parameter passing (or because I'm to lazy), only the
3864 * external visible functions get a search context as a parameter. This is
3865 * then assigned to a static global, which is used throughout the local
3866 * functions.
3870 * type for the directory search stack
3872 typedef struct ff_stack
3874 struct ff_stack *ffs_prev;
3876 /* the fix part (no wildcards) and the part containing the wildcards
3877 * of the search path
3879 char_u *ffs_fix_path;
3880 #ifdef FEAT_PATH_EXTRA
3881 char_u *ffs_wc_path;
3882 #endif
3884 /* files/dirs found in the above directory, matched by the first wildcard
3885 * of wc_part
3887 char_u **ffs_filearray;
3888 int ffs_filearray_size;
3889 char_u ffs_filearray_cur; /* needed for partly handled dirs */
3891 /* to store status of partly handled directories
3892 * 0: we work on this directory for the first time
3893 * 1: this directory was partly searched in an earlier step
3895 int ffs_stage;
3897 /* How deep are we in the directory tree?
3898 * Counts backward from value of level parameter to vim_findfile_init
3900 int ffs_level;
3902 /* Did we already expand '**' to an empty string? */
3903 int ffs_star_star_empty;
3904 } ff_stack_T;
3907 * type for already visited directories or files.
3909 typedef struct ff_visited
3911 struct ff_visited *ffv_next;
3913 #ifdef FEAT_PATH_EXTRA
3914 /* Visited directories are different if the wildcard string are
3915 * different. So we have to save it.
3917 char_u *ffv_wc_path;
3918 #endif
3919 /* for unix use inode etc for comparison (needed because of links), else
3920 * use filename.
3922 #ifdef UNIX
3923 int ffv_dev_valid; /* ffv_dev and ffv_ino were set */
3924 dev_t ffv_dev; /* device number */
3925 ino_t ffv_ino; /* inode number */
3926 #endif
3927 /* The memory for this struct is allocated according to the length of
3928 * ffv_fname.
3930 char_u ffv_fname[1]; /* actually longer */
3931 } ff_visited_T;
3934 * We might have to manage several visited lists during a search.
3935 * This is especially needed for the tags option. If tags is set to:
3936 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
3937 * So we have to do 3 searches:
3938 * 1) search from the current files directory downward for the file "tags"
3939 * 2) search from the current files directory downward for the file "TAGS"
3940 * 3) search from Vims current directory downwards for the file "tags"
3941 * As you can see, the first and the third search are for the same file, so for
3942 * the third search we can use the visited list of the first search. For the
3943 * second search we must start from a empty visited list.
3944 * The struct ff_visited_list_hdr is used to manage a linked list of already
3945 * visited lists.
3947 typedef struct ff_visited_list_hdr
3949 struct ff_visited_list_hdr *ffvl_next;
3951 /* the filename the attached visited list is for */
3952 char_u *ffvl_filename;
3954 ff_visited_T *ffvl_visited_list;
3956 } ff_visited_list_hdr_T;
3960 * '**' can be expanded to several directory levels.
3961 * Set the default maximum depth.
3963 #define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
3966 * The search context:
3967 * ffsc_stack_ptr: the stack for the dirs to search
3968 * ffsc_visited_list: the currently active visited list
3969 * ffsc_dir_visited_list: the currently active visited list for search dirs
3970 * ffsc_visited_lists_list: the list of all visited lists
3971 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
3972 * ffsc_file_to_search: the file to search for
3973 * ffsc_start_dir: the starting directory, if search path was relative
3974 * ffsc_fix_path: the fix part of the given path (without wildcards)
3975 * Needed for upward search.
3976 * ffsc_wc_path: the part of the given path containing wildcards
3977 * ffsc_level: how many levels of dirs to search downwards
3978 * ffsc_stopdirs_v: array of stop directories for upward search
3979 * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
3981 typedef struct ff_search_ctx_T
3983 ff_stack_T *ffsc_stack_ptr;
3984 ff_visited_list_hdr_T *ffsc_visited_list;
3985 ff_visited_list_hdr_T *ffsc_dir_visited_list;
3986 ff_visited_list_hdr_T *ffsc_visited_lists_list;
3987 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
3988 char_u *ffsc_file_to_search;
3989 char_u *ffsc_start_dir;
3990 char_u *ffsc_fix_path;
3991 #ifdef FEAT_PATH_EXTRA
3992 char_u *ffsc_wc_path;
3993 int ffsc_level;
3994 char_u **ffsc_stopdirs_v;
3995 #endif
3996 int ffsc_find_what;
3997 } ff_search_ctx_T;
3999 /* locally needed functions */
4000 #ifdef FEAT_PATH_EXTRA
4001 static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
4002 #else
4003 static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
4004 #endif
4005 static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
4006 static void ff_free_visited_list __ARGS((ff_visited_T *vl));
4007 static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
4008 #ifdef FEAT_PATH_EXTRA
4009 static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
4010 #endif
4012 static void ff_push __ARGS((ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr));
4013 static ff_stack_T *ff_pop __ARGS((ff_search_ctx_T *search_ctx));
4014 static void ff_clear __ARGS((ff_search_ctx_T *search_ctx));
4015 static void ff_free_stack_element __ARGS((ff_stack_T *stack_ptr));
4016 #ifdef FEAT_PATH_EXTRA
4017 static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
4018 #else
4019 static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
4020 #endif
4021 #ifdef FEAT_PATH_EXTRA
4022 static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
4023 #endif
4025 #if 0
4027 * if someone likes findfirst/findnext, here are the functions
4028 * NOT TESTED!!
4031 static void *ff_fn_search_context = NULL;
4033 char_u *
4034 vim_findfirst(path, filename, level)
4035 char_u *path;
4036 char_u *filename;
4037 int level;
4039 ff_fn_search_context =
4040 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
4041 ff_fn_search_context, rel_fname);
4042 if (NULL == ff_fn_search_context)
4043 return NULL;
4044 else
4045 return vim_findnext()
4048 char_u *
4049 vim_findnext()
4051 char_u *ret = vim_findfile(ff_fn_search_context);
4053 if (NULL == ret)
4055 vim_findfile_cleanup(ff_fn_search_context);
4056 ff_fn_search_context = NULL;
4058 return ret;
4060 #endif
4063 * Initialization routine for vim_findfile.
4065 * Returns the newly allocated search context or NULL if an error occured.
4067 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
4068 * with the search context.
4070 * Find the file 'filename' in the directory 'path'.
4071 * The parameter 'path' may contain wildcards. If so only search 'level'
4072 * directories deep. The parameter 'level' is the absolute maximum and is
4073 * not related to restricts given to the '**' wildcard. If 'level' is 100
4074 * and you use '**200' vim_findfile() will stop after 100 levels.
4076 * 'filename' cannot contain wildcards! It is used as-is, no backslashes to
4077 * escape special characters.
4079 * If 'stopdirs' is not NULL and nothing is found downward, the search is
4080 * restarted on the next higher directory level. This is repeated until the
4081 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
4082 * format ";*<dirname>*\(;<dirname>\)*;\=$".
4084 * If the 'path' is relative, the starting dir for the search is either VIM's
4085 * current dir or if the path starts with "./" the current files dir.
4086 * If the 'path' is absolut, the starting dir is that part of the path before
4087 * the first wildcard.
4089 * Upward search is only done on the starting dir.
4091 * If 'free_visited' is TRUE the list of already visited files/directories is
4092 * cleared. Set this to FALSE if you just want to search from another
4093 * directory, but want to be sure that no directory from a previous search is
4094 * searched again. This is useful if you search for a file at different places.
4095 * The list of visited files/dirs can also be cleared with the function
4096 * vim_findfile_free_visited().
4098 * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
4099 * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
4101 * A search context returned by a previous call to vim_findfile_init() can be
4102 * passed in the parameter "search_ctx_arg". This context is reused and
4103 * reinitialized with the new parameters. The list of already visited
4104 * directories from this context is only deleted if the parameter
4105 * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed
4106 * if the reinitialization fails.
4108 * If you don't have a search context from a previous call "search_ctx_arg"
4109 * must be NULL.
4111 * This function silently ignores a few errors, vim_findfile() will have
4112 * limited functionality then.
4114 void *
4115 vim_findfile_init(path, filename, stopdirs, level, free_visited, find_what,
4116 search_ctx_arg, tagfile, rel_fname)
4117 char_u *path;
4118 char_u *filename;
4119 char_u *stopdirs UNUSED;
4120 int level;
4121 int free_visited;
4122 int find_what;
4123 void *search_ctx_arg;
4124 int tagfile;
4125 char_u *rel_fname; /* file name to use for "." */
4127 #ifdef FEAT_PATH_EXTRA
4128 char_u *wc_part;
4129 #endif
4130 ff_stack_T *sptr;
4131 ff_search_ctx_T *search_ctx;
4133 /* If a search context is given by the caller, reuse it, else allocate a
4134 * new one.
4136 if (search_ctx_arg != NULL)
4137 search_ctx = search_ctx_arg;
4138 else
4140 search_ctx = (ff_search_ctx_T*)alloc((unsigned)sizeof(ff_search_ctx_T));
4141 if (search_ctx == NULL)
4142 goto error_return;
4143 memset(search_ctx, 0, sizeof(ff_search_ctx_T));
4145 search_ctx->ffsc_find_what = find_what;
4147 /* clear the search context, but NOT the visited lists */
4148 ff_clear(search_ctx);
4150 /* clear visited list if wanted */
4151 if (free_visited == TRUE)
4152 vim_findfile_free_visited(search_ctx);
4153 else
4155 /* Reuse old visited lists. Get the visited list for the given
4156 * filename. If no list for the current filename exists, creates a new
4157 * one. */
4158 search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
4159 &search_ctx->ffsc_visited_lists_list);
4160 if (search_ctx->ffsc_visited_list == NULL)
4161 goto error_return;
4162 search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
4163 &search_ctx->ffsc_dir_visited_lists_list);
4164 if (search_ctx->ffsc_dir_visited_list == NULL)
4165 goto error_return;
4168 if (ff_expand_buffer == NULL)
4170 ff_expand_buffer = (char_u*)alloc(MAXPATHL);
4171 if (ff_expand_buffer == NULL)
4172 goto error_return;
4175 /* Store information on starting dir now if path is relative.
4176 * If path is absolute, we do that later. */
4177 if (path[0] == '.'
4178 && (vim_ispathsep(path[1]) || path[1] == NUL)
4179 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
4180 && rel_fname != NULL)
4182 int len = (int)(gettail(rel_fname) - rel_fname);
4184 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
4186 /* Make the start dir an absolute path name. */
4187 vim_strncpy(ff_expand_buffer, rel_fname, len);
4188 search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
4190 else
4191 search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
4192 if (search_ctx->ffsc_start_dir == NULL)
4193 goto error_return;
4194 if (*++path != NUL)
4195 ++path;
4197 else if (*path == NUL || !vim_isAbsName(path))
4199 #ifdef BACKSLASH_IN_FILENAME
4200 /* "c:dir" needs "c:" to be expanded, otherwise use current dir */
4201 if (*path != NUL && path[1] == ':')
4203 char_u drive[3];
4205 drive[0] = path[0];
4206 drive[1] = ':';
4207 drive[2] = NUL;
4208 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4209 goto error_return;
4210 path += 2;
4212 else
4213 #endif
4214 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
4215 goto error_return;
4217 search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
4218 if (search_ctx->ffsc_start_dir == NULL)
4219 goto error_return;
4221 #ifdef BACKSLASH_IN_FILENAME
4222 /* A path that starts with "/dir" is relative to the drive, not to the
4223 * directory (but not for "//machine/dir"). Only use the drive name. */
4224 if ((*path == '/' || *path == '\\')
4225 && path[1] != path[0]
4226 && search_ctx->ffsc_start_dir[1] == ':')
4227 search_ctx->ffsc_start_dir[2] = NUL;
4228 #endif
4231 #ifdef FEAT_PATH_EXTRA
4233 * If stopdirs are given, split them into an array of pointers.
4234 * If this fails (mem allocation), there is no upward search at all or a
4235 * stop directory is not recognized -> continue silently.
4236 * If stopdirs just contains a ";" or is empty,
4237 * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
4238 * is handled as unlimited upward search. See function
4239 * ff_path_in_stoplist() for details.
4241 if (stopdirs != NULL)
4243 char_u *walker = stopdirs;
4244 int dircount;
4246 while (*walker == ';')
4247 walker++;
4249 dircount = 1;
4250 search_ctx->ffsc_stopdirs_v =
4251 (char_u **)alloc((unsigned)sizeof(char_u *));
4253 if (search_ctx->ffsc_stopdirs_v != NULL)
4257 char_u *helper;
4258 void *ptr;
4260 helper = walker;
4261 ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
4262 (dircount + 1) * sizeof(char_u *));
4263 if (ptr)
4264 search_ctx->ffsc_stopdirs_v = ptr;
4265 else
4266 /* ignore, keep what we have and continue */
4267 break;
4268 walker = vim_strchr(walker, ';');
4269 if (walker)
4271 search_ctx->ffsc_stopdirs_v[dircount-1] =
4272 vim_strnsave(helper, (int)(walker - helper));
4273 walker++;
4275 else
4276 /* this might be "", which means ascent till top
4277 * of directory tree.
4279 search_ctx->ffsc_stopdirs_v[dircount-1] =
4280 vim_strsave(helper);
4282 dircount++;
4284 } while (walker != NULL);
4285 search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
4288 #endif
4290 #ifdef FEAT_PATH_EXTRA
4291 search_ctx->ffsc_level = level;
4293 /* split into:
4294 * -fix path
4295 * -wildcard_stuff (might be NULL)
4297 wc_part = vim_strchr(path, '*');
4298 if (wc_part != NULL)
4300 int llevel;
4301 int len;
4302 char *errpt;
4304 /* save the fix part of the path */
4305 search_ctx->ffsc_fix_path = vim_strnsave(path, (int)(wc_part - path));
4308 * copy wc_path and add restricts to the '**' wildcard.
4309 * The octet after a '**' is used as a (binary) counter.
4310 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
4311 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
4312 * For EBCDIC you get different character values.
4313 * If no restrict is given after '**' the default is used.
4314 * Due to this technic the path looks awful if you print it as a
4315 * string.
4317 len = 0;
4318 while (*wc_part != NUL)
4320 if (STRNCMP(wc_part, "**", 2) == 0)
4322 ff_expand_buffer[len++] = *wc_part++;
4323 ff_expand_buffer[len++] = *wc_part++;
4325 llevel = strtol((char *)wc_part, &errpt, 10);
4326 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
4327 ff_expand_buffer[len++] = llevel;
4328 else if ((char_u *)errpt != wc_part && llevel == 0)
4329 /* restrict is 0 -> remove already added '**' */
4330 len -= 2;
4331 else
4332 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
4333 wc_part = (char_u *)errpt;
4334 if (*wc_part != NUL && !vim_ispathsep(*wc_part))
4336 EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
4337 goto error_return;
4340 else
4341 ff_expand_buffer[len++] = *wc_part++;
4343 ff_expand_buffer[len] = NUL;
4344 search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
4346 if (search_ctx->ffsc_wc_path == NULL)
4347 goto error_return;
4349 else
4350 #endif
4351 search_ctx->ffsc_fix_path = vim_strsave(path);
4353 if (search_ctx->ffsc_start_dir == NULL)
4355 /* store the fix part as startdir.
4356 * This is needed if the parameter path is fully qualified.
4358 search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
4359 if (search_ctx->ffsc_start_dir)
4360 search_ctx->ffsc_fix_path[0] = NUL;
4363 /* create an absolute path */
4364 STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
4365 add_pathsep(ff_expand_buffer);
4366 STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
4367 add_pathsep(ff_expand_buffer);
4369 sptr = ff_create_stack_element(ff_expand_buffer,
4370 #ifdef FEAT_PATH_EXTRA
4371 search_ctx->ffsc_wc_path,
4372 #endif
4373 level, 0);
4375 if (sptr == NULL)
4376 goto error_return;
4378 ff_push(search_ctx, sptr);
4380 search_ctx->ffsc_file_to_search = vim_strsave(filename);
4381 if (search_ctx->ffsc_file_to_search == NULL)
4382 goto error_return;
4384 return search_ctx;
4386 error_return:
4388 * We clear the search context now!
4389 * Even when the caller gave us a (perhaps valid) context we free it here,
4390 * as we might have already destroyed it.
4392 vim_findfile_cleanup(search_ctx);
4393 return NULL;
4396 #if defined(FEAT_PATH_EXTRA) || defined(PROTO)
4398 * Get the stopdir string. Check that ';' is not escaped.
4400 char_u *
4401 vim_findfile_stopdir(buf)
4402 char_u *buf;
4404 char_u *r_ptr = buf;
4406 while (*r_ptr != NUL && *r_ptr != ';')
4408 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
4410 /* overwrite the escape char,
4411 * use STRLEN(r_ptr) to move the trailing '\0'
4413 STRMOVE(r_ptr, r_ptr + 1);
4414 r_ptr++;
4416 r_ptr++;
4418 if (*r_ptr == ';')
4420 *r_ptr = 0;
4421 r_ptr++;
4423 else if (*r_ptr == NUL)
4424 r_ptr = NULL;
4425 return r_ptr;
4427 #endif
4430 * Clean up the given search context. Can handle a NULL pointer.
4432 void
4433 vim_findfile_cleanup(ctx)
4434 void *ctx;
4436 if (ctx == NULL)
4437 return;
4439 vim_findfile_free_visited(ctx);
4440 ff_clear(ctx);
4441 vim_free(ctx);
4445 * Find a file in a search context.
4446 * The search context was created with vim_findfile_init() above.
4447 * Return a pointer to an allocated file name or NULL if nothing found.
4448 * To get all matching files call this function until you get NULL.
4450 * If the passed search_context is NULL, NULL is returned.
4452 * The search algorithm is depth first. To change this replace the
4453 * stack with a list (don't forget to leave partly searched directories on the
4454 * top of the list).
4456 char_u *
4457 vim_findfile(search_ctx_arg)
4458 void *search_ctx_arg;
4460 char_u *file_path;
4461 #ifdef FEAT_PATH_EXTRA
4462 char_u *rest_of_wildcards;
4463 char_u *path_end = NULL;
4464 #endif
4465 ff_stack_T *stackp;
4466 #if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
4467 int len;
4468 #endif
4469 int i;
4470 char_u *p;
4471 #ifdef FEAT_SEARCHPATH
4472 char_u *suf;
4473 #endif
4474 ff_search_ctx_T *search_ctx;
4476 if (search_ctx_arg == NULL)
4477 return NULL;
4479 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
4482 * filepath is used as buffer for various actions and as the storage to
4483 * return a found filename.
4485 if ((file_path = alloc((int)MAXPATHL)) == NULL)
4486 return NULL;
4488 #ifdef FEAT_PATH_EXTRA
4489 /* store the end of the start dir -- needed for upward search */
4490 if (search_ctx->ffsc_start_dir != NULL)
4491 path_end = &search_ctx->ffsc_start_dir[
4492 STRLEN(search_ctx->ffsc_start_dir)];
4493 #endif
4495 #ifdef FEAT_PATH_EXTRA
4496 /* upward search loop */
4497 for (;;)
4499 #endif
4500 /* downward search loop */
4501 for (;;)
4503 /* check if user user wants to stop the search*/
4504 ui_breakcheck();
4505 if (got_int)
4506 break;
4508 /* get directory to work on from stack */
4509 stackp = ff_pop(search_ctx);
4510 if (stackp == NULL)
4511 break;
4514 * TODO: decide if we leave this test in
4516 * GOOD: don't search a directory(-tree) twice.
4517 * BAD: - check linked list for every new directory entered.
4518 * - check for double files also done below
4520 * Here we check if we already searched this directory.
4521 * We already searched a directory if:
4522 * 1) The directory is the same.
4523 * 2) We would use the same wildcard string.
4525 * Good if you have links on same directory via several ways
4526 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4527 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4529 * This check is only needed for directories we work on for the
4530 * first time (hence stackp->ff_filearray == NULL)
4532 if (stackp->ffs_filearray == NULL
4533 && ff_check_visited(&search_ctx->ffsc_dir_visited_list
4534 ->ffvl_visited_list,
4535 stackp->ffs_fix_path
4536 #ifdef FEAT_PATH_EXTRA
4537 , stackp->ffs_wc_path
4538 #endif
4539 ) == FAIL)
4541 #ifdef FF_VERBOSE
4542 if (p_verbose >= 5)
4544 verbose_enter_scroll();
4545 smsg((char_u *)"Already Searched: %s (%s)",
4546 stackp->ffs_fix_path, stackp->ffs_wc_path);
4547 /* don't overwrite this either */
4548 msg_puts((char_u *)"\n");
4549 verbose_leave_scroll();
4551 #endif
4552 ff_free_stack_element(stackp);
4553 continue;
4555 #ifdef FF_VERBOSE
4556 else if (p_verbose >= 5)
4558 verbose_enter_scroll();
4559 smsg((char_u *)"Searching: %s (%s)",
4560 stackp->ffs_fix_path, stackp->ffs_wc_path);
4561 /* don't overwrite this either */
4562 msg_puts((char_u *)"\n");
4563 verbose_leave_scroll();
4565 #endif
4567 /* check depth */
4568 if (stackp->ffs_level <= 0)
4570 ff_free_stack_element(stackp);
4571 continue;
4574 file_path[0] = NUL;
4577 * If no filearray till now expand wildcards
4578 * The function expand_wildcards() can handle an array of paths
4579 * and all possible expands are returned in one array. We use this
4580 * to handle the expansion of '**' into an empty string.
4582 if (stackp->ffs_filearray == NULL)
4584 char_u *dirptrs[2];
4586 /* we use filepath to build the path expand_wildcards() should
4587 * expand.
4589 dirptrs[0] = file_path;
4590 dirptrs[1] = NULL;
4592 /* if we have a start dir copy it in */
4593 if (!vim_isAbsName(stackp->ffs_fix_path)
4594 && search_ctx->ffsc_start_dir)
4596 STRCPY(file_path, search_ctx->ffsc_start_dir);
4597 add_pathsep(file_path);
4600 /* append the fix part of the search path */
4601 STRCAT(file_path, stackp->ffs_fix_path);
4602 add_pathsep(file_path);
4604 #ifdef FEAT_PATH_EXTRA
4605 rest_of_wildcards = stackp->ffs_wc_path;
4606 if (*rest_of_wildcards != NUL)
4608 len = (int)STRLEN(file_path);
4609 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4611 /* pointer to the restrict byte
4612 * The restrict byte is not a character!
4614 p = rest_of_wildcards + 2;
4616 if (*p > 0)
4618 (*p)--;
4619 file_path[len++] = '*';
4622 if (*p == 0)
4624 /* remove '**<numb> from wildcards */
4625 STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
4627 else
4628 rest_of_wildcards += 3;
4630 if (stackp->ffs_star_star_empty == 0)
4632 /* if not done before, expand '**' to empty */
4633 stackp->ffs_star_star_empty = 1;
4634 dirptrs[1] = stackp->ffs_fix_path;
4639 * Here we copy until the next path separator or the end of
4640 * the path. If we stop at a path separator, there is
4641 * still something else left. This is handled below by
4642 * pushing every directory returned from expand_wildcards()
4643 * on the stack again for further search.
4645 while (*rest_of_wildcards
4646 && !vim_ispathsep(*rest_of_wildcards))
4647 file_path[len++] = *rest_of_wildcards++;
4649 file_path[len] = NUL;
4650 if (vim_ispathsep(*rest_of_wildcards))
4651 rest_of_wildcards++;
4653 #endif
4656 * Expand wildcards like "*" and "$VAR".
4657 * If the path is a URL don't try this.
4659 if (path_with_url(dirptrs[0]))
4661 stackp->ffs_filearray = (char_u **)
4662 alloc((unsigned)sizeof(char *));
4663 if (stackp->ffs_filearray != NULL
4664 && (stackp->ffs_filearray[0]
4665 = vim_strsave(dirptrs[0])) != NULL)
4666 stackp->ffs_filearray_size = 1;
4667 else
4668 stackp->ffs_filearray_size = 0;
4670 else
4671 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
4672 &stackp->ffs_filearray_size,
4673 &stackp->ffs_filearray,
4674 EW_DIR|EW_ADDSLASH|EW_SILENT);
4676 stackp->ffs_filearray_cur = 0;
4677 stackp->ffs_stage = 0;
4679 #ifdef FEAT_PATH_EXTRA
4680 else
4681 rest_of_wildcards = &stackp->ffs_wc_path[
4682 STRLEN(stackp->ffs_wc_path)];
4683 #endif
4685 if (stackp->ffs_stage == 0)
4687 /* this is the first time we work on this directory */
4688 #ifdef FEAT_PATH_EXTRA
4689 if (*rest_of_wildcards == NUL)
4690 #endif
4693 * we don't have further wildcards to expand, so we have to
4694 * check for the final file now
4696 for (i = stackp->ffs_filearray_cur;
4697 i < stackp->ffs_filearray_size; ++i)
4699 if (!path_with_url(stackp->ffs_filearray[i])
4700 && !mch_isdir(stackp->ffs_filearray[i]))
4701 continue; /* not a directory */
4703 /* prepare the filename to be checked for existance
4704 * below */
4705 STRCPY(file_path, stackp->ffs_filearray[i]);
4706 add_pathsep(file_path);
4707 STRCAT(file_path, search_ctx->ffsc_file_to_search);
4710 * Try without extra suffix and then with suffixes
4711 * from 'suffixesadd'.
4713 #ifdef FEAT_SEARCHPATH
4714 len = (int)STRLEN(file_path);
4715 suf = curbuf->b_p_sua;
4716 for (;;)
4717 #endif
4719 /* if file exists and we didn't already find it */
4720 if ((path_with_url(file_path)
4721 || (mch_getperm(file_path) >= 0
4722 && (search_ctx->ffsc_find_what
4723 == FINDFILE_BOTH
4724 || ((search_ctx->ffsc_find_what
4725 == FINDFILE_DIR)
4726 == mch_isdir(file_path)))))
4727 #ifndef FF_VERBOSE
4728 && (ff_check_visited(
4729 &search_ctx->ffsc_visited_list->ffvl_visited_list,
4730 file_path
4731 #ifdef FEAT_PATH_EXTRA
4732 , (char_u *)""
4733 #endif
4734 ) == OK)
4735 #endif
4738 #ifdef FF_VERBOSE
4739 if (ff_check_visited(
4740 &search_ctx->ffsc_visited_list->ffvl_visited_list,
4741 file_path
4742 #ifdef FEAT_PATH_EXTRA
4743 , (char_u *)""
4744 #endif
4745 ) == FAIL)
4747 if (p_verbose >= 5)
4749 verbose_enter_scroll();
4750 smsg((char_u *)"Already: %s",
4751 file_path);
4752 /* don't overwrite this either */
4753 msg_puts((char_u *)"\n");
4754 verbose_leave_scroll();
4756 continue;
4758 #endif
4760 /* push dir to examine rest of subdirs later */
4761 stackp->ffs_filearray_cur = i + 1;
4762 ff_push(search_ctx, stackp);
4764 if (!path_with_url(file_path))
4765 simplify_filename(file_path);
4766 if (mch_dirname(ff_expand_buffer, MAXPATHL)
4767 == OK)
4769 p = shorten_fname(file_path,
4770 ff_expand_buffer);
4771 if (p != NULL)
4772 STRMOVE(file_path, p);
4774 #ifdef FF_VERBOSE
4775 if (p_verbose >= 5)
4777 verbose_enter_scroll();
4778 smsg((char_u *)"HIT: %s", file_path);
4779 /* don't overwrite this either */
4780 msg_puts((char_u *)"\n");
4781 verbose_leave_scroll();
4783 #endif
4784 return file_path;
4787 #ifdef FEAT_SEARCHPATH
4788 /* Not found or found already, try next suffix. */
4789 if (*suf == NUL)
4790 break;
4791 copy_option_part(&suf, file_path + len,
4792 MAXPATHL - len, ",");
4793 #endif
4797 #ifdef FEAT_PATH_EXTRA
4798 else
4801 * still wildcards left, push the directories for further
4802 * search
4804 for (i = stackp->ffs_filearray_cur;
4805 i < stackp->ffs_filearray_size; ++i)
4807 if (!mch_isdir(stackp->ffs_filearray[i]))
4808 continue; /* not a directory */
4810 ff_push(search_ctx,
4811 ff_create_stack_element(
4812 stackp->ffs_filearray[i],
4813 rest_of_wildcards,
4814 stackp->ffs_level - 1, 0));
4817 #endif
4818 stackp->ffs_filearray_cur = 0;
4819 stackp->ffs_stage = 1;
4822 #ifdef FEAT_PATH_EXTRA
4824 * if wildcards contains '**' we have to descent till we reach the
4825 * leaves of the directory tree.
4827 if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
4829 for (i = stackp->ffs_filearray_cur;
4830 i < stackp->ffs_filearray_size; ++i)
4832 if (fnamecmp(stackp->ffs_filearray[i],
4833 stackp->ffs_fix_path) == 0)
4834 continue; /* don't repush same directory */
4835 if (!mch_isdir(stackp->ffs_filearray[i]))
4836 continue; /* not a directory */
4837 ff_push(search_ctx,
4838 ff_create_stack_element(stackp->ffs_filearray[i],
4839 stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
4842 #endif
4844 /* we are done with the current directory */
4845 ff_free_stack_element(stackp);
4849 #ifdef FEAT_PATH_EXTRA
4850 /* If we reached this, we didn't find anything downwards.
4851 * Let's check if we should do an upward search.
4853 if (search_ctx->ffsc_start_dir
4854 && search_ctx->ffsc_stopdirs_v != NULL && !got_int)
4856 ff_stack_T *sptr;
4858 /* is the last starting directory in the stop list? */
4859 if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
4860 (int)(path_end - search_ctx->ffsc_start_dir),
4861 search_ctx->ffsc_stopdirs_v) == TRUE)
4862 break;
4864 /* cut of last dir */
4865 while (path_end > search_ctx->ffsc_start_dir
4866 && vim_ispathsep(*path_end))
4867 path_end--;
4868 while (path_end > search_ctx->ffsc_start_dir
4869 && !vim_ispathsep(path_end[-1]))
4870 path_end--;
4871 *path_end = 0;
4872 path_end--;
4874 if (*search_ctx->ffsc_start_dir == 0)
4875 break;
4877 STRCPY(file_path, search_ctx->ffsc_start_dir);
4878 add_pathsep(file_path);
4879 STRCAT(file_path, search_ctx->ffsc_fix_path);
4881 /* create a new stack entry */
4882 sptr = ff_create_stack_element(file_path,
4883 search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
4884 if (sptr == NULL)
4885 break;
4886 ff_push(search_ctx, sptr);
4888 else
4889 break;
4891 #endif
4893 vim_free(file_path);
4894 return NULL;
4898 * Free the list of lists of visited files and directories
4899 * Can handle it if the passed search_context is NULL;
4901 void
4902 vim_findfile_free_visited(search_ctx_arg)
4903 void *search_ctx_arg;
4905 ff_search_ctx_T *search_ctx;
4907 if (search_ctx_arg == NULL)
4908 return;
4910 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
4911 vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
4912 vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
4915 static void
4916 vim_findfile_free_visited_list(list_headp)
4917 ff_visited_list_hdr_T **list_headp;
4919 ff_visited_list_hdr_T *vp;
4921 while (*list_headp != NULL)
4923 vp = (*list_headp)->ffvl_next;
4924 ff_free_visited_list((*list_headp)->ffvl_visited_list);
4926 vim_free((*list_headp)->ffvl_filename);
4927 vim_free(*list_headp);
4928 *list_headp = vp;
4930 *list_headp = NULL;
4933 static void
4934 ff_free_visited_list(vl)
4935 ff_visited_T *vl;
4937 ff_visited_T *vp;
4939 while (vl != NULL)
4941 vp = vl->ffv_next;
4942 #ifdef FEAT_PATH_EXTRA
4943 vim_free(vl->ffv_wc_path);
4944 #endif
4945 vim_free(vl);
4946 vl = vp;
4948 vl = NULL;
4952 * Returns the already visited list for the given filename. If none is found it
4953 * allocates a new one.
4955 static ff_visited_list_hdr_T*
4956 ff_get_visited_list(filename, list_headp)
4957 char_u *filename;
4958 ff_visited_list_hdr_T **list_headp;
4960 ff_visited_list_hdr_T *retptr = NULL;
4962 /* check if a visited list for the given filename exists */
4963 if (*list_headp != NULL)
4965 retptr = *list_headp;
4966 while (retptr != NULL)
4968 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
4970 #ifdef FF_VERBOSE
4971 if (p_verbose >= 5)
4973 verbose_enter_scroll();
4974 smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
4975 filename);
4976 /* don't overwrite this either */
4977 msg_puts((char_u *)"\n");
4978 verbose_leave_scroll();
4980 #endif
4981 return retptr;
4983 retptr = retptr->ffvl_next;
4987 #ifdef FF_VERBOSE
4988 if (p_verbose >= 5)
4990 verbose_enter_scroll();
4991 smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
4992 /* don't overwrite this either */
4993 msg_puts((char_u *)"\n");
4994 verbose_leave_scroll();
4996 #endif
4999 * if we reach this we didn't find a list and we have to allocate new list
5001 retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
5002 if (retptr == NULL)
5003 return NULL;
5005 retptr->ffvl_visited_list = NULL;
5006 retptr->ffvl_filename = vim_strsave(filename);
5007 if (retptr->ffvl_filename == NULL)
5009 vim_free(retptr);
5010 return NULL;
5012 retptr->ffvl_next = *list_headp;
5013 *list_headp = retptr;
5015 return retptr;
5018 #ifdef FEAT_PATH_EXTRA
5020 * check if two wildcard paths are equal. Returns TRUE or FALSE.
5021 * They are equal if:
5022 * - both paths are NULL
5023 * - they have the same length
5024 * - char by char comparison is OK
5025 * - the only differences are in the counters behind a '**', so
5026 * '**\20' is equal to '**\24'
5028 static int
5029 ff_wc_equal(s1, s2)
5030 char_u *s1;
5031 char_u *s2;
5033 int i;
5035 if (s1 == s2)
5036 return TRUE;
5038 if (s1 == NULL || s2 == NULL)
5039 return FALSE;
5041 if (STRLEN(s1) != STRLEN(s2))
5042 return FAIL;
5044 for (i = 0; s1[i] != NUL && s2[i] != NUL; i++)
5046 if (s1[i] != s2[i]
5047 #ifdef CASE_INSENSITIVE_FILENAME
5048 && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i])
5049 #endif
5052 if (i >= 2)
5053 if (s1[i-1] == '*' && s1[i-2] == '*')
5054 continue;
5055 else
5056 return FAIL;
5057 else
5058 return FAIL;
5061 return TRUE;
5063 #endif
5066 * maintains the list of already visited files and dirs
5067 * returns FAIL if the given file/dir is already in the list
5068 * returns OK if it is newly added
5070 * TODO: What to do on memory allocation problems?
5071 * -> return TRUE - Better the file is found several times instead of
5072 * never.
5074 static int
5075 ff_check_visited(visited_list, fname
5076 #ifdef FEAT_PATH_EXTRA
5077 , wc_path
5078 #endif
5080 ff_visited_T **visited_list;
5081 char_u *fname;
5082 #ifdef FEAT_PATH_EXTRA
5083 char_u *wc_path;
5084 #endif
5086 ff_visited_T *vp;
5087 #ifdef UNIX
5088 struct stat st;
5089 int url = FALSE;
5090 #endif
5092 /* For an URL we only compare the name, otherwise we compare the
5093 * device/inode (unix) or the full path name (not Unix). */
5094 if (path_with_url(fname))
5096 vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
5097 #ifdef UNIX
5098 url = TRUE;
5099 #endif
5101 else
5103 ff_expand_buffer[0] = NUL;
5104 #ifdef UNIX
5105 if (mch_stat((char *)fname, &st) < 0)
5106 #else
5107 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
5108 #endif
5109 return FAIL;
5112 /* check against list of already visited files */
5113 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
5115 if (
5116 #ifdef UNIX
5117 !url ? (vp->ffv_dev_valid && vp->ffv_dev == st.st_dev
5118 && vp->ffv_ino == st.st_ino)
5120 #endif
5121 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
5124 #ifdef FEAT_PATH_EXTRA
5125 /* are the wildcard parts equal */
5126 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
5127 #endif
5128 /* already visited */
5129 return FAIL;
5134 * New file/dir. Add it to the list of visited files/dirs.
5136 vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
5137 + STRLEN(ff_expand_buffer)));
5139 if (vp != NULL)
5141 #ifdef UNIX
5142 if (!url)
5144 vp->ffv_dev_valid = TRUE;
5145 vp->ffv_ino = st.st_ino;
5146 vp->ffv_dev = st.st_dev;
5147 vp->ffv_fname[0] = NUL;
5149 else
5151 vp->ffv_dev_valid = FALSE;
5152 #endif
5153 STRCPY(vp->ffv_fname, ff_expand_buffer);
5154 #ifdef UNIX
5156 #endif
5157 #ifdef FEAT_PATH_EXTRA
5158 if (wc_path != NULL)
5159 vp->ffv_wc_path = vim_strsave(wc_path);
5160 else
5161 vp->ffv_wc_path = NULL;
5162 #endif
5164 vp->ffv_next = *visited_list;
5165 *visited_list = vp;
5168 return OK;
5172 * create stack element from given path pieces
5174 static ff_stack_T *
5175 ff_create_stack_element(fix_part,
5176 #ifdef FEAT_PATH_EXTRA
5177 wc_part,
5178 #endif
5179 level, star_star_empty)
5180 char_u *fix_part;
5181 #ifdef FEAT_PATH_EXTRA
5182 char_u *wc_part;
5183 #endif
5184 int level;
5185 int star_star_empty;
5187 ff_stack_T *new;
5189 new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
5190 if (new == NULL)
5191 return NULL;
5193 new->ffs_prev = NULL;
5194 new->ffs_filearray = NULL;
5195 new->ffs_filearray_size = 0;
5196 new->ffs_filearray_cur = 0;
5197 new->ffs_stage = 0;
5198 new->ffs_level = level;
5199 new->ffs_star_star_empty = star_star_empty;;
5201 /* the following saves NULL pointer checks in vim_findfile */
5202 if (fix_part == NULL)
5203 fix_part = (char_u *)"";
5204 new->ffs_fix_path = vim_strsave(fix_part);
5206 #ifdef FEAT_PATH_EXTRA
5207 if (wc_part == NULL)
5208 wc_part = (char_u *)"";
5209 new->ffs_wc_path = vim_strsave(wc_part);
5210 #endif
5212 if (new->ffs_fix_path == NULL
5213 #ifdef FEAT_PATH_EXTRA
5214 || new->ffs_wc_path == NULL
5215 #endif
5218 ff_free_stack_element(new);
5219 new = NULL;
5222 return new;
5226 * Push a dir on the directory stack.
5228 static void
5229 ff_push(search_ctx, stack_ptr)
5230 ff_search_ctx_T *search_ctx;
5231 ff_stack_T *stack_ptr;
5233 /* check for NULL pointer, not to return an error to the user, but
5234 * to prevent a crash */
5235 if (stack_ptr != NULL)
5237 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
5238 search_ctx->ffsc_stack_ptr = stack_ptr;
5243 * Pop a dir from the directory stack.
5244 * Returns NULL if stack is empty.
5246 static ff_stack_T *
5247 ff_pop(search_ctx)
5248 ff_search_ctx_T *search_ctx;
5250 ff_stack_T *sptr;
5252 sptr = search_ctx->ffsc_stack_ptr;
5253 if (search_ctx->ffsc_stack_ptr != NULL)
5254 search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
5256 return sptr;
5260 * free the given stack element
5262 static void
5263 ff_free_stack_element(stack_ptr)
5264 ff_stack_T *stack_ptr;
5266 /* vim_free handles possible NULL pointers */
5267 vim_free(stack_ptr->ffs_fix_path);
5268 #ifdef FEAT_PATH_EXTRA
5269 vim_free(stack_ptr->ffs_wc_path);
5270 #endif
5272 if (stack_ptr->ffs_filearray != NULL)
5273 FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
5275 vim_free(stack_ptr);
5279 * Clear the search context, but NOT the visited list.
5281 static void
5282 ff_clear(search_ctx)
5283 ff_search_ctx_T *search_ctx;
5285 ff_stack_T *sptr;
5287 /* clear up stack */
5288 while ((sptr = ff_pop(search_ctx)) != NULL)
5289 ff_free_stack_element(sptr);
5291 vim_free(search_ctx->ffsc_file_to_search);
5292 vim_free(search_ctx->ffsc_start_dir);
5293 vim_free(search_ctx->ffsc_fix_path);
5294 #ifdef FEAT_PATH_EXTRA
5295 vim_free(search_ctx->ffsc_wc_path);
5296 #endif
5298 #ifdef FEAT_PATH_EXTRA
5299 if (search_ctx->ffsc_stopdirs_v != NULL)
5301 int i = 0;
5303 while (search_ctx->ffsc_stopdirs_v[i] != NULL)
5305 vim_free(search_ctx->ffsc_stopdirs_v[i]);
5306 i++;
5308 vim_free(search_ctx->ffsc_stopdirs_v);
5310 search_ctx->ffsc_stopdirs_v = NULL;
5311 #endif
5313 /* reset everything */
5314 search_ctx->ffsc_file_to_search = NULL;
5315 search_ctx->ffsc_start_dir = NULL;
5316 search_ctx->ffsc_fix_path = NULL;
5317 #ifdef FEAT_PATH_EXTRA
5318 search_ctx->ffsc_wc_path = NULL;
5319 search_ctx->ffsc_level = 0;
5320 #endif
5323 #ifdef FEAT_PATH_EXTRA
5325 * check if the given path is in the stopdirs
5326 * returns TRUE if yes else FALSE
5328 static int
5329 ff_path_in_stoplist(path, path_len, stopdirs_v)
5330 char_u *path;
5331 int path_len;
5332 char_u **stopdirs_v;
5334 int i = 0;
5336 /* eat up trailing path separators, except the first */
5337 while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
5338 path_len--;
5340 /* if no path consider it as match */
5341 if (path_len == 0)
5342 return TRUE;
5344 for (i = 0; stopdirs_v[i] != NULL; i++)
5346 if ((int)STRLEN(stopdirs_v[i]) > path_len)
5348 /* match for parent directory. So '/home' also matches
5349 * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
5350 * '/home/r' would also match '/home/rks'
5352 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
5353 && vim_ispathsep(stopdirs_v[i][path_len]))
5354 return TRUE;
5356 else
5358 if (fnamecmp(stopdirs_v[i], path) == 0)
5359 return TRUE;
5362 return FALSE;
5364 #endif
5366 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
5368 * Find the file name "ptr[len]" in the path. Also finds directory names.
5370 * On the first call set the parameter 'first' to TRUE to initialize
5371 * the search. For repeating calls to FALSE.
5373 * Repeating calls will return other files called 'ptr[len]' from the path.
5375 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
5376 * don't need valid values.
5378 * If nothing found on the first call the option FNAME_MESS will issue the
5379 * message:
5380 * 'Can't find file "<file>" in path'
5381 * On repeating calls:
5382 * 'No more file "<file>" found in path'
5384 * options:
5385 * FNAME_MESS give error message when not found
5387 * Uses NameBuff[]!
5389 * Returns an allocated string for the file name. NULL for error.
5392 char_u *
5393 find_file_in_path(ptr, len, options, first, rel_fname)
5394 char_u *ptr; /* file name */
5395 int len; /* length of file name */
5396 int options;
5397 int first; /* use count'th matching file name */
5398 char_u *rel_fname; /* file name searching relative to */
5400 return find_file_in_path_option(ptr, len, options, first,
5401 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
5402 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
5405 static char_u *ff_file_to_find = NULL;
5406 static void *fdip_search_ctx = NULL;
5408 #if defined(EXITFREE)
5409 static void
5410 free_findfile()
5412 vim_free(ff_file_to_find);
5413 vim_findfile_cleanup(fdip_search_ctx);
5415 #endif
5418 * Find the directory name "ptr[len]" in the path.
5420 * options:
5421 * FNAME_MESS give error message when not found
5423 * Uses NameBuff[]!
5425 * Returns an allocated string for the file name. NULL for error.
5427 char_u *
5428 find_directory_in_path(ptr, len, options, rel_fname)
5429 char_u *ptr; /* file name */
5430 int len; /* length of file name */
5431 int options;
5432 char_u *rel_fname; /* file name searching relative to */
5434 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
5435 FINDFILE_DIR, rel_fname, (char_u *)"");
5438 char_u *
5439 find_file_in_path_option(ptr, len, options, first, path_option, find_what, rel_fname, suffixes)
5440 char_u *ptr; /* file name */
5441 int len; /* length of file name */
5442 int options;
5443 int first; /* use count'th matching file name */
5444 char_u *path_option; /* p_path or p_cdpath */
5445 int find_what; /* FINDFILE_FILE, _DIR or _BOTH */
5446 char_u *rel_fname; /* file name we are looking relative to. */
5447 char_u *suffixes; /* list of suffixes, 'suffixesadd' option */
5449 static char_u *dir;
5450 static int did_findfile_init = FALSE;
5451 char_u save_char;
5452 char_u *file_name = NULL;
5453 char_u *buf = NULL;
5454 int rel_to_curdir;
5455 #ifdef AMIGA
5456 struct Process *proc = (struct Process *)FindTask(0L);
5457 APTR save_winptr = proc->pr_WindowPtr;
5459 /* Avoid a requester here for a volume that doesn't exist. */
5460 proc->pr_WindowPtr = (APTR)-1L;
5461 #endif
5463 if (first == TRUE)
5465 /* copy file name into NameBuff, expanding environment variables */
5466 save_char = ptr[len];
5467 ptr[len] = NUL;
5468 expand_env(ptr, NameBuff, MAXPATHL);
5469 ptr[len] = save_char;
5471 vim_free(ff_file_to_find);
5472 ff_file_to_find = vim_strsave(NameBuff);
5473 if (ff_file_to_find == NULL) /* out of memory */
5475 file_name = NULL;
5476 goto theend;
5480 rel_to_curdir = (ff_file_to_find[0] == '.'
5481 && (ff_file_to_find[1] == NUL
5482 || vim_ispathsep(ff_file_to_find[1])
5483 || (ff_file_to_find[1] == '.'
5484 && (ff_file_to_find[2] == NUL
5485 || vim_ispathsep(ff_file_to_find[2])))));
5486 if (vim_isAbsName(ff_file_to_find)
5487 /* "..", "../path", "." and "./path": don't use the path_option */
5488 || rel_to_curdir
5489 #if defined(MSWIN) || defined(MSDOS) || defined(OS2)
5490 /* handle "\tmp" as absolute path */
5491 || vim_ispathsep(ff_file_to_find[0])
5492 /* handle "c:name" as absulute path */
5493 || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
5494 #endif
5495 #ifdef AMIGA
5496 /* handle ":tmp" as absolute path */
5497 || ff_file_to_find[0] == ':'
5498 #endif
5502 * Absolute path, no need to use "path_option".
5503 * If this is not a first call, return NULL. We already returned a
5504 * filename on the first call.
5506 if (first == TRUE)
5508 int l;
5509 int run;
5511 if (path_with_url(ff_file_to_find))
5513 file_name = vim_strsave(ff_file_to_find);
5514 goto theend;
5517 /* When FNAME_REL flag given first use the directory of the file.
5518 * Otherwise or when this fails use the current directory. */
5519 for (run = 1; run <= 2; ++run)
5521 l = (int)STRLEN(ff_file_to_find);
5522 if (run == 1
5523 && rel_to_curdir
5524 && (options & FNAME_REL)
5525 && rel_fname != NULL
5526 && STRLEN(rel_fname) + l < MAXPATHL)
5528 STRCPY(NameBuff, rel_fname);
5529 STRCPY(gettail(NameBuff), ff_file_to_find);
5530 l = (int)STRLEN(NameBuff);
5532 else
5534 STRCPY(NameBuff, ff_file_to_find);
5535 run = 2;
5538 /* When the file doesn't exist, try adding parts of
5539 * 'suffixesadd'. */
5540 buf = suffixes;
5541 for (;;)
5543 if (
5544 #ifdef DJGPP
5545 /* "C:" by itself will fail for mch_getperm(),
5546 * assume it's always valid. */
5547 (find_what != FINDFILE_FILE && NameBuff[0] != NUL
5548 && NameBuff[1] == ':'
5549 && NameBuff[2] == NUL) ||
5550 #endif
5551 (mch_getperm(NameBuff) >= 0
5552 && (find_what == FINDFILE_BOTH
5553 || ((find_what == FINDFILE_DIR)
5554 == mch_isdir(NameBuff)))))
5556 file_name = vim_strsave(NameBuff);
5557 goto theend;
5559 if (*buf == NUL)
5560 break;
5561 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5566 else
5569 * Loop over all paths in the 'path' or 'cdpath' option.
5570 * When "first" is set, first setup to the start of the option.
5571 * Otherwise continue to find the next match.
5573 if (first == TRUE)
5575 /* vim_findfile_free_visited can handle a possible NULL pointer */
5576 vim_findfile_free_visited(fdip_search_ctx);
5577 dir = path_option;
5578 did_findfile_init = FALSE;
5581 for (;;)
5583 if (did_findfile_init)
5585 file_name = vim_findfile(fdip_search_ctx);
5586 if (file_name != NULL)
5587 break;
5589 did_findfile_init = FALSE;
5591 else
5593 char_u *r_ptr;
5595 if (dir == NULL || *dir == NUL)
5597 /* We searched all paths of the option, now we can
5598 * free the search context. */
5599 vim_findfile_cleanup(fdip_search_ctx);
5600 fdip_search_ctx = NULL;
5601 break;
5604 if ((buf = alloc((int)(MAXPATHL))) == NULL)
5605 break;
5607 /* copy next path */
5608 buf[0] = 0;
5609 copy_option_part(&dir, buf, MAXPATHL, " ,");
5611 #ifdef FEAT_PATH_EXTRA
5612 /* get the stopdir string */
5613 r_ptr = vim_findfile_stopdir(buf);
5614 #else
5615 r_ptr = NULL;
5616 #endif
5617 fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
5618 r_ptr, 100, FALSE, find_what,
5619 fdip_search_ctx, FALSE, rel_fname);
5620 if (fdip_search_ctx != NULL)
5621 did_findfile_init = TRUE;
5622 vim_free(buf);
5626 if (file_name == NULL && (options & FNAME_MESS))
5628 if (first == TRUE)
5630 if (find_what == FINDFILE_DIR)
5631 EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
5632 ff_file_to_find);
5633 else
5634 EMSG2(_("E345: Can't find file \"%s\" in path"),
5635 ff_file_to_find);
5637 else
5639 if (find_what == FINDFILE_DIR)
5640 EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
5641 ff_file_to_find);
5642 else
5643 EMSG2(_("E347: No more file \"%s\" found in path"),
5644 ff_file_to_find);
5648 theend:
5649 #ifdef AMIGA
5650 proc->pr_WindowPtr = save_winptr;
5651 #endif
5652 return file_name;
5655 #endif /* FEAT_SEARCHPATH */
5658 * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search
5659 * 'cdpath' for relative directory names, otherwise just mch_chdir().
5662 vim_chdir(new_dir)
5663 char_u *new_dir;
5665 #ifndef FEAT_SEARCHPATH
5666 return mch_chdir((char *)new_dir);
5667 #else
5668 char_u *dir_name;
5669 int r;
5671 dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
5672 FNAME_MESS, curbuf->b_ffname);
5673 if (dir_name == NULL)
5674 return -1;
5675 r = mch_chdir((char *)dir_name);
5676 vim_free(dir_name);
5677 return r;
5678 #endif
5682 * Get user name from machine-specific function.
5683 * Returns the user name in "buf[len]".
5684 * Some systems are quite slow in obtaining the user name (Windows NT), thus
5685 * cache the result.
5686 * Returns OK or FAIL.
5689 get_user_name(buf, len)
5690 char_u *buf;
5691 int len;
5693 if (username == NULL)
5695 if (mch_get_user_name(buf, len) == FAIL)
5696 return FAIL;
5697 username = vim_strsave(buf);
5699 else
5700 vim_strncpy(buf, username, len - 1);
5701 return OK;
5704 #ifndef HAVE_QSORT
5706 * Our own qsort(), for systems that don't have it.
5707 * It's simple and slow. From the K&R C book.
5709 void
5710 qsort(base, elm_count, elm_size, cmp)
5711 void *base;
5712 size_t elm_count;
5713 size_t elm_size;
5714 int (*cmp) __ARGS((const void *, const void *));
5716 char_u *buf;
5717 char_u *p1;
5718 char_u *p2;
5719 int i, j;
5720 int gap;
5722 buf = alloc((unsigned)elm_size);
5723 if (buf == NULL)
5724 return;
5726 for (gap = elm_count / 2; gap > 0; gap /= 2)
5727 for (i = gap; i < elm_count; ++i)
5728 for (j = i - gap; j >= 0; j -= gap)
5730 /* Compare the elements. */
5731 p1 = (char_u *)base + j * elm_size;
5732 p2 = (char_u *)base + (j + gap) * elm_size;
5733 if ((*cmp)((void *)p1, (void *)p2) <= 0)
5734 break;
5735 /* Exchange the elemets. */
5736 mch_memmove(buf, p1, elm_size);
5737 mch_memmove(p1, p2, elm_size);
5738 mch_memmove(p2, buf, elm_size);
5741 vim_free(buf);
5743 #endif
5746 * Sort an array of strings.
5748 static int
5749 #ifdef __BORLANDC__
5750 _RTLENTRYF
5751 #endif
5752 sort_compare __ARGS((const void *s1, const void *s2));
5754 static int
5755 #ifdef __BORLANDC__
5756 _RTLENTRYF
5757 #endif
5758 sort_compare(s1, s2)
5759 const void *s1;
5760 const void *s2;
5762 return STRCMP(*(char **)s1, *(char **)s2);
5765 void
5766 sort_strings(files, count)
5767 char_u **files;
5768 int count;
5770 qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
5773 #if !defined(NO_EXPANDPATH) || defined(PROTO)
5775 * Compare path "p[]" to "q[]".
5776 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
5777 * Return value like strcmp(p, q), but consider path separators.
5780 pathcmp(p, q, maxlen)
5781 const char *p, *q;
5782 int maxlen;
5784 int i;
5785 const char *s = NULL;
5787 for (i = 0; maxlen < 0 || i < maxlen; ++i)
5789 /* End of "p": check if "q" also ends or just has a slash. */
5790 if (p[i] == NUL)
5792 if (q[i] == NUL) /* full match */
5793 return 0;
5794 s = q;
5795 break;
5798 /* End of "q": check if "p" just has a slash. */
5799 if (q[i] == NUL)
5801 s = p;
5802 break;
5805 if (
5806 #ifdef CASE_INSENSITIVE_FILENAME
5807 TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i])
5808 #else
5809 p[i] != q[i]
5810 #endif
5811 #ifdef BACKSLASH_IN_FILENAME
5812 /* consider '/' and '\\' to be equal */
5813 && !((p[i] == '/' && q[i] == '\\')
5814 || (p[i] == '\\' && q[i] == '/'))
5815 #endif
5818 if (vim_ispathsep(p[i]))
5819 return -1;
5820 if (vim_ispathsep(q[i]))
5821 return 1;
5822 return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */
5825 if (s == NULL) /* "i" ran into "maxlen" */
5826 return 0;
5828 /* ignore a trailing slash, but not "//" or ":/" */
5829 if (s[i + 1] == NUL
5830 && i > 0
5831 && !after_pathsep((char_u *)s, (char_u *)s + i)
5832 #ifdef BACKSLASH_IN_FILENAME
5833 && (s[i] == '/' || s[i] == '\\')
5834 #else
5835 && s[i] == '/'
5836 #endif
5838 return 0; /* match with trailing slash */
5839 if (s == q)
5840 return -1; /* no match */
5841 return 1;
5843 #endif
5846 * The putenv() implementation below comes from the "screen" program.
5847 * Included with permission from Juergen Weigert.
5848 * See pty.c for the copyright notice.
5852 * putenv -- put value into environment
5854 * Usage: i = putenv (string)
5855 * int i;
5856 * char *string;
5858 * where string is of the form <name>=<value>.
5859 * Putenv returns 0 normally, -1 on error (not enough core for malloc).
5861 * Putenv may need to add a new name into the environment, or to
5862 * associate a value longer than the current value with a particular
5863 * name. So, to make life simpler, putenv() copies your entire
5864 * environment into the heap (i.e. malloc()) from the stack
5865 * (i.e. where it resides when your process is initiated) the first
5866 * time you call it.
5868 * (history removed, not very interesting. See the "screen" sources.)
5871 #if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
5873 #define EXTRASIZE 5 /* increment to add to env. size */
5875 static int envsize = -1; /* current size of environment */
5876 #ifndef MACOS_CLASSIC
5877 extern
5878 #endif
5879 char **environ; /* the global which is your env. */
5881 static int findenv __ARGS((char *name)); /* look for a name in the env. */
5882 static int newenv __ARGS((void)); /* copy env. from stack to heap */
5883 static int moreenv __ARGS((void)); /* incr. size of env. */
5886 putenv(string)
5887 const char *string;
5889 int i;
5890 char *p;
5892 if (envsize < 0)
5893 { /* first time putenv called */
5894 if (newenv() < 0) /* copy env. to heap */
5895 return -1;
5898 i = findenv((char *)string); /* look for name in environment */
5900 if (i < 0)
5901 { /* name must be added */
5902 for (i = 0; environ[i]; i++);
5903 if (i >= (envsize - 1))
5904 { /* need new slot */
5905 if (moreenv() < 0)
5906 return -1;
5908 p = (char *)alloc((unsigned)(strlen(string) + 1));
5909 if (p == NULL) /* not enough core */
5910 return -1;
5911 environ[i + 1] = 0; /* new end of env. */
5913 else
5914 { /* name already in env. */
5915 p = vim_realloc(environ[i], strlen(string) + 1);
5916 if (p == NULL)
5917 return -1;
5919 sprintf(p, "%s", string); /* copy into env. */
5920 environ[i] = p;
5922 return 0;
5925 static int
5926 findenv(name)
5927 char *name;
5929 char *namechar, *envchar;
5930 int i, found;
5932 found = 0;
5933 for (i = 0; environ[i] && !found; i++)
5935 envchar = environ[i];
5936 namechar = name;
5937 while (*namechar && *namechar != '=' && (*namechar == *envchar))
5939 namechar++;
5940 envchar++;
5942 found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
5944 return found ? i - 1 : -1;
5947 static int
5948 newenv()
5950 char **env, *elem;
5951 int i, esize;
5953 #ifdef MACOS
5954 /* for Mac a new, empty environment is created */
5955 i = 0;
5956 #else
5957 for (i = 0; environ[i]; i++)
5959 #endif
5960 esize = i + EXTRASIZE + 1;
5961 env = (char **)alloc((unsigned)(esize * sizeof (elem)));
5962 if (env == NULL)
5963 return -1;
5965 #ifndef MACOS
5966 for (i = 0; environ[i]; i++)
5968 elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
5969 if (elem == NULL)
5970 return -1;
5971 env[i] = elem;
5972 strcpy(elem, environ[i]);
5974 #endif
5976 env[i] = 0;
5977 environ = env;
5978 envsize = esize;
5979 return 0;
5982 static int
5983 moreenv()
5985 int esize;
5986 char **env;
5988 esize = envsize + EXTRASIZE;
5989 env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
5990 if (env == 0)
5991 return -1;
5992 environ = env;
5993 envsize = esize;
5994 return 0;
5997 # ifdef USE_VIMPTY_GETENV
5998 char_u *
5999 vimpty_getenv(string)
6000 const char_u *string;
6002 int i;
6003 char_u *p;
6005 if (envsize < 0)
6006 return NULL;
6008 i = findenv((char *)string);
6010 if (i < 0)
6011 return NULL;
6013 p = vim_strchr((char_u *)environ[i], '=');
6014 return (p + 1);
6016 # endif
6018 #endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
6020 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
6022 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
6023 * rights to write into.
6026 filewritable(fname)
6027 char_u *fname;
6029 int retval = 0;
6030 #if defined(UNIX) || defined(VMS)
6031 int perm = 0;
6032 #endif
6034 #if defined(UNIX) || defined(VMS)
6035 perm = mch_getperm(fname);
6036 #endif
6037 #ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */
6038 if (
6039 # ifdef WIN3264
6040 mch_writable(fname) &&
6041 # else
6042 # if defined(UNIX) || defined(VMS)
6043 (perm & 0222) &&
6044 # endif
6045 # endif
6046 mch_access((char *)fname, W_OK) == 0
6048 #endif
6050 ++retval;
6051 if (mch_isdir(fname))
6052 ++retval;
6054 return retval;
6056 #endif
6059 * Print an error message with one or two "%s" and one or two string arguments.
6060 * This is not in message.c to avoid a warning for prototypes.
6063 emsg3(s, a1, a2)
6064 char_u *s, *a1, *a2;
6066 if (emsg_not_now())
6067 return TRUE; /* no error messages at the moment */
6068 #ifdef HAVE_STDARG_H
6069 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, a1, a2);
6070 #else
6071 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, (long_u)a1, (long_u)a2);
6072 #endif
6073 return emsg(IObuff);
6077 * Print an error message with one "%ld" and one long int argument.
6078 * This is not in message.c to avoid a warning for prototypes.
6081 emsgn(s, n)
6082 char_u *s;
6083 long n;
6085 if (emsg_not_now())
6086 return TRUE; /* no error messages at the moment */
6087 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, n);
6088 return emsg(IObuff);