Use bundle path for main connection name
[MacVim.git] / src / misc2.c
blobbc9091f089df73878dbc487a6f60d5dba283ef2f
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 + curwin->w_cursor.coladd;
500 #endif
502 len = (colnr_T)STRLEN(ml_get_curline());
503 if (len == 0)
504 curwin->w_cursor.col = 0;
505 else if (curwin->w_cursor.col >= len)
507 /* Allow cursor past end-of-line when:
508 * - in Insert mode or restarting Insert mode
509 * - in Visual mode and 'selection' isn't "old"
510 * - 'virtualedit' is set */
511 if ((State & INSERT) || restart_edit
512 #ifdef FEAT_VISUAL
513 || (VIsual_active && *p_sel != 'o')
514 #endif
515 #ifdef FEAT_VIRTUALEDIT
516 || (ve_flags & VE_ONEMORE)
517 #endif
518 || virtual_active())
519 curwin->w_cursor.col = len;
520 else
522 curwin->w_cursor.col = len - 1;
523 #ifdef FEAT_MBYTE
524 /* prevent cursor from moving on the trail byte */
525 if (has_mbyte)
526 mb_adjust_cursor();
527 #endif
531 #ifdef FEAT_VIRTUALEDIT
532 /* If virtual editing is on, we can leave the cursor on the old position,
533 * only we must set it to virtual. But don't do it when at the end of the
534 * line. */
535 if (oldcol == MAXCOL)
536 curwin->w_cursor.coladd = 0;
537 else if (ve_flags == VE_ALL)
538 curwin->w_cursor.coladd = oldcol - curwin->w_cursor.col;
539 #endif
543 * make sure curwin->w_cursor in on a valid character
545 void
546 check_cursor()
548 check_cursor_lnum();
549 check_cursor_col();
552 #if defined(FEAT_TEXTOBJ) || defined(PROTO)
554 * Make sure curwin->w_cursor is not on the NUL at the end of the line.
555 * Allow it when in Visual mode and 'selection' is not "old".
557 void
558 adjust_cursor_col()
560 if (curwin->w_cursor.col > 0
561 # ifdef FEAT_VISUAL
562 && (!VIsual_active || *p_sel == 'o')
563 # endif
564 && gchar_cursor() == NUL)
565 --curwin->w_cursor.col;
567 #endif
570 * When curwin->w_leftcol has changed, adjust the cursor position.
571 * Return TRUE if the cursor was moved.
574 leftcol_changed()
576 long lastcol;
577 colnr_T s, e;
578 int retval = FALSE;
580 changed_cline_bef_curs();
581 lastcol = curwin->w_leftcol + W_WIDTH(curwin) - curwin_col_off() - 1;
582 validate_virtcol();
585 * If the cursor is right or left of the screen, move it to last or first
586 * character.
588 if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso))
590 retval = TRUE;
591 coladvance((colnr_T)(lastcol - p_siso));
593 else if (curwin->w_virtcol < curwin->w_leftcol + p_siso)
595 retval = TRUE;
596 (void)coladvance((colnr_T)(curwin->w_leftcol + p_siso));
600 * If the start of the character under the cursor is not on the screen,
601 * advance the cursor one more char. If this fails (last char of the
602 * line) adjust the scrolling.
604 getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
605 if (e > (colnr_T)lastcol)
607 retval = TRUE;
608 coladvance(s - 1);
610 else if (s < curwin->w_leftcol)
612 retval = TRUE;
613 if (coladvance(e + 1) == FAIL) /* there isn't another character */
615 curwin->w_leftcol = s; /* adjust w_leftcol instead */
616 changed_cline_bef_curs();
620 if (retval)
621 curwin->w_set_curswant = TRUE;
622 redraw_later(NOT_VALID);
623 return retval;
626 /**********************************************************************
627 * Various routines dealing with allocation and deallocation of memory.
630 #if defined(MEM_PROFILE) || defined(PROTO)
632 # define MEM_SIZES 8200
633 static long_u mem_allocs[MEM_SIZES];
634 static long_u mem_frees[MEM_SIZES];
635 static long_u mem_allocated;
636 static long_u mem_freed;
637 static long_u mem_peak;
638 static long_u num_alloc;
639 static long_u num_freed;
641 static void mem_pre_alloc_s __ARGS((size_t *sizep));
642 static void mem_pre_alloc_l __ARGS((long_u *sizep));
643 static void mem_post_alloc __ARGS((void **pp, size_t size));
644 static void mem_pre_free __ARGS((void **pp));
646 static void
647 mem_pre_alloc_s(sizep)
648 size_t *sizep;
650 *sizep += sizeof(size_t);
653 static void
654 mem_pre_alloc_l(sizep)
655 long_u *sizep;
657 *sizep += sizeof(size_t);
660 static void
661 mem_post_alloc(pp, size)
662 void **pp;
663 size_t size;
665 if (*pp == NULL)
666 return;
667 size -= sizeof(size_t);
668 *(long_u *)*pp = size;
669 if (size <= MEM_SIZES-1)
670 mem_allocs[size-1]++;
671 else
672 mem_allocs[MEM_SIZES-1]++;
673 mem_allocated += size;
674 if (mem_allocated - mem_freed > mem_peak)
675 mem_peak = mem_allocated - mem_freed;
676 num_alloc++;
677 *pp = (void *)((char *)*pp + sizeof(size_t));
680 static void
681 mem_pre_free(pp)
682 void **pp;
684 long_u size;
686 *pp = (void *)((char *)*pp - sizeof(size_t));
687 size = *(size_t *)*pp;
688 if (size <= MEM_SIZES-1)
689 mem_frees[size-1]++;
690 else
691 mem_frees[MEM_SIZES-1]++;
692 mem_freed += size;
693 num_freed++;
697 * called on exit via atexit()
699 void
700 vim_mem_profile_dump()
702 int i, j;
704 printf("\r\n");
705 j = 0;
706 for (i = 0; i < MEM_SIZES - 1; i++)
708 if (mem_allocs[i] || mem_frees[i])
710 if (mem_frees[i] > mem_allocs[i])
711 printf("\r\n%s", _("ERROR: "));
712 printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
713 j++;
714 if (j > 3)
716 j = 0;
717 printf("\r\n");
722 i = MEM_SIZES - 1;
723 if (mem_allocs[i])
725 printf("\r\n");
726 if (mem_frees[i] > mem_allocs[i])
727 printf(_("ERROR: "));
728 printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
731 printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
732 mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
733 printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
734 num_alloc, num_freed);
737 #endif /* MEM_PROFILE */
740 * Some memory is reserved for error messages and for being able to
741 * call mf_release_all(), which needs some memory for mf_trans_add().
743 #if defined(MSDOS) && !defined(DJGPP)
744 # define SMALL_MEM
745 # define KEEP_ROOM 8192L
746 #else
747 # define KEEP_ROOM (2 * 8192L)
748 #endif
751 * Note: if unsigned is 16 bits we can only allocate up to 64K with alloc().
752 * Use lalloc for larger blocks.
754 char_u *
755 alloc(size)
756 unsigned size;
758 return (lalloc((long_u)size, TRUE));
762 * Allocate memory and set all bytes to zero.
764 char_u *
765 alloc_clear(size)
766 unsigned size;
768 char_u *p;
770 p = (lalloc((long_u)size, TRUE));
771 if (p != NULL)
772 (void)vim_memset(p, 0, (size_t)size);
773 return p;
777 * alloc() with check for maximum line length
779 char_u *
780 alloc_check(size)
781 unsigned size;
783 #if !defined(UNIX) && !defined(__EMX__)
784 if (sizeof(int) == 2 && size > 0x7fff)
786 /* Don't hide this message */
787 emsg_silent = 0;
788 EMSG(_("E340: Line is becoming too long"));
789 return NULL;
791 #endif
792 return (lalloc((long_u)size, TRUE));
796 * Allocate memory like lalloc() and set all bytes to zero.
798 char_u *
799 lalloc_clear(size, message)
800 long_u size;
801 int message;
803 char_u *p;
805 p = (lalloc(size, message));
806 if (p != NULL)
807 (void)vim_memset(p, 0, (size_t)size);
808 return p;
812 * Low level memory allocation function.
813 * This is used often, KEEP IT FAST!
815 char_u *
816 lalloc(size, message)
817 long_u size;
818 int message;
820 char_u *p; /* pointer to new storage space */
821 static int releasing = FALSE; /* don't do mf_release_all() recursive */
822 int try_again;
823 #if defined(HAVE_AVAIL_MEM) && !defined(SMALL_MEM)
824 static long_u allocated = 0; /* allocated since last avail check */
825 #endif
827 /* Safety check for allocating zero bytes */
828 if (size == 0)
830 /* Don't hide this message */
831 emsg_silent = 0;
832 EMSGN(_("E341: Internal error: lalloc(%ld, )"), size);
833 return NULL;
836 #ifdef MEM_PROFILE
837 mem_pre_alloc_l(&size);
838 #endif
840 #if defined(MSDOS) && !defined(DJGPP)
841 if (size >= 0xfff0) /* in MSDOS we can't deal with >64K blocks */
842 p = NULL;
843 else
844 #endif
847 * Loop when out of memory: Try to release some memfile blocks and
848 * if some blocks are released call malloc again.
850 for (;;)
853 * Handle three kind of systems:
854 * 1. No check for available memory: Just return.
855 * 2. Slow check for available memory: call mch_avail_mem() after
856 * allocating KEEP_ROOM amount of memory.
857 * 3. Strict check for available memory: call mch_avail_mem()
859 if ((p = (char_u *)malloc((size_t)size)) != NULL)
861 #ifndef HAVE_AVAIL_MEM
862 /* 1. No check for available memory: Just return. */
863 goto theend;
864 #else
865 # ifndef SMALL_MEM
866 /* 2. Slow check for available memory: call mch_avail_mem() after
867 * allocating (KEEP_ROOM / 2) amount of memory. */
868 allocated += size;
869 if (allocated < KEEP_ROOM / 2)
870 goto theend;
871 allocated = 0;
872 # endif
873 /* 3. check for available memory: call mch_avail_mem() */
874 if (mch_avail_mem(TRUE) < KEEP_ROOM && !releasing)
876 vim_free((char *)p); /* System is low... no go! */
877 p = NULL;
879 else
880 goto theend;
881 #endif
884 * Remember that mf_release_all() is being called to avoid an endless
885 * loop, because mf_release_all() may call alloc() recursively.
887 if (releasing)
888 break;
889 releasing = TRUE;
891 clear_sb_text(); /* free any scrollback text */
892 try_again = mf_release_all(); /* release as many blocks as possible */
893 #ifdef FEAT_EVAL
894 try_again |= garbage_collect(); /* cleanup recursive lists/dicts */
895 #endif
897 releasing = FALSE;
898 if (!try_again)
899 break;
902 if (message && p == NULL)
903 do_outofmem_msg(size);
905 theend:
906 #ifdef MEM_PROFILE
907 mem_post_alloc((void **)&p, (size_t)size);
908 #endif
909 return p;
912 #if defined(MEM_PROFILE) || defined(PROTO)
914 * realloc() with memory profiling.
916 void *
917 mem_realloc(ptr, size)
918 void *ptr;
919 size_t size;
921 void *p;
923 mem_pre_free(&ptr);
924 mem_pre_alloc_s(&size);
926 p = realloc(ptr, size);
928 mem_post_alloc(&p, size);
930 return p;
932 #endif
935 * Avoid repeating the error message many times (they take 1 second each).
936 * Did_outofmem_msg is reset when a character is read.
938 void
939 do_outofmem_msg(size)
940 long_u size;
942 if (!did_outofmem_msg)
944 /* Don't hide this message */
945 emsg_silent = 0;
946 EMSGN(_("E342: Out of memory! (allocating %lu bytes)"), size);
947 did_outofmem_msg = TRUE;
951 #if defined(EXITFREE) || defined(PROTO)
953 # if defined(FEAT_SEARCHPATH)
954 static void free_findfile __ARGS((void));
955 # endif
958 * Free everything that we allocated.
959 * Can be used to detect memory leaks, e.g., with ccmalloc.
960 * NOTE: This is tricky! Things are freed that functions depend on. Don't be
961 * surprised if Vim crashes...
962 * Some things can't be freed, esp. things local to a library function.
964 void
965 free_all_mem()
967 buf_T *buf, *nextbuf;
968 static int entered = FALSE;
970 /* When we cause a crash here it is caught and Vim tries to exit cleanly.
971 * Don't try freeing everything again. */
972 if (entered)
973 return;
974 entered = TRUE;
976 # ifdef FEAT_AUTOCMD
977 block_autocmds(); /* don't want to trigger autocommands here */
978 # endif
980 # ifdef FEAT_WINDOWS
981 /* close all tabs and windows */
982 if (first_tabpage->tp_next != NULL)
983 do_cmdline_cmd((char_u *)"tabonly!");
984 if (firstwin != lastwin)
985 do_cmdline_cmd((char_u *)"only!");
986 # endif
988 # if defined(FEAT_SPELL)
989 /* Free all spell info. */
990 spell_free_all();
991 # endif
993 # if defined(FEAT_USR_CMDS)
994 /* Clear user commands (before deleting buffers). */
995 ex_comclear(NULL);
996 # endif
998 # ifdef FEAT_MENU
999 /* Clear menus. */
1000 do_cmdline_cmd((char_u *)"aunmenu *");
1001 # endif
1003 /* Clear mappings, abbreviations, breakpoints. */
1004 do_cmdline_cmd((char_u *)"mapclear");
1005 do_cmdline_cmd((char_u *)"mapclear!");
1006 do_cmdline_cmd((char_u *)"abclear");
1007 # if defined(FEAT_EVAL)
1008 do_cmdline_cmd((char_u *)"breakdel *");
1009 # endif
1010 # if defined(FEAT_PROFILE)
1011 do_cmdline_cmd((char_u *)"profdel *");
1012 # endif
1014 # ifdef FEAT_TITLE
1015 free_titles();
1016 # endif
1017 # if defined(FEAT_SEARCHPATH)
1018 free_findfile();
1019 # endif
1021 /* Obviously named calls. */
1022 # if defined(FEAT_AUTOCMD)
1023 free_all_autocmds();
1024 # endif
1025 clear_termcodes();
1026 free_all_options();
1027 free_all_marks();
1028 alist_clear(&global_alist);
1029 free_homedir();
1030 free_search_patterns();
1031 free_old_sub();
1032 free_last_insert();
1033 free_prev_shellcmd();
1034 free_regexp_stuff();
1035 free_tag_stuff();
1036 free_cd_dir();
1037 # ifdef FEAT_EVAL
1038 set_expr_line(NULL);
1039 # endif
1040 # ifdef FEAT_DIFF
1041 diff_clear(curtab);
1042 # endif
1043 clear_sb_text(); /* free any scrollback text */
1045 /* Free some global vars. */
1046 vim_free(username);
1047 # ifdef FEAT_CLIPBOARD
1048 vim_free(clip_exclude_prog);
1049 # endif
1050 vim_free(last_cmdline);
1051 # ifdef FEAT_CMDHIST
1052 vim_free(new_last_cmdline);
1053 # endif
1054 set_keep_msg(NULL, 0);
1055 vim_free(ff_expand_buffer);
1057 /* Clear cmdline history. */
1058 p_hi = 0;
1059 # ifdef FEAT_CMDHIST
1060 init_history();
1061 # endif
1063 #ifdef FEAT_QUICKFIX
1065 win_T *win;
1067 qf_free_all(NULL);
1068 /* Free all location lists */
1069 FOR_ALL_WINDOWS(win)
1070 qf_free_all(win);
1072 #endif
1074 /* Close all script inputs. */
1075 close_all_scripts();
1077 #if defined(FEAT_WINDOWS)
1078 /* Destroy all windows. Must come before freeing buffers. */
1079 win_free_all();
1080 #endif
1082 /* Free all buffers. Reset 'autochdir' to avoid accessing things that
1083 * were freed already. */
1084 #ifdef FEAT_AUTOCHDIR
1085 p_acd = FALSE;
1086 #endif
1087 for (buf = firstbuf; buf != NULL; )
1089 nextbuf = buf->b_next;
1090 close_buffer(NULL, buf, DOBUF_WIPE);
1091 if (buf_valid(buf))
1092 buf = nextbuf; /* didn't work, try next one */
1093 else
1094 buf = firstbuf;
1097 #ifdef FEAT_ARABIC
1098 free_cmdline_buf();
1099 #endif
1101 /* Clear registers. */
1102 clear_registers();
1103 ResetRedobuff();
1104 ResetRedobuff();
1106 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
1107 vim_free(serverDelayedStartName);
1108 #endif
1110 /* highlight info */
1111 free_highlight();
1113 reset_last_sourcing();
1115 #ifdef FEAT_WINDOWS
1116 free_tabpage(first_tabpage);
1117 first_tabpage = NULL;
1118 #endif
1120 # ifdef UNIX
1121 /* Machine-specific free. */
1122 mch_free_mem();
1123 # endif
1125 /* message history */
1126 for (;;)
1127 if (delete_first_msg() == FAIL)
1128 break;
1130 # ifdef FEAT_EVAL
1131 eval_clear();
1132 # endif
1134 free_termoptions();
1136 /* screenlines (can't display anything now!) */
1137 free_screenlines();
1139 #if defined(USE_XSMP)
1140 xsmp_close();
1141 #endif
1142 #ifdef FEAT_GUI_GTK
1143 gui_mch_free_all();
1144 #endif
1145 clear_hl_tables();
1147 vim_free(IObuff);
1148 vim_free(NameBuff);
1150 #endif
1153 * copy a string into newly allocated memory
1155 char_u *
1156 vim_strsave(string)
1157 char_u *string;
1159 char_u *p;
1160 unsigned len;
1162 len = (unsigned)STRLEN(string) + 1;
1163 p = alloc(len);
1164 if (p != NULL)
1165 mch_memmove(p, string, (size_t)len);
1166 return p;
1169 char_u *
1170 vim_strnsave(string, len)
1171 char_u *string;
1172 int len;
1174 char_u *p;
1176 p = alloc((unsigned)(len + 1));
1177 if (p != NULL)
1179 STRNCPY(p, string, len);
1180 p[len] = NUL;
1182 return p;
1186 * Same as vim_strsave(), but any characters found in esc_chars are preceded
1187 * by a backslash.
1189 char_u *
1190 vim_strsave_escaped(string, esc_chars)
1191 char_u *string;
1192 char_u *esc_chars;
1194 return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE);
1198 * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape
1199 * characters where rem_backslash() would remove the backslash.
1200 * Escape the characters with "cc".
1202 char_u *
1203 vim_strsave_escaped_ext(string, esc_chars, cc, bsl)
1204 char_u *string;
1205 char_u *esc_chars;
1206 int cc;
1207 int bsl;
1209 char_u *p;
1210 char_u *p2;
1211 char_u *escaped_string;
1212 unsigned length;
1213 #ifdef FEAT_MBYTE
1214 int l;
1215 #endif
1218 * First count the number of backslashes required.
1219 * Then allocate the memory and insert them.
1221 length = 1; /* count the trailing NUL */
1222 for (p = string; *p; p++)
1224 #ifdef FEAT_MBYTE
1225 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1227 length += l; /* count a multibyte char */
1228 p += l - 1;
1229 continue;
1231 #endif
1232 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1233 ++length; /* count a backslash */
1234 ++length; /* count an ordinary char */
1236 escaped_string = alloc(length);
1237 if (escaped_string != NULL)
1239 p2 = escaped_string;
1240 for (p = string; *p; p++)
1242 #ifdef FEAT_MBYTE
1243 if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1245 mch_memmove(p2, p, (size_t)l);
1246 p2 += l;
1247 p += l - 1; /* skip multibyte char */
1248 continue;
1250 #endif
1251 if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1252 *p2++ = cc;
1253 *p2++ = *p;
1255 *p2 = NUL;
1257 return escaped_string;
1260 #if !defined(BACKSLASH_IN_FILENAME) || defined(FEAT_EVAL) || defined(PROTO)
1262 * Return TRUE when 'shell' has "csh" in the tail.
1265 csh_like_shell()
1267 return (strstr((char *)gettail(p_sh), "csh") != NULL);
1269 #endif
1271 #if defined(FEAT_EVAL) || defined(PROTO)
1273 * Escape "string" for use as a shell argument with system().
1274 * This uses single quotes, except when we know we need to use double qoutes
1275 * (MS-DOS and MS-Windows without 'shellslash' set).
1276 * Escape a newline, depending on the 'shell' option.
1277 * When "do_special" is TRUE also replace "!", "%", "#" and things starting
1278 * with "<" like "<cfile>".
1279 * Returns the result in allocated memory, NULL if we have run out.
1281 char_u *
1282 vim_strsave_shellescape(string, do_special)
1283 char_u *string;
1284 int do_special;
1286 unsigned length;
1287 char_u *p;
1288 char_u *d;
1289 char_u *escaped_string;
1290 int l;
1291 int csh_like;
1293 /* Only csh and similar shells expand '!' within single quotes. For sh and
1294 * the like we must not put a backslash before it, it will be taken
1295 * literally. If do_special is set the '!' will be escaped twice.
1296 * Csh also needs to have "\n" escaped twice when do_special is set. */
1297 csh_like = csh_like_shell();
1299 /* First count the number of extra bytes required. */
1300 length = (unsigned)STRLEN(string) + 3; /* two quotes and a trailing NUL */
1301 for (p = string; *p != NUL; mb_ptr_adv(p))
1303 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1304 if (!p_ssl)
1306 if (*p == '"')
1307 ++length; /* " -> "" */
1309 else
1310 # endif
1311 if (*p == '\'')
1312 length += 3; /* ' => '\'' */
1313 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1315 ++length; /* insert backslash */
1316 if (csh_like && do_special)
1317 ++length; /* insert backslash */
1319 if (do_special && find_cmdline_var(p, &l) >= 0)
1321 ++length; /* insert backslash */
1322 p += l - 1;
1326 /* Allocate memory for the result and fill it. */
1327 escaped_string = alloc(length);
1328 if (escaped_string != NULL)
1330 d = escaped_string;
1332 /* add opening quote */
1333 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1334 if (!p_ssl)
1335 *d++ = '"';
1336 else
1337 # endif
1338 *d++ = '\'';
1340 for (p = string; *p != NUL; )
1342 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1343 if (!p_ssl)
1345 if (*p == '"')
1347 *d++ = '"';
1348 *d++ = '"';
1349 ++p;
1350 continue;
1353 else
1354 # endif
1355 if (*p == '\'')
1357 *d++ = '\'';
1358 *d++ = '\\';
1359 *d++ = '\'';
1360 *d++ = '\'';
1361 ++p;
1362 continue;
1364 if (*p == '\n' || (*p == '!' && (csh_like || do_special)))
1366 *d++ = '\\';
1367 if (csh_like && do_special)
1368 *d++ = '\\';
1369 *d++ = *p++;
1370 continue;
1372 if (do_special && find_cmdline_var(p, &l) >= 0)
1374 *d++ = '\\'; /* insert backslash */
1375 while (--l >= 0) /* copy the var */
1376 *d++ = *p++;
1379 MB_COPY_CHAR(p, d);
1382 /* add terminating quote and finish with a NUL */
1383 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1384 if (!p_ssl)
1385 *d++ = '"';
1386 else
1387 # endif
1388 *d++ = '\'';
1389 *d = NUL;
1392 return escaped_string;
1394 #endif
1397 * Like vim_strsave(), but make all characters uppercase.
1398 * This uses ASCII lower-to-upper case translation, language independent.
1400 char_u *
1401 vim_strsave_up(string)
1402 char_u *string;
1404 char_u *p1;
1406 p1 = vim_strsave(string);
1407 vim_strup(p1);
1408 return p1;
1412 * Like vim_strnsave(), but make all characters uppercase.
1413 * This uses ASCII lower-to-upper case translation, language independent.
1415 char_u *
1416 vim_strnsave_up(string, len)
1417 char_u *string;
1418 int len;
1420 char_u *p1;
1422 p1 = vim_strnsave(string, len);
1423 vim_strup(p1);
1424 return p1;
1428 * ASCII lower-to-upper case translation, language independent.
1430 void
1431 vim_strup(p)
1432 char_u *p;
1434 char_u *p2;
1435 int c;
1437 if (p != NULL)
1439 p2 = p;
1440 while ((c = *p2) != NUL)
1441 #ifdef EBCDIC
1442 *p2++ = isalpha(c) ? toupper(c) : c;
1443 #else
1444 *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20);
1445 #endif
1449 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
1451 * Make string "s" all upper-case and return it in allocated memory.
1452 * Handles multi-byte characters as well as possible.
1453 * Returns NULL when out of memory.
1455 char_u *
1456 strup_save(orig)
1457 char_u *orig;
1459 char_u *p;
1460 char_u *res;
1462 res = p = vim_strsave(orig);
1464 if (res != NULL)
1465 while (*p != NUL)
1467 # ifdef FEAT_MBYTE
1468 int l;
1470 if (enc_utf8)
1472 int c, uc;
1473 int nl;
1474 char_u *s;
1476 c = utf_ptr2char(p);
1477 uc = utf_toupper(c);
1479 /* Reallocate string when byte count changes. This is rare,
1480 * thus it's OK to do another malloc()/free(). */
1481 l = utf_ptr2len(p);
1482 nl = utf_char2len(uc);
1483 if (nl != l)
1485 s = alloc((unsigned)STRLEN(res) + 1 + nl - l);
1486 if (s == NULL)
1487 break;
1488 mch_memmove(s, res, p - res);
1489 STRCPY(s + (p - res) + nl, p + l);
1490 p = s + (p - res);
1491 vim_free(res);
1492 res = s;
1495 utf_char2bytes(uc, p);
1496 p += nl;
1498 else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1499 p += l; /* skip multi-byte character */
1500 else
1501 # endif
1503 *p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */
1504 p++;
1508 return res;
1510 #endif
1513 * copy a space a number of times
1515 void
1516 copy_spaces(ptr, count)
1517 char_u *ptr;
1518 size_t count;
1520 size_t i = count;
1521 char_u *p = ptr;
1523 while (i--)
1524 *p++ = ' ';
1527 #if defined(FEAT_VISUALEXTRA) || defined(PROTO)
1529 * Copy a character a number of times.
1530 * Does not work for multi-byte charactes!
1532 void
1533 copy_chars(ptr, count, c)
1534 char_u *ptr;
1535 size_t count;
1536 int c;
1538 size_t i = count;
1539 char_u *p = ptr;
1541 while (i--)
1542 *p++ = c;
1544 #endif
1547 * delete spaces at the end of a string
1549 void
1550 del_trailing_spaces(ptr)
1551 char_u *ptr;
1553 char_u *q;
1555 q = ptr + STRLEN(ptr);
1556 while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1557 *q = NUL;
1561 * Like strncpy(), but always terminate the result with one NUL.
1562 * "to" must be "len + 1" long!
1564 void
1565 vim_strncpy(to, from, len)
1566 char_u *to;
1567 char_u *from;
1568 size_t len;
1570 STRNCPY(to, from, len);
1571 to[len] = NUL;
1575 * Isolate one part of a string option where parts are separated with
1576 * "sep_chars".
1577 * The part is copied into "buf[maxlen]".
1578 * "*option" is advanced to the next part.
1579 * The length is returned.
1582 copy_option_part(option, buf, maxlen, sep_chars)
1583 char_u **option;
1584 char_u *buf;
1585 int maxlen;
1586 char *sep_chars;
1588 int len = 0;
1589 char_u *p = *option;
1591 /* skip '.' at start of option part, for 'suffixes' */
1592 if (*p == '.')
1593 buf[len++] = *p++;
1594 while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1597 * Skip backslash before a separator character and space.
1599 if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1600 ++p;
1601 if (len < maxlen - 1)
1602 buf[len++] = *p;
1603 ++p;
1605 buf[len] = NUL;
1607 if (*p != NUL && *p != ',') /* skip non-standard separator */
1608 ++p;
1609 p = skip_to_option_part(p); /* p points to next file name */
1611 *option = p;
1612 return len;
1616 * Replacement for free() that ignores NULL pointers.
1617 * Also skip free() when exiting for sure, this helps when we caught a deadly
1618 * signal that was caused by a crash in free().
1620 void
1621 vim_free(x)
1622 void *x;
1624 if (x != NULL && !really_exiting)
1626 #ifdef MEM_PROFILE
1627 mem_pre_free(&x);
1628 #endif
1629 free(x);
1633 #ifndef HAVE_MEMSET
1634 void *
1635 vim_memset(ptr, c, size)
1636 void *ptr;
1637 int c;
1638 size_t size;
1640 char *p = ptr;
1642 while (size-- > 0)
1643 *p++ = c;
1644 return ptr;
1646 #endif
1648 #ifdef VIM_MEMCMP
1650 * Return zero when "b1" and "b2" are the same for "len" bytes.
1651 * Return non-zero otherwise.
1654 vim_memcmp(b1, b2, len)
1655 void *b1;
1656 void *b2;
1657 size_t len;
1659 char_u *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1661 for ( ; len > 0; --len)
1663 if (*p1 != *p2)
1664 return 1;
1665 ++p1;
1666 ++p2;
1668 return 0;
1670 #endif
1672 #ifdef VIM_MEMMOVE
1674 * Version of memmove() that handles overlapping source and destination.
1675 * For systems that don't have a function that is guaranteed to do that (SYSV).
1677 void
1678 mch_memmove(dst_arg, src_arg, len)
1679 void *src_arg, *dst_arg;
1680 size_t len;
1683 * A void doesn't have a size, we use char pointers.
1685 char *dst = dst_arg, *src = src_arg;
1687 /* overlap, copy backwards */
1688 if (dst > src && dst < src + len)
1690 src += len;
1691 dst += len;
1692 while (len-- > 0)
1693 *--dst = *--src;
1695 else /* copy forwards */
1696 while (len-- > 0)
1697 *dst++ = *src++;
1699 #endif
1701 #if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1703 * Compare two strings, ignoring case, using current locale.
1704 * Doesn't work for multi-byte characters.
1705 * return 0 for match, < 0 for smaller, > 0 for bigger
1708 vim_stricmp(s1, s2)
1709 char *s1;
1710 char *s2;
1712 int i;
1714 for (;;)
1716 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1717 if (i != 0)
1718 return i; /* this character different */
1719 if (*s1 == NUL)
1720 break; /* strings match until NUL */
1721 ++s1;
1722 ++s2;
1724 return 0; /* strings match */
1726 #endif
1728 #if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1730 * Compare two strings, for length "len", ignoring case, using current locale.
1731 * Doesn't work for multi-byte characters.
1732 * return 0 for match, < 0 for smaller, > 0 for bigger
1735 vim_strnicmp(s1, s2, len)
1736 char *s1;
1737 char *s2;
1738 size_t len;
1740 int i;
1742 while (len > 0)
1744 i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1745 if (i != 0)
1746 return i; /* this character different */
1747 if (*s1 == NUL)
1748 break; /* strings match until NUL */
1749 ++s1;
1750 ++s2;
1751 --len;
1753 return 0; /* strings match */
1755 #endif
1757 #if 0 /* currently not used */
1759 * Check if string "s2" appears somewhere in "s1" while ignoring case.
1760 * Return NULL if not, a pointer to the first occurrence if it does.
1762 char_u *
1763 vim_stristr(s1, s2)
1764 char_u *s1;
1765 char_u *s2;
1767 char_u *p;
1768 int len = STRLEN(s2);
1769 char_u *end = s1 + STRLEN(s1) - len;
1771 for (p = s1; p <= end; ++p)
1772 if (STRNICMP(p, s2, len) == 0)
1773 return p;
1774 return NULL;
1776 #endif
1779 * Version of strchr() and strrchr() that handle unsigned char strings
1780 * with characters from 128 to 255 correctly. It also doesn't return a
1781 * pointer to the NUL at the end of the string.
1783 char_u *
1784 vim_strchr(string, c)
1785 char_u *string;
1786 int c;
1788 char_u *p;
1789 int b;
1791 p = string;
1792 #ifdef FEAT_MBYTE
1793 if (enc_utf8 && c >= 0x80)
1795 while (*p != NUL)
1797 if (utf_ptr2char(p) == c)
1798 return p;
1799 p += (*mb_ptr2len)(p);
1801 return NULL;
1803 if (enc_dbcs != 0 && c > 255)
1805 int n2 = c & 0xff;
1807 c = ((unsigned)c >> 8) & 0xff;
1808 while ((b = *p) != NUL)
1810 if (b == c && p[1] == n2)
1811 return p;
1812 p += (*mb_ptr2len)(p);
1814 return NULL;
1816 if (has_mbyte)
1818 while ((b = *p) != NUL)
1820 if (b == c)
1821 return p;
1822 p += (*mb_ptr2len)(p);
1824 return NULL;
1826 #endif
1827 while ((b = *p) != NUL)
1829 if (b == c)
1830 return p;
1831 ++p;
1833 return NULL;
1837 * Version of strchr() that only works for bytes and handles unsigned char
1838 * strings with characters above 128 correctly. It also doesn't return a
1839 * pointer to the NUL at the end of the string.
1841 char_u *
1842 vim_strbyte(string, c)
1843 char_u *string;
1844 int c;
1846 char_u *p = string;
1848 while (*p != NUL)
1850 if (*p == c)
1851 return p;
1852 ++p;
1854 return NULL;
1858 * Search for last occurrence of "c" in "string".
1859 * Return NULL if not found.
1860 * Does not handle multi-byte char for "c"!
1862 char_u *
1863 vim_strrchr(string, c)
1864 char_u *string;
1865 int c;
1867 char_u *retval = NULL;
1868 char_u *p = string;
1870 while (*p)
1872 if (*p == c)
1873 retval = p;
1874 mb_ptr_adv(p);
1876 return retval;
1880 * Vim's version of strpbrk(), in case it's missing.
1881 * Don't generate a prototype for this, causes problems when it's not used.
1883 #ifndef PROTO
1884 # ifndef HAVE_STRPBRK
1885 # ifdef vim_strpbrk
1886 # undef vim_strpbrk
1887 # endif
1888 char_u *
1889 vim_strpbrk(s, charset)
1890 char_u *s;
1891 char_u *charset;
1893 while (*s)
1895 if (vim_strchr(charset, *s) != NULL)
1896 return s;
1897 mb_ptr_adv(s);
1899 return NULL;
1901 # endif
1902 #endif
1905 * Vim has its own isspace() function, because on some machines isspace()
1906 * can't handle characters above 128.
1909 vim_isspace(x)
1910 int x;
1912 return ((x >= 9 && x <= 13) || x == ' ');
1915 /************************************************************************
1916 * Functions for handling growing arrays.
1920 * Clear an allocated growing array.
1922 void
1923 ga_clear(gap)
1924 garray_T *gap;
1926 vim_free(gap->ga_data);
1927 ga_init(gap);
1931 * Clear a growing array that contains a list of strings.
1933 void
1934 ga_clear_strings(gap)
1935 garray_T *gap;
1937 int i;
1939 for (i = 0; i < gap->ga_len; ++i)
1940 vim_free(((char_u **)(gap->ga_data))[i]);
1941 ga_clear(gap);
1945 * Initialize a growing array. Don't forget to set ga_itemsize and
1946 * ga_growsize! Or use ga_init2().
1948 void
1949 ga_init(gap)
1950 garray_T *gap;
1952 gap->ga_data = NULL;
1953 gap->ga_maxlen = 0;
1954 gap->ga_len = 0;
1957 void
1958 ga_init2(gap, itemsize, growsize)
1959 garray_T *gap;
1960 int itemsize;
1961 int growsize;
1963 ga_init(gap);
1964 gap->ga_itemsize = itemsize;
1965 gap->ga_growsize = growsize;
1969 * Make room in growing array "gap" for at least "n" items.
1970 * Return FAIL for failure, OK otherwise.
1973 ga_grow(gap, n)
1974 garray_T *gap;
1975 int n;
1977 size_t len;
1978 char_u *pp;
1980 if (gap->ga_maxlen - gap->ga_len < n)
1982 if (n < gap->ga_growsize)
1983 n = gap->ga_growsize;
1984 len = gap->ga_itemsize * (gap->ga_len + n);
1985 pp = alloc_clear((unsigned)len);
1986 if (pp == NULL)
1987 return FAIL;
1988 gap->ga_maxlen = gap->ga_len + n;
1989 if (gap->ga_data != NULL)
1991 mch_memmove(pp, gap->ga_data,
1992 (size_t)(gap->ga_itemsize * gap->ga_len));
1993 vim_free(gap->ga_data);
1995 gap->ga_data = pp;
1997 return OK;
2001 * Concatenate a string to a growarray which contains characters.
2002 * Note: Does NOT copy the NUL at the end!
2004 void
2005 ga_concat(gap, s)
2006 garray_T *gap;
2007 char_u *s;
2009 int len = (int)STRLEN(s);
2011 if (ga_grow(gap, len) == OK)
2013 mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
2014 gap->ga_len += len;
2019 * Append one byte to a growarray which contains bytes.
2021 void
2022 ga_append(gap, c)
2023 garray_T *gap;
2024 int c;
2026 if (ga_grow(gap, 1) == OK)
2028 *((char *)gap->ga_data + gap->ga_len) = c;
2029 ++gap->ga_len;
2033 /************************************************************************
2034 * functions that use lookup tables for various things, generally to do with
2035 * special key codes.
2039 * Some useful tables.
2042 static struct modmasktable
2044 short mod_mask; /* Bit-mask for particular key modifier */
2045 short mod_flag; /* Bit(s) for particular key modifier */
2046 char_u name; /* Single letter name of modifier */
2047 } mod_mask_table[] =
2049 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'M'},
2050 {MOD_MASK_META, MOD_MASK_META, (char_u)'T'},
2051 {MOD_MASK_CTRL, MOD_MASK_CTRL, (char_u)'C'},
2052 {MOD_MASK_SHIFT, MOD_MASK_SHIFT, (char_u)'S'},
2053 {MOD_MASK_MULTI_CLICK, MOD_MASK_2CLICK, (char_u)'2'},
2054 {MOD_MASK_MULTI_CLICK, MOD_MASK_3CLICK, (char_u)'3'},
2055 {MOD_MASK_MULTI_CLICK, MOD_MASK_4CLICK, (char_u)'4'},
2056 #ifdef MACOS
2057 {MOD_MASK_CMD, MOD_MASK_CMD, (char_u)'D'},
2058 #endif
2059 /* 'A' must be the last one */
2060 {MOD_MASK_ALT, MOD_MASK_ALT, (char_u)'A'},
2061 {0, 0, NUL}
2065 * Shifted key terminal codes and their unshifted equivalent.
2066 * Don't add mouse codes here, they are handled separately!
2068 #define MOD_KEYS_ENTRY_SIZE 5
2070 static char_u modifier_keys_table[] =
2072 /* mod mask with modifier without modifier */
2073 MOD_MASK_SHIFT, '&', '9', '@', '1', /* begin */
2074 MOD_MASK_SHIFT, '&', '0', '@', '2', /* cancel */
2075 MOD_MASK_SHIFT, '*', '1', '@', '4', /* command */
2076 MOD_MASK_SHIFT, '*', '2', '@', '5', /* copy */
2077 MOD_MASK_SHIFT, '*', '3', '@', '6', /* create */
2078 MOD_MASK_SHIFT, '*', '4', 'k', 'D', /* delete char */
2079 MOD_MASK_SHIFT, '*', '5', 'k', 'L', /* delete line */
2080 MOD_MASK_SHIFT, '*', '7', '@', '7', /* end */
2081 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_END, '@', '7', /* end */
2082 MOD_MASK_SHIFT, '*', '9', '@', '9', /* exit */
2083 MOD_MASK_SHIFT, '*', '0', '@', '0', /* find */
2084 MOD_MASK_SHIFT, '#', '1', '%', '1', /* help */
2085 MOD_MASK_SHIFT, '#', '2', 'k', 'h', /* home */
2086 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_HOME, 'k', 'h', /* home */
2087 MOD_MASK_SHIFT, '#', '3', 'k', 'I', /* insert */
2088 MOD_MASK_SHIFT, '#', '4', 'k', 'l', /* left arrow */
2089 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_LEFT, 'k', 'l', /* left arrow */
2090 MOD_MASK_SHIFT, '%', 'a', '%', '3', /* message */
2091 MOD_MASK_SHIFT, '%', 'b', '%', '4', /* move */
2092 MOD_MASK_SHIFT, '%', 'c', '%', '5', /* next */
2093 MOD_MASK_SHIFT, '%', 'd', '%', '7', /* options */
2094 MOD_MASK_SHIFT, '%', 'e', '%', '8', /* previous */
2095 MOD_MASK_SHIFT, '%', 'f', '%', '9', /* print */
2096 MOD_MASK_SHIFT, '%', 'g', '%', '0', /* redo */
2097 MOD_MASK_SHIFT, '%', 'h', '&', '3', /* replace */
2098 MOD_MASK_SHIFT, '%', 'i', 'k', 'r', /* right arr. */
2099 MOD_MASK_CTRL, KS_EXTRA, (int)KE_C_RIGHT, 'k', 'r', /* right arr. */
2100 MOD_MASK_SHIFT, '%', 'j', '&', '5', /* resume */
2101 MOD_MASK_SHIFT, '!', '1', '&', '6', /* save */
2102 MOD_MASK_SHIFT, '!', '2', '&', '7', /* suspend */
2103 MOD_MASK_SHIFT, '!', '3', '&', '8', /* undo */
2104 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP, 'k', 'u', /* up arrow */
2105 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN, 'k', 'd', /* down arrow */
2107 /* vt100 F1 */
2108 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1, KS_EXTRA, (int)KE_XF1,
2109 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2, KS_EXTRA, (int)KE_XF2,
2110 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3, KS_EXTRA, (int)KE_XF3,
2111 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4, KS_EXTRA, (int)KE_XF4,
2113 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1, 'k', '1', /* F1 */
2114 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2, 'k', '2',
2115 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3, 'k', '3',
2116 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4, 'k', '4',
2117 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5, 'k', '5',
2118 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6, 'k', '6',
2119 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7, 'k', '7',
2120 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8, 'k', '8',
2121 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9, 'k', '9',
2122 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10, 'k', ';', /* F10 */
2124 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11, 'F', '1',
2125 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12, 'F', '2',
2126 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13, 'F', '3',
2127 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14, 'F', '4',
2128 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15, 'F', '5',
2129 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16, 'F', '6',
2130 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17, 'F', '7',
2131 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18, 'F', '8',
2132 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19, 'F', '9',
2133 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20, 'F', 'A',
2135 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21, 'F', 'B',
2136 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22, 'F', 'C',
2137 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23, 'F', 'D',
2138 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24, 'F', 'E',
2139 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25, 'F', 'F',
2140 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26, 'F', 'G',
2141 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27, 'F', 'H',
2142 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28, 'F', 'I',
2143 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29, 'F', 'J',
2144 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30, 'F', 'K',
2146 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31, 'F', 'L',
2147 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32, 'F', 'M',
2148 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33, 'F', 'N',
2149 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34, 'F', 'O',
2150 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35, 'F', 'P',
2151 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36, 'F', 'Q',
2152 MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37, 'F', 'R',
2154 /* TAB pseudo code*/
2155 MOD_MASK_SHIFT, 'k', 'B', KS_EXTRA, (int)KE_TAB,
2160 static struct key_name_entry
2162 int key; /* Special key code or ascii value */
2163 char_u *name; /* Name of key */
2164 } key_names_table[] =
2166 {' ', (char_u *)"Space"},
2167 {TAB, (char_u *)"Tab"},
2168 {K_TAB, (char_u *)"Tab"},
2169 {NL, (char_u *)"NL"},
2170 {NL, (char_u *)"NewLine"}, /* Alternative name */
2171 {NL, (char_u *)"LineFeed"}, /* Alternative name */
2172 {NL, (char_u *)"LF"}, /* Alternative name */
2173 {CAR, (char_u *)"CR"},
2174 {CAR, (char_u *)"Return"}, /* Alternative name */
2175 {CAR, (char_u *)"Enter"}, /* Alternative name */
2176 {K_BS, (char_u *)"BS"},
2177 {K_BS, (char_u *)"BackSpace"}, /* Alternative name */
2178 {ESC, (char_u *)"Esc"},
2179 {CSI, (char_u *)"CSI"},
2180 {K_CSI, (char_u *)"xCSI"},
2181 {'|', (char_u *)"Bar"},
2182 {'\\', (char_u *)"Bslash"},
2183 {K_DEL, (char_u *)"Del"},
2184 {K_DEL, (char_u *)"Delete"}, /* Alternative name */
2185 {K_KDEL, (char_u *)"kDel"},
2186 {K_UP, (char_u *)"Up"},
2187 {K_DOWN, (char_u *)"Down"},
2188 {K_LEFT, (char_u *)"Left"},
2189 {K_RIGHT, (char_u *)"Right"},
2190 {K_XUP, (char_u *)"xUp"},
2191 {K_XDOWN, (char_u *)"xDown"},
2192 {K_XLEFT, (char_u *)"xLeft"},
2193 {K_XRIGHT, (char_u *)"xRight"},
2195 {K_F1, (char_u *)"F1"},
2196 {K_F2, (char_u *)"F2"},
2197 {K_F3, (char_u *)"F3"},
2198 {K_F4, (char_u *)"F4"},
2199 {K_F5, (char_u *)"F5"},
2200 {K_F6, (char_u *)"F6"},
2201 {K_F7, (char_u *)"F7"},
2202 {K_F8, (char_u *)"F8"},
2203 {K_F9, (char_u *)"F9"},
2204 {K_F10, (char_u *)"F10"},
2206 {K_F11, (char_u *)"F11"},
2207 {K_F12, (char_u *)"F12"},
2208 {K_F13, (char_u *)"F13"},
2209 {K_F14, (char_u *)"F14"},
2210 {K_F15, (char_u *)"F15"},
2211 {K_F16, (char_u *)"F16"},
2212 {K_F17, (char_u *)"F17"},
2213 {K_F18, (char_u *)"F18"},
2214 {K_F19, (char_u *)"F19"},
2215 {K_F20, (char_u *)"F20"},
2217 {K_F21, (char_u *)"F21"},
2218 {K_F22, (char_u *)"F22"},
2219 {K_F23, (char_u *)"F23"},
2220 {K_F24, (char_u *)"F24"},
2221 {K_F25, (char_u *)"F25"},
2222 {K_F26, (char_u *)"F26"},
2223 {K_F27, (char_u *)"F27"},
2224 {K_F28, (char_u *)"F28"},
2225 {K_F29, (char_u *)"F29"},
2226 {K_F30, (char_u *)"F30"},
2228 {K_F31, (char_u *)"F31"},
2229 {K_F32, (char_u *)"F32"},
2230 {K_F33, (char_u *)"F33"},
2231 {K_F34, (char_u *)"F34"},
2232 {K_F35, (char_u *)"F35"},
2233 {K_F36, (char_u *)"F36"},
2234 {K_F37, (char_u *)"F37"},
2236 {K_XF1, (char_u *)"xF1"},
2237 {K_XF2, (char_u *)"xF2"},
2238 {K_XF3, (char_u *)"xF3"},
2239 {K_XF4, (char_u *)"xF4"},
2241 {K_HELP, (char_u *)"Help"},
2242 {K_UNDO, (char_u *)"Undo"},
2243 {K_INS, (char_u *)"Insert"},
2244 {K_INS, (char_u *)"Ins"}, /* Alternative name */
2245 {K_KINS, (char_u *)"kInsert"},
2246 {K_HOME, (char_u *)"Home"},
2247 {K_KHOME, (char_u *)"kHome"},
2248 {K_XHOME, (char_u *)"xHome"},
2249 {K_ZHOME, (char_u *)"zHome"},
2250 {K_END, (char_u *)"End"},
2251 {K_KEND, (char_u *)"kEnd"},
2252 {K_XEND, (char_u *)"xEnd"},
2253 {K_ZEND, (char_u *)"zEnd"},
2254 {K_PAGEUP, (char_u *)"PageUp"},
2255 {K_PAGEDOWN, (char_u *)"PageDown"},
2256 {K_KPAGEUP, (char_u *)"kPageUp"},
2257 {K_KPAGEDOWN, (char_u *)"kPageDown"},
2259 {K_KPLUS, (char_u *)"kPlus"},
2260 {K_KMINUS, (char_u *)"kMinus"},
2261 {K_KDIVIDE, (char_u *)"kDivide"},
2262 {K_KMULTIPLY, (char_u *)"kMultiply"},
2263 {K_KENTER, (char_u *)"kEnter"},
2264 {K_KPOINT, (char_u *)"kPoint"},
2266 {K_K0, (char_u *)"k0"},
2267 {K_K1, (char_u *)"k1"},
2268 {K_K2, (char_u *)"k2"},
2269 {K_K3, (char_u *)"k3"},
2270 {K_K4, (char_u *)"k4"},
2271 {K_K5, (char_u *)"k5"},
2272 {K_K6, (char_u *)"k6"},
2273 {K_K7, (char_u *)"k7"},
2274 {K_K8, (char_u *)"k8"},
2275 {K_K9, (char_u *)"k9"},
2277 {'<', (char_u *)"lt"},
2279 {K_MOUSE, (char_u *)"Mouse"},
2280 {K_NETTERM_MOUSE, (char_u *)"NetMouse"},
2281 {K_DEC_MOUSE, (char_u *)"DecMouse"},
2282 {K_JSBTERM_MOUSE, (char_u *)"JsbMouse"},
2283 {K_PTERM_MOUSE, (char_u *)"PtermMouse"},
2284 {K_LEFTMOUSE, (char_u *)"LeftMouse"},
2285 {K_LEFTMOUSE_NM, (char_u *)"LeftMouseNM"},
2286 {K_LEFTDRAG, (char_u *)"LeftDrag"},
2287 {K_LEFTRELEASE, (char_u *)"LeftRelease"},
2288 {K_LEFTRELEASE_NM, (char_u *)"LeftReleaseNM"},
2289 {K_MIDDLEMOUSE, (char_u *)"MiddleMouse"},
2290 {K_MIDDLEDRAG, (char_u *)"MiddleDrag"},
2291 {K_MIDDLERELEASE, (char_u *)"MiddleRelease"},
2292 {K_RIGHTMOUSE, (char_u *)"RightMouse"},
2293 {K_RIGHTDRAG, (char_u *)"RightDrag"},
2294 {K_RIGHTRELEASE, (char_u *)"RightRelease"},
2295 {K_MOUSEDOWN, (char_u *)"MouseDown"},
2296 {K_MOUSEUP, (char_u *)"MouseUp"},
2297 {K_X1MOUSE, (char_u *)"X1Mouse"},
2298 {K_X1DRAG, (char_u *)"X1Drag"},
2299 {K_X1RELEASE, (char_u *)"X1Release"},
2300 {K_X2MOUSE, (char_u *)"X2Mouse"},
2301 {K_X2DRAG, (char_u *)"X2Drag"},
2302 {K_X2RELEASE, (char_u *)"X2Release"},
2303 {K_DROP, (char_u *)"Drop"},
2304 {K_ZERO, (char_u *)"Nul"},
2305 #ifdef FEAT_EVAL
2306 {K_SNR, (char_u *)"SNR"},
2307 #endif
2308 {K_PLUG, (char_u *)"Plug"},
2309 {0, NULL}
2312 #define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
2314 #ifdef FEAT_MOUSE
2315 static struct mousetable
2317 int pseudo_code; /* Code for pseudo mouse event */
2318 int button; /* Which mouse button is it? */
2319 int is_click; /* Is it a mouse button click event? */
2320 int is_drag; /* Is it a mouse drag event? */
2321 } mouse_table[] =
2323 {(int)KE_LEFTMOUSE, MOUSE_LEFT, TRUE, FALSE},
2324 #ifdef FEAT_GUI
2325 {(int)KE_LEFTMOUSE_NM, MOUSE_LEFT, TRUE, FALSE},
2326 #endif
2327 {(int)KE_LEFTDRAG, MOUSE_LEFT, FALSE, TRUE},
2328 {(int)KE_LEFTRELEASE, MOUSE_LEFT, FALSE, FALSE},
2329 #ifdef FEAT_GUI
2330 {(int)KE_LEFTRELEASE_NM, MOUSE_LEFT, FALSE, FALSE},
2331 #endif
2332 {(int)KE_MIDDLEMOUSE, MOUSE_MIDDLE, TRUE, FALSE},
2333 {(int)KE_MIDDLEDRAG, MOUSE_MIDDLE, FALSE, TRUE},
2334 {(int)KE_MIDDLERELEASE, MOUSE_MIDDLE, FALSE, FALSE},
2335 {(int)KE_RIGHTMOUSE, MOUSE_RIGHT, TRUE, FALSE},
2336 {(int)KE_RIGHTDRAG, MOUSE_RIGHT, FALSE, TRUE},
2337 {(int)KE_RIGHTRELEASE, MOUSE_RIGHT, FALSE, FALSE},
2338 {(int)KE_X1MOUSE, MOUSE_X1, TRUE, FALSE},
2339 {(int)KE_X1DRAG, MOUSE_X1, FALSE, TRUE},
2340 {(int)KE_X1RELEASE, MOUSE_X1, FALSE, FALSE},
2341 {(int)KE_X2MOUSE, MOUSE_X2, TRUE, FALSE},
2342 {(int)KE_X2DRAG, MOUSE_X2, FALSE, TRUE},
2343 {(int)KE_X2RELEASE, MOUSE_X2, FALSE, FALSE},
2344 /* DRAG without CLICK */
2345 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, TRUE},
2346 /* RELEASE without CLICK */
2347 {(int)KE_IGNORE, MOUSE_RELEASE, FALSE, FALSE},
2348 {0, 0, 0, 0},
2350 #endif /* FEAT_MOUSE */
2353 * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
2354 * modifier name ('S' for Shift, 'C' for Ctrl etc).
2357 name_to_mod_mask(c)
2358 int c;
2360 int i;
2362 c = TOUPPER_ASC(c);
2363 for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
2364 if (c == mod_mask_table[i].name)
2365 return mod_mask_table[i].mod_flag;
2366 return 0;
2370 * Check if if there is a special key code for "key" that includes the
2371 * modifiers specified.
2374 simplify_key(key, modifiers)
2375 int key;
2376 int *modifiers;
2378 int i;
2379 int key0;
2380 int key1;
2382 if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2384 /* TAB is a special case */
2385 if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2387 *modifiers &= ~MOD_MASK_SHIFT;
2388 return K_S_TAB;
2390 key0 = KEY2TERMCAP0(key);
2391 key1 = KEY2TERMCAP1(key);
2392 for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2393 if (key0 == modifier_keys_table[i + 3]
2394 && key1 == modifier_keys_table[i + 4]
2395 && (*modifiers & modifier_keys_table[i]))
2397 *modifiers &= ~modifier_keys_table[i];
2398 return TERMCAP2KEY(modifier_keys_table[i + 1],
2399 modifier_keys_table[i + 2]);
2402 return key;
2406 * Change <xHome> to <Home>, <xUp> to <Up>, etc.
2409 handle_x_keys(key)
2410 int key;
2412 switch (key)
2414 case K_XUP: return K_UP;
2415 case K_XDOWN: return K_DOWN;
2416 case K_XLEFT: return K_LEFT;
2417 case K_XRIGHT: return K_RIGHT;
2418 case K_XHOME: return K_HOME;
2419 case K_ZHOME: return K_HOME;
2420 case K_XEND: return K_END;
2421 case K_ZEND: return K_END;
2422 case K_XF1: return K_F1;
2423 case K_XF2: return K_F2;
2424 case K_XF3: return K_F3;
2425 case K_XF4: return K_F4;
2426 case K_S_XF1: return K_S_F1;
2427 case K_S_XF2: return K_S_F2;
2428 case K_S_XF3: return K_S_F3;
2429 case K_S_XF4: return K_S_F4;
2431 return key;
2435 * Return a string which contains the name of the given key when the given
2436 * modifiers are down.
2438 char_u *
2439 get_special_key_name(c, modifiers)
2440 int c;
2441 int modifiers;
2443 static char_u string[MAX_KEY_NAME_LEN + 1];
2445 int i, idx;
2446 int table_idx;
2447 char_u *s;
2449 string[0] = '<';
2450 idx = 1;
2452 /* Key that stands for a normal character. */
2453 if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2454 c = KEY2TERMCAP1(c);
2457 * Translate shifted special keys into unshifted keys and set modifier.
2458 * Same for CTRL and ALT modifiers.
2460 if (IS_SPECIAL(c))
2462 for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2463 if ( KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2464 && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2466 modifiers |= modifier_keys_table[i];
2467 c = TERMCAP2KEY(modifier_keys_table[i + 3],
2468 modifier_keys_table[i + 4]);
2469 break;
2473 /* try to find the key in the special key table */
2474 table_idx = find_special_key_in_table(c);
2477 * When not a known special key, and not a printable character, try to
2478 * extract modifiers.
2480 if (c > 0
2481 #ifdef FEAT_MBYTE
2482 && (*mb_char2len)(c) == 1
2483 #endif
2486 if (table_idx < 0
2487 && (!vim_isprintc(c) || (c & 0x7f) == ' ')
2488 && (c & 0x80))
2490 c &= 0x7f;
2491 modifiers |= MOD_MASK_ALT;
2492 /* try again, to find the un-alted key in the special key table */
2493 table_idx = find_special_key_in_table(c);
2495 if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2497 #ifdef EBCDIC
2498 c = CtrlChar(c);
2499 #else
2500 c += '@';
2501 #endif
2502 modifiers |= MOD_MASK_CTRL;
2506 /* translate the modifier into a string */
2507 for (i = 0; mod_mask_table[i].name != 'A'; i++)
2508 if ((modifiers & mod_mask_table[i].mod_mask)
2509 == mod_mask_table[i].mod_flag)
2511 string[idx++] = mod_mask_table[i].name;
2512 string[idx++] = (char_u)'-';
2515 if (table_idx < 0) /* unknown special key, may output t_xx */
2517 if (IS_SPECIAL(c))
2519 string[idx++] = 't';
2520 string[idx++] = '_';
2521 string[idx++] = KEY2TERMCAP0(c);
2522 string[idx++] = KEY2TERMCAP1(c);
2524 /* Not a special key, only modifiers, output directly */
2525 else
2527 #ifdef FEAT_MBYTE
2528 if (has_mbyte && (*mb_char2len)(c) > 1)
2529 idx += (*mb_char2bytes)(c, string + idx);
2530 else
2531 #endif
2532 if (vim_isprintc(c))
2533 string[idx++] = c;
2534 else
2536 s = transchar(c);
2537 while (*s)
2538 string[idx++] = *s++;
2542 else /* use name of special key */
2544 STRCPY(string + idx, key_names_table[table_idx].name);
2545 idx = (int)STRLEN(string);
2547 string[idx++] = '>';
2548 string[idx] = NUL;
2549 return string;
2553 * Try translating a <> name at (*srcp)[] to dst[].
2554 * Return the number of characters added to dst[], zero for no match.
2555 * If there is a match, srcp is advanced to after the <> name.
2556 * dst[] must be big enough to hold the result (up to six characters)!
2559 trans_special(srcp, dst, keycode)
2560 char_u **srcp;
2561 char_u *dst;
2562 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2564 int modifiers = 0;
2565 int key;
2566 int dlen = 0;
2568 key = find_special_key(srcp, &modifiers, keycode);
2569 if (key == 0)
2570 return 0;
2572 /* Put the appropriate modifier in a string */
2573 if (modifiers != 0)
2575 dst[dlen++] = K_SPECIAL;
2576 dst[dlen++] = KS_MODIFIER;
2577 dst[dlen++] = modifiers;
2580 if (IS_SPECIAL(key))
2582 dst[dlen++] = K_SPECIAL;
2583 dst[dlen++] = KEY2TERMCAP0(key);
2584 dst[dlen++] = KEY2TERMCAP1(key);
2586 #ifdef FEAT_MBYTE
2587 else if (has_mbyte && !keycode)
2588 dlen += (*mb_char2bytes)(key, dst + dlen);
2589 #endif
2590 else if (keycode)
2591 dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2592 else
2593 dst[dlen++] = key;
2595 return dlen;
2599 * Try translating a <> name at (*srcp)[], return the key and modifiers.
2600 * srcp is advanced to after the <> name.
2601 * returns 0 if there is no match.
2604 find_special_key(srcp, modp, keycode)
2605 char_u **srcp;
2606 int *modp;
2607 int keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2609 char_u *last_dash;
2610 char_u *end_of_name;
2611 char_u *src;
2612 char_u *bp;
2613 int modifiers;
2614 int bit;
2615 int key;
2616 unsigned long n;
2618 src = *srcp;
2619 if (src[0] != '<')
2620 return 0;
2622 /* Find end of modifier list */
2623 last_dash = src;
2624 for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2626 if (*bp == '-')
2628 last_dash = bp;
2629 if (bp[1] != NUL && bp[2] == '>')
2630 ++bp; /* anything accepted, like <C-?> */
2632 if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2633 bp += 3; /* skip t_xx, xx may be '-' or '>' */
2636 if (*bp == '>') /* found matching '>' */
2638 end_of_name = bp + 1;
2640 if (STRNICMP(src + 1, "char-", 5) == 0 && VIM_ISDIGIT(src[6]))
2642 /* <Char-123> or <Char-033> or <Char-0x33> */
2643 vim_str2nr(src + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2644 *modp = 0;
2645 *srcp = end_of_name;
2646 return (int)n;
2649 /* Which modifiers are given? */
2650 modifiers = 0x0;
2651 for (bp = src + 1; bp < last_dash; bp++)
2653 if (*bp != '-')
2655 bit = name_to_mod_mask(*bp);
2656 if (bit == 0x0)
2657 break; /* Illegal modifier name */
2658 modifiers |= bit;
2663 * Legal modifier name.
2665 if (bp >= last_dash)
2668 * Modifier with single letter, or special key name.
2670 if (modifiers != 0 && last_dash[2] == '>')
2671 key = last_dash[1];
2672 else
2674 key = get_special_key_code(last_dash + 1);
2675 key = handle_x_keys(key);
2679 * get_special_key_code() may return NUL for invalid
2680 * special key name.
2682 if (key != NUL)
2685 * Only use a modifier when there is no special key code that
2686 * includes the modifier.
2688 key = simplify_key(key, &modifiers);
2690 if (!keycode)
2692 /* don't want keycode, use single byte code */
2693 if (key == K_BS)
2694 key = BS;
2695 else if (key == K_DEL || key == K_KDEL)
2696 key = DEL;
2700 * Normal Key with modifier: Try to make a single byte code.
2702 if (!IS_SPECIAL(key))
2703 key = extract_modifiers(key, &modifiers);
2705 *modp = modifiers;
2706 *srcp = end_of_name;
2707 return key;
2711 return 0;
2715 * Try to include modifiers in the key.
2716 * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2719 extract_modifiers(key, modp)
2720 int key;
2721 int *modp;
2723 int modifiers = *modp;
2725 #ifdef MACOS
2726 /* Command-key really special, No fancynest */
2727 if (!(modifiers & MOD_MASK_CMD))
2728 #endif
2729 if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2731 key = TOUPPER_ASC(key);
2732 modifiers &= ~MOD_MASK_SHIFT;
2734 if ((modifiers & MOD_MASK_CTRL)
2735 #ifdef EBCDIC
2736 /* * TODO: EBCDIC Better use:
2737 * && (Ctrl_chr(key) || key == '?')
2738 * ??? */
2739 && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2740 != NULL
2741 #else
2742 && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2743 #endif
2746 key = Ctrl_chr(key);
2747 modifiers &= ~MOD_MASK_CTRL;
2748 /* <C-@> is <Nul> */
2749 if (key == 0)
2750 key = K_ZERO;
2752 #ifdef MACOS
2753 /* Command-key really special, No fancynest */
2754 if (!(modifiers & MOD_MASK_CMD))
2755 #endif
2756 if ((modifiers & MOD_MASK_ALT) && key < 0x80
2757 #ifdef FEAT_MBYTE
2758 && !enc_dbcs /* avoid creating a lead byte */
2759 #endif
2762 key |= 0x80;
2763 modifiers &= ~MOD_MASK_ALT; /* remove the META modifier */
2766 *modp = modifiers;
2767 return key;
2771 * Try to find key "c" in the special key table.
2772 * Return the index when found, -1 when not found.
2775 find_special_key_in_table(c)
2776 int c;
2778 int i;
2780 for (i = 0; key_names_table[i].name != NULL; i++)
2781 if (c == key_names_table[i].key)
2782 break;
2783 if (key_names_table[i].name == NULL)
2784 i = -1;
2785 return i;
2789 * Find the special key with the given name (the given string does not have to
2790 * end with NUL, the name is assumed to end before the first non-idchar).
2791 * If the name starts with "t_" the next two characters are interpreted as a
2792 * termcap name.
2793 * Return the key code, or 0 if not found.
2796 get_special_key_code(name)
2797 char_u *name;
2799 char_u *table_name;
2800 char_u string[3];
2801 int i, j;
2804 * If it's <t_xx> we get the code for xx from the termcap
2806 if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2808 string[0] = name[2];
2809 string[1] = name[3];
2810 string[2] = NUL;
2811 if (add_termcap_entry(string, FALSE) == OK)
2812 return TERMCAP2KEY(name[2], name[3]);
2814 else
2815 for (i = 0; key_names_table[i].name != NULL; i++)
2817 table_name = key_names_table[i].name;
2818 for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
2819 if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
2820 break;
2821 if (!vim_isIDc(name[j]) && table_name[j] == NUL)
2822 return key_names_table[i].key;
2824 return 0;
2827 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2828 char_u *
2829 get_key_name(i)
2830 int i;
2832 if (i >= KEY_NAMES_TABLE_LEN)
2833 return NULL;
2834 return key_names_table[i].name;
2836 #endif
2838 #if defined(FEAT_MOUSE) || defined(PROTO)
2840 * Look up the given mouse code to return the relevant information in the other
2841 * arguments. Return which button is down or was released.
2844 get_mouse_button(code, is_click, is_drag)
2845 int code;
2846 int *is_click;
2847 int *is_drag;
2849 int i;
2851 for (i = 0; mouse_table[i].pseudo_code; i++)
2852 if (code == mouse_table[i].pseudo_code)
2854 *is_click = mouse_table[i].is_click;
2855 *is_drag = mouse_table[i].is_drag;
2856 return mouse_table[i].button;
2858 return 0; /* Shouldn't get here */
2862 * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
2863 * the given information about which mouse button is down, and whether the
2864 * mouse was clicked, dragged or released.
2867 get_pseudo_mouse_code(button, is_click, is_drag)
2868 int button; /* eg MOUSE_LEFT */
2869 int is_click;
2870 int is_drag;
2872 int i;
2874 for (i = 0; mouse_table[i].pseudo_code; i++)
2875 if (button == mouse_table[i].button
2876 && is_click == mouse_table[i].is_click
2877 && is_drag == mouse_table[i].is_drag)
2879 #ifdef FEAT_GUI
2880 /* Trick: a non mappable left click and release has mouse_col -1
2881 * or added MOUSE_COLOFF. Used for 'mousefocus' in
2882 * gui_mouse_moved() */
2883 if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
2885 if (mouse_col < 0)
2886 mouse_col = 0;
2887 else
2888 mouse_col -= MOUSE_COLOFF;
2889 if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
2890 return (int)KE_LEFTMOUSE_NM;
2891 if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
2892 return (int)KE_LEFTRELEASE_NM;
2894 #endif
2895 return mouse_table[i].pseudo_code;
2897 return (int)KE_IGNORE; /* not recognized, ignore it */
2899 #endif /* FEAT_MOUSE */
2902 * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
2905 get_fileformat(buf)
2906 buf_T *buf;
2908 int c = *buf->b_p_ff;
2910 if (buf->b_p_bin || c == 'u')
2911 return EOL_UNIX;
2912 if (c == 'm')
2913 return EOL_MAC;
2914 return EOL_DOS;
2918 * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
2919 * argument.
2922 get_fileformat_force(buf, eap)
2923 buf_T *buf;
2924 exarg_T *eap; /* can be NULL! */
2926 int c;
2928 if (eap != NULL && eap->force_ff != 0)
2929 c = eap->cmd[eap->force_ff];
2930 else
2932 if ((eap != NULL && eap->force_bin != 0)
2933 ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
2934 return EOL_UNIX;
2935 c = *buf->b_p_ff;
2937 if (c == 'u')
2938 return EOL_UNIX;
2939 if (c == 'm')
2940 return EOL_MAC;
2941 return EOL_DOS;
2945 * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
2946 * Sets both 'textmode' and 'fileformat'.
2947 * Note: Does _not_ set global value of 'textmode'!
2949 void
2950 set_fileformat(t, opt_flags)
2951 int t;
2952 int opt_flags; /* OPT_LOCAL and/or OPT_GLOBAL */
2954 char *p = NULL;
2956 switch (t)
2958 case EOL_DOS:
2959 p = FF_DOS;
2960 curbuf->b_p_tx = TRUE;
2961 break;
2962 case EOL_UNIX:
2963 p = FF_UNIX;
2964 curbuf->b_p_tx = FALSE;
2965 break;
2966 case EOL_MAC:
2967 p = FF_MAC;
2968 curbuf->b_p_tx = FALSE;
2969 break;
2971 if (p != NULL)
2972 set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
2973 OPT_FREE | opt_flags, 0);
2975 #ifdef FEAT_WINDOWS
2976 /* This may cause the buffer to become (un)modified. */
2977 check_status(curbuf);
2978 redraw_tabline = TRUE;
2979 #endif
2980 #ifdef FEAT_TITLE
2981 need_maketitle = TRUE; /* set window title later */
2982 #endif
2986 * Return the default fileformat from 'fileformats'.
2989 default_fileformat()
2991 switch (*p_ffs)
2993 case 'm': return EOL_MAC;
2994 case 'd': return EOL_DOS;
2996 return EOL_UNIX;
3000 * Call shell. Calls mch_call_shell, with 'shellxquote' added.
3003 call_shell(cmd, opt)
3004 char_u *cmd;
3005 int opt;
3007 char_u *ncmd;
3008 int retval;
3009 #ifdef FEAT_PROFILE
3010 proftime_T wait_time;
3011 #endif
3013 if (p_verbose > 3)
3015 verbose_enter();
3016 smsg((char_u *)_("Calling shell to execute: \"%s\""),
3017 cmd == NULL ? p_sh : cmd);
3018 out_char('\n');
3019 cursor_on();
3020 verbose_leave();
3023 #ifdef FEAT_PROFILE
3024 if (do_profiling == PROF_YES)
3025 prof_child_enter(&wait_time);
3026 #endif
3028 if (*p_sh == NUL)
3030 EMSG(_(e_shellempty));
3031 retval = -1;
3033 else
3035 #ifdef FEAT_GUI_MSWIN
3036 /* Don't hide the pointer while executing a shell command. */
3037 gui_mch_mousehide(FALSE);
3038 #endif
3039 #ifdef FEAT_GUI
3040 ++hold_gui_events;
3041 #endif
3042 /* The external command may update a tags file, clear cached tags. */
3043 tag_freematch();
3045 if (cmd == NULL || *p_sxq == NUL)
3046 retval = mch_call_shell(cmd, opt);
3047 else
3049 ncmd = alloc((unsigned)(STRLEN(cmd) + STRLEN(p_sxq) * 2 + 1));
3050 if (ncmd != NULL)
3052 STRCPY(ncmd, p_sxq);
3053 STRCAT(ncmd, cmd);
3054 STRCAT(ncmd, p_sxq);
3055 retval = mch_call_shell(ncmd, opt);
3056 vim_free(ncmd);
3058 else
3059 retval = -1;
3061 #ifdef FEAT_GUI
3062 --hold_gui_events;
3063 #endif
3065 * Check the window size, in case it changed while executing the
3066 * external command.
3068 shell_resized_check();
3071 #ifdef FEAT_EVAL
3072 set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
3073 # ifdef FEAT_PROFILE
3074 if (do_profiling == PROF_YES)
3075 prof_child_exit(&wait_time);
3076 # endif
3077 #endif
3079 return retval;
3083 * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to
3084 * NORMAL State with a condition. This function returns the real State.
3087 get_real_state()
3089 if (State & NORMAL)
3091 #ifdef FEAT_VISUAL
3092 if (VIsual_active)
3094 if (VIsual_select)
3095 return SELECTMODE;
3096 return VISUAL;
3098 else
3099 #endif
3100 if (finish_op)
3101 return OP_PENDING;
3103 return State;
3106 #if defined(FEAT_MBYTE) || defined(PROTO)
3108 * Return TRUE if "p" points to just after a path separator.
3109 * Take care of multi-byte characters.
3110 * "b" must point to the start of the file name
3113 after_pathsep(b, p)
3114 char_u *b;
3115 char_u *p;
3117 return vim_ispathsep(p[-1])
3118 && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
3120 #endif
3123 * Return TRUE if file names "f1" and "f2" are in the same directory.
3124 * "f1" may be a short name, "f2" must be a full path.
3127 same_directory(f1, f2)
3128 char_u *f1;
3129 char_u *f2;
3131 char_u ffname[MAXPATHL];
3132 char_u *t1;
3133 char_u *t2;
3135 /* safety check */
3136 if (f1 == NULL || f2 == NULL)
3137 return FALSE;
3139 (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
3140 t1 = gettail_sep(ffname);
3141 t2 = gettail_sep(f2);
3142 return (t1 - ffname == t2 - f2
3143 && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
3146 #if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
3147 || ((defined(FEAT_GUI_GTK)) \
3148 && ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
3149 || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
3150 || defined(PROTO)
3152 * Change to a file's directory.
3153 * Caller must call shorten_fnames()!
3154 * Return OK or FAIL.
3157 vim_chdirfile(fname)
3158 char_u *fname;
3160 char_u dir[MAXPATHL];
3162 vim_strncpy(dir, fname, MAXPATHL - 1);
3163 *gettail_sep(dir) = NUL;
3164 return mch_chdir((char *)dir) == 0 ? OK : FAIL;
3166 #endif
3168 #if defined(STAT_IGNORES_SLASH) || defined(PROTO)
3170 * Check if "name" ends in a slash and is not a directory.
3171 * Used for systems where stat() ignores a trailing slash on a file name.
3172 * The Vim code assumes a trailing slash is only ignored for a directory.
3175 illegal_slash(name)
3176 char *name;
3178 if (name[0] == NUL)
3179 return FALSE; /* no file name is not illegal */
3180 if (name[strlen(name) - 1] != '/')
3181 return FALSE; /* no trailing slash */
3182 if (mch_isdir((char_u *)name))
3183 return FALSE; /* trailing slash for a directory */
3184 return TRUE;
3186 #endif
3188 #if defined(CURSOR_SHAPE) || defined(PROTO)
3191 * Handling of cursor and mouse pointer shapes in various modes.
3194 cursorentry_T shape_table[SHAPE_IDX_COUNT] =
3196 /* The values will be filled in from the 'guicursor' and 'mouseshape'
3197 * defaults when Vim starts.
3198 * Adjust the SHAPE_IDX_ defines when making changes! */
3199 {0, 0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
3200 {0, 0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
3201 {0, 0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
3202 {0, 0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
3203 {0, 0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
3204 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
3205 {0, 0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
3206 {0, 0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
3207 {0, 0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
3208 {0, 0, 0, 0L, 0L, 0L, 0, 0, "e", SHAPE_MOUSE},
3209 {0, 0, 0, 0L, 0L, 0L, 0, 0, "s", SHAPE_MOUSE},
3210 {0, 0, 0, 0L, 0L, 0L, 0, 0, "sd", SHAPE_MOUSE},
3211 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vs", SHAPE_MOUSE},
3212 {0, 0, 0, 0L, 0L, 0L, 0, 0, "vd", SHAPE_MOUSE},
3213 {0, 0, 0, 0L, 0L, 0L, 0, 0, "m", SHAPE_MOUSE},
3214 {0, 0, 0, 0L, 0L, 0L, 0, 0, "ml", SHAPE_MOUSE},
3215 {0, 0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
3218 #ifdef FEAT_MOUSESHAPE
3220 * Table with names for mouse shapes. Keep in sync with all the tables for
3221 * mch_set_mouse_shape()!.
3223 static char * mshape_names[] =
3225 "arrow", /* default, must be the first one */
3226 "blank", /* hidden */
3227 "beam",
3228 "updown",
3229 "udsizing",
3230 "leftright",
3231 "lrsizing",
3232 "busy",
3233 "no",
3234 "crosshair",
3235 "hand1",
3236 "hand2",
3237 "pencil",
3238 "question",
3239 "rightup-arrow",
3240 "up-arrow",
3241 NULL
3243 #endif
3246 * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
3247 * ("what" is SHAPE_MOUSE).
3248 * Returns error message for an illegal option, NULL otherwise.
3250 char_u *
3251 parse_shape_opt(what)
3252 int what;
3254 char_u *modep;
3255 char_u *colonp;
3256 char_u *commap;
3257 char_u *slashp;
3258 char_u *p, *endp;
3259 int idx = 0; /* init for GCC */
3260 int all_idx;
3261 int len;
3262 int i;
3263 long n;
3264 int found_ve = FALSE; /* found "ve" flag */
3265 int round;
3268 * First round: check for errors; second round: do it for real.
3270 for (round = 1; round <= 2; ++round)
3273 * Repeat for all comma separated parts.
3275 #ifdef FEAT_MOUSESHAPE
3276 if (what == SHAPE_MOUSE)
3277 modep = p_mouseshape;
3278 else
3279 #endif
3280 modep = p_guicursor;
3281 while (*modep != NUL)
3283 colonp = vim_strchr(modep, ':');
3284 if (colonp == NULL)
3285 return (char_u *)N_("E545: Missing colon");
3286 if (colonp == modep)
3287 return (char_u *)N_("E546: Illegal mode");
3288 commap = vim_strchr(modep, ',');
3291 * Repeat for all mode's before the colon.
3292 * For the 'a' mode, we loop to handle all the modes.
3294 all_idx = -1;
3295 while (modep < colonp || all_idx >= 0)
3297 if (all_idx < 0)
3299 /* Find the mode. */
3300 if (modep[1] == '-' || modep[1] == ':')
3301 len = 1;
3302 else
3303 len = 2;
3304 if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
3305 all_idx = SHAPE_IDX_COUNT - 1;
3306 else
3308 for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
3309 if (STRNICMP(modep, shape_table[idx].name, len)
3310 == 0)
3311 break;
3312 if (idx == SHAPE_IDX_COUNT
3313 || (shape_table[idx].used_for & what) == 0)
3314 return (char_u *)N_("E546: Illegal mode");
3315 if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
3316 found_ve = TRUE;
3318 modep += len + 1;
3321 if (all_idx >= 0)
3322 idx = all_idx--;
3323 else if (round == 2)
3325 #ifdef FEAT_MOUSESHAPE
3326 if (what == SHAPE_MOUSE)
3328 /* Set the default, for the missing parts */
3329 shape_table[idx].mshape = 0;
3331 else
3332 #endif
3334 /* Set the defaults, for the missing parts */
3335 shape_table[idx].shape = SHAPE_BLOCK;
3336 shape_table[idx].blinkwait = 700L;
3337 shape_table[idx].blinkon = 400L;
3338 shape_table[idx].blinkoff = 250L;
3342 /* Parse the part after the colon */
3343 for (p = colonp + 1; *p && *p != ','; )
3345 #ifdef FEAT_MOUSESHAPE
3346 if (what == SHAPE_MOUSE)
3348 for (i = 0; ; ++i)
3350 if (mshape_names[i] == NULL)
3352 if (!VIM_ISDIGIT(*p))
3353 return (char_u *)N_("E547: Illegal mouseshape");
3354 if (round == 2)
3355 shape_table[idx].mshape =
3356 getdigits(&p) + MSHAPE_NUMBERED;
3357 else
3358 (void)getdigits(&p);
3359 break;
3361 len = (int)STRLEN(mshape_names[i]);
3362 if (STRNICMP(p, mshape_names[i], len) == 0)
3364 if (round == 2)
3365 shape_table[idx].mshape = i;
3366 p += len;
3367 break;
3371 else /* if (what == SHAPE_MOUSE) */
3372 #endif
3375 * First handle the ones with a number argument.
3377 i = *p;
3378 len = 0;
3379 if (STRNICMP(p, "ver", 3) == 0)
3380 len = 3;
3381 else if (STRNICMP(p, "hor", 3) == 0)
3382 len = 3;
3383 else if (STRNICMP(p, "blinkwait", 9) == 0)
3384 len = 9;
3385 else if (STRNICMP(p, "blinkon", 7) == 0)
3386 len = 7;
3387 else if (STRNICMP(p, "blinkoff", 8) == 0)
3388 len = 8;
3389 if (len != 0)
3391 p += len;
3392 if (!VIM_ISDIGIT(*p))
3393 return (char_u *)N_("E548: digit expected");
3394 n = getdigits(&p);
3395 if (len == 3) /* "ver" or "hor" */
3397 if (n == 0)
3398 return (char_u *)N_("E549: Illegal percentage");
3399 if (round == 2)
3401 if (TOLOWER_ASC(i) == 'v')
3402 shape_table[idx].shape = SHAPE_VER;
3403 else
3404 shape_table[idx].shape = SHAPE_HOR;
3405 shape_table[idx].percentage = n;
3408 else if (round == 2)
3410 if (len == 9)
3411 shape_table[idx].blinkwait = n;
3412 else if (len == 7)
3413 shape_table[idx].blinkon = n;
3414 else
3415 shape_table[idx].blinkoff = n;
3418 else if (STRNICMP(p, "block", 5) == 0)
3420 if (round == 2)
3421 shape_table[idx].shape = SHAPE_BLOCK;
3422 p += 5;
3424 else /* must be a highlight group name then */
3426 endp = vim_strchr(p, '-');
3427 if (commap == NULL) /* last part */
3429 if (endp == NULL)
3430 endp = p + STRLEN(p); /* find end of part */
3432 else if (endp > commap || endp == NULL)
3433 endp = commap;
3434 slashp = vim_strchr(p, '/');
3435 if (slashp != NULL && slashp < endp)
3437 /* "group/langmap_group" */
3438 i = syn_check_group(p, (int)(slashp - p));
3439 p = slashp + 1;
3441 if (round == 2)
3443 shape_table[idx].id = syn_check_group(p,
3444 (int)(endp - p));
3445 shape_table[idx].id_lm = shape_table[idx].id;
3446 if (slashp != NULL && slashp < endp)
3447 shape_table[idx].id = i;
3449 p = endp;
3451 } /* if (what != SHAPE_MOUSE) */
3453 if (*p == '-')
3454 ++p;
3457 modep = p;
3458 if (*modep == ',')
3459 ++modep;
3463 /* If the 's' flag is not given, use the 'v' cursor for 's' */
3464 if (!found_ve)
3466 #ifdef FEAT_MOUSESHAPE
3467 if (what == SHAPE_MOUSE)
3469 shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3471 else
3472 #endif
3474 shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3475 shape_table[SHAPE_IDX_VE].percentage =
3476 shape_table[SHAPE_IDX_V].percentage;
3477 shape_table[SHAPE_IDX_VE].blinkwait =
3478 shape_table[SHAPE_IDX_V].blinkwait;
3479 shape_table[SHAPE_IDX_VE].blinkon =
3480 shape_table[SHAPE_IDX_V].blinkon;
3481 shape_table[SHAPE_IDX_VE].blinkoff =
3482 shape_table[SHAPE_IDX_V].blinkoff;
3483 shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3484 shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3488 return NULL;
3491 # if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
3492 || defined(FEAT_MOUSESHAPE) || defined(PROTO)
3494 * Return the index into shape_table[] for the current mode.
3495 * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3498 get_shape_idx(mouse)
3499 int mouse;
3501 #ifdef FEAT_MOUSESHAPE
3502 if (mouse && (State == HITRETURN || State == ASKMORE))
3504 # ifdef FEAT_GUI
3505 int x, y;
3506 gui_mch_getmouse(&x, &y);
3507 if (Y_2_ROW(y) == Rows - 1)
3508 return SHAPE_IDX_MOREL;
3509 # endif
3510 return SHAPE_IDX_MORE;
3512 if (mouse && drag_status_line)
3513 return SHAPE_IDX_SDRAG;
3514 # ifdef FEAT_VERTSPLIT
3515 if (mouse && drag_sep_line)
3516 return SHAPE_IDX_VDRAG;
3517 # endif
3518 #endif
3519 if (!mouse && State == SHOWMATCH)
3520 return SHAPE_IDX_SM;
3521 #ifdef FEAT_VREPLACE
3522 if (State & VREPLACE_FLAG)
3523 return SHAPE_IDX_R;
3524 #endif
3525 if (State & REPLACE_FLAG)
3526 return SHAPE_IDX_R;
3527 if (State & INSERT)
3528 return SHAPE_IDX_I;
3529 if (State & CMDLINE)
3531 if (cmdline_at_end())
3532 return SHAPE_IDX_C;
3533 if (cmdline_overstrike())
3534 return SHAPE_IDX_CR;
3535 return SHAPE_IDX_CI;
3537 if (finish_op)
3538 return SHAPE_IDX_O;
3539 #ifdef FEAT_VISUAL
3540 if (VIsual_active)
3542 if (*p_sel == 'e')
3543 return SHAPE_IDX_VE;
3544 else
3545 return SHAPE_IDX_V;
3547 #endif
3548 return SHAPE_IDX_N;
3550 #endif
3552 # if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3553 static int old_mouse_shape = 0;
3556 * Set the mouse shape:
3557 * If "shape" is -1, use shape depending on the current mode,
3558 * depending on the current state.
3559 * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3560 * when the mouse moves off the status or command line).
3562 void
3563 update_mouseshape(shape_idx)
3564 int shape_idx;
3566 int new_mouse_shape;
3568 /* Only works in GUI mode. */
3569 if (!gui.in_use || gui.starting)
3570 return;
3572 /* Postpone the updating when more is to come. Speeds up executing of
3573 * mappings. */
3574 if (shape_idx == -1 && char_avail())
3576 postponed_mouseshape = TRUE;
3577 return;
3580 /* When ignoring the mouse don't change shape on the statusline. */
3581 if (*p_mouse == NUL
3582 && (shape_idx == SHAPE_IDX_CLINE
3583 || shape_idx == SHAPE_IDX_STATUS
3584 || shape_idx == SHAPE_IDX_VSEP))
3585 shape_idx = -2;
3587 if (shape_idx == -2
3588 && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3589 && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3590 && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3591 return;
3592 if (shape_idx < 0)
3593 new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3594 else
3595 new_mouse_shape = shape_table[shape_idx].mshape;
3596 if (new_mouse_shape != old_mouse_shape)
3598 mch_set_mouse_shape(new_mouse_shape);
3599 old_mouse_shape = new_mouse_shape;
3601 postponed_mouseshape = FALSE;
3603 # endif
3605 #endif /* CURSOR_SHAPE */
3608 #ifdef FEAT_CRYPT
3610 * Optional encryption support.
3611 * Mohsin Ahmed, mosh@sasi.com, 98-09-24
3612 * Based on zip/crypt sources.
3614 * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3615 * most countries. There are a few exceptions, but that still should not be a
3616 * problem since this code was originally created in Europe and India.
3619 /* from zip.h */
3621 typedef unsigned short ush; /* unsigned 16-bit value */
3622 typedef unsigned long ulg; /* unsigned 32-bit value */
3624 static void make_crc_tab __ARGS((void));
3626 static ulg crc_32_tab[256];
3629 * Fill the CRC table.
3631 static void
3632 make_crc_tab()
3634 ulg s,t,v;
3635 static int done = FALSE;
3637 if (done)
3638 return;
3639 for (t = 0; t < 256; t++)
3641 v = t;
3642 for (s = 0; s < 8; s++)
3643 v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3644 crc_32_tab[t] = v;
3646 done = TRUE;
3649 #define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3652 static ulg keys[3]; /* keys defining the pseudo-random sequence */
3655 * Return the next byte in the pseudo-random sequence
3658 decrypt_byte()
3660 ush temp;
3662 temp = (ush)keys[2] | 2;
3663 return (int)(((unsigned)(temp * (temp ^ 1)) >> 8) & 0xff);
3667 * Update the encryption keys with the next byte of plain text
3670 update_keys(c)
3671 int c; /* byte of plain text */
3673 keys[0] = CRC32(keys[0], c);
3674 keys[1] += keys[0] & 0xff;
3675 keys[1] = keys[1] * 134775813L + 1;
3676 keys[2] = CRC32(keys[2], (int)(keys[1] >> 24));
3677 return c;
3681 * Initialize the encryption keys and the random header according to
3682 * the given password.
3683 * If "passwd" is NULL or empty, don't do anything.
3685 void
3686 crypt_init_keys(passwd)
3687 char_u *passwd; /* password string with which to modify keys */
3689 if (passwd != NULL && *passwd != NUL)
3691 make_crc_tab();
3692 keys[0] = 305419896L;
3693 keys[1] = 591751049L;
3694 keys[2] = 878082192L;
3695 while (*passwd != '\0')
3696 update_keys((int)*passwd++);
3701 * Ask the user for a crypt key.
3702 * When "store" is TRUE, the new key in stored in the 'key' option, and the
3703 * 'key' option value is returned: Don't free it.
3704 * When "store" is FALSE, the typed key is returned in allocated memory.
3705 * Returns NULL on failure.
3707 char_u *
3708 get_crypt_key(store, twice)
3709 int store;
3710 int twice; /* Ask for the key twice. */
3712 char_u *p1, *p2 = NULL;
3713 int round;
3715 for (round = 0; ; ++round)
3717 cmdline_star = TRUE;
3718 cmdline_row = msg_row;
3719 p1 = getcmdline_prompt(NUL, round == 0
3720 ? (char_u *)_("Enter encryption key: ")
3721 : (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING,
3722 NULL);
3723 cmdline_star = FALSE;
3725 if (p1 == NULL)
3726 break;
3728 if (round == twice)
3730 if (p2 != NULL && STRCMP(p1, p2) != 0)
3732 MSG(_("Keys don't match!"));
3733 vim_free(p1);
3734 vim_free(p2);
3735 p2 = NULL;
3736 round = -1; /* do it again */
3737 continue;
3739 if (store)
3741 set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
3742 vim_free(p1);
3743 p1 = curbuf->b_p_key;
3745 break;
3747 p2 = p1;
3750 /* since the user typed this, no need to wait for return */
3751 need_wait_return = FALSE;
3752 msg_didout = FALSE;
3754 vim_free(p2);
3755 return p1;
3758 #endif /* FEAT_CRYPT */
3760 /* TODO: make some #ifdef for this */
3761 /*--------[ file searching ]-------------------------------------------------*/
3763 * File searching functions for 'path', 'tags' and 'cdpath' options.
3764 * External visible functions:
3765 * vim_findfile_init() creates/initialises the search context
3766 * vim_findfile_free_visited() free list of visited files/dirs of search
3767 * context
3768 * vim_findfile() find a file in the search context
3769 * vim_findfile_cleanup() cleanup/free search context created by
3770 * vim_findfile_init()
3772 * All static functions and variables start with 'ff_'
3774 * In general it works like this:
3775 * First you create yourself a search context by calling vim_findfile_init().
3776 * It is possible to give a search context from a previous call to
3777 * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
3778 * until you are satisfied with the result or it returns NULL. On every call it
3779 * returns the next file which matches the conditions given to
3780 * vim_findfile_init(). If it doesn't find a next file it returns NULL.
3782 * It is possible to call vim_findfile_init() again to reinitialise your search
3783 * with some new parameters. Don't forget to pass your old search context to
3784 * it, so it can reuse it and especially reuse the list of already visited
3785 * directories. If you want to delete the list of already visited directories
3786 * simply call vim_findfile_free_visited().
3788 * When you are done call vim_findfile_cleanup() to free the search context.
3790 * The function vim_findfile_init() has a long comment, which describes the
3791 * needed parameters.
3795 * ATTENTION:
3796 * ==========
3797 * Also we use an allocated search context here, this functions are NOT
3798 * thread-safe!!!!!
3800 * To minimize parameter passing (or because I'm to lazy), only the
3801 * external visible functions get a search context as a parameter. This is
3802 * then assigned to a static global, which is used throughout the local
3803 * functions.
3807 * type for the directory search stack
3809 typedef struct ff_stack
3811 struct ff_stack *ffs_prev;
3813 /* the fix part (no wildcards) and the part containing the wildcards
3814 * of the search path
3816 char_u *ffs_fix_path;
3817 #ifdef FEAT_PATH_EXTRA
3818 char_u *ffs_wc_path;
3819 #endif
3821 /* files/dirs found in the above directory, matched by the first wildcard
3822 * of wc_part
3824 char_u **ffs_filearray;
3825 int ffs_filearray_size;
3826 char_u ffs_filearray_cur; /* needed for partly handled dirs */
3828 /* to store status of partly handled directories
3829 * 0: we work on this directory for the first time
3830 * 1: this directory was partly searched in an earlier step
3832 int ffs_stage;
3834 /* How deep are we in the directory tree?
3835 * Counts backward from value of level parameter to vim_findfile_init
3837 int ffs_level;
3839 /* Did we already expand '**' to an empty string? */
3840 int ffs_star_star_empty;
3841 } ff_stack_T;
3844 * type for already visited directories or files.
3846 typedef struct ff_visited
3848 struct ff_visited *ffv_next;
3850 #ifdef FEAT_PATH_EXTRA
3851 /* Visited directories are different if the wildcard string are
3852 * different. So we have to save it.
3854 char_u *ffv_wc_path;
3855 #endif
3856 /* for unix use inode etc for comparison (needed because of links), else
3857 * use filename.
3859 #ifdef UNIX
3860 int ffv_dev; /* device number (-1 if not set) */
3861 ino_t ffv_ino; /* inode number */
3862 #endif
3863 /* The memory for this struct is allocated according to the length of
3864 * ffv_fname.
3866 char_u ffv_fname[1]; /* actually longer */
3867 } ff_visited_T;
3870 * We might have to manage several visited lists during a search.
3871 * This is especially needed for the tags option. If tags is set to:
3872 * "./++/tags,./++/TAGS,++/tags" (replace + with *)
3873 * So we have to do 3 searches:
3874 * 1) search from the current files directory downward for the file "tags"
3875 * 2) search from the current files directory downward for the file "TAGS"
3876 * 3) search from Vims current directory downwards for the file "tags"
3877 * As you can see, the first and the third search are for the same file, so for
3878 * the third search we can use the visited list of the first search. For the
3879 * second search we must start from a empty visited list.
3880 * The struct ff_visited_list_hdr is used to manage a linked list of already
3881 * visited lists.
3883 typedef struct ff_visited_list_hdr
3885 struct ff_visited_list_hdr *ffvl_next;
3887 /* the filename the attached visited list is for */
3888 char_u *ffvl_filename;
3890 ff_visited_T *ffvl_visited_list;
3892 } ff_visited_list_hdr_T;
3896 * '**' can be expanded to several directory levels.
3897 * Set the default maximum depth.
3899 #define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
3902 * The search context:
3903 * ffsc_stack_ptr: the stack for the dirs to search
3904 * ffsc_visited_list: the currently active visited list
3905 * ffsc_dir_visited_list: the currently active visited list for search dirs
3906 * ffsc_visited_lists_list: the list of all visited lists
3907 * ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
3908 * ffsc_file_to_search: the file to search for
3909 * ffsc_start_dir: the starting directory, if search path was relative
3910 * ffsc_fix_path: the fix part of the given path (without wildcards)
3911 * Needed for upward search.
3912 * ffsc_wc_path: the part of the given path containing wildcards
3913 * ffsc_level: how many levels of dirs to search downwards
3914 * ffsc_stopdirs_v: array of stop directories for upward search
3915 * ffsc_find_what: FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
3917 typedef struct ff_search_ctx_T
3919 ff_stack_T *ffsc_stack_ptr;
3920 ff_visited_list_hdr_T *ffsc_visited_list;
3921 ff_visited_list_hdr_T *ffsc_dir_visited_list;
3922 ff_visited_list_hdr_T *ffsc_visited_lists_list;
3923 ff_visited_list_hdr_T *ffsc_dir_visited_lists_list;
3924 char_u *ffsc_file_to_search;
3925 char_u *ffsc_start_dir;
3926 char_u *ffsc_fix_path;
3927 #ifdef FEAT_PATH_EXTRA
3928 char_u *ffsc_wc_path;
3929 int ffsc_level;
3930 char_u **ffsc_stopdirs_v;
3931 #endif
3932 int ffsc_find_what;
3933 } ff_search_ctx_T;
3935 /* locally needed functions */
3936 #ifdef FEAT_PATH_EXTRA
3937 static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
3938 #else
3939 static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
3940 #endif
3941 static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
3942 static void ff_free_visited_list __ARGS((ff_visited_T *vl));
3943 static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
3944 #ifdef FEAT_PATH_EXTRA
3945 static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
3946 #endif
3948 static void ff_push __ARGS((ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr));
3949 static ff_stack_T *ff_pop __ARGS((ff_search_ctx_T *search_ctx));
3950 static void ff_clear __ARGS((ff_search_ctx_T *search_ctx));
3951 static void ff_free_stack_element __ARGS((ff_stack_T *stack_ptr));
3952 #ifdef FEAT_PATH_EXTRA
3953 static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
3954 #else
3955 static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
3956 #endif
3957 #ifdef FEAT_PATH_EXTRA
3958 static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
3959 #endif
3961 #if 0
3963 * if someone likes findfirst/findnext, here are the functions
3964 * NOT TESTED!!
3967 static void *ff_fn_search_context = NULL;
3969 char_u *
3970 vim_findfirst(path, filename, level)
3971 char_u *path;
3972 char_u *filename;
3973 int level;
3975 ff_fn_search_context =
3976 vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
3977 ff_fn_search_context, rel_fname);
3978 if (NULL == ff_fn_search_context)
3979 return NULL;
3980 else
3981 return vim_findnext()
3984 char_u *
3985 vim_findnext()
3987 char_u *ret = vim_findfile(ff_fn_search_context);
3989 if (NULL == ret)
3991 vim_findfile_cleanup(ff_fn_search_context);
3992 ff_fn_search_context = NULL;
3994 return ret;
3996 #endif
3999 * Initialization routine for vim_findfile.
4001 * Returns the newly allocated search context or NULL if an error occured.
4003 * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
4004 * with the search context.
4006 * Find the file 'filename' in the directory 'path'.
4007 * The parameter 'path' may contain wildcards. If so only search 'level'
4008 * directories deep. The parameter 'level' is the absolute maximum and is
4009 * not related to restricts given to the '**' wildcard. If 'level' is 100
4010 * and you use '**200' vim_findfile() will stop after 100 levels.
4012 * 'filename' cannot contain wildcards! It is used as-is, no backslashes to
4013 * escape special characters.
4015 * If 'stopdirs' is not NULL and nothing is found downward, the search is
4016 * restarted on the next higher directory level. This is repeated until the
4017 * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
4018 * format ";*<dirname>*\(;<dirname>\)*;\=$".
4020 * If the 'path' is relative, the starting dir for the search is either VIM's
4021 * current dir or if the path starts with "./" the current files dir.
4022 * If the 'path' is absolut, the starting dir is that part of the path before
4023 * the first wildcard.
4025 * Upward search is only done on the starting dir.
4027 * If 'free_visited' is TRUE the list of already visited files/directories is
4028 * cleared. Set this to FALSE if you just want to search from another
4029 * directory, but want to be sure that no directory from a previous search is
4030 * searched again. This is useful if you search for a file at different places.
4031 * The list of visited files/dirs can also be cleared with the function
4032 * vim_findfile_free_visited().
4034 * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
4035 * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
4037 * A search context returned by a previous call to vim_findfile_init() can be
4038 * passed in the parameter "search_ctx_arg". This context is reused and
4039 * reinitialized with the new parameters. The list of already visited
4040 * directories from this context is only deleted if the parameter
4041 * "free_visited" is true. Be aware that the passed "search_ctx_arg" is freed
4042 * if the reinitialization fails.
4044 * If you don't have a search context from a previous call "search_ctx_arg"
4045 * must be NULL.
4047 * This function silently ignores a few errors, vim_findfile() will have
4048 * limited functionality then.
4050 /*ARGSUSED*/
4051 void *
4052 vim_findfile_init(path, filename, stopdirs, level, free_visited, find_what,
4053 search_ctx_arg, tagfile, rel_fname)
4054 char_u *path;
4055 char_u *filename;
4056 char_u *stopdirs;
4057 int level;
4058 int free_visited;
4059 int find_what;
4060 void *search_ctx_arg;
4061 int tagfile;
4062 char_u *rel_fname; /* file name to use for "." */
4064 #ifdef FEAT_PATH_EXTRA
4065 char_u *wc_part;
4066 #endif
4067 ff_stack_T *sptr;
4068 ff_search_ctx_T *search_ctx;
4070 /* If a search context is given by the caller, reuse it, else allocate a
4071 * new one.
4073 if (search_ctx_arg != NULL)
4074 search_ctx = search_ctx_arg;
4075 else
4077 search_ctx = (ff_search_ctx_T*)alloc((unsigned)sizeof(ff_search_ctx_T));
4078 if (search_ctx == NULL)
4079 goto error_return;
4080 memset(search_ctx, 0, sizeof(ff_search_ctx_T));
4082 search_ctx->ffsc_find_what = find_what;
4084 /* clear the search context, but NOT the visited lists */
4085 ff_clear(search_ctx);
4087 /* clear visited list if wanted */
4088 if (free_visited == TRUE)
4089 vim_findfile_free_visited(search_ctx);
4090 else
4092 /* Reuse old visited lists. Get the visited list for the given
4093 * filename. If no list for the current filename exists, creates a new
4094 * one. */
4095 search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
4096 &search_ctx->ffsc_visited_lists_list);
4097 if (search_ctx->ffsc_visited_list == NULL)
4098 goto error_return;
4099 search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
4100 &search_ctx->ffsc_dir_visited_lists_list);
4101 if (search_ctx->ffsc_dir_visited_list == NULL)
4102 goto error_return;
4105 if (ff_expand_buffer == NULL)
4107 ff_expand_buffer = (char_u*)alloc(MAXPATHL);
4108 if (ff_expand_buffer == NULL)
4109 goto error_return;
4112 /* Store information on starting dir now if path is relative.
4113 * If path is absolute, we do that later. */
4114 if (path[0] == '.'
4115 && (vim_ispathsep(path[1]) || path[1] == NUL)
4116 && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
4117 && rel_fname != NULL)
4119 int len = (int)(gettail(rel_fname) - rel_fname);
4121 if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
4123 /* Make the start dir an absolute path name. */
4124 vim_strncpy(ff_expand_buffer, rel_fname, len);
4125 search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
4127 else
4128 search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
4129 if (search_ctx->ffsc_start_dir == NULL)
4130 goto error_return;
4131 if (*++path != NUL)
4132 ++path;
4134 else if (*path == NUL || !vim_isAbsName(path))
4136 #ifdef BACKSLASH_IN_FILENAME
4137 /* "c:dir" needs "c:" to be expanded, otherwise use current dir */
4138 if (*path != NUL && path[1] == ':')
4140 char_u drive[3];
4142 drive[0] = path[0];
4143 drive[1] = ':';
4144 drive[2] = NUL;
4145 if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4146 goto error_return;
4147 path += 2;
4149 else
4150 #endif
4151 if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
4152 goto error_return;
4154 search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
4155 if (search_ctx->ffsc_start_dir == NULL)
4156 goto error_return;
4158 #ifdef BACKSLASH_IN_FILENAME
4159 /* A path that starts with "/dir" is relative to the drive, not to the
4160 * directory (but not for "//machine/dir"). Only use the drive name. */
4161 if ((*path == '/' || *path == '\\')
4162 && path[1] != path[0]
4163 && search_ctx->ffsc_start_dir[1] == ':')
4164 search_ctx->ffsc_start_dir[2] = NUL;
4165 #endif
4168 #ifdef FEAT_PATH_EXTRA
4170 * If stopdirs are given, split them into an array of pointers.
4171 * If this fails (mem allocation), there is no upward search at all or a
4172 * stop directory is not recognized -> continue silently.
4173 * If stopdirs just contains a ";" or is empty,
4174 * search_ctx->ffsc_stopdirs_v will only contain a NULL pointer. This
4175 * is handled as unlimited upward search. See function
4176 * ff_path_in_stoplist() for details.
4178 if (stopdirs != NULL)
4180 char_u *walker = stopdirs;
4181 int dircount;
4183 while (*walker == ';')
4184 walker++;
4186 dircount = 1;
4187 search_ctx->ffsc_stopdirs_v =
4188 (char_u **)alloc((unsigned)sizeof(char_u *));
4190 if (search_ctx->ffsc_stopdirs_v != NULL)
4194 char_u *helper;
4195 void *ptr;
4197 helper = walker;
4198 ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
4199 (dircount + 1) * sizeof(char_u *));
4200 if (ptr)
4201 search_ctx->ffsc_stopdirs_v = ptr;
4202 else
4203 /* ignore, keep what we have and continue */
4204 break;
4205 walker = vim_strchr(walker, ';');
4206 if (walker)
4208 search_ctx->ffsc_stopdirs_v[dircount-1] =
4209 vim_strnsave(helper, (int)(walker - helper));
4210 walker++;
4212 else
4213 /* this might be "", which means ascent till top
4214 * of directory tree.
4216 search_ctx->ffsc_stopdirs_v[dircount-1] =
4217 vim_strsave(helper);
4219 dircount++;
4221 } while (walker != NULL);
4222 search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
4225 #endif
4227 #ifdef FEAT_PATH_EXTRA
4228 search_ctx->ffsc_level = level;
4230 /* split into:
4231 * -fix path
4232 * -wildcard_stuff (might be NULL)
4234 wc_part = vim_strchr(path, '*');
4235 if (wc_part != NULL)
4237 int llevel;
4238 int len;
4239 char *errpt;
4241 /* save the fix part of the path */
4242 search_ctx->ffsc_fix_path = vim_strnsave(path, (int)(wc_part - path));
4245 * copy wc_path and add restricts to the '**' wildcard.
4246 * The octet after a '**' is used as a (binary) counter.
4247 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
4248 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
4249 * For EBCDIC you get different character values.
4250 * If no restrict is given after '**' the default is used.
4251 * Due to this technic the path looks awful if you print it as a
4252 * string.
4254 len = 0;
4255 while (*wc_part != NUL)
4257 if (STRNCMP(wc_part, "**", 2) == 0)
4259 ff_expand_buffer[len++] = *wc_part++;
4260 ff_expand_buffer[len++] = *wc_part++;
4262 llevel = strtol((char *)wc_part, &errpt, 10);
4263 if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
4264 ff_expand_buffer[len++] = llevel;
4265 else if ((char_u *)errpt != wc_part && llevel == 0)
4266 /* restrict is 0 -> remove already added '**' */
4267 len -= 2;
4268 else
4269 ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
4270 wc_part = (char_u *)errpt;
4271 if (*wc_part != NUL && !vim_ispathsep(*wc_part))
4273 EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
4274 goto error_return;
4277 else
4278 ff_expand_buffer[len++] = *wc_part++;
4280 ff_expand_buffer[len] = NUL;
4281 search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
4283 if (search_ctx->ffsc_wc_path == NULL)
4284 goto error_return;
4286 else
4287 #endif
4288 search_ctx->ffsc_fix_path = vim_strsave(path);
4290 if (search_ctx->ffsc_start_dir == NULL)
4292 /* store the fix part as startdir.
4293 * This is needed if the parameter path is fully qualified.
4295 search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
4296 if (search_ctx->ffsc_start_dir)
4297 search_ctx->ffsc_fix_path[0] = NUL;
4300 /* create an absolute path */
4301 STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
4302 add_pathsep(ff_expand_buffer);
4303 STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
4304 add_pathsep(ff_expand_buffer);
4306 sptr = ff_create_stack_element(ff_expand_buffer,
4307 #ifdef FEAT_PATH_EXTRA
4308 search_ctx->ffsc_wc_path,
4309 #endif
4310 level, 0);
4312 if (sptr == NULL)
4313 goto error_return;
4315 ff_push(search_ctx, sptr);
4317 search_ctx->ffsc_file_to_search = vim_strsave(filename);
4318 if (search_ctx->ffsc_file_to_search == NULL)
4319 goto error_return;
4321 return search_ctx;
4323 error_return:
4325 * We clear the search context now!
4326 * Even when the caller gave us a (perhaps valid) context we free it here,
4327 * as we might have already destroyed it.
4329 vim_findfile_cleanup(search_ctx);
4330 return NULL;
4333 #if defined(FEAT_PATH_EXTRA) || defined(PROTO)
4335 * Get the stopdir string. Check that ';' is not escaped.
4337 char_u *
4338 vim_findfile_stopdir(buf)
4339 char_u *buf;
4341 char_u *r_ptr = buf;
4343 while (*r_ptr != NUL && *r_ptr != ';')
4345 if (r_ptr[0] == '\\' && r_ptr[1] == ';')
4347 /* overwrite the escape char,
4348 * use STRLEN(r_ptr) to move the trailing '\0'
4350 STRMOVE(r_ptr, r_ptr + 1);
4351 r_ptr++;
4353 r_ptr++;
4355 if (*r_ptr == ';')
4357 *r_ptr = 0;
4358 r_ptr++;
4360 else if (*r_ptr == NUL)
4361 r_ptr = NULL;
4362 return r_ptr;
4364 #endif
4367 * Clean up the given search context. Can handle a NULL pointer.
4369 void
4370 vim_findfile_cleanup(ctx)
4371 void *ctx;
4373 if (ctx == NULL)
4374 return;
4376 vim_findfile_free_visited(ctx);
4377 ff_clear(ctx);
4378 vim_free(ctx);
4382 * Find a file in a search context.
4383 * The search context was created with vim_findfile_init() above.
4384 * Return a pointer to an allocated file name or NULL if nothing found.
4385 * To get all matching files call this function until you get NULL.
4387 * If the passed search_context is NULL, NULL is returned.
4389 * The search algorithm is depth first. To change this replace the
4390 * stack with a list (don't forget to leave partly searched directories on the
4391 * top of the list).
4393 char_u *
4394 vim_findfile(search_ctx_arg)
4395 void *search_ctx_arg;
4397 char_u *file_path;
4398 #ifdef FEAT_PATH_EXTRA
4399 char_u *rest_of_wildcards;
4400 char_u *path_end = NULL;
4401 #endif
4402 ff_stack_T *stackp;
4403 #if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
4404 int len;
4405 #endif
4406 int i;
4407 char_u *p;
4408 #ifdef FEAT_SEARCHPATH
4409 char_u *suf;
4410 #endif
4411 ff_search_ctx_T *search_ctx;
4413 if (search_ctx_arg == NULL)
4414 return NULL;
4416 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
4419 * filepath is used as buffer for various actions and as the storage to
4420 * return a found filename.
4422 if ((file_path = alloc((int)MAXPATHL)) == NULL)
4423 return NULL;
4425 #ifdef FEAT_PATH_EXTRA
4426 /* store the end of the start dir -- needed for upward search */
4427 if (search_ctx->ffsc_start_dir != NULL)
4428 path_end = &search_ctx->ffsc_start_dir[
4429 STRLEN(search_ctx->ffsc_start_dir)];
4430 #endif
4432 #ifdef FEAT_PATH_EXTRA
4433 /* upward search loop */
4434 for (;;)
4436 #endif
4437 /* downward search loop */
4438 for (;;)
4440 /* check if user user wants to stop the search*/
4441 ui_breakcheck();
4442 if (got_int)
4443 break;
4445 /* get directory to work on from stack */
4446 stackp = ff_pop(search_ctx);
4447 if (stackp == NULL)
4448 break;
4451 * TODO: decide if we leave this test in
4453 * GOOD: don't search a directory(-tree) twice.
4454 * BAD: - check linked list for every new directory entered.
4455 * - check for double files also done below
4457 * Here we check if we already searched this directory.
4458 * We already searched a directory if:
4459 * 1) The directory is the same.
4460 * 2) We would use the same wildcard string.
4462 * Good if you have links on same directory via several ways
4463 * or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4464 * /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4466 * This check is only needed for directories we work on for the
4467 * first time (hence stackp->ff_filearray == NULL)
4469 if (stackp->ffs_filearray == NULL
4470 && ff_check_visited(&search_ctx->ffsc_dir_visited_list
4471 ->ffvl_visited_list,
4472 stackp->ffs_fix_path
4473 #ifdef FEAT_PATH_EXTRA
4474 , stackp->ffs_wc_path
4475 #endif
4476 ) == FAIL)
4478 #ifdef FF_VERBOSE
4479 if (p_verbose >= 5)
4481 verbose_enter_scroll();
4482 smsg((char_u *)"Already Searched: %s (%s)",
4483 stackp->ffs_fix_path, stackp->ffs_wc_path);
4484 /* don't overwrite this either */
4485 msg_puts((char_u *)"\n");
4486 verbose_leave_scroll();
4488 #endif
4489 ff_free_stack_element(stackp);
4490 continue;
4492 #ifdef FF_VERBOSE
4493 else if (p_verbose >= 5)
4495 verbose_enter_scroll();
4496 smsg((char_u *)"Searching: %s (%s)",
4497 stackp->ffs_fix_path, stackp->ffs_wc_path);
4498 /* don't overwrite this either */
4499 msg_puts((char_u *)"\n");
4500 verbose_leave_scroll();
4502 #endif
4504 /* check depth */
4505 if (stackp->ffs_level <= 0)
4507 ff_free_stack_element(stackp);
4508 continue;
4511 file_path[0] = NUL;
4514 * If no filearray till now expand wildcards
4515 * The function expand_wildcards() can handle an array of paths
4516 * and all possible expands are returned in one array. We use this
4517 * to handle the expansion of '**' into an empty string.
4519 if (stackp->ffs_filearray == NULL)
4521 char_u *dirptrs[2];
4523 /* we use filepath to build the path expand_wildcards() should
4524 * expand.
4526 dirptrs[0] = file_path;
4527 dirptrs[1] = NULL;
4529 /* if we have a start dir copy it in */
4530 if (!vim_isAbsName(stackp->ffs_fix_path)
4531 && search_ctx->ffsc_start_dir)
4533 STRCPY(file_path, search_ctx->ffsc_start_dir);
4534 add_pathsep(file_path);
4537 /* append the fix part of the search path */
4538 STRCAT(file_path, stackp->ffs_fix_path);
4539 add_pathsep(file_path);
4541 #ifdef FEAT_PATH_EXTRA
4542 rest_of_wildcards = stackp->ffs_wc_path;
4543 if (*rest_of_wildcards != NUL)
4545 len = (int)STRLEN(file_path);
4546 if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4548 /* pointer to the restrict byte
4549 * The restrict byte is not a character!
4551 p = rest_of_wildcards + 2;
4553 if (*p > 0)
4555 (*p)--;
4556 file_path[len++] = '*';
4559 if (*p == 0)
4561 /* remove '**<numb> from wildcards */
4562 STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
4564 else
4565 rest_of_wildcards += 3;
4567 if (stackp->ffs_star_star_empty == 0)
4569 /* if not done before, expand '**' to empty */
4570 stackp->ffs_star_star_empty = 1;
4571 dirptrs[1] = stackp->ffs_fix_path;
4576 * Here we copy until the next path separator or the end of
4577 * the path. If we stop at a path separator, there is
4578 * still something else left. This is handled below by
4579 * pushing every directory returned from expand_wildcards()
4580 * on the stack again for further search.
4582 while (*rest_of_wildcards
4583 && !vim_ispathsep(*rest_of_wildcards))
4584 file_path[len++] = *rest_of_wildcards++;
4586 file_path[len] = NUL;
4587 if (vim_ispathsep(*rest_of_wildcards))
4588 rest_of_wildcards++;
4590 #endif
4593 * Expand wildcards like "*" and "$VAR".
4594 * If the path is a URL don't try this.
4596 if (path_with_url(dirptrs[0]))
4598 stackp->ffs_filearray = (char_u **)
4599 alloc((unsigned)sizeof(char *));
4600 if (stackp->ffs_filearray != NULL
4601 && (stackp->ffs_filearray[0]
4602 = vim_strsave(dirptrs[0])) != NULL)
4603 stackp->ffs_filearray_size = 1;
4604 else
4605 stackp->ffs_filearray_size = 0;
4607 else
4608 expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
4609 &stackp->ffs_filearray_size,
4610 &stackp->ffs_filearray,
4611 EW_DIR|EW_ADDSLASH|EW_SILENT);
4613 stackp->ffs_filearray_cur = 0;
4614 stackp->ffs_stage = 0;
4616 #ifdef FEAT_PATH_EXTRA
4617 else
4618 rest_of_wildcards = &stackp->ffs_wc_path[
4619 STRLEN(stackp->ffs_wc_path)];
4620 #endif
4622 if (stackp->ffs_stage == 0)
4624 /* this is the first time we work on this directory */
4625 #ifdef FEAT_PATH_EXTRA
4626 if (*rest_of_wildcards == NUL)
4627 #endif
4630 * we don't have further wildcards to expand, so we have to
4631 * check for the final file now
4633 for (i = stackp->ffs_filearray_cur;
4634 i < stackp->ffs_filearray_size; ++i)
4636 if (!path_with_url(stackp->ffs_filearray[i])
4637 && !mch_isdir(stackp->ffs_filearray[i]))
4638 continue; /* not a directory */
4640 /* prepare the filename to be checked for existance
4641 * below */
4642 STRCPY(file_path, stackp->ffs_filearray[i]);
4643 add_pathsep(file_path);
4644 STRCAT(file_path, search_ctx->ffsc_file_to_search);
4647 * Try without extra suffix and then with suffixes
4648 * from 'suffixesadd'.
4650 #ifdef FEAT_SEARCHPATH
4651 len = (int)STRLEN(file_path);
4652 suf = curbuf->b_p_sua;
4653 for (;;)
4654 #endif
4656 /* if file exists and we didn't already find it */
4657 if ((path_with_url(file_path)
4658 || (mch_getperm(file_path) >= 0
4659 && (search_ctx->ffsc_find_what
4660 == FINDFILE_BOTH
4661 || ((search_ctx->ffsc_find_what
4662 == FINDFILE_DIR)
4663 == mch_isdir(file_path)))))
4664 #ifndef FF_VERBOSE
4665 && (ff_check_visited(
4666 &search_ctx->ffsc_visited_list->ffvl_visited_list,
4667 file_path
4668 #ifdef FEAT_PATH_EXTRA
4669 , (char_u *)""
4670 #endif
4671 ) == OK)
4672 #endif
4675 #ifdef FF_VERBOSE
4676 if (ff_check_visited(
4677 &search_ctx->ffsc_visited_list->ffvl_visited_list,
4678 file_path
4679 #ifdef FEAT_PATH_EXTRA
4680 , (char_u *)""
4681 #endif
4682 ) == FAIL)
4684 if (p_verbose >= 5)
4686 verbose_enter_scroll();
4687 smsg((char_u *)"Already: %s",
4688 file_path);
4689 /* don't overwrite this either */
4690 msg_puts((char_u *)"\n");
4691 verbose_leave_scroll();
4693 continue;
4695 #endif
4697 /* push dir to examine rest of subdirs later */
4698 stackp->ffs_filearray_cur = i + 1;
4699 ff_push(search_ctx, stackp);
4701 simplify_filename(file_path);
4702 if (mch_dirname(ff_expand_buffer, MAXPATHL)
4703 == OK)
4705 p = shorten_fname(file_path,
4706 ff_expand_buffer);
4707 if (p != NULL)
4708 STRMOVE(file_path, p);
4710 #ifdef FF_VERBOSE
4711 if (p_verbose >= 5)
4713 verbose_enter_scroll();
4714 smsg((char_u *)"HIT: %s", file_path);
4715 /* don't overwrite this either */
4716 msg_puts((char_u *)"\n");
4717 verbose_leave_scroll();
4719 #endif
4720 return file_path;
4723 #ifdef FEAT_SEARCHPATH
4724 /* Not found or found already, try next suffix. */
4725 if (*suf == NUL)
4726 break;
4727 copy_option_part(&suf, file_path + len,
4728 MAXPATHL - len, ",");
4729 #endif
4733 #ifdef FEAT_PATH_EXTRA
4734 else
4737 * still wildcards left, push the directories for further
4738 * search
4740 for (i = stackp->ffs_filearray_cur;
4741 i < stackp->ffs_filearray_size; ++i)
4743 if (!mch_isdir(stackp->ffs_filearray[i]))
4744 continue; /* not a directory */
4746 ff_push(search_ctx,
4747 ff_create_stack_element(
4748 stackp->ffs_filearray[i],
4749 rest_of_wildcards,
4750 stackp->ffs_level - 1, 0));
4753 #endif
4754 stackp->ffs_filearray_cur = 0;
4755 stackp->ffs_stage = 1;
4758 #ifdef FEAT_PATH_EXTRA
4760 * if wildcards contains '**' we have to descent till we reach the
4761 * leaves of the directory tree.
4763 if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
4765 for (i = stackp->ffs_filearray_cur;
4766 i < stackp->ffs_filearray_size; ++i)
4768 if (fnamecmp(stackp->ffs_filearray[i],
4769 stackp->ffs_fix_path) == 0)
4770 continue; /* don't repush same directory */
4771 if (!mch_isdir(stackp->ffs_filearray[i]))
4772 continue; /* not a directory */
4773 ff_push(search_ctx,
4774 ff_create_stack_element(stackp->ffs_filearray[i],
4775 stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
4778 #endif
4780 /* we are done with the current directory */
4781 ff_free_stack_element(stackp);
4785 #ifdef FEAT_PATH_EXTRA
4786 /* If we reached this, we didn't find anything downwards.
4787 * Let's check if we should do an upward search.
4789 if (search_ctx->ffsc_start_dir
4790 && search_ctx->ffsc_stopdirs_v != NULL && !got_int)
4792 ff_stack_T *sptr;
4794 /* is the last starting directory in the stop list? */
4795 if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
4796 (int)(path_end - search_ctx->ffsc_start_dir),
4797 search_ctx->ffsc_stopdirs_v) == TRUE)
4798 break;
4800 /* cut of last dir */
4801 while (path_end > search_ctx->ffsc_start_dir
4802 && vim_ispathsep(*path_end))
4803 path_end--;
4804 while (path_end > search_ctx->ffsc_start_dir
4805 && !vim_ispathsep(path_end[-1]))
4806 path_end--;
4807 *path_end = 0;
4808 path_end--;
4810 if (*search_ctx->ffsc_start_dir == 0)
4811 break;
4813 STRCPY(file_path, search_ctx->ffsc_start_dir);
4814 add_pathsep(file_path);
4815 STRCAT(file_path, search_ctx->ffsc_fix_path);
4817 /* create a new stack entry */
4818 sptr = ff_create_stack_element(file_path,
4819 search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
4820 if (sptr == NULL)
4821 break;
4822 ff_push(search_ctx, sptr);
4824 else
4825 break;
4827 #endif
4829 vim_free(file_path);
4830 return NULL;
4834 * Free the list of lists of visited files and directories
4835 * Can handle it if the passed search_context is NULL;
4837 void
4838 vim_findfile_free_visited(search_ctx_arg)
4839 void *search_ctx_arg;
4841 ff_search_ctx_T *search_ctx;
4843 if (search_ctx_arg == NULL)
4844 return;
4846 search_ctx = (ff_search_ctx_T *)search_ctx_arg;
4847 vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
4848 vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
4851 static void
4852 vim_findfile_free_visited_list(list_headp)
4853 ff_visited_list_hdr_T **list_headp;
4855 ff_visited_list_hdr_T *vp;
4857 while (*list_headp != NULL)
4859 vp = (*list_headp)->ffvl_next;
4860 ff_free_visited_list((*list_headp)->ffvl_visited_list);
4862 vim_free((*list_headp)->ffvl_filename);
4863 vim_free(*list_headp);
4864 *list_headp = vp;
4866 *list_headp = NULL;
4869 static void
4870 ff_free_visited_list(vl)
4871 ff_visited_T *vl;
4873 ff_visited_T *vp;
4875 while (vl != NULL)
4877 vp = vl->ffv_next;
4878 #ifdef FEAT_PATH_EXTRA
4879 vim_free(vl->ffv_wc_path);
4880 #endif
4881 vim_free(vl);
4882 vl = vp;
4884 vl = NULL;
4888 * Returns the already visited list for the given filename. If none is found it
4889 * allocates a new one.
4891 static ff_visited_list_hdr_T*
4892 ff_get_visited_list(filename, list_headp)
4893 char_u *filename;
4894 ff_visited_list_hdr_T **list_headp;
4896 ff_visited_list_hdr_T *retptr = NULL;
4898 /* check if a visited list for the given filename exists */
4899 if (*list_headp != NULL)
4901 retptr = *list_headp;
4902 while (retptr != NULL)
4904 if (fnamecmp(filename, retptr->ffvl_filename) == 0)
4906 #ifdef FF_VERBOSE
4907 if (p_verbose >= 5)
4909 verbose_enter_scroll();
4910 smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
4911 filename);
4912 /* don't overwrite this either */
4913 msg_puts((char_u *)"\n");
4914 verbose_leave_scroll();
4916 #endif
4917 return retptr;
4919 retptr = retptr->ffvl_next;
4923 #ifdef FF_VERBOSE
4924 if (p_verbose >= 5)
4926 verbose_enter_scroll();
4927 smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
4928 /* don't overwrite this either */
4929 msg_puts((char_u *)"\n");
4930 verbose_leave_scroll();
4932 #endif
4935 * if we reach this we didn't find a list and we have to allocate new list
4937 retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
4938 if (retptr == NULL)
4939 return NULL;
4941 retptr->ffvl_visited_list = NULL;
4942 retptr->ffvl_filename = vim_strsave(filename);
4943 if (retptr->ffvl_filename == NULL)
4945 vim_free(retptr);
4946 return NULL;
4948 retptr->ffvl_next = *list_headp;
4949 *list_headp = retptr;
4951 return retptr;
4954 #ifdef FEAT_PATH_EXTRA
4956 * check if two wildcard paths are equal. Returns TRUE or FALSE.
4957 * They are equal if:
4958 * - both paths are NULL
4959 * - they have the same length
4960 * - char by char comparison is OK
4961 * - the only differences are in the counters behind a '**', so
4962 * '**\20' is equal to '**\24'
4964 static int
4965 ff_wc_equal(s1, s2)
4966 char_u *s1;
4967 char_u *s2;
4969 int i;
4971 if (s1 == s2)
4972 return TRUE;
4974 if (s1 == NULL || s2 == NULL)
4975 return FALSE;
4977 if (STRLEN(s1) != STRLEN(s2))
4978 return FAIL;
4980 for (i = 0; s1[i] != NUL && s2[i] != NUL; i++)
4982 if (s1[i] != s2[i]
4983 #ifdef CASE_INSENSITIVE_FILENAME
4984 && TOUPPER_LOC(s1[i]) != TOUPPER_LOC(s2[i])
4985 #endif
4988 if (i >= 2)
4989 if (s1[i-1] == '*' && s1[i-2] == '*')
4990 continue;
4991 else
4992 return FAIL;
4993 else
4994 return FAIL;
4997 return TRUE;
4999 #endif
5002 * maintains the list of already visited files and dirs
5003 * returns FAIL if the given file/dir is already in the list
5004 * returns OK if it is newly added
5006 * TODO: What to do on memory allocation problems?
5007 * -> return TRUE - Better the file is found several times instead of
5008 * never.
5010 static int
5011 ff_check_visited(visited_list, fname
5012 #ifdef FEAT_PATH_EXTRA
5013 , wc_path
5014 #endif
5016 ff_visited_T **visited_list;
5017 char_u *fname;
5018 #ifdef FEAT_PATH_EXTRA
5019 char_u *wc_path;
5020 #endif
5022 ff_visited_T *vp;
5023 #ifdef UNIX
5024 struct stat st;
5025 int url = FALSE;
5026 #endif
5028 /* For an URL we only compare the name, otherwise we compare the
5029 * device/inode (unix) or the full path name (not Unix). */
5030 if (path_with_url(fname))
5032 vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
5033 #ifdef UNIX
5034 url = TRUE;
5035 #endif
5037 else
5039 ff_expand_buffer[0] = NUL;
5040 #ifdef UNIX
5041 if (mch_stat((char *)fname, &st) < 0)
5042 #else
5043 if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
5044 #endif
5045 return FAIL;
5048 /* check against list of already visited files */
5049 for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
5051 if (
5052 #ifdef UNIX
5053 !url
5054 ? (vp->ffv_dev == st.st_dev
5055 && vp->ffv_ino == st.st_ino)
5057 #endif
5058 fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
5061 #ifdef FEAT_PATH_EXTRA
5062 /* are the wildcard parts equal */
5063 if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
5064 #endif
5065 /* already visited */
5066 return FAIL;
5071 * New file/dir. Add it to the list of visited files/dirs.
5073 vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
5074 + STRLEN(ff_expand_buffer)));
5076 if (vp != NULL)
5078 #ifdef UNIX
5079 if (!url)
5081 vp->ffv_ino = st.st_ino;
5082 vp->ffv_dev = st.st_dev;
5083 vp->ffv_fname[0] = NUL;
5085 else
5087 vp->ffv_ino = 0;
5088 vp->ffv_dev = -1;
5089 #endif
5090 STRCPY(vp->ffv_fname, ff_expand_buffer);
5091 #ifdef UNIX
5093 #endif
5094 #ifdef FEAT_PATH_EXTRA
5095 if (wc_path != NULL)
5096 vp->ffv_wc_path = vim_strsave(wc_path);
5097 else
5098 vp->ffv_wc_path = NULL;
5099 #endif
5101 vp->ffv_next = *visited_list;
5102 *visited_list = vp;
5105 return OK;
5109 * create stack element from given path pieces
5111 static ff_stack_T *
5112 ff_create_stack_element(fix_part,
5113 #ifdef FEAT_PATH_EXTRA
5114 wc_part,
5115 #endif
5116 level, star_star_empty)
5117 char_u *fix_part;
5118 #ifdef FEAT_PATH_EXTRA
5119 char_u *wc_part;
5120 #endif
5121 int level;
5122 int star_star_empty;
5124 ff_stack_T *new;
5126 new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
5127 if (new == NULL)
5128 return NULL;
5130 new->ffs_prev = NULL;
5131 new->ffs_filearray = NULL;
5132 new->ffs_filearray_size = 0;
5133 new->ffs_filearray_cur = 0;
5134 new->ffs_stage = 0;
5135 new->ffs_level = level;
5136 new->ffs_star_star_empty = star_star_empty;;
5138 /* the following saves NULL pointer checks in vim_findfile */
5139 if (fix_part == NULL)
5140 fix_part = (char_u *)"";
5141 new->ffs_fix_path = vim_strsave(fix_part);
5143 #ifdef FEAT_PATH_EXTRA
5144 if (wc_part == NULL)
5145 wc_part = (char_u *)"";
5146 new->ffs_wc_path = vim_strsave(wc_part);
5147 #endif
5149 if (new->ffs_fix_path == NULL
5150 #ifdef FEAT_PATH_EXTRA
5151 || new->ffs_wc_path == NULL
5152 #endif
5155 ff_free_stack_element(new);
5156 new = NULL;
5159 return new;
5163 * Push a dir on the directory stack.
5165 static void
5166 ff_push(search_ctx, stack_ptr)
5167 ff_search_ctx_T *search_ctx;
5168 ff_stack_T *stack_ptr;
5170 /* check for NULL pointer, not to return an error to the user, but
5171 * to prevent a crash */
5172 if (stack_ptr != NULL)
5174 stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
5175 search_ctx->ffsc_stack_ptr = stack_ptr;
5180 * Pop a dir from the directory stack.
5181 * Returns NULL if stack is empty.
5183 static ff_stack_T *
5184 ff_pop(search_ctx)
5185 ff_search_ctx_T *search_ctx;
5187 ff_stack_T *sptr;
5189 sptr = search_ctx->ffsc_stack_ptr;
5190 if (search_ctx->ffsc_stack_ptr != NULL)
5191 search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
5193 return sptr;
5197 * free the given stack element
5199 static void
5200 ff_free_stack_element(stack_ptr)
5201 ff_stack_T *stack_ptr;
5203 /* vim_free handles possible NULL pointers */
5204 vim_free(stack_ptr->ffs_fix_path);
5205 #ifdef FEAT_PATH_EXTRA
5206 vim_free(stack_ptr->ffs_wc_path);
5207 #endif
5209 if (stack_ptr->ffs_filearray != NULL)
5210 FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
5212 vim_free(stack_ptr);
5216 * Clear the search context, but NOT the visited list.
5218 static void
5219 ff_clear(search_ctx)
5220 ff_search_ctx_T *search_ctx;
5222 ff_stack_T *sptr;
5224 /* clear up stack */
5225 while ((sptr = ff_pop(search_ctx)) != NULL)
5226 ff_free_stack_element(sptr);
5228 vim_free(search_ctx->ffsc_file_to_search);
5229 vim_free(search_ctx->ffsc_start_dir);
5230 vim_free(search_ctx->ffsc_fix_path);
5231 #ifdef FEAT_PATH_EXTRA
5232 vim_free(search_ctx->ffsc_wc_path);
5233 #endif
5235 #ifdef FEAT_PATH_EXTRA
5236 if (search_ctx->ffsc_stopdirs_v != NULL)
5238 int i = 0;
5240 while (search_ctx->ffsc_stopdirs_v[i] != NULL)
5242 vim_free(search_ctx->ffsc_stopdirs_v[i]);
5243 i++;
5245 vim_free(search_ctx->ffsc_stopdirs_v);
5247 search_ctx->ffsc_stopdirs_v = NULL;
5248 #endif
5250 /* reset everything */
5251 search_ctx->ffsc_file_to_search = NULL;
5252 search_ctx->ffsc_start_dir = NULL;
5253 search_ctx->ffsc_fix_path = NULL;
5254 #ifdef FEAT_PATH_EXTRA
5255 search_ctx->ffsc_wc_path = NULL;
5256 search_ctx->ffsc_level = 0;
5257 #endif
5260 #ifdef FEAT_PATH_EXTRA
5262 * check if the given path is in the stopdirs
5263 * returns TRUE if yes else FALSE
5265 static int
5266 ff_path_in_stoplist(path, path_len, stopdirs_v)
5267 char_u *path;
5268 int path_len;
5269 char_u **stopdirs_v;
5271 int i = 0;
5273 /* eat up trailing path separators, except the first */
5274 while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
5275 path_len--;
5277 /* if no path consider it as match */
5278 if (path_len == 0)
5279 return TRUE;
5281 for (i = 0; stopdirs_v[i] != NULL; i++)
5283 if ((int)STRLEN(stopdirs_v[i]) > path_len)
5285 /* match for parent directory. So '/home' also matches
5286 * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
5287 * '/home/r' would also match '/home/rks'
5289 if (fnamencmp(stopdirs_v[i], path, path_len) == 0
5290 && vim_ispathsep(stopdirs_v[i][path_len]))
5291 return TRUE;
5293 else
5295 if (fnamecmp(stopdirs_v[i], path) == 0)
5296 return TRUE;
5299 return FALSE;
5301 #endif
5303 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
5305 * Find the file name "ptr[len]" in the path. Also finds directory names.
5307 * On the first call set the parameter 'first' to TRUE to initialize
5308 * the search. For repeating calls to FALSE.
5310 * Repeating calls will return other files called 'ptr[len]' from the path.
5312 * Only on the first call 'ptr' and 'len' are used. For repeating calls they
5313 * don't need valid values.
5315 * If nothing found on the first call the option FNAME_MESS will issue the
5316 * message:
5317 * 'Can't find file "<file>" in path'
5318 * On repeating calls:
5319 * 'No more file "<file>" found in path'
5321 * options:
5322 * FNAME_MESS give error message when not found
5324 * Uses NameBuff[]!
5326 * Returns an allocated string for the file name. NULL for error.
5329 char_u *
5330 find_file_in_path(ptr, len, options, first, rel_fname)
5331 char_u *ptr; /* file name */
5332 int len; /* length of file name */
5333 int options;
5334 int first; /* use count'th matching file name */
5335 char_u *rel_fname; /* file name searching relative to */
5337 return find_file_in_path_option(ptr, len, options, first,
5338 *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
5339 FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
5342 static char_u *ff_file_to_find = NULL;
5343 static void *fdip_search_ctx = NULL;
5345 #if defined(EXITFREE)
5346 static void
5347 free_findfile()
5349 vim_free(ff_file_to_find);
5350 vim_findfile_cleanup(fdip_search_ctx);
5352 #endif
5355 * Find the directory name "ptr[len]" in the path.
5357 * options:
5358 * FNAME_MESS give error message when not found
5360 * Uses NameBuff[]!
5362 * Returns an allocated string for the file name. NULL for error.
5364 char_u *
5365 find_directory_in_path(ptr, len, options, rel_fname)
5366 char_u *ptr; /* file name */
5367 int len; /* length of file name */
5368 int options;
5369 char_u *rel_fname; /* file name searching relative to */
5371 return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
5372 FINDFILE_DIR, rel_fname, (char_u *)"");
5375 char_u *
5376 find_file_in_path_option(ptr, len, options, first, path_option, find_what, rel_fname, suffixes)
5377 char_u *ptr; /* file name */
5378 int len; /* length of file name */
5379 int options;
5380 int first; /* use count'th matching file name */
5381 char_u *path_option; /* p_path or p_cdpath */
5382 int find_what; /* FINDFILE_FILE, _DIR or _BOTH */
5383 char_u *rel_fname; /* file name we are looking relative to. */
5384 char_u *suffixes; /* list of suffixes, 'suffixesadd' option */
5386 static char_u *dir;
5387 static int did_findfile_init = FALSE;
5388 char_u save_char;
5389 char_u *file_name = NULL;
5390 char_u *buf = NULL;
5391 int rel_to_curdir;
5392 #ifdef AMIGA
5393 struct Process *proc = (struct Process *)FindTask(0L);
5394 APTR save_winptr = proc->pr_WindowPtr;
5396 /* Avoid a requester here for a volume that doesn't exist. */
5397 proc->pr_WindowPtr = (APTR)-1L;
5398 #endif
5400 if (first == TRUE)
5402 /* copy file name into NameBuff, expanding environment variables */
5403 save_char = ptr[len];
5404 ptr[len] = NUL;
5405 expand_env(ptr, NameBuff, MAXPATHL);
5406 ptr[len] = save_char;
5408 vim_free(ff_file_to_find);
5409 ff_file_to_find = vim_strsave(NameBuff);
5410 if (ff_file_to_find == NULL) /* out of memory */
5412 file_name = NULL;
5413 goto theend;
5417 rel_to_curdir = (ff_file_to_find[0] == '.'
5418 && (ff_file_to_find[1] == NUL
5419 || vim_ispathsep(ff_file_to_find[1])
5420 || (ff_file_to_find[1] == '.'
5421 && (ff_file_to_find[2] == NUL
5422 || vim_ispathsep(ff_file_to_find[2])))));
5423 if (vim_isAbsName(ff_file_to_find)
5424 /* "..", "../path", "." and "./path": don't use the path_option */
5425 || rel_to_curdir
5426 #if defined(MSWIN) || defined(MSDOS) || defined(OS2)
5427 /* handle "\tmp" as absolute path */
5428 || vim_ispathsep(ff_file_to_find[0])
5429 /* handle "c:name" as absulute path */
5430 || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
5431 #endif
5432 #ifdef AMIGA
5433 /* handle ":tmp" as absolute path */
5434 || ff_file_to_find[0] == ':'
5435 #endif
5439 * Absolute path, no need to use "path_option".
5440 * If this is not a first call, return NULL. We already returned a
5441 * filename on the first call.
5443 if (first == TRUE)
5445 int l;
5446 int run;
5448 if (path_with_url(ff_file_to_find))
5450 file_name = vim_strsave(ff_file_to_find);
5451 goto theend;
5454 /* When FNAME_REL flag given first use the directory of the file.
5455 * Otherwise or when this fails use the current directory. */
5456 for (run = 1; run <= 2; ++run)
5458 l = (int)STRLEN(ff_file_to_find);
5459 if (run == 1
5460 && rel_to_curdir
5461 && (options & FNAME_REL)
5462 && rel_fname != NULL
5463 && STRLEN(rel_fname) + l < MAXPATHL)
5465 STRCPY(NameBuff, rel_fname);
5466 STRCPY(gettail(NameBuff), ff_file_to_find);
5467 l = (int)STRLEN(NameBuff);
5469 else
5471 STRCPY(NameBuff, ff_file_to_find);
5472 run = 2;
5475 /* When the file doesn't exist, try adding parts of
5476 * 'suffixesadd'. */
5477 buf = suffixes;
5478 for (;;)
5480 if (
5481 #ifdef DJGPP
5482 /* "C:" by itself will fail for mch_getperm(),
5483 * assume it's always valid. */
5484 (find_what != FINDFILE_FILE && NameBuff[0] != NUL
5485 && NameBuff[1] == ':'
5486 && NameBuff[2] == NUL) ||
5487 #endif
5488 (mch_getperm(NameBuff) >= 0
5489 && (find_what == FINDFILE_BOTH
5490 || ((find_what == FINDFILE_DIR)
5491 == mch_isdir(NameBuff)))))
5493 file_name = vim_strsave(NameBuff);
5494 goto theend;
5496 if (*buf == NUL)
5497 break;
5498 copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5503 else
5506 * Loop over all paths in the 'path' or 'cdpath' option.
5507 * When "first" is set, first setup to the start of the option.
5508 * Otherwise continue to find the next match.
5510 if (first == TRUE)
5512 /* vim_findfile_free_visited can handle a possible NULL pointer */
5513 vim_findfile_free_visited(fdip_search_ctx);
5514 dir = path_option;
5515 did_findfile_init = FALSE;
5518 for (;;)
5520 if (did_findfile_init)
5522 file_name = vim_findfile(fdip_search_ctx);
5523 if (file_name != NULL)
5524 break;
5526 did_findfile_init = FALSE;
5528 else
5530 char_u *r_ptr;
5532 if (dir == NULL || *dir == NUL)
5534 /* We searched all paths of the option, now we can
5535 * free the search context. */
5536 vim_findfile_cleanup(fdip_search_ctx);
5537 fdip_search_ctx = NULL;
5538 break;
5541 if ((buf = alloc((int)(MAXPATHL))) == NULL)
5542 break;
5544 /* copy next path */
5545 buf[0] = 0;
5546 copy_option_part(&dir, buf, MAXPATHL, " ,");
5548 #ifdef FEAT_PATH_EXTRA
5549 /* get the stopdir string */
5550 r_ptr = vim_findfile_stopdir(buf);
5551 #else
5552 r_ptr = NULL;
5553 #endif
5554 fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
5555 r_ptr, 100, FALSE, find_what,
5556 fdip_search_ctx, FALSE, rel_fname);
5557 if (fdip_search_ctx != NULL)
5558 did_findfile_init = TRUE;
5559 vim_free(buf);
5563 if (file_name == NULL && (options & FNAME_MESS))
5565 if (first == TRUE)
5567 if (find_what == FINDFILE_DIR)
5568 EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
5569 ff_file_to_find);
5570 else
5571 EMSG2(_("E345: Can't find file \"%s\" in path"),
5572 ff_file_to_find);
5574 else
5576 if (find_what == FINDFILE_DIR)
5577 EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
5578 ff_file_to_find);
5579 else
5580 EMSG2(_("E347: No more file \"%s\" found in path"),
5581 ff_file_to_find);
5585 theend:
5586 #ifdef AMIGA
5587 proc->pr_WindowPtr = save_winptr;
5588 #endif
5589 return file_name;
5592 #endif /* FEAT_SEARCHPATH */
5595 * Change directory to "new_dir". If FEAT_SEARCHPATH is defined, search
5596 * 'cdpath' for relative directory names, otherwise just mch_chdir().
5599 vim_chdir(new_dir)
5600 char_u *new_dir;
5602 #ifndef FEAT_SEARCHPATH
5603 return mch_chdir((char *)new_dir);
5604 #else
5605 char_u *dir_name;
5606 int r;
5608 dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
5609 FNAME_MESS, curbuf->b_ffname);
5610 if (dir_name == NULL)
5611 return -1;
5612 r = mch_chdir((char *)dir_name);
5613 vim_free(dir_name);
5614 return r;
5615 #endif
5619 * Get user name from machine-specific function.
5620 * Returns the user name in "buf[len]".
5621 * Some systems are quite slow in obtaining the user name (Windows NT), thus
5622 * cache the result.
5623 * Returns OK or FAIL.
5626 get_user_name(buf, len)
5627 char_u *buf;
5628 int len;
5630 if (username == NULL)
5632 if (mch_get_user_name(buf, len) == FAIL)
5633 return FAIL;
5634 username = vim_strsave(buf);
5636 else
5637 vim_strncpy(buf, username, len - 1);
5638 return OK;
5641 #ifndef HAVE_QSORT
5643 * Our own qsort(), for systems that don't have it.
5644 * It's simple and slow. From the K&R C book.
5646 void
5647 qsort(base, elm_count, elm_size, cmp)
5648 void *base;
5649 size_t elm_count;
5650 size_t elm_size;
5651 int (*cmp) __ARGS((const void *, const void *));
5653 char_u *buf;
5654 char_u *p1;
5655 char_u *p2;
5656 int i, j;
5657 int gap;
5659 buf = alloc((unsigned)elm_size);
5660 if (buf == NULL)
5661 return;
5663 for (gap = elm_count / 2; gap > 0; gap /= 2)
5664 for (i = gap; i < elm_count; ++i)
5665 for (j = i - gap; j >= 0; j -= gap)
5667 /* Compare the elements. */
5668 p1 = (char_u *)base + j * elm_size;
5669 p2 = (char_u *)base + (j + gap) * elm_size;
5670 if ((*cmp)((void *)p1, (void *)p2) <= 0)
5671 break;
5672 /* Exchange the elemets. */
5673 mch_memmove(buf, p1, elm_size);
5674 mch_memmove(p1, p2, elm_size);
5675 mch_memmove(p2, buf, elm_size);
5678 vim_free(buf);
5680 #endif
5683 * Sort an array of strings.
5685 static int
5686 #ifdef __BORLANDC__
5687 _RTLENTRYF
5688 #endif
5689 sort_compare __ARGS((const void *s1, const void *s2));
5691 static int
5692 #ifdef __BORLANDC__
5693 _RTLENTRYF
5694 #endif
5695 sort_compare(s1, s2)
5696 const void *s1;
5697 const void *s2;
5699 return STRCMP(*(char **)s1, *(char **)s2);
5702 void
5703 sort_strings(files, count)
5704 char_u **files;
5705 int count;
5707 qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
5710 #if !defined(NO_EXPANDPATH) || defined(PROTO)
5712 * Compare path "p[]" to "q[]".
5713 * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
5714 * Return value like strcmp(p, q), but consider path separators.
5717 pathcmp(p, q, maxlen)
5718 const char *p, *q;
5719 int maxlen;
5721 int i;
5722 const char *s = NULL;
5724 for (i = 0; maxlen < 0 || i < maxlen; ++i)
5726 /* End of "p": check if "q" also ends or just has a slash. */
5727 if (p[i] == NUL)
5729 if (q[i] == NUL) /* full match */
5730 return 0;
5731 s = q;
5732 break;
5735 /* End of "q": check if "p" just has a slash. */
5736 if (q[i] == NUL)
5738 s = p;
5739 break;
5742 if (
5743 #ifdef CASE_INSENSITIVE_FILENAME
5744 TOUPPER_LOC(p[i]) != TOUPPER_LOC(q[i])
5745 #else
5746 p[i] != q[i]
5747 #endif
5748 #ifdef BACKSLASH_IN_FILENAME
5749 /* consider '/' and '\\' to be equal */
5750 && !((p[i] == '/' && q[i] == '\\')
5751 || (p[i] == '\\' && q[i] == '/'))
5752 #endif
5755 if (vim_ispathsep(p[i]))
5756 return -1;
5757 if (vim_ispathsep(q[i]))
5758 return 1;
5759 return ((char_u *)p)[i] - ((char_u *)q)[i]; /* no match */
5762 if (s == NULL) /* "i" ran into "maxlen" */
5763 return 0;
5765 /* ignore a trailing slash, but not "//" or ":/" */
5766 if (s[i + 1] == NUL
5767 && i > 0
5768 && !after_pathsep((char_u *)s, (char_u *)s + i)
5769 #ifdef BACKSLASH_IN_FILENAME
5770 && (s[i] == '/' || s[i] == '\\')
5771 #else
5772 && s[i] == '/'
5773 #endif
5775 return 0; /* match with trailing slash */
5776 if (s == q)
5777 return -1; /* no match */
5778 return 1;
5780 #endif
5783 * The putenv() implementation below comes from the "screen" program.
5784 * Included with permission from Juergen Weigert.
5785 * See pty.c for the copyright notice.
5789 * putenv -- put value into environment
5791 * Usage: i = putenv (string)
5792 * int i;
5793 * char *string;
5795 * where string is of the form <name>=<value>.
5796 * Putenv returns 0 normally, -1 on error (not enough core for malloc).
5798 * Putenv may need to add a new name into the environment, or to
5799 * associate a value longer than the current value with a particular
5800 * name. So, to make life simpler, putenv() copies your entire
5801 * environment into the heap (i.e. malloc()) from the stack
5802 * (i.e. where it resides when your process is initiated) the first
5803 * time you call it.
5805 * (history removed, not very interesting. See the "screen" sources.)
5808 #if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
5810 #define EXTRASIZE 5 /* increment to add to env. size */
5812 static int envsize = -1; /* current size of environment */
5813 #ifndef MACOS_CLASSIC
5814 extern
5815 #endif
5816 char **environ; /* the global which is your env. */
5818 static int findenv __ARGS((char *name)); /* look for a name in the env. */
5819 static int newenv __ARGS((void)); /* copy env. from stack to heap */
5820 static int moreenv __ARGS((void)); /* incr. size of env. */
5823 putenv(string)
5824 const char *string;
5826 int i;
5827 char *p;
5829 if (envsize < 0)
5830 { /* first time putenv called */
5831 if (newenv() < 0) /* copy env. to heap */
5832 return -1;
5835 i = findenv((char *)string); /* look for name in environment */
5837 if (i < 0)
5838 { /* name must be added */
5839 for (i = 0; environ[i]; i++);
5840 if (i >= (envsize - 1))
5841 { /* need new slot */
5842 if (moreenv() < 0)
5843 return -1;
5845 p = (char *)alloc((unsigned)(strlen(string) + 1));
5846 if (p == NULL) /* not enough core */
5847 return -1;
5848 environ[i + 1] = 0; /* new end of env. */
5850 else
5851 { /* name already in env. */
5852 p = vim_realloc(environ[i], strlen(string) + 1);
5853 if (p == NULL)
5854 return -1;
5856 sprintf(p, "%s", string); /* copy into env. */
5857 environ[i] = p;
5859 return 0;
5862 static int
5863 findenv(name)
5864 char *name;
5866 char *namechar, *envchar;
5867 int i, found;
5869 found = 0;
5870 for (i = 0; environ[i] && !found; i++)
5872 envchar = environ[i];
5873 namechar = name;
5874 while (*namechar && *namechar != '=' && (*namechar == *envchar))
5876 namechar++;
5877 envchar++;
5879 found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
5881 return found ? i - 1 : -1;
5884 static int
5885 newenv()
5887 char **env, *elem;
5888 int i, esize;
5890 #ifdef MACOS
5891 /* for Mac a new, empty environment is created */
5892 i = 0;
5893 #else
5894 for (i = 0; environ[i]; i++)
5896 #endif
5897 esize = i + EXTRASIZE + 1;
5898 env = (char **)alloc((unsigned)(esize * sizeof (elem)));
5899 if (env == NULL)
5900 return -1;
5902 #ifndef MACOS
5903 for (i = 0; environ[i]; i++)
5905 elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
5906 if (elem == NULL)
5907 return -1;
5908 env[i] = elem;
5909 strcpy(elem, environ[i]);
5911 #endif
5913 env[i] = 0;
5914 environ = env;
5915 envsize = esize;
5916 return 0;
5919 static int
5920 moreenv()
5922 int esize;
5923 char **env;
5925 esize = envsize + EXTRASIZE;
5926 env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
5927 if (env == 0)
5928 return -1;
5929 environ = env;
5930 envsize = esize;
5931 return 0;
5934 # ifdef USE_VIMPTY_GETENV
5935 char_u *
5936 vimpty_getenv(string)
5937 const char_u *string;
5939 int i;
5940 char_u *p;
5942 if (envsize < 0)
5943 return NULL;
5945 i = findenv((char *)string);
5947 if (i < 0)
5948 return NULL;
5950 p = vim_strchr((char_u *)environ[i], '=');
5951 return (p + 1);
5953 # endif
5955 #endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
5957 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
5959 * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
5960 * rights to write into.
5963 filewritable(fname)
5964 char_u *fname;
5966 int retval = 0;
5967 #if defined(UNIX) || defined(VMS)
5968 int perm = 0;
5969 #endif
5971 #if defined(UNIX) || defined(VMS)
5972 perm = mch_getperm(fname);
5973 #endif
5974 #ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */
5975 if (
5976 # ifdef WIN3264
5977 mch_writable(fname) &&
5978 # else
5979 # if defined(UNIX) || defined(VMS)
5980 (perm & 0222) &&
5981 # endif
5982 # endif
5983 mch_access((char *)fname, W_OK) == 0
5985 #endif
5987 ++retval;
5988 if (mch_isdir(fname))
5989 ++retval;
5991 return retval;
5993 #endif
5996 * Print an error message with one or two "%s" and one or two string arguments.
5997 * This is not in message.c to avoid a warning for prototypes.
6000 emsg3(s, a1, a2)
6001 char_u *s, *a1, *a2;
6003 if (emsg_not_now())
6004 return TRUE; /* no error messages at the moment */
6005 #ifdef HAVE_STDARG_H
6006 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, a1, a2);
6007 #else
6008 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, (long_u)a1, (long_u)a2);
6009 #endif
6010 return emsg(IObuff);
6014 * Print an error message with one "%ld" and one long int argument.
6015 * This is not in message.c to avoid a warning for prototypes.
6018 emsgn(s, n)
6019 char_u *s;
6020 long n;
6022 if (emsg_not_now())
6023 return TRUE; /* no error messages at the moment */
6024 vim_snprintf((char *)IObuff, IOSIZE, (char *)s, n);
6025 return emsg(IObuff);