Merged from the latest developing branch.
[MacVim.git] / src / misc2.c
blob9fda8d58ffa6b39962c99821d99a45640fbafda3
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_curline();
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 cursor from moving on the trail byte */
336 if (has_mbyte)
337 mb_adjust_cursor();
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 * Make sure curwin->w_cursor.lnum is valid.
474 void
475 check_cursor_lnum()
477 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
479 #ifdef FEAT_FOLDING
480 /* If there is a closed fold at the end of the file, put the cursor in
481 * its first line. Otherwise in the last line. */
482 if (!hasFolding(curbuf->b_ml.ml_line_count,
483 &curwin->w_cursor.lnum, NULL))
484 #endif
485 curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
487 if (curwin->w_cursor.lnum <= 0)
488 curwin->w_cursor.lnum = 1;
492 * Make sure curwin->w_cursor.col is valid.
494 void
495 check_cursor_col()
497 colnr_T len;
498 #ifdef FEAT_VIRTUALEDIT
499 colnr_T oldcol = curwin->w_cursor.col;
500 colnr_T oldcoladd = curwin->w_cursor.col + curwin->w_cursor.coladd;
501 #endif
503 len = (colnr_T)STRLEN(ml_get_curline());
504 if (len == 0)
505 curwin->w_cursor.col = 0;
506 else if (curwin->w_cursor.col >= len)
508 /* Allow cursor past end-of-line when:
509 * - in Insert mode or restarting Insert mode
510 * - in Visual mode and 'selection' isn't "old"
511 * - 'virtualedit' is set */
512 if ((State & INSERT) || restart_edit
513 #ifdef FEAT_VISUAL
514 || (VIsual_active && *p_sel != 'o')
515 #endif
516 #ifdef FEAT_VIRTUALEDIT
517 || (ve_flags & VE_ONEMORE)
518 #endif
519 || virtual_active())
520 curwin->w_cursor.col = len;
521 else
523 curwin->w_cursor.col = len - 1;
524 #ifdef FEAT_MBYTE
525 /* prevent cursor from moving on the trail byte */
526 if (has_mbyte)
527 mb_adjust_cursor();
528 #endif
532 #ifdef FEAT_VIRTUALEDIT
533 /* If virtual editing is on, we can leave the cursor on the old position,
534 * only we must set it to virtual. But don't do it when at the end of the
535 * line. */
536 if (oldcol == MAXCOL)
537 curwin->w_cursor.coladd = 0;
538 else if (ve_flags == VE_ALL)
540 if (oldcoladd > curwin->w_cursor.col)
541 curwin->w_cursor.coladd = oldcoladd - curwin->w_cursor.col;
542 else
543 /* avoid weird number when there is a miscalculation or overflow */
544 curwin->w_cursor.coladd = 0;
546 #endif
550 * make sure curwin->w_cursor in on a valid character
552 void
553 check_cursor()
555 check_cursor_lnum();
556 check_cursor_col();
559 #if defined(FEAT_TEXTOBJ) || defined(PROTO)
561 * Make sure curwin->w_cursor is not on the NUL at the end of the line.
562 * Allow it when in Visual mode and 'selection' is not "old".
564 void
565 adjust_cursor_col()
567 if (curwin->w_cursor.col > 0
568 # ifdef FEAT_VISUAL
569 && (!VIsual_active || *p_sel == 'o')
570 # endif
571 && gchar_cursor() == NUL)
572 --curwin->w_cursor.col;
574 #endif
577 * When curwin->w_leftcol has changed, adjust the cursor position.
578 * Return TRUE if the cursor was moved.
581 leftcol_changed()
583 long lastcol;
584 colnr_T s, e;
585 int retval = FALSE;
587 changed_cline_bef_curs();
588 lastcol = curwin->w_leftcol + W_WIDTH(curwin) - curwin_col_off() - 1;
589 validate_virtcol();
592 * If the cursor is right or left of the screen, move it to last or first
593 * character.
595 if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso))
597 retval = TRUE;
598 coladvance((colnr_T)(lastcol - p_siso));
600 else if (curwin->w_virtcol < curwin->w_leftcol + p_siso)
602 retval = TRUE;
603 (void)coladvance((colnr_T)(curwin->w_leftcol + p_siso));
607 * If the start of the character under the cursor is not on the screen,
608 * advance the cursor one more char. If this fails (last char of the
609 * line) adjust the scrolling.
611 getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
612 if (e > (colnr_T)lastcol)
614 retval = TRUE;
615 coladvance(s - 1);
617 else if (s < curwin->w_leftcol)
619 retval = TRUE;
620 if (coladvance(e + 1) == FAIL) /* there isn't another character */
622 curwin->w_leftcol = s; /* adjust w_leftcol instead */
623 changed_cline_bef_curs();
627 if (retval)
628 curwin->w_set_curswant = TRUE;
629 redraw_later(NOT_VALID);
630 return retval;
633 /**********************************************************************
634 * Various routines dealing with allocation and deallocation of memory.
637 #if defined(MEM_PROFILE) || defined(PROTO)
639 # define MEM_SIZES 8200
640 static long_u mem_allocs[MEM_SIZES];
641 static long_u mem_frees[MEM_SIZES];
642 static long_u mem_allocated;
643 static long_u mem_freed;
644 static long_u mem_peak;
645 static long_u num_alloc;
646 static long_u num_freed;
648 static void mem_pre_alloc_s __ARGS((size_t *sizep));
649 static void mem_pre_alloc_l __ARGS((long_u *sizep));
650 static void mem_post_alloc __ARGS((void **pp, size_t size));
651 static void mem_pre_free __ARGS((void **pp));
653 static void
654 mem_pre_alloc_s(sizep)
655 size_t *sizep;
657 *sizep += sizeof(size_t);
660 static void
661 mem_pre_alloc_l(sizep)
662 long_u *sizep;
664 *sizep += sizeof(size_t);
667 static void
668 mem_post_alloc(pp, size)
669 void **pp;
670 size_t size;
672 if (*pp == NULL)
673 return;
674 size -= sizeof(size_t);
675 *(long_u *)*pp = size;
676 if (size <= MEM_SIZES-1)
677 mem_allocs[size-1]++;
678 else
679 mem_allocs[MEM_SIZES-1]++;
680 mem_allocated += size;
681 if (mem_allocated - mem_freed > mem_peak)
682 mem_peak = mem_allocated - mem_freed;
683 num_alloc++;
684 *pp = (void *)((char *)*pp + sizeof(size_t));
687 static void
688 mem_pre_free(pp)
689 void **pp;
691 long_u size;
693 *pp = (void *)((char *)*pp - sizeof(size_t));
694 size = *(size_t *)*pp;
695 if (size <= MEM_SIZES-1)
696 mem_frees[size-1]++;
697 else
698 mem_frees[MEM_SIZES-1]++;
699 mem_freed += size;
700 num_freed++;
704 * called on exit via atexit()
706 void
707 vim_mem_profile_dump()
709 int i, j;
711 printf("\r\n");
712 j = 0;
713 for (i = 0; i < MEM_SIZES - 1; i++)
715 if (mem_allocs[i] || mem_frees[i])
717 if (mem_frees[i] > mem_allocs[i])
718 printf("\r\n%s", _("ERROR: "));
719 printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
720 j++;
721 if (j > 3)
723 j = 0;
724 printf("\r\n");
729 i = MEM_SIZES - 1;
730 if (mem_allocs[i])
732 printf("\r\n");
733 if (mem_frees[i] > mem_allocs[i])
734 printf(_("ERROR: "));
735 printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
738 printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
739 mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
740 printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
741 num_alloc, num_freed);
744 #endif /* MEM_PROFILE */
747 * Some memory is reserved for error messages and for being able to
748 * call mf_release_all(), which needs some memory for mf_trans_add().
750 #if defined(MSDOS) && !defined(DJGPP)
751 # define SMALL_MEM
752 # define KEEP_ROOM 8192L
753 #else
754 # define KEEP_ROOM (2 * 8192L)
755 #endif
758 * Note: if unsigned is 16 bits we can only allocate up to 64K with alloc().
759 * Use lalloc for larger blocks.
761 char_u *
762 alloc(size)
763 unsigned size;
765 return (lalloc((long_u)size, TRUE));
769 * Allocate memory and set all bytes to zero.
771 char_u *
772 alloc_clear(size)
773 unsigned size;
775 char_u *p;
777 p = (lalloc((long_u)size, TRUE));
778 if (p != NULL)
779 (void)vim_memset(p, 0, (size_t)size);
780 return p;
784 * alloc() with check for maximum line length
786 char_u *
787 alloc_check(size)
788 unsigned size;
790 #if !defined(UNIX) && !defined(__EMX__)
791 if (sizeof(int) == 2 && size > 0x7fff)
793 /* Don't hide this message */
794 emsg_silent = 0;
795 EMSG(_("E340: Line is becoming too long"));
796 return NULL;
798 #endif
799 return (lalloc((long_u)size, TRUE));
803 * Allocate memory like lalloc() and set all bytes to zero.
805 char_u *
806 lalloc_clear(size, message)
807 long_u size;
808 int message;
810 char_u *p;
812 p = (lalloc(size, message));
813 if (p != NULL)
814 (void)vim_memset(p, 0, (size_t)size);
815 return p;
819 * Low level memory allocation function.
820 * This is used often, KEEP IT FAST!
822 char_u *
823 lalloc(size, message)
824 long_u size;
825 int message;
827 char_u *p; /* pointer to new storage space */
828 static int releasing = FALSE; /* don't do mf_release_all() recursive */
829 int try_again;
830 #if defined(HAVE_AVAIL_MEM) && !defined(SMALL_MEM)
831 static long_u allocated = 0; /* allocated since last avail check */
832 #endif
834 /* Safety check for allocating zero bytes */
835 if (size == 0)
837 /* Don't hide this message */
838 emsg_silent = 0;
839 EMSGN(_("E341: Internal error: lalloc(%ld, )"), size);
840 return NULL;
843 #ifdef MEM_PROFILE
844 mem_pre_alloc_l(&size);
845 #endif
847 #if defined(MSDOS) && !defined(DJGPP)
848 if (size >= 0xfff0) /* in MSDOS we can't deal with >64K blocks */
849 p = NULL;
850 else
851 #endif
854 * Loop when out of memory: Try to release some memfile blocks and
855 * if some blocks are released call malloc again.
857 for (;;)
860 * Handle three kind of systems:
861 * 1. No check for available memory: Just return.
862 * 2. Slow check for available memory: call mch_avail_mem() after
863 * allocating KEEP_ROOM amount of memory.
864 * 3. Strict check for available memory: call mch_avail_mem()
866 if ((p = (char_u *)malloc((size_t)size)) != NULL)
868 #ifndef HAVE_AVAIL_MEM
869 /* 1. No check for available memory: Just return. */
870 goto theend;
871 #else
872 # ifndef SMALL_MEM
873 /* 2. Slow check for available memory: call mch_avail_mem() after
874 * allocating (KEEP_ROOM / 2) amount of memory. */
875 allocated += size;
876 if (allocated < KEEP_ROOM / 2)
877 goto theend;
878 allocated = 0;
879 # endif
880 /* 3. check for available memory: call mch_avail_mem() */
881 if (mch_avail_mem(TRUE) < KEEP_ROOM && !releasing)
883 free((char *)p); /* System is low... no go! */
884 p = NULL;
886 else
887 goto theend;
888 #endif
891 * Remember that mf_release_all() is being called to avoid an endless
892 * loop, because mf_release_all() may call alloc() recursively.
894 if (releasing)
895 break;
896 releasing = TRUE;
898 clear_sb_text(); /* free any scrollback text */
899 try_again = mf_release_all(); /* release as many blocks as possible */
900 #ifdef FEAT_EVAL
901 try_again |= garbage_collect(); /* cleanup recursive lists/dicts */
902 #endif
904 releasing = FALSE;
905 if (!try_again)
906 break;
909 if (message && p == NULL)
910 do_outofmem_msg(size);
912 theend:
913 #ifdef MEM_PROFILE
914 mem_post_alloc((void **)&p, (size_t)size);
915 #endif
916 return p;
919 #if defined(MEM_PROFILE) || defined(PROTO)
921 * realloc() with memory profiling.
923 void *
924 mem_realloc(ptr, size)
925 void *ptr;
926 size_t size;
928 void *p;
930 mem_pre_free(&ptr);
931 mem_pre_alloc_s(&size);
933 p = realloc(ptr, size);
935 mem_post_alloc(&p, size);
937 return p;
939 #endif
942 * Avoid repeating the error message many times (they take 1 second each).
943 * Did_outofmem_msg is reset when a character is read.
945 void
946 do_outofmem_msg(size)
947 long_u size;
949 if (!did_outofmem_msg)
951 /* Don't hide this message */
952 emsg_silent = 0;
953 EMSGN(_("E342: Out of memory! (allocating %lu bytes)"), size);
954 did_outofmem_msg = TRUE;
958 #if defined(EXITFREE) || defined(PROTO)
960 # if defined(FEAT_SEARCHPATH)
961 static void free_findfile __ARGS((void));
962 # endif
965 * Free everything that we allocated.
966 * Can be used to detect memory leaks, e.g., with ccmalloc.
967 * NOTE: This is tricky! Things are freed that functions depend on. Don't be
968 * surprised if Vim crashes...
969 * Some things can't be freed, esp. things local to a library function.
971 void
972 free_all_mem()
974 buf_T *buf, *nextbuf;
975 static int entered = FALSE;
977 /* When we cause a crash here it is caught and Vim tries to exit cleanly.
978 * Don't try freeing everything again. */
979 if (entered)
980 return;
981 entered = TRUE;
983 # ifdef FEAT_AUTOCMD
984 block_autocmds(); /* don't want to trigger autocommands here */
985 # endif
987 # ifdef FEAT_WINDOWS
988 /* close all tabs and windows */
989 if (first_tabpage->tp_next != NULL)
990 do_cmdline_cmd((char_u *)"tabonly!");
991 if (firstwin != lastwin)
992 do_cmdline_cmd((char_u *)"only!");
993 # endif
995 # if defined(FEAT_SPELL)
996 /* Free all spell info. */
997 spell_free_all();
998 # endif
1000 # if defined(FEAT_USR_CMDS)
1001 /* Clear user commands (before deleting buffers). */
1002 ex_comclear(NULL);
1003 # endif
1005 # ifdef FEAT_MENU
1006 /* Clear menus. */
1007 do_cmdline_cmd((char_u *)"aunmenu *");
1008 # endif
1010 /* Clear mappings, abbreviations, breakpoints. */
1011 do_cmdline_cmd((char_u *)"mapclear");
1012 do_cmdline_cmd((char_u *)"mapclear!");
1013 do_cmdline_cmd((char_u *)"abclear");
1014 # if defined(FEAT_EVAL)
1015 do_cmdline_cmd((char_u *)"breakdel *");
1016 # endif
1017 # if defined(FEAT_PROFILE)
1018 do_cmdline_cmd((char_u *)"profdel *");
1019 # endif
1020 # if defined(FEAT_KEYMAP)
1021 do_cmdline_cmd((char_u *)"set keymap=");
1022 #endif
1024 # ifdef FEAT_TITLE
1025 free_titles();
1026 # endif
1027 # if defined(FEAT_SEARCHPATH)
1028 free_findfile();
1029 # endif
1031 /* Obviously named calls. */
1032 # if defined(FEAT_AUTOCMD)
1033 free_all_autocmds();
1034 # endif
1035 clear_termcodes();
1036 free_all_options();
1037 free_all_marks();
1038 alist_clear(&global_alist);
1039 free_homedir();
1040 free_search_patterns();
1041 free_old_sub();
1042 free_last_insert();
1043 free_prev_shellcmd();
1044 free_regexp_stuff();
1045 free_tag_stuff();
1046 free_cd_dir();
1047 # ifdef FEAT_SIGNS
1048 free_signs();
1049 # endif
1050 # ifdef FEAT_EVAL
1051 set_expr_line(NULL);
1052 # endif
1053 # ifdef FEAT_DIFF
1054 diff_clear(curtab);
1055 # endif
1056 clear_sb_text(); /* free any scrollback text */
1058 /* Free some global vars. */
1059 vim_free(username);
1060 # ifdef FEAT_CLIPBOARD
1061 vim_free(clip_exclude_prog);
1062 # endif
1063 vim_free(last_cmdline);
1064 # ifdef FEAT_CMDHIST
1065 vim_free(new_last_cmdline);
1066 # endif
1067 set_keep_msg(NULL, 0);
1068 vim_free(ff_expand_buffer);
1070 /* Clear cmdline history. */
1071 p_hi = 0;
1072 # ifdef FEAT_CMDHIST
1073 init_history();
1074 # endif
1076 #ifdef FEAT_QUICKFIX
1078 win_T *win;
1079 tabpage_T *tab;
1081 qf_free_all(NULL);
1082 /* Free all location lists */
1083 FOR_ALL_TAB_WINDOWS(tab, win)
1084 qf_free_all(win);
1086 #endif
1088 /* Close all script inputs. */
1089 close_all_scripts();
1091 #if defined(FEAT_WINDOWS)
1092 /* Destroy all windows. Must come before freeing buffers. */
1093 win_free_all();
1094 #endif
1096 /* Free all buffers. Reset 'autochdir' to avoid accessing things that
1097 * were freed already. */
1098 #ifdef FEAT_AUTOCHDIR
1099 p_acd = FALSE;
1100 #endif
1101 for (buf = firstbuf; buf != NULL; )
1103 nextbuf = buf->b_next;
1104 close_buffer(NULL, buf, DOBUF_WIPE);
1105 if (buf_valid(buf))
1106 buf = nextbuf; /* didn't work, try next one */
1107 else
1108 buf = firstbuf;
1111 #ifdef FEAT_ARABIC
1112 free_cmdline_buf();
1113 #endif
1115 /* Clear registers. */
1116 clear_registers();
1117 ResetRedobuff();
1118 ResetRedobuff();
1120 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
1121 vim_free(serverDelayedStartName);
1122 #endif
1124 /* highlight info */
1125 free_highlight();
1127 reset_last_sourcing();
1129 #ifdef FEAT_WINDOWS
1130 free_tabpage(first_tabpage);
1131 first_tabpage = NULL;
1132 #endif
1134 # ifdef UNIX
1135 /* Machine-specific free. */
1136 mch_free_mem();
1137 # endif
1139 /* message history */
1140 for (;;)
1141 if (delete_first_msg() == FAIL)
1142 break;
1144 # ifdef FEAT_EVAL
1145 eval_clear();
1146 # endif
1148 free_termoptions();
1150 /* screenlines (can't display anything now!) */
1151 free_screenlines();
1153 #if defined(USE_XSMP)
1154 xsmp_close();
1155 #endif
1156 #ifdef FEAT_GUI_GTK
1157 gui_mch_free_all();
1158 #endif
1159 clear_hl_tables();
1161 vim_free(IObuff);
1162 vim_free(NameBuff);
1164 #endif
1167 * copy a string into newly allocated memory
1169 char_u *
1170 vim_strsave(string)
1171 char_u *string;
1173 char_u *p;
1174 unsigned len;
1176 len = (unsigned)STRLEN(string) + 1;
1177 p = alloc(len);
1178 if (p != NULL)
1179 mch_memmove(p, string, (size_t)len);
1180 return p;
1183 char_u *
1184 vim_strnsave(string, len)
1185 char_u *string;
1186 int len;
1188 char_u *p;
1190 p = alloc((unsigned)(len + 1));
1191 if (p != NULL)
1193 STRNCPY(p, string, len);
1194 p[len] = NUL;
1196 return p;
1200 * Same as vim_strsave(), but any characters found in esc_chars are preceded
1201 * by a backslash.
1203 char_u *
1204 vim_strsave_escaped(string, esc_chars)
1205 char_u *string;
1206 char_u *esc_chars;
1208 return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE);
1212 * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape
1213 * characters where rem_backslash() would remove the backslash.
1214 * Escape the characters with "cc".
1216 char_u *
1217 vim_strsave_escaped_ext(string, esc_chars, cc, bsl)
1218 char_u *string;
1219 char_u *esc_chars;
1220 int cc;
1221 int bsl;
1223 char_u *p;
1224 char_u *p2;
1225 char_u *escaped_string;
1226 unsigned length;
1227 #ifdef FEAT_MBYTE
1228 int l;
1229 #endif
1232 * First count the number of backslashes required.
1233 * Then allocate the memory and insert them.
1235 length = 1; /* count the trailing NUL */
1236 for (p = string; *p; p++)
1238 #ifdef FEAT_MBYTE
1239 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1241 length += l; /* count a multibyte char */
1242 p += l - 1;
1243 continue;
1245 #endif
1246 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1247 ++length; /* count a backslash */
1248 ++length; /* count an ordinary char */
1250 escaped_string = alloc(length);
1251 if (escaped_string != NULL)
1253 p2 = escaped_string;
1254 for (p = string; *p; p++)
1256 #ifdef FEAT_MBYTE
1257 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1259 mch_memmove(p2, p, (size_t)l);
1260 p2 += l;
1261 p += l - 1; /* skip multibyte char */
1262 continue;
1264 #endif
1265 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1266 *p2++ = cc;
1267 *p2++ = *p;
1269 *p2 = NUL;
1271 return escaped_string;
1275 * Return TRUE when 'shell' has "csh" in the tail.
1278 csh_like_shell()
1280 return (strstr((char *)gettail(p_sh), "csh") != NULL);
1284 * Escape "string" for use as a shell argument with system().
1285 * This uses single quotes, except when we know we need to use double qoutes
1286 * (MS-DOS and MS-Windows without 'shellslash' set).
1287 * Escape a newline, depending on the 'shell' option.
1288 * When "do_special" is TRUE also replace "!", "%", "#" and things starting
1289 * with "<" like "<cfile>".
1290 * Returns the result in allocated memory, NULL if we have run out.
1292 char_u *
1293 vim_strsave_shellescape(string, do_special)
1294 char_u *string;
1295 int do_special;
1297 unsigned length;
1298 char_u *p;
1299 char_u *d;
1300 char_u *escaped_string;
1301 int l;
1302 int csh_like;
1304 /* Only csh and similar shells expand '!' within single quotes. For sh and
1305 * the like we must not put a backslash before it, it will be taken
1306 * literally. If do_special is set the '!' will be escaped twice.
1307 * Csh also needs to have "\n" escaped twice when do_special is set. */
1308 csh_like = csh_like_shell();
1310 /* First count the number of extra bytes required. */
1311 length = (unsigned)STRLEN(string) + 3; /* two quotes and a trailing NUL */
1312 for (p = string; *p != NUL; mb_ptr_adv(p))
1314 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1315 if (!p_ssl)
1317 if (*p == '"')
1318 ++length; /* " -> "" */
1320 else
1321 # endif
1322 if (*p == '\'')
1323 length += 3; /* ' => '\'' */
1324 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1326 ++length; /* insert backslash */
1327 if (csh_like && do_special)
1328 ++length; /* insert backslash */
1330 if (do_special && find_cmdline_var(p, &l) >= 0)
1332 ++length; /* insert backslash */
1333 p += l - 1;
1337 /* Allocate memory for the result and fill it. */
1338 escaped_string = alloc(length);
1339 if (escaped_string != NULL)
1341 d = escaped_string;
1343 /* add opening quote */
1344 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1345 if (!p_ssl)
1346 *d++ = '"';
1347 else
1348 # endif
1349 *d++ = '\'';
1351 for (p = string; *p != NUL; )
1353 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1354 if (!p_ssl)
1356 if (*p == '"')
1358 *d++ = '"';
1359 *d++ = '"';
1360 ++p;
1361 continue;
1364 else
1365 # endif
1366 if (*p == '\'')
1368 *d++ = '\'';
1369 *d++ = '\\';
1370 *d++ = '\'';
1371 *d++ = '\'';
1372 ++p;
1373 continue;
1375 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1377 *d++ = '\\';
1378 if (csh_like && do_special)
1379 *d++ = '\\';
1380 *d++ = *p++;
1381 continue;
1383 if (do_special && find_cmdline_var(p, &l) >= 0)
1385 *d++ = '\\'; /* insert backslash */
1386 while (--l >= 0) /* copy the var */
1387 *d++ = *p++;
1390 MB_COPY_CHAR(p, d);
1393 /* add terminating quote and finish with a NUL */
1394 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1395 if (!p_ssl)
1396 *d++ = '"';
1397 else
1398 # endif
1399 *d++ = '\'';
1400 *d = NUL;
1403 return escaped_string;
1407 * Like vim_strsave(), but make all characters uppercase.
1408 * This uses ASCII lower-to-upper case translation, language independent.
1410 char_u *
1411 vim_strsave_up(string)
1412 char_u *string;
1414 char_u *p1;
1416 p1 = vim_strsave(string);
1417 vim_strup(p1);
1418 return p1;
1422 * Like vim_strnsave(), but make all characters uppercase.
1423 * This uses ASCII lower-to-upper case translation, language independent.
1425 char_u *
1426 vim_strnsave_up(string, len)
1427 char_u *string;
1428 int len;
1430 char_u *p1;
1432 p1 = vim_strnsave(string, len);
1433 vim_strup(p1);
1434 return p1;
1438 * ASCII lower-to-upper case translation, language independent.
1440 void
1441 vim_strup(p)
1442 char_u *p;
1444 char_u *p2;
1445 int c;
1447 if (p != NULL)
1449 p2 = p;
1450 while ((c = *p2) != NUL)
1451 #ifdef EBCDIC
1452 *p2++ = isalpha(c) ? toupper(c) : c;
1453 #else
1454 *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20);
1455 #endif
1459 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
1461 * Make string "s" all upper-case and return it in allocated memory.
1462 * Handles multi-byte characters as well as possible.
1463 * Returns NULL when out of memory.
1465 char_u *
1466 strup_save(orig)
1467 char_u *orig;
1469 char_u *p;
1470 char_u *res;
1472 res = p = vim_strsave(orig);
1474 if (res != NULL)
1475 while (*p != NUL)
1477 # ifdef FEAT_MBYTE
1478 int l;
1480 if (enc_utf8)
1482 int c, uc;
1483 int nl;
1484 char_u *s;
1486 c = utf_ptr2char(p);
1487 uc = utf_toupper(c);
1489 /* Reallocate string when byte count changes. This is rare,
1490 * thus it's OK to do another malloc()/free(). */
1491 l = utf_ptr2len(p);
1492 nl = utf_char2len(uc);
1493 if (nl != l)
1495 s = alloc((unsigned)STRLEN(res) + 1 + nl - l);
1496 if (s == NULL)
1497 break;
1498 mch_memmove(s, res, p - res);
1499 STRCPY(s + (p - res) + nl, p + l);
1500 p = s + (p - res);
1501 vim_free(res);
1502 res = s;
1505 utf_char2bytes(uc, p);
1506 p += nl;
1508 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1509 p += l; /* skip multi-byte character */
1510 else
1511 # endif
1513 *p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */
1514 p++;
1518 return res;
1520 #endif
1523 * copy a space a number of times
1525 void
1526 copy_spaces(ptr, count)
1527 char_u *ptr;
1528 size_t count;
1530 size_t i = count;
1531 char_u *p = ptr;
1533 while (i--)
1534 *p++ = ' ';
1537 #if defined(FEAT_VISUALEXTRA) || defined(PROTO)
1539 * Copy a character a number of times.
1540 * Does not work for multi-byte charactes!
1542 void
1543 copy_chars(ptr, count, c)
1544 char_u *ptr;
1545 size_t count;
1546 int c;
1548 size_t i = count;
1549 char_u *p = ptr;
1551 while (i--)
1552 *p++ = c;
1554 #endif
1557 * delete spaces at the end of a string
1559 void
1560 del_trailing_spaces(ptr)
1561 char_u *ptr;
1563 char_u *q;
1565 q = ptr + STRLEN(ptr);
1566 while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1567 *q = NUL;
1571 * Like strncpy(), but always terminate the result with one NUL.
1572 * "to" must be "len + 1" long!
1574 void
1575 vim_strncpy(to, from, len)
1576 char_u *to;
1577 char_u *from;
1578 size_t len;
1580 STRNCPY(to, from, len);
1581 to[len] = NUL;
1585 * Isolate one part of a string option where parts are separated with
1586 * "sep_chars".
1587 * The part is copied into "buf[maxlen]".
1588 * "*option" is advanced to the next part.
1589 * The length is returned.
1592 copy_option_part(option, buf, maxlen, sep_chars)
1593 char_u **option;
1594 char_u *buf;
1595 int maxlen;
1596 char *sep_chars;
1598 int len = 0;
1599 char_u *p = *option;
1601 /* skip '.' at start of option part, for 'suffixes' */
1602 if (*p == '.')
1603 buf[len++] = *p++;
1604 while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1607 * Skip backslash before a separator character and space.
1609 if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1610 ++p;
1611 if (len < maxlen - 1)
1612 buf[len++] = *p;
1613 ++p;
1615 buf[len] = NUL;
1617 if (*p != NUL && *p != ',') /* skip non-standard separator */
1618 ++p;
1619 p = skip_to_option_part(p); /* p points to next file name */
1621 *option = p;
1622 return len;
1626 * Replacement for free() that ignores NULL pointers.
1627 * Also skip free() when exiting for sure, this helps when we caught a deadly
1628 * signal that was caused by a crash in free().
1630 void
1631 vim_free(x)
1632 void *x;
1634 if (x != NULL && !really_exiting)
1636 #ifdef MEM_PROFILE
1637 mem_pre_free(&x);
1638 #endif
1639 free(x);
1643 #ifndef HAVE_MEMSET
1644 void *
1645 vim_memset(ptr, c, size)
1646 void *ptr;
1647 int c;
1648 size_t size;
1650 char *p = ptr;
1652 while (size-- > 0)
1653 *p++ = c;
1654 return ptr;
1656 #endif
1658 #ifdef VIM_MEMCMP
1660 * Return zero when "b1" and "b2" are the same for "len" bytes.
1661 * Return non-zero otherwise.
1664 vim_memcmp(b1, b2, len)
1665 void *b1;
1666 void *b2;
1667 size_t len;
1669 char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1671 for ( ; len > 0; --len)
1673 if (*p1 != *p2)
1674 return 1;
1675 ++p1;
1676 ++p2;
1678 return 0;
1680 #endif
1682 #ifdef VIM_MEMMOVE
1684 * Version of memmove() that handles overlapping source and destination.
1685 * For systems that don't have a function that is guaranteed to do that (SYSV).
1687 void
1688 mch_memmove(dst_arg, src_arg, len)
1689 void *src_arg, *dst_arg;
1690 size_t len;
1693 * A void doesn't have a size, we use char pointers.
1695 char *dst = dst_arg, *src = src_arg;
1697 /* overlap, copy backwards */
1698 if (dst > src && dst < src + len)
1700 src += len;
1701 dst += len;
1702 while (len-- > 0)
1703 *--dst = *--src;
1705 else /* copy forwards */
1706 while (len-- > 0)
1707 *dst++ = *src++;
1709 #endif
1711 #if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1713 * Compare two strings, ignoring case, using current locale.
1714 * Doesn't work for multi-byte characters.
1715 * return 0 for match, < 0 for smaller, > 0 for bigger
1718 vim_stricmp(s1, s2)
1719 char *s1;
1720 char *s2;
1722 int i;
1724 for (;;)
1726 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1727 if (i != 0)
1728 return i; /* this character different */
1729 if (*s1 == NUL)
1730 break; /* strings match until NUL */
1731 ++s1;
1732 ++s2;
1734 return 0; /* strings match */
1736 #endif
1738 #if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1740 * Compare two strings, for length "len", ignoring case, using current locale.
1741 * Doesn't work for multi-byte characters.
1742 * return 0 for match, < 0 for smaller, > 0 for bigger
1745 vim_strnicmp(s1, s2, len)
1746 char *s1;
1747 char *s2;
1748 size_t len;
1750 int i;
1752 while (len > 0)
1754 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1755 if (i != 0)
1756 return i; /* this character different */
1757 if (*s1 == NUL)
1758 break; /* strings match until NUL */
1759 ++s1;
1760 ++s2;
1761 --len;
1763 return 0; /* strings match */
1765 #endif
1767 #if 0 /* currently not used */
1769 * Check if string "s2" appears somewhere in "s1" while ignoring case.
1770 * Return NULL if not, a pointer to the first occurrence if it does.
1772 char_u *
1773 vim_stristr(s1, s2)
1774 char_u *s1;
1775 char_u *s2;
1777 char_u *p;
1778 int len = STRLEN(s2);
1779 char_u *end = s1 + STRLEN(s1) - len;
1781 for (p = s1; p <= end; ++p)
1782 if (STRNICMP(p, s2, len) == 0)
1783 return p;
1784 return NULL;
1786 #endif
1789 * Version of strchr() and strrchr() that handle unsigned char strings
1790 * with characters from 128 to 255 correctly. It also doesn't return a
1791 * pointer to the NUL at the end of the string.
1793 char_u *
1794 vim_strchr(string, c)
1795 char_u *string;
1796 int c;
1798 char_u *p;
1799 int b;
1801 p = string;
1802 #ifdef FEAT_MBYTE
1803 if (enc_utf8 && c >= 0x80)
1805 while (*p != NUL)
1807 if (utf_ptr2char(p) == c)
1808 return p;
1809 p += (*mb_ptr2len)(p);
1811 return NULL;
1813 if (enc_dbcs != 0 && c > 255)
1815 int n2 = c & 0xff;
1817 c = ((unsigned)c >> 8) & 0xff;
1818 while ((b = *p) != NUL)
1820 if (b == c && p[1] == n2)
1821 return p;
1822 p += (*mb_ptr2len)(p);
1824 return NULL;
1826 if (has_mbyte)
1828 while ((b = *p) != NUL)
1830 if (b == c)
1831 return p;
1832 p += (*mb_ptr2len)(p);
1834 return NULL;
1836 #endif
1837 while ((b = *p) != NUL)
1839 if (b == c)
1840 return p;
1841 ++p;
1843 return NULL;
1847 * Version of strchr() that only works for bytes and handles unsigned char
1848 * strings with characters above 128 correctly. It also doesn't return a
1849 * pointer to the NUL at the end of the string.
1851 char_u *
1852 vim_strbyte(string, c)
1853 char_u *string;
1854 int c;
1856 char_u *p = string;
1858 while (*p != NUL)
1860 if (*p == c)
1861 return p;
1862 ++p;
1864 return NULL;
1868 * Search for last occurrence of "c" in "string".
1869 * Return NULL if not found.
1870 * Does not handle multi-byte char for "c"!
1872 char_u *
1873 vim_strrchr(string, c)
1874 char_u *string;
1875 int c;
1877 char_u *retval = NULL;
1878 char_u *p = string;
1880 while (*p)
1882 if (*p == c)
1883 retval = p;
1884 mb_ptr_adv(p);
1886 return retval;
1890 * Vim's version of strpbrk(), in case it's missing.
1891 * Don't generate a prototype for this, causes problems when it's not used.
1893 #ifndef PROTO
1894 # ifndef HAVE_STRPBRK
1895 # ifdef vim_strpbrk
1896 # undef vim_strpbrk
1897 # endif
1898 char_u *
1899 vim_strpbrk(s, charset)
1900 char_u *s;
1901 char_u *charset;
1903 while (*s)
1905 if (vim_strchr(charset, *s) != NULL)
1906 return s;
1907 mb_ptr_adv(s);
1909 return NULL;
1911 # endif
1912 #endif
1915 * Vim has its own isspace() function, because on some machines isspace()
1916 * can't handle characters above 128.
1919 vim_isspace(x)
1920 int x;
1922 return ((x >= 9 && x <= 13) || x == ' ');
1925 /************************************************************************
1926 * Functions for handling growing arrays.
1930 * Clear an allocated growing array.
1932 void
1933 ga_clear(gap)
1934 garray_T *gap;
1936 vim_free(gap->ga_data);
1937 ga_init(gap);
1941 * Clear a growing array that contains a list of strings.
1943 void
1944 ga_clear_strings(gap)
1945 garray_T *gap;
1947 int i;
1949 for (i = 0; i < gap->ga_len; ++i)
1950 vim_free(((char_u **)(gap->ga_data))[i]);
1951 ga_clear(gap);
1955 * Initialize a growing array. Don't forget to set ga_itemsize and
1956 * ga_growsize! Or use ga_init2().
1958 void
1959 ga_init(gap)
1960 garray_T *gap;
1962 gap->ga_data = NULL;
1963 gap->ga_maxlen = 0;
1964 gap->ga_len = 0;
1967 void
1968 ga_init2(gap, itemsize, growsize)
1969 garray_T *gap;
1970 int itemsize;
1971 int growsize;
1973 ga_init(gap);
1974 gap->ga_itemsize = itemsize;
1975 gap->ga_growsize = growsize;
1979 * Make room in growing array "gap" for at least "n" items.
1980 * Return FAIL for failure, OK otherwise.
1983 ga_grow(gap, n)
1984 garray_T *gap;
1985 int n;
1987 size_t len;
1988 char_u *pp;
1990 if (gap->ga_maxlen - gap->ga_len < n)
1992 if (n < gap->ga_growsize)
1993 n = gap->ga_growsize;
1994 len = gap->ga_itemsize * (gap->ga_len + n);
1995 pp = alloc_clear((unsigned)len);
1996 if (pp == NULL)
1997 return FAIL;
1998 gap->ga_maxlen = gap->ga_len + n;
1999 if (gap->ga_data != NULL)
2001 mch_memmove(pp, gap->ga_data,
2002 (size_t)(gap->ga_itemsize * gap->ga_len));
2003 vim_free(gap->ga_data);
2005 gap->ga_data = pp;
2007 return OK;
2011 * Concatenate a string to a growarray which contains characters.
2012 * Note: Does NOT copy the NUL at the end!
2014 void
2015 ga_concat(gap, s)
2016 garray_T *gap;
2017 char_u *s;
2019 int len = (int)STRLEN(s);
2021 if (ga_grow(gap, len) == OK)
2023 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
2024 gap->ga_len += len;
2029 * Append one byte to a growarray which contains bytes.
2031 void
2032 ga_append(gap, c)
2033 garray_T *gap;
2034 int c;
2036 if (ga_grow(gap, 1) == OK)
2038 *((char *)gap->ga_data + gap->ga_len) = c;
2039 ++gap->ga_len;
2043 /************************************************************************
2044 * functions that use lookup tables for various things, generally to do with
2045 * special key codes.
2049 * Some useful tables.
2052 static struct modmasktable
2054 short mod_mask; /* Bit-mask for particular key modifier */
2055 short mod_flag; /* Bit(s) for particular key modifier */
2056 char_u name; /* Single letter name of modifier */
2057 } mod_mask_table[] =
2059 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'},
2060 {MOD_MASK_META, MOD_MASK_META, (char_u)'T'},
2061 {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'},
2062 {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'},
2063 {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'},
2064 {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'},
2065 {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'},
2066 #ifdef MACOS
2067 {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'},
2068 #endif
2069 /* 'A' must be the last one */
2070 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'},
2071 {0, 0, NUL}
2075 * Shifted key terminal codes and their unshifted equivalent.
2076 * Don't add mouse codes here, they are handled separately!
2078 #define MOD_KEYS_ENTRY_SIZE 5
2080 static char_u modifier_keys_table[] =
2082 /* mod mask with modifier without modifier */
2083 MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */
2084 MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */
2085 MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */
2086 MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */
2087 MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */
2088 MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */
2089 MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */
2090 MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */
2091 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */
2092 MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */
2093 MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */
2094 MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */
2095 MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */
2096 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */
2097 MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */
2098 MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */
2099 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */
2100 MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */
2101 MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */
2102 MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */
2103 MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */
2104 MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */
2105 MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */
2106 MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */
2107 MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */
2108 MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */
2109 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */
2110 MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */
2111 MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */
2112 MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */
2113 MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */
2114 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */
2115 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */
2117 /* vt100 F1 */
2118 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1,
2119 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2,
2120 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3,
2121 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4,
2123 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */
2124 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2',
2125 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3',
2126 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4',
2127 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5',
2128 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6',
2129 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7',
2130 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8',
2131 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9',
2132 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */
2134 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1',
2135 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2',
2136 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3',
2137 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4',
2138 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5',
2139 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6',
2140 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7',
2141 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8',
2142 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9',
2143 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A',
2145 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B',
2146 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C',
2147 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D',
2148 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E',
2149 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F',
2150 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G',
2151 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H',
2152 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I',
2153 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J',
2154 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K',
2156 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L',
2157 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M',
2158 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N',
2159 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O',
2160 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P',
2161 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q',
2162 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R',
2164 /* TAB pseudo code*/
2165 MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB,
2170 static struct key_name_entry
2172 int key; /* Special key code or ascii value */
2173 char_u *name; /* Name of key */
2174 } key_names_table[] =
2176 {' ', (char_u *)"Space"},
2177 {TAB, (char_u *)"Tab"},
2178 {K_TAB, (char_u *)"Tab"},
2179 {NL, (char_u *)"NL"},
2180 {NL, (char_u *)"NewLine"}, /* Alternative name */
2181 {NL, (char_u *)"LineFeed"}, /* Alternative name */
2182 {NL, (char_u *)"LF"}, /* Alternative name */
2183 {CAR, (char_u *)"CR"},
2184 {CAR, (char_u *)"Return"}, /* Alternative name */
2185 {CAR, (char_u *)"Enter"}, /* Alternative name */
2186 {K_BS, (char_u *)"BS"},
2187 {K_BS, (char_u *)"BackSpace"}, /* Alternative name */
2188 {ESC, (char_u *)"Esc"},
2189 {CSI, (char_u *)"CSI"},
2190 {K_CSI, (char_u *)"xCSI"},
2191 {'|', (char_u *)"Bar"},
2192 {'\\', (char_u *)"Bslash"},
2193 {K_DEL, (char_u *)"Del"},
2194 {K_DEL, (char_u *)"Delete"}, /* Alternative name */
2195 {K_KDEL, (char_u *)"kDel"},
2196 {K_UP, (char_u *)"Up"},
2197 {K_DOWN, (char_u *)"Down"},
2198 {K_LEFT, (char_u *)"Left"},
2199 {K_RIGHT, (char_u *)"Right"},
2200 {K_XUP, (char_u *)"xUp"},
2201 {K_XDOWN, (char_u *)"xDown"},
2202 {K_XLEFT, (char_u *)"xLeft"},
2203 {K_XRIGHT, (char_u *)"xRight"},
2205 {K_F1, (char_u *)"F1"},
2206 {K_F2, (char_u *)"F2"},
2207 {K_F3, (char_u *)"F3"},
2208 {K_F4, (char_u *)"F4"},
2209 {K_F5, (char_u *)"F5"},
2210 {K_F6, (char_u *)"F6"},
2211 {K_F7, (char_u *)"F7"},
2212 {K_F8, (char_u *)"F8"},
2213 {K_F9, (char_u *)"F9"},
2214 {K_F10, (char_u *)"F10"},
2216 {K_F11, (char_u *)"F11"},
2217 {K_F12, (char_u *)"F12"},
2218 {K_F13, (char_u *)"F13"},
2219 {K_F14, (char_u *)"F14"},
2220 {K_F15, (char_u *)"F15"},
2221 {K_F16, (char_u *)"F16"},
2222 {K_F17, (char_u *)"F17"},
2223 {K_F18, (char_u *)"F18"},
2224 {K_F19, (char_u *)"F19"},
2225 {K_F20, (char_u *)"F20"},
2227 {K_F21, (char_u *)"F21"},
2228 {K_F22, (char_u *)"F22"},
2229 {K_F23, (char_u *)"F23"},
2230 {K_F24, (char_u *)"F24"},
2231 {K_F25, (char_u *)"F25"},
2232 {K_F26, (char_u *)"F26"},
2233 {K_F27, (char_u *)"F27"},
2234 {K_F28, (char_u *)"F28"},
2235 {K_F29, (char_u *)"F29"},
2236 {K_F30, (char_u *)"F30"},
2238 {K_F31, (char_u *)"F31"},
2239 {K_F32, (char_u *)"F32"},
2240 {K_F33, (char_u *)"F33"},
2241 {K_F34, (char_u *)"F34"},
2242 {K_F35, (char_u *)"F35"},
2243 {K_F36, (char_u *)"F36"},
2244 {K_F37, (char_u *)"F37"},
2246 {K_XF1, (char_u *)"xF1"},
2247 {K_XF2, (char_u *)"xF2"},
2248 {K_XF3, (char_u *)"xF3"},
2249 {K_XF4, (char_u *)"xF4"},
2251 {K_HELP, (char_u *)"Help"},
2252 {K_UNDO, (char_u *)"Undo"},
2253 {K_INS, (char_u *)"Insert"},
2254 {K_INS, (char_u *)"Ins"}, /* Alternative name */
2255 {K_KINS, (char_u *)"kInsert"},
2256 {K_HOME, (char_u *)"Home"},
2257 {K_KHOME, (char_u *)"kHome"},
2258 {K_XHOME, (char_u *)"xHome"},
2259 {K_ZHOME, (char_u *)"zHome"},
2260 {K_END, (char_u *)"End"},
2261 {K_KEND, (char_u *)"kEnd"},
2262 {K_XEND, (char_u *)"xEnd"},
2263 {K_ZEND, (char_u *)"zEnd"},
2264 {K_PAGEUP, (char_u *)"PageUp"},
2265 {K_PAGEDOWN, (char_u *)"PageDown"},
2266 {K_KPAGEUP, (char_u *)"kPageUp"},
2267 {K_KPAGEDOWN, (char_u *)"kPageDown"},
2269 {K_KPLUS, (char_u *)"kPlus"},
2270 {K_KMINUS, (char_u *)"kMinus"},
2271 {K_KDIVIDE, (char_u *)"kDivide"},
2272 {K_KMULTIPLY, (char_u *)"kMultiply"},
2273 {K_KENTER, (char_u *)"kEnter"},
2274 {K_KPOINT, (char_u *)"kPoint"},
2276 {K_K0, (char_u *)"k0"},
2277 {K_K1, (char_u *)"k1"},
2278 {K_K2, (char_u *)"k2"},
2279 {K_K3, (char_u *)"k3"},
2280 {K_K4, (char_u *)"k4"},
2281 {K_K5, (char_u *)"k5"},
2282 {K_K6, (char_u *)"k6"},
2283 {K_K7, (char_u *)"k7"},
2284 {K_K8, (char_u *)"k8"},
2285 {K_K9, (char_u *)"k9"},
2287 {'<', (char_u *)"lt"},
2289 {K_MOUSE, (char_u *)"Mouse"},
2290 {K_NETTERM_MOUSE, (char_u *)"NetMouse"},
2291 {K_DEC_MOUSE, (char_u *)"DecMouse"},
2292 {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"},
2293 {K_PTERM_MOUSE, (char_u *)"PtermMouse"},
2294 {K_LEFTMOUSE, (char_u *)"LeftMouse"},
2295 {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"},
2296 {K_LEFTDRAG, (char_u *)"LeftDrag"},
2297 {K_LEFTRELEASE, (char_u *)"LeftRelease"},
2298 {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"},
2299 {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"},
2300 {K_MIDDLEDRAG, (char_u *)"MiddleDrag"},
2301 {K_MIDDLERELEASE, (char_u *)"MiddleRelease"},
2302 {K_RIGHTMOUSE, (char_u *)"RightMouse"},
2303 {K_RIGHTDRAG, (char_u *)"RightDrag"},
2304 {K_RIGHTRELEASE, (char_u *)"RightRelease"},
2305 {K_MOUSEDOWN, (char_u *)"MouseDown"},
2306 {K_MOUSEUP, (char_u *)"MouseUp"},
2307 {K_X1MOUSE, (char_u *)"X1Mouse"},
2308 {K_X1DRAG, (char_u *)"X1Drag"},
2309 {K_X1RELEASE, (char_u *)"X1Release"},
2310 {K_X2MOUSE, (char_u *)"X2Mouse"},
2311 {K_X2DRAG, (char_u *)"X2Drag"},
2312 {K_X2RELEASE, (char_u *)"X2Release"},
2313 {K_DROP, (char_u *)"Drop"},
2314 {K_ZERO, (char_u *)"Nul"},
2315 #ifdef FEAT_EVAL
2316 {K_SNR, (char_u *)"SNR"},
2317 #endif
2318 {K_PLUG, (char_u *)"Plug"},
2319 {0, NULL}
2322 #define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
2324 #ifdef FEAT_MOUSE
2325 static struct mousetable
2327 int pseudo_code; /* Code for pseudo mouse event */
2328 int button; /* Which mouse button is it? */
2329 int is_click; /* Is it a mouse button click event? */
2330 int is_drag; /* Is it a mouse drag event? */
2331 } mouse_table[] =
2333 {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE},
2334 #ifdef FEAT_GUI
2335 {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE},
2336 #endif
2337 {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE},
2338 {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE},
2339 #ifdef FEAT_GUI
2340 {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE},
2341 #endif
2342 {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE},
2343 {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE},
2344 {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE},
2345 {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE},
2346 {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE},
2347 {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE},
2348 {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE},
2349 {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE},
2350 {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE},
2351 {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE},
2352 {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE},
2353 {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE},
2354 /* DRAG without CLICK */
2355 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE},
2356 /* RELEASE without CLICK */
2357 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE},
2358 {0, 0, 0, 0},
2360 #endif /* FEAT_MOUSE */
2363 * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
2364 * modifier name ('S' for Shift, 'C' for Ctrl etc).
2367 name_to_mod_mask(c)
2368 int c;
2370 int i;
2372 c = TOUPPER_ASC(c);
2373 for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
2374 if (c == mod_mask_table[i].name)
2375 return mod_mask_table[i].mod_flag;
2376 return 0;
2380 * Check if if there is a special key code for "key" that includes the
2381 * modifiers specified.
2384 simplify_key(key, modifiers)
2385 int key;
2386 int *modifiers;
2388 int i;
2389 int key0;
2390 int key1;
2392 if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2394 /* TAB is a special case */
2395 if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2397 *modifiers &= ~MOD_MASK_SHIFT;
2398 return K_S_TAB;
2400 key0 = KEY2TERMCAP0(key);
2401 key1 = KEY2TERMCAP1(key);
2402 for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2403 if (key0 == modifier_keys_table[i + 3]
2404 && key1 == modifier_keys_table[i + 4]
2405 && (*modifiers & modifier_keys_table[i]))
2407 *modifiers &= ~modifier_keys_table[i];
2408 return TERMCAP2KEY(modifier_keys_table[i + 1],
2409 modifier_keys_table[i + 2]);
2412 return key;
2416 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
2419 handle_x_keys(key)
2420 int key;
2422 switch (key)
2424 case K_XUP: return K_UP;
2425 case K_XDOWN: return K_DOWN;
2426 case K_XLEFT: return K_LEFT;
2427 case K_XRIGHT: return K_RIGHT;
2428 case K_XHOME: return K_HOME;
2429 case K_ZHOME: return K_HOME;
2430 case K_XEND: return K_END;
2431 case K_ZEND: return K_END;
2432 case K_XF1: return K_F1;
2433 case K_XF2: return K_F2;
2434 case K_XF3: return K_F3;
2435 case K_XF4: return K_F4;
2436 case K_S_XF1: return K_S_F1;
2437 case K_S_XF2: return K_S_F2;
2438 case K_S_XF3: return K_S_F3;
2439 case K_S_XF4: return K_S_F4;
2441 return key;
2445 * Return a string which contains the name of the given key when the given
2446 * modifiers are down.
2448 char_u *
2449 get_special_key_name(c, modifiers)
2450 int c;
2451 int modifiers;
2453 static char_u string[MAX_KEY_NAME_LEN + 1];
2455 int i, idx;
2456 int table_idx;
2457 char_u *s;
2459 string[0] = '<';
2460 idx = 1;
2462 /* Key that stands for a normal character. */
2463 if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2464 c = KEY2TERMCAP1(c);
2467 * Translate shifted special keys into unshifted keys and set modifier.
2468 * Same for CTRL and ALT modifiers.
2470 if (IS_SPECIAL(c))
2472 for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2473 if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2474 && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2476 modifiers |= modifier_keys_table[i];
2477 c = TERMCAP2KEY(modifier_keys_table[i + 3],
2478 modifier_keys_table[i + 4]);
2479 break;
2483 /* try to find the key in the special key table */
2484 table_idx = find_special_key_in_table(c);
2487 * When not a known special key, and not a printable character, try to
2488 * extract modifiers.
2490 if (c > 0
2491 #ifdef FEAT_MBYTE
2492 && (*mb_char2len)(c) == 1
2493 #endif
2496 if (table_idx < 0
2497 && (!vim_isprintc(c) || (c & 0x7f) == ' ')
2498 && (c & 0x80))
2500 c &= 0x7f;
2501 modifiers |= MOD_MASK_ALT;
2502 /* try again, to find the un-alted key in the special key table */
2503 table_idx = find_special_key_in_table(c);
2505 if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2507 #ifdef EBCDIC
2508 c = CtrlChar(c);
2509 #else
2510 c += '@';
2511 #endif
2512 modifiers |= MOD_MASK_CTRL;
2516 /* translate the modifier into a string */
2517 for (i = 0; mod_mask_table[i].name != 'A'; i++)
2518 if ((modifiers & mod_mask_table[i].mod_mask)
2519 == mod_mask_table[i].mod_flag)
2521 string[idx++] = mod_mask_table[i].name;
2522 string[idx++] = (char_u)'-';
2525 if (table_idx < 0) /* unknown special key, may output t_xx */
2527 if (IS_SPECIAL(c))
2529 string[idx++] = 't';
2530 string[idx++] = '_';
2531 string[idx++] = KEY2TERMCAP0(c);
2532 string[idx++] = KEY2TERMCAP1(c);
2534 /* Not a special key, only modifiers, output directly */
2535 else
2537 #ifdef FEAT_MBYTE
2538 if (has_mbyte && (*mb_char2len)(c) > 1)
2539 idx += (*mb_char2bytes)(c, string + idx);
2540 else
2541 #endif
2542 if (vim_isprintc(c))
2543 string[idx++] = c;
2544 else
2546 s = transchar(c);
2547 while (*s)
2548 string[idx++] = *s++;
2552 else /* use name of special key */
2554 STRCPY(string + idx, key_names_table[table_idx].name);
2555 idx = (int)STRLEN(string);
2557 string[idx++] = '>';
2558 string[idx] = NUL;
2559 return string;
2563 * Try translating a <> name at (*srcp)[] to dst[].
2564 * Return the number of characters added to dst[], zero for no match.
2565 * If there is a match, srcp is advanced to after the <> name.
2566 * dst[] must be big enough to hold the result (up to six characters)!
2569 trans_special(srcp, dst, keycode)
2570 char_u **srcp;
2571 char_u *dst;
2572 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2574 int modifiers = 0;
2575 int key;
2576 int dlen = 0;
2578 key = find_special_key(srcp, &modifiers, keycode, FALSE);
2579 if (key == 0)
2580 return 0;
2582 /* Put the appropriate modifier in a string */
2583 if (modifiers != 0)
2585 dst[dlen++] = K_SPECIAL;
2586 dst[dlen++] = KS_MODIFIER;
2587 dst[dlen++] = modifiers;
2590 if (IS_SPECIAL(key))
2592 dst[dlen++] = K_SPECIAL;
2593 dst[dlen++] = KEY2TERMCAP0(key);
2594 dst[dlen++] = KEY2TERMCAP1(key);
2596 #ifdef FEAT_MBYTE
2597 else if (has_mbyte && !keycode)
2598 dlen += (*mb_char2bytes)(key, dst + dlen);
2599 #endif
2600 else if (keycode)
2601 dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2602 else
2603 dst[dlen++] = key;
2605 return dlen;
2609 * Try translating a <> name at (*srcp)[], return the key and modifiers.
2610 * srcp is advanced to after the <> name.
2611 * returns 0 if there is no match.
2614 find_special_key(srcp, modp, keycode, keep_x_key)
2615 char_u **srcp;
2616 int *modp;
2617 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2618 int keep_x_key; /* don't translate xHome to Home key */
2620 char_u *last_dash;
2621 char_u *end_of_name;
2622 char_u *src;
2623 char_u *bp;
2624 int modifiers;
2625 int bit;
2626 int key;
2627 unsigned long n;
2629 src = *srcp;
2630 if (src[0] != '<')
2631 return 0;
2633 /* Find end of modifier list */
2634 last_dash = src;
2635 for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2637 if (*bp == '-')
2639 last_dash = bp;
2640 if (bp[1] != NUL && bp[2] == '>')
2641 ++bp; /* anything accepted, like <C-?> */
2643 if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2644 bp += 3; /* skip t_xx, xx may be '-' or '>' */
2647 if (*bp == '>') /* found matching '>' */
2649 end_of_name = bp + 1;
2651 if (STRNICMP(src + 1, "char-", 5) == 0 && VIM_ISDIGIT(src[6]))
2653 /* <Char-123> or <Char-033> or <Char-0x33> */
2654 vim_str2nr(src + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2655 *modp = 0;
2656 *srcp = end_of_name;
2657 return (int)n;
2660 /* Which modifiers are given? */
2661 modifiers = 0x0;
2662 for (bp = src + 1; bp < last_dash; bp++)
2664 if (*bp != '-')
2666 bit = name_to_mod_mask(*bp);
2667 if (bit == 0x0)
2668 break; /* Illegal modifier name */
2669 modifiers |= bit;
2674 * Legal modifier name.
2676 if (bp >= last_dash)
2679 * Modifier with single letter, or special key name.
2681 if (modifiers != 0 && last_dash[2] == '>')
2682 key = last_dash[1];
2683 else
2685 key = get_special_key_code(last_dash + 1);
2686 if (!keep_x_key)
2687 key = handle_x_keys(key);
2691 * get_special_key_code() may return NUL for invalid
2692 * special key name.
2694 if (key != NUL)
2697 * Only use a modifier when there is no special key code that
2698 * includes the modifier.
2700 key = simplify_key(key, &modifiers);
2702 if (!keycode)
2704 /* don't want keycode, use single byte code */
2705 if (key == K_BS)
2706 key = BS;
2707 else if (key == K_DEL || key == K_KDEL)
2708 key = DEL;
2712 * Normal Key with modifier: Try to make a single byte code.
2714 if (!IS_SPECIAL(key))
2715 key = extract_modifiers(key, &modifiers);
2717 *modp = modifiers;
2718 *srcp = end_of_name;
2719 return key;
2723 return 0;
2727 * Try to include modifiers in the key.
2728 * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2731 extract_modifiers(key, modp)
2732 int key;
2733 int *modp;
2735 int modifiers = *modp;
2737 #ifdef MACOS
2738 /* Command-key really special, No fancynest */
2739 if (!(modifiers & MOD_MASK_CMD))
2740 #endif
2741 if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2743 key = TOUPPER_ASC(key);
2744 modifiers &= ~MOD_MASK_SHIFT;
2746 if ((modifiers & MOD_MASK_CTRL)
2747 #ifdef EBCDIC
2748 /* * TODO: EBCDIC Better use:
2749 * && (Ctrl_chr(key) || key == '?')
2750 * ??? */
2751 && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2752 != NULL
2753 #else
2754 && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2755 #endif
2758 key = Ctrl_chr(key);
2759 modifiers &= ~MOD_MASK_CTRL;
2760 /* <C-@> is <Nul> */
2761 if (key == 0)
2762 key = K_ZERO;
2764 #ifdef MACOS
2765 /* Command-key really special, No fancynest */
2766 if (!(modifiers & MOD_MASK_CMD))
2767 #endif
2768 if ((modifiers & MOD_MASK_ALT) && key < 0x80
2769 #ifdef FEAT_MBYTE
2770 && !enc_dbcs /* avoid creating a lead byte */
2771 #endif
2774 key |= 0x80;
2775 modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */
2778 *modp = modifiers;
2779 return key;
2783 * Try to find key "c" in the special key table.
2784 * Return the index when found, -1 when not found.
2787 find_special_key_in_table(c)
2788 int c;
2790 int i;
2792 for (i = 0; key_names_table[i].name != NULL; i++)
2793 if (c == key_names_table[i].key)
2794 break;
2795 if (key_names_table[i].name == NULL)
2796 i = -1;
2797 return i;
2801 * Find the special key with the given name (the given string does not have to
2802 * end with NUL, the name is assumed to end before the first non-idchar).
2803 * If the name starts with "t_" the next two characters are interpreted as a
2804 * termcap name.
2805 * Return the key code, or 0 if not found.
2808 get_special_key_code(name)
2809 char_u *name;
2811 char_u *table_name;
2812 char_u string[3];
2813 int i, j;
2816 * If it's <t_xx> we get the code for xx from the termcap
2818 if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2820 string[0] = name[2];
2821 string[1] = name[3];
2822 string[2] = NUL;
2823 if (add_termcap_entry(string, FALSE) == OK)
2824 return TERMCAP2KEY(name[2], name[3]);
2826 else
2827 for (i = 0; key_names_table[i].name != NULL; i++)
2829 table_name = key_names_table[i].name;
2830 for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
2831 if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
2832 break;
2833 if (!vim_isIDc(name[j]) && table_name[j] == NUL)
2834 return key_names_table[i].key;
2836 return 0;
2839 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2840 char_u *
2841 get_key_name(i)
2842 int i;
2844 if (i >= KEY_NAMES_TABLE_LEN)
2845 return NULL;
2846 return key_names_table[i].name;
2848 #endif
2850 #if defined(FEAT_MOUSE) || defined(PROTO)
2852 * Look up the given mouse code to return the relevant information in the other
2853 * arguments. Return which button is down or was released.
2856 get_mouse_button(code, is_click, is_drag)
2857 int code;
2858 int *is_click;
2859 int *is_drag;
2861 int i;
2863 for (i = 0; mouse_table[i].pseudo_code; i++)
2864 if (code == mouse_table[i].pseudo_code)
2866 *is_click = mouse_table[i].is_click;
2867 *is_drag = mouse_table[i].is_drag;
2868 return mouse_table[i].button;
2870 return 0; /* Shouldn't get here */
2874 * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
2875 * the given information about which mouse button is down, and whether the
2876 * mouse was clicked, dragged or released.
2879 get_pseudo_mouse_code(button, is_click, is_drag)
2880 int button; /* eg MOUSE_LEFT */
2881 int is_click;
2882 int is_drag;
2884 int i;
2886 for (i = 0; mouse_table[i].pseudo_code; i++)
2887 if (button == mouse_table[i].button
2888 && is_click == mouse_table[i].is_click
2889 && is_drag == mouse_table[i].is_drag)
2891 #ifdef FEAT_GUI
2892 /* Trick: a non mappable left click and release has mouse_col -1
2893 * or added MOUSE_COLOFF. Used for 'mousefocus' in
2894 * gui_mouse_moved() */
2895 if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
2897 if (mouse_col < 0)
2898 mouse_col = 0;
2899 else
2900 mouse_col -= MOUSE_COLOFF;
2901 if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
2902 return (int)KE_LEFTMOUSE_NM;
2903 if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
2904 return (int)KE_LEFTRELEASE_NM;
2906 #endif
2907 return mouse_table[i].pseudo_code;
2909 return (int)KE_IGNORE; /* not recognized, ignore it */
2911 #endif /* FEAT_MOUSE */
2914 * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
2917 get_fileformat(buf)
2918 buf_T *buf;
2920 int c = *buf->b_p_ff;
2922 if (buf->b_p_bin || c == 'u')
2923 return EOL_UNIX;
2924 if (c == 'm')
2925 return EOL_MAC;
2926 return EOL_DOS;
2930 * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
2931 * argument.
2934 get_fileformat_force(buf, eap)
2935 buf_T *buf;
2936 exarg_T *eap; /* can be NULL! */
2938 int c;
2940 if (eap != NULL && eap->force_ff != 0)
2941 c = eap->cmd[eap->force_ff];
2942 else
2944 if ((eap != NULL && eap->force_bin != 0)
2945 ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
2946 return EOL_UNIX;
2947 c = *buf->b_p_ff;
2949 if (c == 'u')
2950 return EOL_UNIX;
2951 if (c == 'm')
2952 return EOL_MAC;
2953 return EOL_DOS;
2957 * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
2958 * Sets both 'textmode' and 'fileformat'.
2959 * Note: Does _not_ set global value of 'textmode'!
2961 void
2962 set_fileformat(t, opt_flags)
2963 int t;
2964 int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */
2966 char *p = NULL;
2968 switch (t)
2970 case EOL_DOS:
2971 p = FF_DOS;
2972 curbuf->b_p_tx = TRUE;
2973 break;
2974 case EOL_UNIX:
2975 p = FF_UNIX;
2976 curbuf->b_p_tx = FALSE;
2977 break;
2978 case EOL_MAC:
2979 p = FF_MAC;
2980 curbuf->b_p_tx = FALSE;
2981 break;
2983 if (p != NULL)
2984 set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
2985 OPT_FREE | opt_flags, 0);
2987 #ifdef FEAT_WINDOWS
2988 /* This may cause the buffer to become (un)modified. */
2989 check_status(curbuf);
2990 redraw_tabline = TRUE;
2991 #endif
2992 #ifdef FEAT_TITLE
2993 need_maketitle = TRUE; /* set window title later */
2994 #endif
2998 * Return the default fileformat from 'fileformats'.
3001 default_fileformat()
3003 switch (*p_ffs)
3005 case 'm': return EOL_MAC;
3006 case 'd': return EOL_DOS;
3008 return EOL_UNIX;
3012 * Call shell. Calls mch_call_shell, with 'shellxquote' added.
3015 call_shell(cmd, opt)
3016 char_u *cmd;
3017 int opt;
3019 char_u *ncmd;
3020 int retval;
3021 #ifdef FEAT_PROFILE
3022 proftime_T wait_time;
3023 #endif
3025 if (p_verbose > 3)
3027 verbose_enter();
3028 smsg((char_u *)_("Calling shell to execute: \"%s\""),
3029 cmd == NULL ? p_sh : cmd);
3030 out_char('\n');
3031 cursor_on();
3032 verbose_leave();
3035 #ifdef FEAT_PROFILE
3036 if (do_profiling == PROF_YES)
3037 prof_child_enter(&wait_time);
3038 #endif
3040 if (*p_sh == NUL)
3042 EMSG(_(e_shellempty));
3043 retval = -1;
3045 else
3047 #ifdef FEAT_GUI_MSWIN
3048 /* Don't hide the pointer while executing a shell command. */
3049 gui_mch_mousehide(FALSE);
3050 #endif
3051 #ifdef FEAT_GUI
3052 ++hold_gui_events;
3053 #endif
3054 /* The external command may update a tags file, clear cached tags. */
3055 tag_freematch();
3057 if (cmd == NULL || *p_sxq == NUL)
3058 retval = mch_call_shell(cmd, opt);
3059 else
3061 ncmd = alloc((unsigned)(STRLEN(cmd) + STRLEN(p_sxq) * 2 + 1));
3062 if (ncmd != NULL)
3064 STRCPY(ncmd, p_sxq);
3065 STRCAT(ncmd, cmd);
3066 STRCAT(ncmd, p_sxq);
3067 retval = mch_call_shell(ncmd, opt);
3068 vim_free(ncmd);
3070 else
3071 retval = -1;
3073 #ifdef FEAT_GUI
3074 --hold_gui_events;
3075 #endif
3077 * Check the window size, in case it changed while executing the
3078 * external command.
3080 shell_resized_check();
3083 #ifdef FEAT_EVAL
3084 set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
3085 # ifdef FEAT_PROFILE
3086 if (do_profiling == PROF_YES)
3087 prof_child_exit(&wait_time);
3088 # endif
3089 #endif
3091 return retval;
3095 * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to
3096 * NORMAL State with a condition. This function returns the real State.
3099 get_real_state()
3101 if (State & NORMAL)
3103 #ifdef FEAT_VISUAL
3104 if (VIsual_active)
3106 if (VIsual_select)
3107 return SELECTMODE;
3108 return VISUAL;
3110 else
3111 #endif
3112 if (finish_op)
3113 return OP_PENDING;
3115 return State;
3118 #if defined(FEAT_MBYTE) || defined(PROTO)
3120 * Return TRUE if "p" points to just after a path separator.
3121 * Take care of multi-byte characters.
3122 * "b" must point to the start of the file name
3125 after_pathsep(b, p)
3126 char_u *b;
3127 char_u *p;
3129 return vim_ispathsep(p[-1])
3130 && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
3132 #endif
3135 * Return TRUE if file names "f1" and "f2" are in the same directory.
3136 * "f1" may be a short name, "f2" must be a full path.
3139 same_directory(f1, f2)
3140 char_u *f1;
3141 char_u *f2;
3143 char_u ffname[MAXPATHL];
3144 char_u *t1;
3145 char_u *t2;
3147 /* safety check */
3148 if (f1 == NULL || f2 == NULL)
3149 return FALSE;
3151 (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
3152 t1 = gettail_sep(ffname);
3153 t2 = gettail_sep(f2);
3154 return (t1 - ffname == t2 - f2
3155 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
3158 #if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
3159 || ((defined(FEAT_GUI_GTK)) \
3160 && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
3161 || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
3162 || defined(PROTO)
3164 * Change to a file's directory.
3165 * Caller must call shorten_fnames()!
3166 * Return OK or FAIL.
3169 vim_chdirfile(fname)
3170 char_u *fname;
3172 char_u dir[MAXPATHL];
3174 vim_strncpy(dir, fname, MAXPATHL - 1);
3175 *gettail_sep(dir) = NUL;
3176 return mch_chdir((char *)dir) == 0 ? OK : FAIL;
3178 #endif
3180 #if defined(STAT_IGNORES_SLASH) || defined(PROTO)
3182 * Check if "name" ends in a slash and is not a directory.
3183 * Used for systems where stat() ignores a trailing slash on a file name.
3184 * The Vim code assumes a trailing slash is only ignored for a directory.
3187 illegal_slash(name)
3188 char *name;
3190 if (name[0] == NUL)
3191 return FALSE; /* no file name is not illegal */
3192 if (name[strlen(name) - 1] != '/')
3193 return FALSE; /* no trailing slash */
3194 if (mch_isdir((char_u *)name))
3195 return FALSE; /* trailing slash for a directory */
3196 return TRUE;
3198 #endif
3200 #if defined(CURSOR_SHAPE) || defined(PROTO)
3203 * Handling of cursor and mouse pointer shapes in various modes.
3206 cursorentry_T shape_table[SHAPE_IDX_COUNT] =
3208 /* The values will be filled in from the 'guicursor' and 'mouseshape'
3209 * defaults when Vim starts.
3210 * Adjust the SHAPE_IDX_ defines when making changes! */
3211 {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
3212 {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
3213 {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
3214 {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
3215 {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
3216 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
3217 {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
3218 {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
3219 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
3220 {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE},
3221 {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE},
3222 {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE},
3223 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE},
3224 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE},
3225 {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE},
3226 {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE},
3227 {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
3230 #ifdef FEAT_MOUSESHAPE
3232 * Table with names for mouse shapes. Keep in sync with all the tables for
3233 * mch_set_mouse_shape()!.
3235 static char * mshape_names[] =
3237 "arrow", /* default, must be the first one */
3238 "blank", /* hidden */
3239 "beam",
3240 "updown",
3241 "udsizing",
3242 "leftright",
3243 "lrsizing",
3244 "busy",
3245 "no",
3246 "crosshair",
3247 "hand1",
3248 "hand2",
3249 "pencil",
3250 "question",
3251 "rightup-arrow",
3252 "up-arrow",
3253 NULL
3255 #endif
3258 * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
3259 * ("what" is SHAPE_MOUSE).
3260 * Returns error message for an illegal option, NULL otherwise.
3262 char_u *
3263 parse_shape_opt(what)
3264 int what;
3266 char_u *modep;
3267 char_u *colonp;
3268 char_u *commap;
3269 char_u *slashp;
3270 char_u *p, *endp;
3271 int idx = 0; /* init for GCC */
3272 int all_idx;
3273 int len;
3274 int i;
3275 long n;
3276 int found_ve = FALSE; /* found "ve" flag */
3277 int round;
3280 * First round: check for errors; second round: do it for real.
3282 for (round = 1; round <= 2; ++round)
3285 * Repeat for all comma separated parts.
3287 #ifdef FEAT_MOUSESHAPE
3288 if (what == SHAPE_MOUSE)
3289 modep = p_mouseshape;
3290 else
3291 #endif
3292 modep = p_guicursor;
3293 while (*modep != NUL)
3295 colonp = vim_strchr(modep, ':');
3296 if (colonp == NULL)
3297 return (char_u *)N_("E545: Missing colon");
3298 if (colonp == modep)
3299 return (char_u *)N_("E546: Illegal mode");
3300 commap = vim_strchr(modep, ',');
3303 * Repeat for all mode's before the colon.
3304 * For the 'a' mode, we loop to handle all the modes.
3306 all_idx = -1;
3307 while (modep < colonp || all_idx >= 0)
3309 if (all_idx < 0)
3311 /* Find the mode. */
3312 if (modep[1] == '-' || modep[1] == ':')
3313 len = 1;
3314 else
3315 len = 2;
3316 if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
3317 all_idx = SHAPE_IDX_COUNT - 1;
3318 else
3320 for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
3321 if (STRNICMP(modep, shape_table[idx].name, len)
3322 == 0)
3323 break;
3324 if (idx == SHAPE_IDX_COUNT
3325 || (shape_table[idx].used_for & what) == 0)
3326 return (char_u *)N_("E546: Illegal mode");
3327 if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
3328 found_ve = TRUE;
3330 modep += len + 1;
3333 if (all_idx >= 0)
3334 idx = all_idx--;
3335 else if (round == 2)
3337 #ifdef FEAT_MOUSESHAPE
3338 if (what == SHAPE_MOUSE)
3340 /* Set the default, for the missing parts */
3341 shape_table[idx].mshape = 0;
3343 else
3344 #endif
3346 /* Set the defaults, for the missing parts */
3347 shape_table[idx].shape = SHAPE_BLOCK;
3348 shape_table[idx].blinkwait = 700L;
3349 shape_table[idx].blinkon = 400L;
3350 shape_table[idx].blinkoff = 250L;
3354 /* Parse the part after the colon */
3355 for (p = colonp + 1; *p && *p != ','; )
3357 #ifdef FEAT_MOUSESHAPE
3358 if (what == SHAPE_MOUSE)
3360 for (i = 0; ; ++i)
3362 if (mshape_names[i] == NULL)
3364 if (!VIM_ISDIGIT(*p))
3365 return (char_u *)N_("E547: Illegal mouseshape");
3366 if (round == 2)
3367 shape_table[idx].mshape =
3368 getdigits(&p) + MSHAPE_NUMBERED;
3369 else
3370 (void)getdigits(&p);
3371 break;
3373 len = (int)STRLEN(mshape_names[i]);
3374 if (STRNICMP(p, mshape_names[i], len) == 0)
3376 if (round == 2)
3377 shape_table[idx].mshape = i;
3378 p += len;
3379 break;
3383 else /* if (what == SHAPE_MOUSE) */
3384 #endif
3387 * First handle the ones with a number argument.
3389 i = *p;
3390 len = 0;
3391 if (STRNICMP(p, "ver", 3) == 0)
3392 len = 3;
3393 else if (STRNICMP(p, "hor", 3) == 0)
3394 len = 3;
3395 else if (STRNICMP(p, "blinkwait", 9) == 0)
3396 len = 9;
3397 else if (STRNICMP(p, "blinkon", 7) == 0)
3398 len = 7;
3399 else if (STRNICMP(p, "blinkoff", 8) == 0)
3400 len = 8;
3401 if (len != 0)
3403 p += len;
3404 if (!VIM_ISDIGIT(*p))
3405 return (char_u *)N_("E548: digit expected");
3406 n = getdigits(&p);
3407 if (len == 3) /* "ver" or "hor" */
3409 if (n == 0)
3410 return (char_u *)N_("E549: Illegal percentage");
3411 if (round == 2)
3413 if (TOLOWER_ASC(i) == 'v')
3414 shape_table[idx].shape = SHAPE_VER;
3415 else
3416 shape_table[idx].shape = SHAPE_HOR;
3417 shape_table[idx].percentage = n;
3420 else if (round == 2)
3422 if (len == 9)
3423 shape_table[idx].blinkwait = n;
3424 else if (len == 7)
3425 shape_table[idx].blinkon = n;
3426 else
3427 shape_table[idx].blinkoff = n;
3430 else if (STRNICMP(p, "block", 5) == 0)
3432 if (round == 2)
3433 shape_table[idx].shape = SHAPE_BLOCK;
3434 p += 5;
3436 else /* must be a highlight group name then */
3438 endp = vim_strchr(p, '-');
3439 if (commap == NULL) /* last part */
3441 if (endp == NULL)
3442 endp = p + STRLEN(p); /* find end of part */
3444 else if (endp > commap || endp == NULL)
3445 endp = commap;
3446 slashp = vim_strchr(p, '/');
3447 if (slashp != NULL && slashp < endp)
3449 /* "group/langmap_group" */
3450 i = syn_check_group(p, (int)(slashp - p));
3451 p = slashp + 1;
3453 if (round == 2)
3455 shape_table[idx].id = syn_check_group(p,
3456 (int)(endp - p));
3457 shape_table[idx].id_lm = shape_table[idx].id;
3458 if (slashp != NULL && slashp < endp)
3459 shape_table[idx].id = i;
3461 p = endp;
3463 } /* if (what != SHAPE_MOUSE) */
3465 if (*p == '-')
3466 ++p;
3469 modep = p;
3470 if (*modep == ',')
3471 ++modep;
3475 /* If the 's' flag is not given, use the 'v' cursor for 's' */
3476 if (!found_ve)
3478 #ifdef FEAT_MOUSESHAPE
3479 if (what == SHAPE_MOUSE)
3481 shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3483 else
3484 #endif
3486 shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3487 shape_table[SHAPE_IDX_VE].percentage =
3488 shape_table[SHAPE_IDX_V].percentage;
3489 shape_table[SHAPE_IDX_VE].blinkwait =
3490 shape_table[SHAPE_IDX_V].blinkwait;
3491 shape_table[SHAPE_IDX_VE].blinkon =
3492 shape_table[SHAPE_IDX_V].blinkon;
3493 shape_table[SHAPE_IDX_VE].blinkoff =
3494 shape_table[SHAPE_IDX_V].blinkoff;
3495 shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3496 shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3500 return NULL;
3503 # if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
3504 || defined(FEAT_MOUSESHAPE) || defined(PROTO)
3506 * Return the index into shape_table[] for the current mode.
3507 * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3510 get_shape_idx(mouse)
3511 int mouse;
3513 #ifdef FEAT_MOUSESHAPE
3514 if (mouse && (State == HITRETURN || State == ASKMORE))
3516 # ifdef FEAT_GUI
3517 int x, y;
3518 gui_mch_getmouse(&x, &y);
3519 if (Y_2_ROW(y) == Rows - 1)
3520 return SHAPE_IDX_MOREL;
3521 # endif
3522 return SHAPE_IDX_MORE;
3524 if (mouse && drag_status_line)
3525 return SHAPE_IDX_SDRAG;
3526 # ifdef FEAT_VERTSPLIT
3527 if (mouse && drag_sep_line)
3528 return SHAPE_IDX_VDRAG;
3529 # endif
3530 #endif
3531 if (!mouse && State == SHOWMATCH)
3532 return SHAPE_IDX_SM;
3533 #ifdef FEAT_VREPLACE
3534 if (State & VREPLACE_FLAG)
3535 return SHAPE_IDX_R;
3536 #endif
3537 if (State & REPLACE_FLAG)
3538 return SHAPE_IDX_R;
3539 if (State & INSERT)
3540 return SHAPE_IDX_I;
3541 if (State & CMDLINE)
3543 if (cmdline_at_end())
3544 return SHAPE_IDX_C;
3545 if (cmdline_overstrike())
3546 return SHAPE_IDX_CR;
3547 return SHAPE_IDX_CI;
3549 if (finish_op)
3550 return SHAPE_IDX_O;
3551 #ifdef FEAT_VISUAL
3552 if (VIsual_active)
3554 if (*p_sel == 'e')
3555 return SHAPE_IDX_VE;
3556 else
3557 return SHAPE_IDX_V;
3559 #endif
3560 return SHAPE_IDX_N;
3562 #endif
3564 # if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3565 static int old_mouse_shape = 0;
3568 * Set the mouse shape:
3569 * If "shape" is -1, use shape depending on the current mode,
3570 * depending on the current state.
3571 * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3572 * when the mouse moves off the status or command line).
3574 void
3575 update_mouseshape(shape_idx)
3576 int shape_idx;
3578 int new_mouse_shape;
3580 /* Only works in GUI mode. */
3581 if (!gui.in_use || gui.starting)
3582 return;
3584 /* Postpone the updating when more is to come. Speeds up executing of
3585 * mappings. */
3586 if (shape_idx == -1 && char_avail())
3588 postponed_mouseshape = TRUE;
3589 return;
3592 /* When ignoring the mouse don't change shape on the statusline. */
3593 if (*p_mouse == NUL
3594 && (shape_idx == SHAPE_IDX_CLINE
3595 || shape_idx == SHAPE_IDX_STATUS
3596 || shape_idx == SHAPE_IDX_VSEP))
3597 shape_idx = -2;
3599 if (shape_idx == -2
3600 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3601 && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3602 && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3603 return;
3604 if (shape_idx < 0)
3605 new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3606 else
3607 new_mouse_shape = shape_table[shape_idx].mshape;
3608 if (new_mouse_shape != old_mouse_shape)
3610 mch_set_mouse_shape(new_mouse_shape);
3611 old_mouse_shape = new_mouse_shape;
3613 postponed_mouseshape = FALSE;
3615 # endif
3617 #endif /* CURSOR_SHAPE */
3620 #ifdef FEAT_CRYPT
3622 * Optional encryption support.
3623 * Mohsin Ahmed, mosh@sasi.com, 98-09-24
3624 * Based on zip/crypt sources.
3626 * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3627 * most countries. There are a few exceptions, but that still should not be a
3628 * problem since this code was originally created in Europe and India.
3631 /* from zip.h */
3633 typedef unsigned short ush; /* unsigned 16-bit value */
3634 typedef unsigned long ulg; /* unsigned 32-bit value */
3636 static void make_crc_tab __ARGS((void));
3638 static ulg crc_32_tab[256];
3641 * Fill the CRC table.
3643 static void
3644 make_crc_tab()
3646 ulg s,t,v;
3647 static int done = FALSE;
3649 if (done)
3650 return;
3651 for (t = 0; t < 256; t++)
3653 v = t;
3654 for (s = 0; s < 8; s++)
3655 v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3656 crc_32_tab[t] = v;
3658 done = TRUE;
3661 #define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3664 static ulg keys[3]; /* keys defining the pseudo-random sequence */
3667 * Return the next byte in the pseudo-random sequence
3670 decrypt_byte()
3672 ush temp;
3674 temp = (ush)keys[2] | 2;
3675 return (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff);
3679 * Update the encryption keys with the next byte of plain text
3682 update_keys(c)
3683 int c; /* byte of plain text */
3685 keys[0] = CRC32(keys[0], c);
3686 keys[1] += keys[0] & 0xff;
3687 keys[1] = keys[1] * 134775813L + 1;
3688 keys[2] = CRC32(keys[2], (int)(keys[1] >> 24));
3689 return c;
3693 * Initialize the encryption keys and the random header according to
3694 * the given password.
3695 * If "passwd" is NULL or empty, don't do anything.
3697 void
3698 crypt_init_keys(passwd)
3699 char_u *passwd; /* password string with which to modify keys */
3701 if (passwd != NULL && *passwd != NUL)
3703 make_crc_tab();
3704 keys[0] = 305419896L;
3705 keys[1] = 591751049L;
3706 keys[2] = 878082192L;
3707 while (*passwd != '\0')
3708 update_keys((int)*passwd++);
3713 * Ask the user for a crypt key.
3714 * When "store" is TRUE, the new key in stored in the 'key' option, and the
3715 * 'key' option value is returned: Don't free it.
3716 * When "store" is FALSE, the typed key is returned in allocated memory.
3717 * Returns NULL on failure.
3719 char_u *
3720 get_crypt_key(store, twice)
3721 int store;
3722 int twice; /* Ask for the key twice. */
3724 char_u *p1, *p2 = NULL;
3725 int round;
3727 for (round = 0; ; ++round)
3729 cmdline_star = TRUE;
3730 cmdline_row = msg_row;
3731 p1 = getcmdline_prompt(NUL, round == 0
3732 ? (char_u *)_("Enter encryption key: ")
3733 : (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING,
3734 NULL);
3735 cmdline_star = FALSE;
3737 if (p1 == NULL)
3738 break;
3740 if (round == twice)
3742 if (p2 != NULL && STRCMP(p1, p2) != 0)
3744 MSG(_("Keys don't match!"));
3745 vim_free(p1);
3746 vim_free(p2);
3747 p2 = NULL;
3748 round = -1; /* do it again */
3749 continue;
3751 if (store)
3753 set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
3754 vim_free(p1);
3755 p1 = curbuf->b_p_key;
3757 break;
3759 p2 = p1;
3762 /* since the user typed this, no need to wait for return */
3763 need_wait_return = FALSE;
3764 msg_didout = FALSE;
3766 vim_free(p2);
3767 return p1;
3770 #endif /* FEAT_CRYPT */
3772 /* TODO: make some #ifdef for this */
3773 /*--------[ file searching ]-------------------------------------------------*/
3775 * File searching functions for 'path', 'tags' and 'cdpath' options.
3776 * External visible functions:
3777 * vim_findfile_init() creates/initialises the search context
3778 * vim_findfile_free_visited() free list of visited files/dirs of search
3779 * context
3780 * vim_findfile() find a file in the search context
3781 * vim_findfile_cleanup() cleanup/free search context created by
3782 * vim_findfile_init()
3784 * All static functions and variables start with 'ff_'
3786 * In general it works like this:
3787 * First you create yourself a search context by calling vim_findfile_init().
3788 * It is possible to give a search context from a previous call to
3789 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
3790 * until you are satisfied with the result or it returns NULL. On every call it
3791 * returns the next file which matches the conditions given to
3792 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
3794 * It is possible to call vim_findfile_init() again to reinitialise your search
3795 * with some new parameters. Don't forget to pass your old search context to
3796 * it, so it can reuse it and especially reuse the list of already visited
3797 * directories. If you want to delete the list of already visited directories
3798 * simply call vim_findfile_free_visited().
3800 * When you are done call vim_findfile_cleanup() to free the search context.
3802 * The function vim_findfile_init() has a long comment, which describes the
3803 * needed parameters.
3807 * ATTENTION:
3808 * ==========
3809 * Also we use an allocated search context here, this functions are NOT
3810 * thread-safe!!!!!
3812 * To minimize parameter passing (or because I'm to lazy), only the
3813 * external visible functions get a search context as a parameter. This is
3814 * then assigned to a static global, which is used throughout the local
3815 * functions.
3819 * type for the directory search stack
3821 typedef struct ff_stack
3823 struct ff_stack *ffs_prev;
3825 /* the fix part (no wildcards) and the part containing the wildcards
3826 * of the search path
3828 char_u *ffs_fix_path;
3829 #ifdef FEAT_PATH_EXTRA
3830 char_u *ffs_wc_path;
3831 #endif
3833 /* files/dirs found in the above directory, matched by the first wildcard
3834 * of wc_part
3836 char_u **ffs_filearray;
3837 int ffs_filearray_size;
3838 char_u ffs_filearray_cur; /* needed for partly handled dirs */
3840 /* to store status of partly handled directories
3841 * 0: we work on this directory for the first time
3842 * 1: this directory was partly searched in an earlier step
3844 int ffs_stage;
3846 /* How deep are we in the directory tree?
3847 * Counts backward from value of level parameter to vim_findfile_init
3849 int ffs_level;
3851 /* Did we already expand '**' to an empty string? */
3852 int ffs_star_star_empty;
3853 } ff_stack_T;
3856 * type for already visited directories or files.
3858 typedef struct ff_visited
3860 struct ff_visited *ffv_next;
3862 #ifdef FEAT_PATH_EXTRA
3863 /* Visited directories are different if the wildcard string are
3864 * different. So we have to save it.
3866 char_u *ffv_wc_path;
3867 #endif
3868 /* for unix use inode etc for comparison (needed because of links), else
3869 * use filename.
3871 #ifdef UNIX
3872 int ffv_dev; /* device number (-1 if not set) */
3873 ino_t ffv_ino; /* inode number */
3874 #endif
3875 /* The memory for this struct is allocated according to the length of
3876 * ffv_fname.
3878 char_u ffv_fname[1]; /* actually longer */
3879 } ff_visited_T;
3882 * We might have to manage several visited lists during a search.
3883 * This is especially needed for the tags option. If tags is set to:
3884 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
3885 * So we have to do 3 searches:
3886 * 1) search from the current files directory downward for the file "tags"
3887 * 2) search from the current files directory downward for the file "TAGS"
3888 * 3) search from Vims current directory downwards for the file "tags"
3889 * As you can see, the first and the third search are for the same file, so for
3890 * the third search we can use the visited list of the first search. For the
3891 * second search we must start from a empty visited list.
3892 * The struct ff_visited_list_hdr is used to manage a linked list of already
3893 * visited lists.
3895 typedef struct ff_visited_list_hdr
3897 struct ff_visited_list_hdr *ffvl_next;
3899 /* the filename the attached visited list is for */
3900 char_u *ffvl_filename;
3902 ff_visited_T *ffvl_visited_list;
3904 } ff_visited_list_hdr_T;
3908 * '**' can be expanded to several directory levels.
3909 * Set the default maximum depth.
3911 #define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
3914 * The search context:
3915 * ffsc_stack_ptr: the stack for the dirs to search
3916 * ffsc_visited_list: the currently active visited list
3917 * ffsc_dir_visited_list: the currently active visited list for search dirs
3918 * ffsc_visited_lists_list: the list of all visited lists
3919 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
3920 * ffsc_file_to_search: the file to search for
3921 * ffsc_start_dir: the starting directory, if search path was relative
3922 * ffsc_fix_path: the fix part of the given path (without wildcards)
3923 * Needed for upward search.
3924 * ffsc_wc_path: the part of the given path containing wildcards
3925 * ffsc_level: how many levels of dirs to search downwards
3926 * ffsc_stopdirs_v: array of stop directories for upward search
3927 * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
3929 typedef struct ff_search_ctx_T
3931 ff_stack_T *ffsc_stack_ptr;
3932 ff_visited_list_hdr_T *ffsc_visited_list;
3933 ff_visited_list_hdr_T *ffsc_dir_visited_list;
3934 ff_visited_list_hdr_T *ffsc_visited_lists_list;
3935 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
3936 char_u *ffsc_file_to_search;
3937 char_u *ffsc_start_dir;
3938 char_u *ffsc_fix_path;
3939 #ifdef FEAT_PATH_EXTRA
3940 char_u *ffsc_wc_path;
3941 int ffsc_level;
3942 char_u **ffsc_stopdirs_v;
3943 #endif
3944 int ffsc_find_what;
3945 } ff_search_ctx_T;
3947 /* locally needed functions */
3948 #ifdef FEAT_PATH_EXTRA
3949 static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
3950 #else
3951 static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
3952 #endif
3953 static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
3954 static void ff_free_visited_list __ARGS((ff_visited_T *vl));
3955 static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
3956 #ifdef FEAT_PATH_EXTRA
3957 static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
3958 #endif
3960 static void ff_push __ARGS((ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr));
3961 static ff_stack_T *ff_pop __ARGS((ff_search_ctx_T *search_ctx));
3962 static void ff_clear __ARGS((ff_search_ctx_T *search_ctx));
3963 static void ff_free_stack_element __ARGS((ff_stack_T *stack_ptr));
3964 #ifdef FEAT_PATH_EXTRA
3965 static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
3966 #else
3967 static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
3968 #endif
3969 #ifdef FEAT_PATH_EXTRA
3970 static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
3971 #endif
3973 #if 0
3975 * if someone likes findfirst/findnext, here are the functions
3976 * NOT TESTED!!
3979 static void *ff_fn_search_context = NULL;
3981 char_u *
3982 vim_findfirst(path, filename, level)
3983 char_u *path;
3984 char_u *filename;
3985 int level;
3987 ff_fn_search_context =
3988 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
3989 ff_fn_search_context, rel_fname);
3990 if (NULL == ff_fn_search_context)
3991 return NULL;
3992 else
3993 return vim_findnext()
3996 char_u *
3997 vim_findnext()
3999 char_u *ret = vim_findfile(ff_fn_search_context);
4001 if (NULL == ret)
4003 vim_findfile_cleanup(ff_fn_search_context);
4004 ff_fn_search_context = NULL;
4006 return ret;
4008 #endif
4011 * Initialization routine for vim_findfile.
4013 * Returns the newly allocated search context or NULL if an error occured.
4015 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
4016 * with the search context.
4018 * Find the file 'filename' in the directory 'path'.
4019 * The parameter 'path' may contain wildcards. If so only search 'level'
4020 * directories deep. The parameter 'level' is the absolute maximum and is
4021 * not related to restricts given to the '**' wildcard. If 'level' is 100
4022 * and you use '**200' vim_findfile() will stop after 100 levels.
4024 * 'filename' cannot contain wildcards! It is used as-is, no backslashes to
4025 * escape special characters.
4027 * If 'stopdirs' is not NULL and nothing is found downward, the search is
4028 * restarted on the next higher directory level. This is repeated until the
4029 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
4030 * format ";*<dirname>*\(;<dirname>\)*;\=$".
4032 * If the 'path' is relative, the starting dir for the search is either VIM's
4033 * current dir or if the path starts with "./" the current files dir.
4034 * If the 'path' is absolut, the starting dir is that part of the path before
4035 * the first wildcard.
4037 * Upward search is only done on the starting dir.
4039 * If 'free_visited' is TRUE the list of already visited files/directories is
4040 * cleared. Set this to FALSE if you just want to search from another
4041 * directory, but want to be sure that no directory from a previous search is
4042 * searched again. This is useful if you search for a file at different places.
4043 * The list of visited files/dirs can also be cleared with the function
4044 * vim_findfile_free_visited().
4046 * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
4047 * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
4049 * A search context returned by a previous call to vim_findfile_init() can be
4050 * passed in the parameter "search_ctx_arg". This context is reused and
4051 * reinitialized with the new parameters. The list of already visited
4052 * directories from this context is only deleted if the parameter
4053 * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed
4054 * if the reinitialization fails.
4056 * If you don't have a search context from a previous call "search_ctx_arg"
4057 * must be NULL.
4059 * This function silently ignores a few errors, vim_findfile() will have
4060 * limited functionality then.
4062 /*ARGSUSED*/
4063 void *
4064 vim_findfile_init(path, filename, stopdirs, level, free_visited, find_what,
4065 search_ctx_arg, tagfile, rel_fname)
4066 char_u *path;
4067 char_u *filename;
4068 char_u *stopdirs;
4069 int level;
4070 int free_visited;
4071 int find_what;
4072 void *search_ctx_arg;
4073 int tagfile;
4074 char_u *rel_fname; /* file name to use for "." */
4076 #ifdef FEAT_PATH_EXTRA
4077 char_u *wc_part;
4078 #endif
4079 ff_stack_T *sptr;
4080 ff_search_ctx_T *search_ctx;
4082 /* If a search context is given by the caller, reuse it, else allocate a
4083 * new one.
4085 if (search_ctx_arg != NULL)
4086 search_ctx = search_ctx_arg;
4087 else
4089 search_ctx = (ff_search_ctx_T*)alloc((unsigned)sizeof(ff_search_ctx_T));
4090 if (search_ctx == NULL)
4091 goto error_return;
4092 memset(search_ctx, 0, sizeof(ff_search_ctx_T));
4094 search_ctx->ffsc_find_what = find_what;
4096 /* clear the search context, but NOT the visited lists */
4097 ff_clear(search_ctx);
4099 /* clear visited list if wanted */
4100 if (free_visited == TRUE)
4101 vim_findfile_free_visited(search_ctx);
4102 else
4104 /* Reuse old visited lists. Get the visited list for the given
4105 * filename. If no list for the current filename exists, creates a new
4106 * one. */
4107 search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
4108 &search_ctx->ffsc_visited_lists_list);
4109 if (search_ctx->ffsc_visited_list == NULL)
4110 goto error_return;
4111 search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
4112 &search_ctx->ffsc_dir_visited_lists_list);
4113 if (search_ctx->ffsc_dir_visited_list == NULL)
4114 goto error_return;
4117 if (ff_expand_buffer == NULL)
4119 ff_expand_buffer = (char_u*)alloc(MAXPATHL);
4120 if (ff_expand_buffer == NULL)
4121 goto error_return;
4124 /* Store information on starting dir now if path is relative.
4125 * If path is absolute, we do that later. */
4126 if (path[0] == '.'
4127 && (vim_ispathsep(path[1]) || path[1] == NUL)
4128 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
4129 && rel_fname != NULL)
4131 int len = (int)(gettail(rel_fname) - rel_fname);
4133 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
4135 /* Make the start dir an absolute path name. */
4136 vim_strncpy(ff_expand_buffer, rel_fname, len);
4137 search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
4139 else
4140 search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
4141 if (search_ctx->ffsc_start_dir == NULL)
4142 goto error_return;
4143 if (*++path != NUL)
4144 ++path;
4146 else if (*path == NUL || !vim_isAbsName(path))
4148 #ifdef BACKSLASH_IN_FILENAME
4149 /* "c:dir" needs "c:" to be expanded, otherwise use current dir */
4150 if (*path != NUL && path[1] == ':')
4152 char_u drive[3];
4154 drive[0] = path[0];
4155 drive[1] = ':';
4156 drive[2] = NUL;
4157 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4158 goto error_return;
4159 path += 2;
4161 else
4162 #endif
4163 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
4164 goto error_return;
4166 search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
4167 if (search_ctx->ffsc_start_dir == NULL)
4168 goto error_return;
4170 #ifdef BACKSLASH_IN_FILENAME
4171 /* A path that starts with "/dir" is relative to the drive, not to the
4172 * directory (but not for "//machine/dir"). Only use the drive name. */
4173 if ((*path == '/' || *path == '\\')
4174 && path[1] != path[0]
4175 && search_ctx->ffsc_start_dir[1] == ':')
4176 search_ctx->ffsc_start_dir[2] = NUL;
4177 #endif
4180 #ifdef FEAT_PATH_EXTRA
4182 * If stopdirs are given, split them into an array of pointers.
4183 * If this fails (mem allocation), there is no upward search at all or a
4184 * stop directory is not recognized -> continue silently.
4185 * If stopdirs just contains a ";" or is empty,
4186 * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
4187 * is handled as unlimited upward search. See function
4188 * ff_path_in_stoplist() for details.
4190 if (stopdirs != NULL)
4192 char_u *walker = stopdirs;
4193 int dircount;
4195 while (*walker == ';')
4196 walker++;
4198 dircount = 1;
4199 search_ctx->ffsc_stopdirs_v =
4200 (char_u **)alloc((unsigned)sizeof(char_u *));
4202 if (search_ctx->ffsc_stopdirs_v != NULL)
4206 char_u *helper;
4207 void *ptr;
4209 helper = walker;
4210 ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
4211 (dircount + 1) * sizeof(char_u *));
4212 if (ptr)
4213 search_ctx->ffsc_stopdirs_v = ptr;
4214 else
4215 /* ignore, keep what we have and continue */
4216 break;
4217 walker = vim_strchr(walker, ';');
4218 if (walker)
4220 search_ctx->ffsc_stopdirs_v[dircount-1] =
4221 vim_strnsave(helper, (int)(walker - helper));
4222 walker++;
4224 else
4225 /* this might be "", which means ascent till top
4226 * of directory tree.
4228 search_ctx->ffsc_stopdirs_v[dircount-1] =
4229 vim_strsave(helper);
4231 dircount++;
4233 } while (walker != NULL);
4234 search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
4237 #endif
4239 #ifdef FEAT_PATH_EXTRA
4240 search_ctx->ffsc_level = level;
4242 /* split into:
4243 * -fix path
4244 * -wildcard_stuff (might be NULL)
4246 wc_part = vim_strchr(path, '*');
4247 if (wc_part != NULL)
4249 int llevel;
4250 int len;
4251 char *errpt;
4253 /* save the fix part of the path */
4254 search_ctx->ffsc_fix_path = vim_strnsave(path, (int)(wc_part - path));
4257 * copy wc_path and add restricts to the '**' wildcard.
4258 * The octet after a '**' is used as a (binary) counter.
4259 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
4260 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
4261 * For EBCDIC you get different character values.
4262 * If no restrict is given after '**' the default is used.
4263 * Due to this technic the path looks awful if you print it as a
4264 * string.
4266 len = 0;
4267 while (*wc_part != NUL)
4269 if (STRNCMP(wc_part, "**", 2) == 0)
4271 ff_expand_buffer[len++] = *wc_part++;
4272 ff_expand_buffer[len++] = *wc_part++;
4274 llevel = strtol((char *)wc_part, &errpt, 10);
4275 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
4276 ff_expand_buffer[len++] = llevel;
4277 else if ((char_u *)errpt != wc_part && llevel == 0)
4278 /* restrict is 0 -> remove already added '**' */
4279 len -= 2;
4280 else
4281 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
4282 wc_part = (char_u *)errpt;
4283 if (*wc_part != NUL && !vim_ispathsep(*wc_part))
4285 EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
4286 goto error_return;
4289 else
4290 ff_expand_buffer[len++] = *wc_part++;
4292 ff_expand_buffer[len] = NUL;
4293 search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
4295 if (search_ctx->ffsc_wc_path == NULL)
4296 goto error_return;
4298 else
4299 #endif
4300 search_ctx->ffsc_fix_path = vim_strsave(path);
4302 if (search_ctx->ffsc_start_dir == NULL)
4304 /* store the fix part as startdir.
4305 * This is needed if the parameter path is fully qualified.
4307 search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
4308 if (search_ctx->ffsc_start_dir)
4309 search_ctx->ffsc_fix_path[0] = NUL;
4312 /* create an absolute path */
4313 STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
4314 add_pathsep(ff_expand_buffer);
4315 STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
4316 add_pathsep(ff_expand_buffer);
4318 sptr = ff_create_stack_element(ff_expand_buffer,
4319 #ifdef FEAT_PATH_EXTRA
4320 search_ctx->ffsc_wc_path,
4321 #endif
4322 level, 0);
4324 if (sptr == NULL)
4325 goto error_return;
4327 ff_push(search_ctx, sptr);
4329 search_ctx->ffsc_file_to_search = vim_strsave(filename);
4330 if (search_ctx->ffsc_file_to_search == NULL)
4331 goto error_return;
4333 return search_ctx;
4335 error_return:
4337 * We clear the search context now!
4338 * Even when the caller gave us a (perhaps valid) context we free it here,
4339 * as we might have already destroyed it.
4341 vim_findfile_cleanup(search_ctx);
4342 return NULL;
4345 #if defined(FEAT_PATH_EXTRA) || defined(PROTO)
4347 * Get the stopdir string. Check that ';' is not escaped.
4349 char_u *
4350 vim_findfile_stopdir(buf)
4351 char_u *buf;
4353 char_u *r_ptr = buf;
4355 while (*r_ptr != NUL && *r_ptr != ';')
4357 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
4359 /* overwrite the escape char,
4360 * use STRLEN(r_ptr) to move the trailing '\0'
4362 STRMOVE(r_ptr, r_ptr + 1);
4363 r_ptr++;
4365 r_ptr++;
4367 if (*r_ptr == ';')
4369 *r_ptr = 0;
4370 r_ptr++;
4372 else if (*r_ptr == NUL)
4373 r_ptr = NULL;
4374 return r_ptr;
4376 #endif
4379 * Clean up the given search context. Can handle a NULL pointer.
4381 void
4382 vim_findfile_cleanup(ctx)
4383 void *ctx;
4385 if (ctx == NULL)
4386 return;
4388 vim_findfile_free_visited(ctx);
4389 ff_clear(ctx);
4390 vim_free(ctx);
4394 * Find a file in a search context.
4395 * The search context was created with vim_findfile_init() above.
4396 * Return a pointer to an allocated file name or NULL if nothing found.
4397 * To get all matching files call this function until you get NULL.
4399 * If the passed search_context is NULL, NULL is returned.
4401 * The search algorithm is depth first. To change this replace the
4402 * stack with a list (don't forget to leave partly searched directories on the
4403 * top of the list).
4405 char_u *
4406 vim_findfile(search_ctx_arg)
4407 void *search_ctx_arg;
4409 char_u *file_path;
4410 #ifdef FEAT_PATH_EXTRA
4411 char_u *rest_of_wildcards;
4412 char_u *path_end = NULL;
4413 #endif
4414 ff_stack_T *stackp;
4415 #if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
4416 int len;
4417 #endif
4418 int i;
4419 char_u *p;
4420 #ifdef FEAT_SEARCHPATH
4421 char_u *suf;
4422 #endif
4423 ff_search_ctx_T *search_ctx;
4425 if (search_ctx_arg == NULL)
4426 return NULL;
4428 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
4431 * filepath is used as buffer for various actions and as the storage to
4432 * return a found filename.
4434 if ((file_path = alloc((int)MAXPATHL)) == NULL)
4435 return NULL;
4437 #ifdef FEAT_PATH_EXTRA
4438 /* store the end of the start dir -- needed for upward search */
4439 if (search_ctx->ffsc_start_dir != NULL)
4440 path_end = &search_ctx->ffsc_start_dir[
4441 STRLEN(search_ctx->ffsc_start_dir)];
4442 #endif
4444 #ifdef FEAT_PATH_EXTRA
4445 /* upward search loop */
4446 for (;;)
4448 #endif
4449 /* downward search loop */
4450 for (;;)
4452 /* check if user user wants to stop the search*/
4453 ui_breakcheck();
4454 if (got_int)
4455 break;
4457 /* get directory to work on from stack */
4458 stackp = ff_pop(search_ctx);
4459 if (stackp == NULL)
4460 break;
4463 * TODO: decide if we leave this test in
4465 * GOOD: don't search a directory(-tree) twice.
4466 * BAD: - check linked list for every new directory entered.
4467 * - check for double files also done below
4469 * Here we check if we already searched this directory.
4470 * We already searched a directory if:
4471 * 1) The directory is the same.
4472 * 2) We would use the same wildcard string.
4474 * Good if you have links on same directory via several ways
4475 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4476 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4478 * This check is only needed for directories we work on for the
4479 * first time (hence stackp->ff_filearray == NULL)
4481 if (stackp->ffs_filearray == NULL
4482 && ff_check_visited(&search_ctx->ffsc_dir_visited_list
4483 ->ffvl_visited_list,
4484 stackp->ffs_fix_path
4485 #ifdef FEAT_PATH_EXTRA
4486 , stackp->ffs_wc_path
4487 #endif
4488 ) == FAIL)
4490 #ifdef FF_VERBOSE
4491 if (p_verbose >= 5)
4493 verbose_enter_scroll();
4494 smsg((char_u *)"Already Searched: %s (%s)",
4495 stackp->ffs_fix_path, stackp->ffs_wc_path);
4496 /* don't overwrite this either */
4497 msg_puts((char_u *)"\n");
4498 verbose_leave_scroll();
4500 #endif
4501 ff_free_stack_element(stackp);
4502 continue;
4504 #ifdef FF_VERBOSE
4505 else if (p_verbose >= 5)
4507 verbose_enter_scroll();
4508 smsg((char_u *)"Searching: %s (%s)",
4509 stackp->ffs_fix_path, stackp->ffs_wc_path);
4510 /* don't overwrite this either */
4511 msg_puts((char_u *)"\n");
4512 verbose_leave_scroll();
4514 #endif
4516 /* check depth */
4517 if (stackp->ffs_level <= 0)
4519 ff_free_stack_element(stackp);
4520 continue;
4523 file_path[0] = NUL;
4526 * If no filearray till now expand wildcards
4527 * The function expand_wildcards() can handle an array of paths
4528 * and all possible expands are returned in one array. We use this
4529 * to handle the expansion of '**' into an empty string.
4531 if (stackp->ffs_filearray == NULL)
4533 char_u *dirptrs[2];
4535 /* we use filepath to build the path expand_wildcards() should
4536 * expand.
4538 dirptrs[0] = file_path;
4539 dirptrs[1] = NULL;
4541 /* if we have a start dir copy it in */
4542 if (!vim_isAbsName(stackp->ffs_fix_path)
4543 && search_ctx->ffsc_start_dir)
4545 STRCPY(file_path, search_ctx->ffsc_start_dir);
4546 add_pathsep(file_path);
4549 /* append the fix part of the search path */
4550 STRCAT(file_path, stackp->ffs_fix_path);
4551 add_pathsep(file_path);
4553 #ifdef FEAT_PATH_EXTRA
4554 rest_of_wildcards = stackp->ffs_wc_path;
4555 if (*rest_of_wildcards != NUL)
4557 len = (int)STRLEN(file_path);
4558 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4560 /* pointer to the restrict byte
4561 * The restrict byte is not a character!
4563 p = rest_of_wildcards + 2;
4565 if (*p > 0)
4567 (*p)--;
4568 file_path[len++] = '*';
4571 if (*p == 0)
4573 /* remove '**<numb> from wildcards */
4574 STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
4576 else
4577 rest_of_wildcards += 3;
4579 if (stackp->ffs_star_star_empty == 0)
4581 /* if not done before, expand '**' to empty */
4582 stackp->ffs_star_star_empty = 1;
4583 dirptrs[1] = stackp->ffs_fix_path;
4588 * Here we copy until the next path separator or the end of
4589 * the path. If we stop at a path separator, there is
4590 * still something else left. This is handled below by
4591 * pushing every directory returned from expand_wildcards()
4592 * on the stack again for further search.
4594 while (*rest_of_wildcards
4595 && !vim_ispathsep(*rest_of_wildcards))
4596 file_path[len++] = *rest_of_wildcards++;
4598 file_path[len] = NUL;
4599 if (vim_ispathsep(*rest_of_wildcards))
4600 rest_of_wildcards++;
4602 #endif
4605 * Expand wildcards like "*" and "$VAR".
4606 * If the path is a URL don't try this.
4608 if (path_with_url(dirptrs[0]))
4610 stackp->ffs_filearray = (char_u **)
4611 alloc((unsigned)sizeof(char *));
4612 if (stackp->ffs_filearray != NULL
4613 && (stackp->ffs_filearray[0]
4614 = vim_strsave(dirptrs[0])) != NULL)
4615 stackp->ffs_filearray_size = 1;
4616 else
4617 stackp->ffs_filearray_size = 0;
4619 else
4620 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
4621 &stackp->ffs_filearray_size,
4622 &stackp->ffs_filearray,
4623 EW_DIR|EW_ADDSLASH|EW_SILENT);
4625 stackp->ffs_filearray_cur = 0;
4626 stackp->ffs_stage = 0;
4628 #ifdef FEAT_PATH_EXTRA
4629 else
4630 rest_of_wildcards = &stackp->ffs_wc_path[
4631 STRLEN(stackp->ffs_wc_path)];
4632 #endif
4634 if (stackp->ffs_stage == 0)
4636 /* this is the first time we work on this directory */
4637 #ifdef FEAT_PATH_EXTRA
4638 if (*rest_of_wildcards == NUL)
4639 #endif
4642 * we don't have further wildcards to expand, so we have to
4643 * check for the final file now
4645 for (i = stackp->ffs_filearray_cur;
4646 i < stackp->ffs_filearray_size; ++i)
4648 if (!path_with_url(stackp->ffs_filearray[i])
4649 && !mch_isdir(stackp->ffs_filearray[i]))
4650 continue; /* not a directory */
4652 /* prepare the filename to be checked for existance
4653 * below */
4654 STRCPY(file_path, stackp->ffs_filearray[i]);
4655 add_pathsep(file_path);
4656 STRCAT(file_path, search_ctx->ffsc_file_to_search);
4659 * Try without extra suffix and then with suffixes
4660 * from 'suffixesadd'.
4662 #ifdef FEAT_SEARCHPATH
4663 len = (int)STRLEN(file_path);
4664 suf = curbuf->b_p_sua;
4665 for (;;)
4666 #endif
4668 /* if file exists and we didn't already find it */
4669 if ((path_with_url(file_path)
4670 || (mch_getperm(file_path) >= 0
4671 && (search_ctx->ffsc_find_what
4672 == FINDFILE_BOTH
4673 || ((search_ctx->ffsc_find_what
4674 == FINDFILE_DIR)
4675 == mch_isdir(file_path)))))
4676 #ifndef FF_VERBOSE
4677 && (ff_check_visited(
4678 &search_ctx->ffsc_visited_list->ffvl_visited_list,
4679 file_path
4680 #ifdef FEAT_PATH_EXTRA
4681 , (char_u *)""
4682 #endif
4683 ) == OK)
4684 #endif
4687 #ifdef FF_VERBOSE
4688 if (ff_check_visited(
4689 &search_ctx->ffsc_visited_list->ffvl_visited_list,
4690 file_path
4691 #ifdef FEAT_PATH_EXTRA
4692 , (char_u *)""
4693 #endif
4694 ) == FAIL)
4696 if (p_verbose >= 5)
4698 verbose_enter_scroll();
4699 smsg((char_u *)"Already: %s",
4700 file_path);
4701 /* don't overwrite this either */
4702 msg_puts((char_u *)"\n");
4703 verbose_leave_scroll();
4705 continue;
4707 #endif
4709 /* push dir to examine rest of subdirs later */
4710 stackp->ffs_filearray_cur = i + 1;
4711 ff_push(search_ctx, stackp);
4713 if (!path_with_url(file_path))
4714 simplify_filename(file_path);
4715 if (mch_dirname(ff_expand_buffer, MAXPATHL)
4716 == OK)
4718 p = shorten_fname(file_path,
4719 ff_expand_buffer);
4720 if (p != NULL)
4721 STRMOVE(file_path, p);
4723 #ifdef FF_VERBOSE
4724 if (p_verbose >= 5)
4726 verbose_enter_scroll();
4727 smsg((char_u *)"HIT: %s", file_path);
4728 /* don't overwrite this either */
4729 msg_puts((char_u *)"\n");
4730 verbose_leave_scroll();
4732 #endif
4733 return file_path;
4736 #ifdef FEAT_SEARCHPATH
4737 /* Not found or found already, try next suffix. */
4738 if (*suf == NUL)
4739 break;
4740 copy_option_part(&suf, file_path + len,
4741 MAXPATHL - len, ",");
4742 #endif
4746 #ifdef FEAT_PATH_EXTRA
4747 else
4750 * still wildcards left, push the directories for further
4751 * search
4753 for (i = stackp->ffs_filearray_cur;
4754 i < stackp->ffs_filearray_size; ++i)
4756 if (!mch_isdir(stackp->ffs_filearray[i]))
4757 continue; /* not a directory */
4759 ff_push(search_ctx,
4760 ff_create_stack_element(
4761 stackp->ffs_filearray[i],
4762 rest_of_wildcards,
4763 stackp->ffs_level - 1, 0));
4766 #endif
4767 stackp->ffs_filearray_cur = 0;
4768 stackp->ffs_stage = 1;
4771 #ifdef FEAT_PATH_EXTRA
4773 * if wildcards contains '**' we have to descent till we reach the
4774 * leaves of the directory tree.
4776 if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
4778 for (i = stackp->ffs_filearray_cur;
4779 i < stackp->ffs_filearray_size; ++i)
4781 if (fnamecmp(stackp->ffs_filearray[i],
4782 stackp->ffs_fix_path) == 0)
4783 continue; /* don't repush same directory */
4784 if (!mch_isdir(stackp->ffs_filearray[i]))
4785 continue; /* not a directory */
4786 ff_push(search_ctx,
4787 ff_create_stack_element(stackp->ffs_filearray[i],
4788 stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
4791 #endif
4793 /* we are done with the current directory */
4794 ff_free_stack_element(stackp);
4798 #ifdef FEAT_PATH_EXTRA
4799 /* If we reached this, we didn't find anything downwards.
4800 * Let's check if we should do an upward search.
4802 if (search_ctx->ffsc_start_dir
4803 && search_ctx->ffsc_stopdirs_v != NULL && !got_int)
4805 ff_stack_T *sptr;
4807 /* is the last starting directory in the stop list? */
4808 if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
4809 (int)(path_end - search_ctx->ffsc_start_dir),
4810 search_ctx->ffsc_stopdirs_v) == TRUE)
4811 break;
4813 /* cut of last dir */
4814 while (path_end > search_ctx->ffsc_start_dir
4815 && vim_ispathsep(*path_end))
4816 path_end--;
4817 while (path_end > search_ctx->ffsc_start_dir
4818 && !vim_ispathsep(path_end[-1]))
4819 path_end--;
4820 *path_end = 0;
4821 path_end--;
4823 if (*search_ctx->ffsc_start_dir == 0)
4824 break;
4826 STRCPY(file_path, search_ctx->ffsc_start_dir);
4827 add_pathsep(file_path);
4828 STRCAT(file_path, search_ctx->ffsc_fix_path);
4830 /* create a new stack entry */
4831 sptr = ff_create_stack_element(file_path,
4832 search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
4833 if (sptr == NULL)
4834 break;
4835 ff_push(search_ctx, sptr);
4837 else
4838 break;
4840 #endif
4842 vim_free(file_path);
4843 return NULL;
4847 * Free the list of lists of visited files and directories
4848 * Can handle it if the passed search_context is NULL;
4850 void
4851 vim_findfile_free_visited(search_ctx_arg)
4852 void *search_ctx_arg;
4854 ff_search_ctx_T *search_ctx;
4856 if (search_ctx_arg == NULL)
4857 return;
4859 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
4860 vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
4861 vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
4864 static void
4865 vim_findfile_free_visited_list(list_headp)
4866 ff_visited_list_hdr_T **list_headp;
4868 ff_visited_list_hdr_T *vp;
4870 while (*list_headp != NULL)
4872 vp = (*list_headp)->ffvl_next;
4873 ff_free_visited_list((*list_headp)->ffvl_visited_list);
4875 vim_free((*list_headp)->ffvl_filename);
4876 vim_free(*list_headp);
4877 *list_headp = vp;
4879 *list_headp = NULL;
4882 static void
4883 ff_free_visited_list(vl)
4884 ff_visited_T *vl;
4886 ff_visited_T *vp;
4888 while (vl != NULL)
4890 vp = vl->ffv_next;
4891 #ifdef FEAT_PATH_EXTRA
4892 vim_free(vl->ffv_wc_path);
4893 #endif
4894 vim_free(vl);
4895 vl = vp;
4897 vl = NULL;
4901 * Returns the already visited list for the given filename. If none is found it
4902 * allocates a new one.
4904 static ff_visited_list_hdr_T*
4905 ff_get_visited_list(filename, list_headp)
4906 char_u *filename;
4907 ff_visited_list_hdr_T **list_headp;
4909 ff_visited_list_hdr_T *retptr = NULL;
4911 /* check if a visited list for the given filename exists */
4912 if (*list_headp != NULL)
4914 retptr = *list_headp;
4915 while (retptr != NULL)
4917 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
4919 #ifdef FF_VERBOSE
4920 if (p_verbose >= 5)
4922 verbose_enter_scroll();
4923 smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
4924 filename);
4925 /* don't overwrite this either */
4926 msg_puts((char_u *)"\n");
4927 verbose_leave_scroll();
4929 #endif
4930 return retptr;
4932 retptr = retptr->ffvl_next;
4936 #ifdef FF_VERBOSE
4937 if (p_verbose >= 5)
4939 verbose_enter_scroll();
4940 smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
4941 /* don't overwrite this either */
4942 msg_puts((char_u *)"\n");
4943 verbose_leave_scroll();
4945 #endif
4948 * if we reach this we didn't find a list and we have to allocate new list
4950 retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
4951 if (retptr == NULL)
4952 return NULL;
4954 retptr->ffvl_visited_list = NULL;
4955 retptr->ffvl_filename = vim_strsave(filename);
4956 if (retptr->ffvl_filename == NULL)
4958 vim_free(retptr);
4959 return NULL;
4961 retptr->ffvl_next = *list_headp;
4962 *list_headp = retptr;
4964 return retptr;
4967 #ifdef FEAT_PATH_EXTRA
4969 * check if two wildcard paths are equal. Returns TRUE or FALSE.
4970 * They are equal if:
4971 * - both paths are NULL
4972 * - they have the same length
4973 * - char by char comparison is OK
4974 * - the only differences are in the counters behind a '**', so
4975 * '**\20' is equal to '**\24'
4977 static int
4978 ff_wc_equal(s1, s2)
4979 char_u *s1;
4980 char_u *s2;
4982 int i;
4984 if (s1 == s2)
4985 return TRUE;
4987 if (s1 == NULL || s2 == NULL)
4988 return FALSE;
4990 if (STRLEN(s1) != STRLEN(s2))
4991 return FAIL;
4993 for (i = 0; s1[i] != NUL && s2[i] != NUL; i++)
4995 if (s1[i] != s2[i]
4996 #ifdef CASE_INSENSITIVE_FILENAME
4997 && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i])
4998 #endif
5001 if (i >= 2)
5002 if (s1[i-1] == '*' && s1[i-2] == '*')
5003 continue;
5004 else
5005 return FAIL;
5006 else
5007 return FAIL;
5010 return TRUE;
5012 #endif
5015 * maintains the list of already visited files and dirs
5016 * returns FAIL if the given file/dir is already in the list
5017 * returns OK if it is newly added
5019 * TODO: What to do on memory allocation problems?
5020 * -> return TRUE - Better the file is found several times instead of
5021 * never.
5023 static int
5024 ff_check_visited(visited_list, fname
5025 #ifdef FEAT_PATH_EXTRA
5026 , wc_path
5027 #endif
5029 ff_visited_T **visited_list;
5030 char_u *fname;
5031 #ifdef FEAT_PATH_EXTRA
5032 char_u *wc_path;
5033 #endif
5035 ff_visited_T *vp;
5036 #ifdef UNIX
5037 struct stat st;
5038 int url = FALSE;
5039 #endif
5041 /* For an URL we only compare the name, otherwise we compare the
5042 * device/inode (unix) or the full path name (not Unix). */
5043 if (path_with_url(fname))
5045 vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
5046 #ifdef UNIX
5047 url = TRUE;
5048 #endif
5050 else
5052 ff_expand_buffer[0] = NUL;
5053 #ifdef UNIX
5054 if (mch_stat((char *)fname, &st) < 0)
5055 #else
5056 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
5057 #endif
5058 return FAIL;
5061 /* check against list of already visited files */
5062 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
5064 if (
5065 #ifdef UNIX
5066 !url
5067 ? (vp->ffv_dev == st.st_dev
5068 && vp->ffv_ino == st.st_ino)
5070 #endif
5071 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
5074 #ifdef FEAT_PATH_EXTRA
5075 /* are the wildcard parts equal */
5076 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
5077 #endif
5078 /* already visited */
5079 return FAIL;
5084 * New file/dir. Add it to the list of visited files/dirs.
5086 vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
5087 + STRLEN(ff_expand_buffer)));
5089 if (vp != NULL)
5091 #ifdef UNIX
5092 if (!url)
5094 vp->ffv_ino = st.st_ino;
5095 vp->ffv_dev = st.st_dev;
5096 vp->ffv_fname[0] = NUL;
5098 else
5100 vp->ffv_ino = 0;
5101 vp->ffv_dev = -1;
5102 #endif
5103 STRCPY(vp->ffv_fname, ff_expand_buffer);
5104 #ifdef UNIX
5106 #endif
5107 #ifdef FEAT_PATH_EXTRA
5108 if (wc_path != NULL)
5109 vp->ffv_wc_path = vim_strsave(wc_path);
5110 else
5111 vp->ffv_wc_path = NULL;
5112 #endif
5114 vp->ffv_next = *visited_list;
5115 *visited_list = vp;
5118 return OK;
5122 * create stack element from given path pieces
5124 static ff_stack_T *
5125 ff_create_stack_element(fix_part,
5126 #ifdef FEAT_PATH_EXTRA
5127 wc_part,
5128 #endif
5129 level, star_star_empty)
5130 char_u *fix_part;
5131 #ifdef FEAT_PATH_EXTRA
5132 char_u *wc_part;
5133 #endif
5134 int level;
5135 int star_star_empty;
5137 ff_stack_T *new;
5139 new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
5140 if (new == NULL)
5141 return NULL;
5143 new->ffs_prev = NULL;
5144 new->ffs_filearray = NULL;
5145 new->ffs_filearray_size = 0;
5146 new->ffs_filearray_cur = 0;
5147 new->ffs_stage = 0;
5148 new->ffs_level = level;
5149 new->ffs_star_star_empty = star_star_empty;;
5151 /* the following saves NULL pointer checks in vim_findfile */
5152 if (fix_part == NULL)
5153 fix_part = (char_u *)"";
5154 new->ffs_fix_path = vim_strsave(fix_part);
5156 #ifdef FEAT_PATH_EXTRA
5157 if (wc_part == NULL)
5158 wc_part = (char_u *)"";
5159 new->ffs_wc_path = vim_strsave(wc_part);
5160 #endif
5162 if (new->ffs_fix_path == NULL
5163 #ifdef FEAT_PATH_EXTRA
5164 || new->ffs_wc_path == NULL
5165 #endif
5168 ff_free_stack_element(new);
5169 new = NULL;
5172 return new;
5176 * Push a dir on the directory stack.
5178 static void
5179 ff_push(search_ctx, stack_ptr)
5180 ff_search_ctx_T *search_ctx;
5181 ff_stack_T *stack_ptr;
5183 /* check for NULL pointer, not to return an error to the user, but
5184 * to prevent a crash */
5185 if (stack_ptr != NULL)
5187 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
5188 search_ctx->ffsc_stack_ptr = stack_ptr;
5193 * Pop a dir from the directory stack.
5194 * Returns NULL if stack is empty.
5196 static ff_stack_T *
5197 ff_pop(search_ctx)
5198 ff_search_ctx_T *search_ctx;
5200 ff_stack_T *sptr;
5202 sptr = search_ctx->ffsc_stack_ptr;
5203 if (search_ctx->ffsc_stack_ptr != NULL)
5204 search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
5206 return sptr;
5210 * free the given stack element
5212 static void
5213 ff_free_stack_element(stack_ptr)
5214 ff_stack_T *stack_ptr;
5216 /* vim_free handles possible NULL pointers */
5217 vim_free(stack_ptr->ffs_fix_path);
5218 #ifdef FEAT_PATH_EXTRA
5219 vim_free(stack_ptr->ffs_wc_path);
5220 #endif
5222 if (stack_ptr->ffs_filearray != NULL)
5223 FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
5225 vim_free(stack_ptr);
5229 * Clear the search context, but NOT the visited list.
5231 static void
5232 ff_clear(search_ctx)
5233 ff_search_ctx_T *search_ctx;
5235 ff_stack_T *sptr;
5237 /* clear up stack */
5238 while ((sptr = ff_pop(search_ctx)) != NULL)
5239 ff_free_stack_element(sptr);
5241 vim_free(search_ctx->ffsc_file_to_search);
5242 vim_free(search_ctx->ffsc_start_dir);
5243 vim_free(search_ctx->ffsc_fix_path);
5244 #ifdef FEAT_PATH_EXTRA
5245 vim_free(search_ctx->ffsc_wc_path);
5246 #endif
5248 #ifdef FEAT_PATH_EXTRA
5249 if (search_ctx->ffsc_stopdirs_v != NULL)
5251 int i = 0;
5253 while (search_ctx->ffsc_stopdirs_v[i] != NULL)
5255 vim_free(search_ctx->ffsc_stopdirs_v[i]);
5256 i++;
5258 vim_free(search_ctx->ffsc_stopdirs_v);
5260 search_ctx->ffsc_stopdirs_v = NULL;
5261 #endif
5263 /* reset everything */
5264 search_ctx->ffsc_file_to_search = NULL;
5265 search_ctx->ffsc_start_dir = NULL;
5266 search_ctx->ffsc_fix_path = NULL;
5267 #ifdef FEAT_PATH_EXTRA
5268 search_ctx->ffsc_wc_path = NULL;
5269 search_ctx->ffsc_level = 0;
5270 #endif
5273 #ifdef FEAT_PATH_EXTRA
5275 * check if the given path is in the stopdirs
5276 * returns TRUE if yes else FALSE
5278 static int
5279 ff_path_in_stoplist(path, path_len, stopdirs_v)
5280 char_u *path;
5281 int path_len;
5282 char_u **stopdirs_v;
5284 int i = 0;
5286 /* eat up trailing path separators, except the first */
5287 while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
5288 path_len--;
5290 /* if no path consider it as match */
5291 if (path_len == 0)
5292 return TRUE;
5294 for (i = 0; stopdirs_v[i] != NULL; i++)
5296 if ((int)STRLEN(stopdirs_v[i]) > path_len)
5298 /* match for parent directory. So '/home' also matches
5299 * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
5300 * '/home/r' would also match '/home/rks'
5302 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
5303 && vim_ispathsep(stopdirs_v[i][path_len]))
5304 return TRUE;
5306 else
5308 if (fnamecmp(stopdirs_v[i], path) == 0)
5309 return TRUE;
5312 return FALSE;
5314 #endif
5316 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
5318 * Find the file name "ptr[len]" in the path. Also finds directory names.
5320 * On the first call set the parameter 'first' to TRUE to initialize
5321 * the search. For repeating calls to FALSE.
5323 * Repeating calls will return other files called 'ptr[len]' from the path.
5325 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
5326 * don't need valid values.
5328 * If nothing found on the first call the option FNAME_MESS will issue the
5329 * message:
5330 * 'Can't find file "<file>" in path'
5331 * On repeating calls:
5332 * 'No more file "<file>" found in path'
5334 * options:
5335 * FNAME_MESS give error message when not found
5337 * Uses NameBuff[]!
5339 * Returns an allocated string for the file name. NULL for error.
5342 char_u *
5343 find_file_in_path(ptr, len, options, first, rel_fname)
5344 char_u *ptr; /* file name */
5345 int len; /* length of file name */
5346 int options;
5347 int first; /* use count'th matching file name */
5348 char_u *rel_fname; /* file name searching relative to */
5350 return find_file_in_path_option(ptr, len, options, first,
5351 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
5352 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
5355 static char_u *ff_file_to_find = NULL;
5356 static void *fdip_search_ctx = NULL;
5358 #if defined(EXITFREE)
5359 static void
5360 free_findfile()
5362 vim_free(ff_file_to_find);
5363 vim_findfile_cleanup(fdip_search_ctx);
5365 #endif
5368 * Find the directory name "ptr[len]" in the path.
5370 * options:
5371 * FNAME_MESS give error message when not found
5373 * Uses NameBuff[]!
5375 * Returns an allocated string for the file name. NULL for error.
5377 char_u *
5378 find_directory_in_path(ptr, len, options, rel_fname)
5379 char_u *ptr; /* file name */
5380 int len; /* length of file name */
5381 int options;
5382 char_u *rel_fname; /* file name searching relative to */
5384 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
5385 FINDFILE_DIR, rel_fname, (char_u *)"");
5388 char_u *
5389 find_file_in_path_option(ptr, len, options, first, path_option, find_what, rel_fname, suffixes)
5390 char_u *ptr; /* file name */
5391 int len; /* length of file name */
5392 int options;
5393 int first; /* use count'th matching file name */
5394 char_u *path_option; /* p_path or p_cdpath */
5395 int find_what; /* FINDFILE_FILE, _DIR or _BOTH */
5396 char_u *rel_fname; /* file name we are looking relative to. */
5397 char_u *suffixes; /* list of suffixes, 'suffixesadd' option */
5399 static char_u *dir;
5400 static int did_findfile_init = FALSE;
5401 char_u save_char;
5402 char_u *file_name = NULL;
5403 char_u *buf = NULL;
5404 int rel_to_curdir;
5405 #ifdef AMIGA
5406 struct Process *proc = (struct Process *)FindTask(0L);
5407 APTR save_winptr = proc->pr_WindowPtr;
5409 /* Avoid a requester here for a volume that doesn't exist. */
5410 proc->pr_WindowPtr = (APTR)-1L;
5411 #endif
5413 if (first == TRUE)
5415 /* copy file name into NameBuff, expanding environment variables */
5416 save_char = ptr[len];
5417 ptr[len] = NUL;
5418 expand_env(ptr, NameBuff, MAXPATHL);
5419 ptr[len] = save_char;
5421 vim_free(ff_file_to_find);
5422 ff_file_to_find = vim_strsave(NameBuff);
5423 if (ff_file_to_find == NULL) /* out of memory */
5425 file_name = NULL;
5426 goto theend;
5430 rel_to_curdir = (ff_file_to_find[0] == '.'
5431 && (ff_file_to_find[1] == NUL
5432 || vim_ispathsep(ff_file_to_find[1])
5433 || (ff_file_to_find[1] == '.'
5434 && (ff_file_to_find[2] == NUL
5435 || vim_ispathsep(ff_file_to_find[2])))));
5436 if (vim_isAbsName(ff_file_to_find)
5437 /* "..", "../path", "." and "./path": don't use the path_option */
5438 || rel_to_curdir
5439 #if defined(MSWIN) || defined(MSDOS) || defined(OS2)
5440 /* handle "\tmp" as absolute path */
5441 || vim_ispathsep(ff_file_to_find[0])
5442 /* handle "c:name" as absulute path */
5443 || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
5444 #endif
5445 #ifdef AMIGA
5446 /* handle ":tmp" as absolute path */
5447 || ff_file_to_find[0] == ':'
5448 #endif
5452 * Absolute path, no need to use "path_option".
5453 * If this is not a first call, return NULL. We already returned a
5454 * filename on the first call.
5456 if (first == TRUE)
5458 int l;
5459 int run;
5461 if (path_with_url(ff_file_to_find))
5463 file_name = vim_strsave(ff_file_to_find);
5464 goto theend;
5467 /* When FNAME_REL flag given first use the directory of the file.
5468 * Otherwise or when this fails use the current directory. */
5469 for (run = 1; run <= 2; ++run)
5471 l = (int)STRLEN(ff_file_to_find);
5472 if (run == 1
5473 && rel_to_curdir
5474 && (options & FNAME_REL)
5475 && rel_fname != NULL
5476 && STRLEN(rel_fname) + l < MAXPATHL)
5478 STRCPY(NameBuff, rel_fname);
5479 STRCPY(gettail(NameBuff), ff_file_to_find);
5480 l = (int)STRLEN(NameBuff);
5482 else
5484 STRCPY(NameBuff, ff_file_to_find);
5485 run = 2;
5488 /* When the file doesn't exist, try adding parts of
5489 * 'suffixesadd'. */
5490 buf = suffixes;
5491 for (;;)
5493 if (
5494 #ifdef DJGPP
5495 /* "C:" by itself will fail for mch_getperm(),
5496 * assume it's always valid. */
5497 (find_what != FINDFILE_FILE && NameBuff[0] != NUL
5498 && NameBuff[1] == ':'
5499 && NameBuff[2] == NUL) ||
5500 #endif
5501 (mch_getperm(NameBuff) >= 0
5502 && (find_what == FINDFILE_BOTH
5503 || ((find_what == FINDFILE_DIR)
5504 == mch_isdir(NameBuff)))))
5506 file_name = vim_strsave(NameBuff);
5507 goto theend;
5509 if (*buf == NUL)
5510 break;
5511 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5516 else
5519 * Loop over all paths in the 'path' or 'cdpath' option.
5520 * When "first" is set, first setup to the start of the option.
5521 * Otherwise continue to find the next match.
5523 if (first == TRUE)
5525 /* vim_findfile_free_visited can handle a possible NULL pointer */
5526 vim_findfile_free_visited(fdip_search_ctx);
5527 dir = path_option;
5528 did_findfile_init = FALSE;
5531 for (;;)
5533 if (did_findfile_init)
5535 file_name = vim_findfile(fdip_search_ctx);
5536 if (file_name != NULL)
5537 break;
5539 did_findfile_init = FALSE;
5541 else
5543 char_u *r_ptr;
5545 if (dir == NULL || *dir == NUL)
5547 /* We searched all paths of the option, now we can
5548 * free the search context. */
5549 vim_findfile_cleanup(fdip_search_ctx);
5550 fdip_search_ctx = NULL;
5551 break;
5554 if ((buf = alloc((int)(MAXPATHL))) == NULL)
5555 break;
5557 /* copy next path */
5558 buf[0] = 0;
5559 copy_option_part(&dir, buf, MAXPATHL, " ,");
5561 #ifdef FEAT_PATH_EXTRA
5562 /* get the stopdir string */
5563 r_ptr = vim_findfile_stopdir(buf);
5564 #else
5565 r_ptr = NULL;
5566 #endif
5567 fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
5568 r_ptr, 100, FALSE, find_what,
5569 fdip_search_ctx, FALSE, rel_fname);
5570 if (fdip_search_ctx != NULL)
5571 did_findfile_init = TRUE;
5572 vim_free(buf);
5576 if (file_name == NULL && (options & FNAME_MESS))
5578 if (first == TRUE)
5580 if (find_what == FINDFILE_DIR)
5581 EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
5582 ff_file_to_find);
5583 else
5584 EMSG2(_("E345: Can't find file \"%s\" in path"),
5585 ff_file_to_find);
5587 else
5589 if (find_what == FINDFILE_DIR)
5590 EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
5591 ff_file_to_find);
5592 else
5593 EMSG2(_("E347: No more file \"%s\" found in path"),
5594 ff_file_to_find);
5598 theend:
5599 #ifdef AMIGA
5600 proc->pr_WindowPtr = save_winptr;
5601 #endif
5602 return file_name;
5605 #endif /* FEAT_SEARCHPATH */
5608 * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search
5609 * 'cdpath' for relative directory names, otherwise just mch_chdir().
5612 vim_chdir(new_dir)
5613 char_u *new_dir;
5615 #ifndef FEAT_SEARCHPATH
5616 return mch_chdir((char *)new_dir);
5617 #else
5618 char_u *dir_name;
5619 int r;
5621 dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
5622 FNAME_MESS, curbuf->b_ffname);
5623 if (dir_name == NULL)
5624 return -1;
5625 r = mch_chdir((char *)dir_name);
5626 vim_free(dir_name);
5627 return r;
5628 #endif
5632 * Get user name from machine-specific function.
5633 * Returns the user name in "buf[len]".
5634 * Some systems are quite slow in obtaining the user name (Windows NT), thus
5635 * cache the result.
5636 * Returns OK or FAIL.
5639 get_user_name(buf, len)
5640 char_u *buf;
5641 int len;
5643 if (username == NULL)
5645 if (mch_get_user_name(buf, len) == FAIL)
5646 return FAIL;
5647 username = vim_strsave(buf);
5649 else
5650 vim_strncpy(buf, username, len - 1);
5651 return OK;
5654 #ifndef HAVE_QSORT
5656 * Our own qsort(), for systems that don't have it.
5657 * It's simple and slow. From the K&R C book.
5659 void
5660 qsort(base, elm_count, elm_size, cmp)
5661 void *base;
5662 size_t elm_count;
5663 size_t elm_size;
5664 int (*cmp) __ARGS((const void *, const void *));
5666 char_u *buf;
5667 char_u *p1;
5668 char_u *p2;
5669 int i, j;
5670 int gap;
5672 buf = alloc((unsigned)elm_size);
5673 if (buf == NULL)
5674 return;
5676 for (gap = elm_count / 2; gap > 0; gap /= 2)
5677 for (i = gap; i < elm_count; ++i)
5678 for (j = i - gap; j >= 0; j -= gap)
5680 /* Compare the elements. */
5681 p1 = (char_u *)base + j * elm_size;
5682 p2 = (char_u *)base + (j + gap) * elm_size;
5683 if ((*cmp)((void *)p1, (void *)p2) <= 0)
5684 break;
5685 /* Exchange the elemets. */
5686 mch_memmove(buf, p1, elm_size);
5687 mch_memmove(p1, p2, elm_size);
5688 mch_memmove(p2, buf, elm_size);
5691 vim_free(buf);
5693 #endif
5696 * Sort an array of strings.
5698 static int
5699 #ifdef __BORLANDC__
5700 _RTLENTRYF
5701 #endif
5702 sort_compare __ARGS((const void *s1, const void *s2));
5704 static int
5705 #ifdef __BORLANDC__
5706 _RTLENTRYF
5707 #endif
5708 sort_compare(s1, s2)
5709 const void *s1;
5710 const void *s2;
5712 return STRCMP(*(char **)s1, *(char **)s2);
5715 void
5716 sort_strings(files, count)
5717 char_u **files;
5718 int count;
5720 qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
5723 #if !defined(NO_EXPANDPATH) || defined(PROTO)
5725 * Compare path "p[]" to "q[]".
5726 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
5727 * Return value like strcmp(p, q), but consider path separators.
5730 pathcmp(p, q, maxlen)
5731 const char *p, *q;
5732 int maxlen;
5734 int i;
5735 const char *s = NULL;
5737 for (i = 0; maxlen < 0 || i < maxlen; ++i)
5739 /* End of "p": check if "q" also ends or just has a slash. */
5740 if (p[i] == NUL)
5742 if (q[i] == NUL) /* full match */
5743 return 0;
5744 s = q;
5745 break;
5748 /* End of "q": check if "p" just has a slash. */
5749 if (q[i] == NUL)
5751 s = p;
5752 break;
5755 if (
5756 #ifdef CASE_INSENSITIVE_FILENAME
5757 TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i])
5758 #else
5759 p[i] != q[i]
5760 #endif
5761 #ifdef BACKSLASH_IN_FILENAME
5762 /* consider '/' and '\\' to be equal */
5763 && !((p[i] == '/' && q[i] == '\\')
5764 || (p[i] == '\\' && q[i] == '/'))
5765 #endif
5768 if (vim_ispathsep(p[i]))
5769 return -1;
5770 if (vim_ispathsep(q[i]))
5771 return 1;
5772 return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */
5775 if (s == NULL) /* "i" ran into "maxlen" */
5776 return 0;
5778 /* ignore a trailing slash, but not "//" or ":/" */
5779 if (s[i + 1] == NUL
5780 && i > 0
5781 && !after_pathsep((char_u *)s, (char_u *)s + i)
5782 #ifdef BACKSLASH_IN_FILENAME
5783 && (s[i] == '/' || s[i] == '\\')
5784 #else
5785 && s[i] == '/'
5786 #endif
5788 return 0; /* match with trailing slash */
5789 if (s == q)
5790 return -1; /* no match */
5791 return 1;
5793 #endif
5796 * The putenv() implementation below comes from the "screen" program.
5797 * Included with permission from Juergen Weigert.
5798 * See pty.c for the copyright notice.
5802 * putenv -- put value into environment
5804 * Usage: i = putenv (string)
5805 * int i;
5806 * char *string;
5808 * where string is of the form <name>=<value>.
5809 * Putenv returns 0 normally, -1 on error (not enough core for malloc).
5811 * Putenv may need to add a new name into the environment, or to
5812 * associate a value longer than the current value with a particular
5813 * name. So, to make life simpler, putenv() copies your entire
5814 * environment into the heap (i.e. malloc()) from the stack
5815 * (i.e. where it resides when your process is initiated) the first
5816 * time you call it.
5818 * (history removed, not very interesting. See the "screen" sources.)
5821 #if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
5823 #define EXTRASIZE 5 /* increment to add to env. size */
5825 static int envsize = -1; /* current size of environment */
5826 #ifndef MACOS_CLASSIC
5827 extern
5828 #endif
5829 char **environ; /* the global which is your env. */
5831 static int findenv __ARGS((char *name)); /* look for a name in the env. */
5832 static int newenv __ARGS((void)); /* copy env. from stack to heap */
5833 static int moreenv __ARGS((void)); /* incr. size of env. */
5836 putenv(string)
5837 const char *string;
5839 int i;
5840 char *p;
5842 if (envsize < 0)
5843 { /* first time putenv called */
5844 if (newenv() < 0) /* copy env. to heap */
5845 return -1;
5848 i = findenv((char *)string); /* look for name in environment */
5850 if (i < 0)
5851 { /* name must be added */
5852 for (i = 0; environ[i]; i++);
5853 if (i >= (envsize - 1))
5854 { /* need new slot */
5855 if (moreenv() < 0)
5856 return -1;
5858 p = (char *)alloc((unsigned)(strlen(string) + 1));
5859 if (p == NULL) /* not enough core */
5860 return -1;
5861 environ[i + 1] = 0; /* new end of env. */
5863 else
5864 { /* name already in env. */
5865 p = vim_realloc(environ[i], strlen(string) + 1);
5866 if (p == NULL)
5867 return -1;
5869 sprintf(p, "%s", string); /* copy into env. */
5870 environ[i] = p;
5872 return 0;
5875 static int
5876 findenv(name)
5877 char *name;
5879 char *namechar, *envchar;
5880 int i, found;
5882 found = 0;
5883 for (i = 0; environ[i] && !found; i++)
5885 envchar = environ[i];
5886 namechar = name;
5887 while (*namechar && *namechar != '=' && (*namechar == *envchar))
5889 namechar++;
5890 envchar++;
5892 found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
5894 return found ? i - 1 : -1;
5897 static int
5898 newenv()
5900 char **env, *elem;
5901 int i, esize;
5903 #ifdef MACOS
5904 /* for Mac a new, empty environment is created */
5905 i = 0;
5906 #else
5907 for (i = 0; environ[i]; i++)
5909 #endif
5910 esize = i + EXTRASIZE + 1;
5911 env = (char **)alloc((unsigned)(esize * sizeof (elem)));
5912 if (env == NULL)
5913 return -1;
5915 #ifndef MACOS
5916 for (i = 0; environ[i]; i++)
5918 elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
5919 if (elem == NULL)
5920 return -1;
5921 env[i] = elem;
5922 strcpy(elem, environ[i]);
5924 #endif
5926 env[i] = 0;
5927 environ = env;
5928 envsize = esize;
5929 return 0;
5932 static int
5933 moreenv()
5935 int esize;
5936 char **env;
5938 esize = envsize + EXTRASIZE;
5939 env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
5940 if (env == 0)
5941 return -1;
5942 environ = env;
5943 envsize = esize;
5944 return 0;
5947 # ifdef USE_VIMPTY_GETENV
5948 char_u *
5949 vimpty_getenv(string)
5950 const char_u *string;
5952 int i;
5953 char_u *p;
5955 if (envsize < 0)
5956 return NULL;
5958 i = findenv((char *)string);
5960 if (i < 0)
5961 return NULL;
5963 p = vim_strchr((char_u *)environ[i], '=');
5964 return (p + 1);
5966 # endif
5968 #endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
5970 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
5972 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
5973 * rights to write into.
5976 filewritable(fname)
5977 char_u *fname;
5979 int retval = 0;
5980 #if defined(UNIX) || defined(VMS)
5981 int perm = 0;
5982 #endif
5984 #if defined(UNIX) || defined(VMS)
5985 perm = mch_getperm(fname);
5986 #endif
5987 #ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */
5988 if (
5989 # ifdef WIN3264
5990 mch_writable(fname) &&
5991 # else
5992 # if defined(UNIX) || defined(VMS)
5993 (perm & 0222) &&
5994 # endif
5995 # endif
5996 mch_access((char *)fname, W_OK) == 0
5998 #endif
6000 ++retval;
6001 if (mch_isdir(fname))
6002 ++retval;
6004 return retval;
6006 #endif
6009 * Print an error message with one or two "%s" and one or two string arguments.
6010 * This is not in message.c to avoid a warning for prototypes.
6013 emsg3(s, a1, a2)
6014 char_u *s, *a1, *a2;
6016 if (emsg_not_now())
6017 return TRUE; /* no error messages at the moment */
6018 #ifdef HAVE_STDARG_H
6019 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, a1, a2);
6020 #else
6021 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, (long_u)a1, (long_u)a2);
6022 #endif
6023 return emsg(IObuff);
6027 * Print an error message with one "%ld" and one long int argument.
6028 * This is not in message.c to avoid a warning for prototypes.
6031 emsgn(s, n)
6032 char_u *s;
6033 long n;
6035 if (emsg_not_now())
6036 return TRUE; /* no error messages at the moment */
6037 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, n);
6038 return emsg(IObuff);