xref: /vim-8.2.3635/src/misc2.c (revision e968e36a)
1 /* vi:set ts=8 sts=4 sw=4:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * misc2.c: Various functions.
12  */
13 #include "vim.h"
14 
15 static char_u	*username = NULL; /* cached result of mch_get_user_name() */
16 
17 static char_u	*ff_expand_buffer = NULL; /* used for expanding filenames */
18 
19 #if defined(FEAT_VIRTUALEDIT) || defined(PROTO)
20 static int coladvance2 __ARGS((pos_T *pos, int addspaces, int finetune, colnr_T wcol));
21 
22 /*
23  * Return TRUE if in the current mode we need to use virtual.
24  */
25     int
26 virtual_active()
27 {
28     /* While an operator is being executed we return "virtual_op", because
29      * VIsual_active has already been reset, thus we can't check for "block"
30      * being used. */
31     if (virtual_op != MAYBE)
32 	return virtual_op;
33     return (ve_flags == VE_ALL
34 	    || ((ve_flags & VE_BLOCK) && VIsual_active && VIsual_mode == Ctrl_V)
35 	    || ((ve_flags & VE_INSERT) && (State & INSERT)));
36 }
37 
38 /*
39  * Get the screen position of the cursor.
40  */
41     int
42 getviscol()
43 {
44     colnr_T	x;
45 
46     getvvcol(curwin, &curwin->w_cursor, &x, NULL, NULL);
47     return (int)x;
48 }
49 
50 /*
51  * Get the screen position of character col with a coladd in the cursor line.
52  */
53     int
54 getviscol2(col, coladd)
55     colnr_T	col;
56     colnr_T	coladd;
57 {
58     colnr_T	x;
59     pos_T	pos;
60 
61     pos.lnum = curwin->w_cursor.lnum;
62     pos.col = col;
63     pos.coladd = coladd;
64     getvvcol(curwin, &pos, &x, NULL, NULL);
65     return (int)x;
66 }
67 
68 /*
69  * Go to column "wcol", and add/insert white space as necessary to get the
70  * cursor in that column.
71  * The caller must have saved the cursor line for undo!
72  */
73     int
74 coladvance_force(wcol)
75     colnr_T wcol;
76 {
77     int rc = coladvance2(&curwin->w_cursor, TRUE, FALSE, wcol);
78 
79     if (wcol == MAXCOL)
80 	curwin->w_valid &= ~VALID_VIRTCOL;
81     else
82     {
83 	/* Virtcol is valid */
84 	curwin->w_valid |= VALID_VIRTCOL;
85 	curwin->w_virtcol = wcol;
86     }
87     return rc;
88 }
89 #endif
90 
91 /*
92  * Try to advance the Cursor to the specified screen column.
93  * If virtual editing: fine tune the cursor position.
94  * Note that all virtual positions off the end of a line should share
95  * a curwin->w_cursor.col value (n.b. this is equal to STRLEN(line)),
96  * beginning at coladd 0.
97  *
98  * return OK if desired column is reached, FAIL if not
99  */
100     int
101 coladvance(wcol)
102     colnr_T	wcol;
103 {
104     int rc = getvpos(&curwin->w_cursor, wcol);
105 
106     if (wcol == MAXCOL || rc == FAIL)
107 	curwin->w_valid &= ~VALID_VIRTCOL;
108     else if (*ml_get_cursor() != TAB)
109     {
110 	/* Virtcol is valid when not on a TAB */
111 	curwin->w_valid |= VALID_VIRTCOL;
112 	curwin->w_virtcol = wcol;
113     }
114     return rc;
115 }
116 
117 /*
118  * Return in "pos" the position of the cursor advanced to screen column "wcol".
119  * return OK if desired column is reached, FAIL if not
120  */
121     int
122 getvpos(pos, wcol)
123     pos_T   *pos;
124     colnr_T wcol;
125 {
126 #ifdef FEAT_VIRTUALEDIT
127     return coladvance2(pos, FALSE, virtual_active(), wcol);
128 }
129 
130     static int
131 coladvance2(pos, addspaces, finetune, wcol)
132     pos_T	*pos;
133     int		addspaces;	/* change the text to achieve our goal? */
134     int		finetune;	/* change char offset for the exact column */
135     colnr_T	wcol;		/* column to move to */
136 {
137 #endif
138     int		idx;
139     char_u	*ptr;
140     char_u	*line;
141     colnr_T	col = 0;
142     int		csize = 0;
143     int		one_more;
144 #ifdef FEAT_LINEBREAK
145     int		head = 0;
146 #endif
147 
148     one_more = (State & INSERT)
149 		    || restart_edit != NUL
150 		    || (VIsual_active && *p_sel != 'o')
151 #ifdef FEAT_VIRTUALEDIT
152 		    || ((ve_flags & VE_ONEMORE) && wcol < MAXCOL)
153 #endif
154 		    ;
155     line = ml_get_buf(curbuf, pos->lnum, FALSE);
156 
157     if (wcol >= MAXCOL)
158     {
159 	    idx = (int)STRLEN(line) - 1 + one_more;
160 	    col = wcol;
161 
162 #ifdef FEAT_VIRTUALEDIT
163 	    if ((addspaces || finetune) && !VIsual_active)
164 	    {
165 		curwin->w_curswant = linetabsize(line) + one_more;
166 		if (curwin->w_curswant > 0)
167 		    --curwin->w_curswant;
168 	    }
169 #endif
170     }
171     else
172     {
173 #ifdef FEAT_VIRTUALEDIT
174 	int width = W_WIDTH(curwin) - win_col_off(curwin);
175 
176 	if (finetune
177 		&& curwin->w_p_wrap
178 # ifdef FEAT_VERTSPLIT
179 		&& curwin->w_width != 0
180 # endif
181 		&& wcol >= (colnr_T)width)
182 	{
183 	    csize = linetabsize(line);
184 	    if (csize > 0)
185 		csize--;
186 
187 	    if (wcol / width > (colnr_T)csize / width
188 		    && ((State & INSERT) == 0 || (int)wcol > csize + 1))
189 	    {
190 		/* In case of line wrapping don't move the cursor beyond the
191 		 * right screen edge.  In Insert mode allow going just beyond
192 		 * the last character (like what happens when typing and
193 		 * reaching the right window edge). */
194 		wcol = (csize / width + 1) * width - 1;
195 	    }
196 	}
197 #endif
198 
199 	ptr = line;
200 	while (col <= wcol && *ptr != NUL)
201 	{
202 	    /* Count a tab for what it's worth (if list mode not on) */
203 #ifdef FEAT_LINEBREAK
204 	    csize = win_lbr_chartabsize(curwin, ptr, col, &head);
205 	    mb_ptr_adv(ptr);
206 #else
207 	    csize = lbr_chartabsize_adv(&ptr, col);
208 #endif
209 	    col += csize;
210 	}
211 	idx = (int)(ptr - line);
212 	/*
213 	 * Handle all the special cases.  The virtual_active() check
214 	 * is needed to ensure that a virtual position off the end of
215 	 * a line has the correct indexing.  The one_more comparison
216 	 * replaces an explicit add of one_more later on.
217 	 */
218 	if (col > wcol || (!virtual_active() && one_more == 0))
219 	{
220 	    idx -= 1;
221 # ifdef FEAT_LINEBREAK
222 	    /* Don't count the chars from 'showbreak'. */
223 	    csize -= head;
224 # endif
225 	    col -= csize;
226 	}
227 
228 #ifdef FEAT_VIRTUALEDIT
229 	if (virtual_active()
230 		&& addspaces
231 		&& ((col != wcol && col != wcol + 1) || csize > 1))
232 	{
233 	    /* 'virtualedit' is set: The difference between wcol and col is
234 	     * filled with spaces. */
235 
236 	    if (line[idx] == NUL)
237 	    {
238 		/* Append spaces */
239 		int	correct = wcol - col;
240 		char_u	*newline = alloc(idx + correct + 1);
241 		int	t;
242 
243 		if (newline == NULL)
244 		    return FAIL;
245 
246 		for (t = 0; t < idx; ++t)
247 		    newline[t] = line[t];
248 
249 		for (t = 0; t < correct; ++t)
250 		    newline[t + idx] = ' ';
251 
252 		newline[idx + correct] = NUL;
253 
254 		ml_replace(pos->lnum, newline, FALSE);
255 		changed_bytes(pos->lnum, (colnr_T)idx);
256 		idx += correct;
257 		col = wcol;
258 	    }
259 	    else
260 	    {
261 		/* Break a tab */
262 		int	linelen = (int)STRLEN(line);
263 		int	correct = wcol - col - csize + 1; /* negative!! */
264 		char_u	*newline;
265 		int	t, s = 0;
266 		int	v;
267 
268 		if (-correct > csize)
269 		    return FAIL;
270 
271 		newline = alloc(linelen + csize);
272 		if (newline == NULL)
273 		    return FAIL;
274 
275 		for (t = 0; t < linelen; t++)
276 		{
277 		    if (t != idx)
278 			newline[s++] = line[t];
279 		    else
280 			for (v = 0; v < csize; v++)
281 			    newline[s++] = ' ';
282 		}
283 
284 		newline[linelen + csize - 1] = NUL;
285 
286 		ml_replace(pos->lnum, newline, FALSE);
287 		changed_bytes(pos->lnum, idx);
288 		idx += (csize - 1 + correct);
289 		col += correct;
290 	    }
291 	}
292 #endif
293     }
294 
295     if (idx < 0)
296 	pos->col = 0;
297     else
298 	pos->col = idx;
299 
300 #ifdef FEAT_VIRTUALEDIT
301     pos->coladd = 0;
302 
303     if (finetune)
304     {
305 	if (wcol == MAXCOL)
306 	{
307 	    /* The width of the last character is used to set coladd. */
308 	    if (!one_more)
309 	    {
310 		colnr_T	    scol, ecol;
311 
312 		getvcol(curwin, pos, &scol, NULL, &ecol);
313 		pos->coladd = ecol - scol;
314 	    }
315 	}
316 	else
317 	{
318 	    int b = (int)wcol - (int)col;
319 
320 	    /* The difference between wcol and col is used to set coladd. */
321 	    if (b > 0 && b < (MAXCOL - 2 * W_WIDTH(curwin)))
322 		pos->coladd = b;
323 
324 	    col += b;
325 	}
326     }
327 #endif
328 
329 #ifdef FEAT_MBYTE
330     /* prevent from moving onto a trail byte */
331     if (has_mbyte)
332 	mb_adjustpos(curbuf, pos);
333 #endif
334 
335     if (col < wcol)
336 	return FAIL;
337     return OK;
338 }
339 
340 /*
341  * Increment the cursor position.  See inc() for return values.
342  */
343     int
344 inc_cursor()
345 {
346     return inc(&curwin->w_cursor);
347 }
348 
349 /*
350  * Increment the line pointer "lp" crossing line boundaries as necessary.
351  * Return 1 when going to the next line.
352  * Return 2 when moving forward onto a NUL at the end of the line).
353  * Return -1 when at the end of file.
354  * Return 0 otherwise.
355  */
356     int
357 inc(lp)
358     pos_T  *lp;
359 {
360     char_u  *p = ml_get_pos(lp);
361 
362     if (*p != NUL)	/* still within line, move to next char (may be NUL) */
363     {
364 #ifdef FEAT_MBYTE
365 	if (has_mbyte)
366 	{
367 	    int l = (*mb_ptr2len)(p);
368 
369 	    lp->col += l;
370 	    return ((p[l] != NUL) ? 0 : 2);
371 	}
372 #endif
373 	lp->col++;
374 #ifdef FEAT_VIRTUALEDIT
375 	lp->coladd = 0;
376 #endif
377 	return ((p[1] != NUL) ? 0 : 2);
378     }
379     if (lp->lnum != curbuf->b_ml.ml_line_count)     /* there is a next line */
380     {
381 	lp->col = 0;
382 	lp->lnum++;
383 #ifdef FEAT_VIRTUALEDIT
384 	lp->coladd = 0;
385 #endif
386 	return 1;
387     }
388     return -1;
389 }
390 
391 /*
392  * incl(lp): same as inc(), but skip the NUL at the end of non-empty lines
393  */
394     int
395 incl(lp)
396     pos_T    *lp;
397 {
398     int	    r;
399 
400     if ((r = inc(lp)) >= 1 && lp->col)
401 	r = inc(lp);
402     return r;
403 }
404 
405 /*
406  * dec(p)
407  *
408  * Decrement the line pointer 'p' crossing line boundaries as necessary.
409  * Return 1 when crossing a line, -1 when at start of file, 0 otherwise.
410  */
411     int
412 dec_cursor()
413 {
414     return dec(&curwin->w_cursor);
415 }
416 
417     int
418 dec(lp)
419     pos_T  *lp;
420 {
421     char_u	*p;
422 
423 #ifdef FEAT_VIRTUALEDIT
424     lp->coladd = 0;
425 #endif
426     if (lp->col > 0)		/* still within line */
427     {
428 	lp->col--;
429 #ifdef FEAT_MBYTE
430 	if (has_mbyte)
431 	{
432 	    p = ml_get(lp->lnum);
433 	    lp->col -= (*mb_head_off)(p, p + lp->col);
434 	}
435 #endif
436 	return 0;
437     }
438     if (lp->lnum > 1)		/* there is a prior line */
439     {
440 	lp->lnum--;
441 	p = ml_get(lp->lnum);
442 	lp->col = (colnr_T)STRLEN(p);
443 #ifdef FEAT_MBYTE
444 	if (has_mbyte)
445 	    lp->col -= (*mb_head_off)(p, p + lp->col);
446 #endif
447 	return 1;
448     }
449     return -1;			/* at start of file */
450 }
451 
452 /*
453  * decl(lp): same as dec(), but skip the NUL at the end of non-empty lines
454  */
455     int
456 decl(lp)
457     pos_T    *lp;
458 {
459     int	    r;
460 
461     if ((r = dec(lp)) == 1 && lp->col)
462 	r = dec(lp);
463     return r;
464 }
465 
466 /*
467  * Get the line number relative to the current cursor position, i.e. the
468  * difference between line number and cursor position. Only look for lines that
469  * can be visible, folded lines don't count.
470  */
471     linenr_T
472 get_cursor_rel_lnum(wp, lnum)
473     win_T	*wp;
474     linenr_T	lnum;		    /* line number to get the result for */
475 {
476     linenr_T	cursor = wp->w_cursor.lnum;
477     linenr_T	retval = 0;
478 
479 #ifdef FEAT_FOLDING
480     if (hasAnyFolding(wp))
481     {
482 	if (lnum > cursor)
483 	{
484 	    while (lnum > cursor)
485 	    {
486 		(void)hasFoldingWin(wp, lnum, &lnum, NULL, TRUE, NULL);
487 		/* if lnum and cursor are in the same fold,
488 		 * now lnum <= cursor */
489 		if (lnum > cursor)
490 		    retval++;
491 		lnum--;
492 	    }
493 	}
494 	else if (lnum < cursor)
495 	{
496 	    while (lnum < cursor)
497 	    {
498 		(void)hasFoldingWin(wp, lnum, NULL, &lnum, TRUE, NULL);
499 		/* if lnum and cursor are in the same fold,
500 		 * now lnum >= cursor */
501 		if (lnum < cursor)
502 		    retval--;
503 		lnum++;
504 	    }
505 	}
506 	/* else if (lnum == cursor)
507 	 *     retval = 0;
508 	 */
509     }
510     else
511 #endif
512 	retval = lnum - cursor;
513 
514     return retval;
515 }
516 
517 /*
518  * Make sure curwin->w_cursor.lnum is valid.
519  */
520     void
521 check_cursor_lnum()
522 {
523     if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
524     {
525 #ifdef FEAT_FOLDING
526 	/* If there is a closed fold at the end of the file, put the cursor in
527 	 * its first line.  Otherwise in the last line. */
528 	if (!hasFolding(curbuf->b_ml.ml_line_count,
529 						&curwin->w_cursor.lnum, NULL))
530 #endif
531 	    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
532     }
533     if (curwin->w_cursor.lnum <= 0)
534 	curwin->w_cursor.lnum = 1;
535 }
536 
537 /*
538  * Make sure curwin->w_cursor.col is valid.
539  */
540     void
541 check_cursor_col()
542 {
543     check_cursor_col_win(curwin);
544 }
545 
546 /*
547  * Make sure win->w_cursor.col is valid.
548  */
549     void
550 check_cursor_col_win(win)
551     win_T *win;
552 {
553     colnr_T len;
554 #ifdef FEAT_VIRTUALEDIT
555     colnr_T oldcol = win->w_cursor.col;
556     colnr_T oldcoladd = win->w_cursor.col + win->w_cursor.coladd;
557 #endif
558 
559     len = (colnr_T)STRLEN(ml_get_buf(win->w_buffer, win->w_cursor.lnum, FALSE));
560     if (len == 0)
561 	win->w_cursor.col = 0;
562     else if (win->w_cursor.col >= len)
563     {
564 	/* Allow cursor past end-of-line when:
565 	 * - in Insert mode or restarting Insert mode
566 	 * - in Visual mode and 'selection' isn't "old"
567 	 * - 'virtualedit' is set */
568 	if ((State & INSERT) || restart_edit
569 		|| (VIsual_active && *p_sel != 'o')
570 #ifdef FEAT_VIRTUALEDIT
571 		|| (ve_flags & VE_ONEMORE)
572 #endif
573 		|| virtual_active())
574 	    win->w_cursor.col = len;
575 	else
576 	{
577 	    win->w_cursor.col = len - 1;
578 #ifdef FEAT_MBYTE
579 	    /* Move the cursor to the head byte. */
580 	    if (has_mbyte)
581 		mb_adjustpos(win->w_buffer, &win->w_cursor);
582 #endif
583 	}
584     }
585     else if (win->w_cursor.col < 0)
586 	win->w_cursor.col = 0;
587 
588 #ifdef FEAT_VIRTUALEDIT
589     /* If virtual editing is on, we can leave the cursor on the old position,
590      * only we must set it to virtual.  But don't do it when at the end of the
591      * line. */
592     if (oldcol == MAXCOL)
593 	win->w_cursor.coladd = 0;
594     else if (ve_flags == VE_ALL)
595     {
596 	if (oldcoladd > win->w_cursor.col)
597 	    win->w_cursor.coladd = oldcoladd - win->w_cursor.col;
598 	else
599 	    /* avoid weird number when there is a miscalculation or overflow */
600 	    win->w_cursor.coladd = 0;
601     }
602 #endif
603 }
604 
605 /*
606  * make sure curwin->w_cursor in on a valid character
607  */
608     void
609 check_cursor()
610 {
611     check_cursor_lnum();
612     check_cursor_col();
613 }
614 
615 #if defined(FEAT_TEXTOBJ) || defined(PROTO)
616 /*
617  * Make sure curwin->w_cursor is not on the NUL at the end of the line.
618  * Allow it when in Visual mode and 'selection' is not "old".
619  */
620     void
621 adjust_cursor_col()
622 {
623     if (curwin->w_cursor.col > 0
624 	    && (!VIsual_active || *p_sel == 'o')
625 	    && gchar_cursor() == NUL)
626 	--curwin->w_cursor.col;
627 }
628 #endif
629 
630 /*
631  * When curwin->w_leftcol has changed, adjust the cursor position.
632  * Return TRUE if the cursor was moved.
633  */
634     int
635 leftcol_changed()
636 {
637     long	lastcol;
638     colnr_T	s, e;
639     int		retval = FALSE;
640 
641     changed_cline_bef_curs();
642     lastcol = curwin->w_leftcol + W_WIDTH(curwin) - curwin_col_off() - 1;
643     validate_virtcol();
644 
645     /*
646      * If the cursor is right or left of the screen, move it to last or first
647      * character.
648      */
649     if (curwin->w_virtcol > (colnr_T)(lastcol - p_siso))
650     {
651 	retval = TRUE;
652 	coladvance((colnr_T)(lastcol - p_siso));
653     }
654     else if (curwin->w_virtcol < curwin->w_leftcol + p_siso)
655     {
656 	retval = TRUE;
657 	(void)coladvance((colnr_T)(curwin->w_leftcol + p_siso));
658     }
659 
660     /*
661      * If the start of the character under the cursor is not on the screen,
662      * advance the cursor one more char.  If this fails (last char of the
663      * line) adjust the scrolling.
664      */
665     getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
666     if (e > (colnr_T)lastcol)
667     {
668 	retval = TRUE;
669 	coladvance(s - 1);
670     }
671     else if (s < curwin->w_leftcol)
672     {
673 	retval = TRUE;
674 	if (coladvance(e + 1) == FAIL)	/* there isn't another character */
675 	{
676 	    curwin->w_leftcol = s;	/* adjust w_leftcol instead */
677 	    changed_cline_bef_curs();
678 	}
679     }
680 
681     if (retval)
682 	curwin->w_set_curswant = TRUE;
683     redraw_later(NOT_VALID);
684     return retval;
685 }
686 
687 /**********************************************************************
688  * Various routines dealing with allocation and deallocation of memory.
689  */
690 
691 #if defined(MEM_PROFILE) || defined(PROTO)
692 
693 # define MEM_SIZES  8200
694 static long_u mem_allocs[MEM_SIZES];
695 static long_u mem_frees[MEM_SIZES];
696 static long_u mem_allocated;
697 static long_u mem_freed;
698 static long_u mem_peak;
699 static long_u num_alloc;
700 static long_u num_freed;
701 
702 static void mem_pre_alloc_s __ARGS((size_t *sizep));
703 static void mem_pre_alloc_l __ARGS((long_u *sizep));
704 static void mem_post_alloc __ARGS((void **pp, size_t size));
705 static void mem_pre_free __ARGS((void **pp));
706 
707     static void
708 mem_pre_alloc_s(sizep)
709     size_t *sizep;
710 {
711     *sizep += sizeof(size_t);
712 }
713 
714     static void
715 mem_pre_alloc_l(sizep)
716     long_u *sizep;
717 {
718     *sizep += sizeof(size_t);
719 }
720 
721     static void
722 mem_post_alloc(pp, size)
723     void **pp;
724     size_t size;
725 {
726     if (*pp == NULL)
727 	return;
728     size -= sizeof(size_t);
729     *(long_u *)*pp = size;
730     if (size <= MEM_SIZES-1)
731 	mem_allocs[size-1]++;
732     else
733 	mem_allocs[MEM_SIZES-1]++;
734     mem_allocated += size;
735     if (mem_allocated - mem_freed > mem_peak)
736 	mem_peak = mem_allocated - mem_freed;
737     num_alloc++;
738     *pp = (void *)((char *)*pp + sizeof(size_t));
739 }
740 
741     static void
742 mem_pre_free(pp)
743     void **pp;
744 {
745     long_u size;
746 
747     *pp = (void *)((char *)*pp - sizeof(size_t));
748     size = *(size_t *)*pp;
749     if (size <= MEM_SIZES-1)
750 	mem_frees[size-1]++;
751     else
752 	mem_frees[MEM_SIZES-1]++;
753     mem_freed += size;
754     num_freed++;
755 }
756 
757 /*
758  * called on exit via atexit()
759  */
760     void
761 vim_mem_profile_dump()
762 {
763     int i, j;
764 
765     printf("\r\n");
766     j = 0;
767     for (i = 0; i < MEM_SIZES - 1; i++)
768     {
769 	if (mem_allocs[i] || mem_frees[i])
770 	{
771 	    if (mem_frees[i] > mem_allocs[i])
772 		printf("\r\n%s", _("ERROR: "));
773 	    printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
774 	    j++;
775 	    if (j > 3)
776 	    {
777 		j = 0;
778 		printf("\r\n");
779 	    }
780 	}
781     }
782 
783     i = MEM_SIZES - 1;
784     if (mem_allocs[i])
785     {
786 	printf("\r\n");
787 	if (mem_frees[i] > mem_allocs[i])
788 	    puts(_("ERROR: "));
789 	printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
790     }
791 
792     printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
793 	    mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
794     printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
795 	    num_alloc, num_freed);
796 }
797 
798 #endif /* MEM_PROFILE */
799 
800 /*
801  * Some memory is reserved for error messages and for being able to
802  * call mf_release_all(), which needs some memory for mf_trans_add().
803  */
804 #if defined(MSDOS) && !defined(DJGPP)
805 # define SMALL_MEM
806 # define KEEP_ROOM 8192L
807 #else
808 # define KEEP_ROOM (2 * 8192L)
809 #endif
810 #define KEEP_ROOM_KB (KEEP_ROOM / 1024L)
811 
812 /*
813  * Note: if unsigned is 16 bits we can only allocate up to 64K with alloc().
814  * Use lalloc for larger blocks.
815  */
816     char_u *
817 alloc(size)
818     unsigned	    size;
819 {
820     return (lalloc((long_u)size, TRUE));
821 }
822 
823 /*
824  * Allocate memory and set all bytes to zero.
825  */
826     char_u *
827 alloc_clear(size)
828     unsigned	    size;
829 {
830     char_u *p;
831 
832     p = lalloc((long_u)size, TRUE);
833     if (p != NULL)
834 	(void)vim_memset(p, 0, (size_t)size);
835     return p;
836 }
837 
838 /*
839  * alloc() with check for maximum line length
840  */
841     char_u *
842 alloc_check(size)
843     unsigned	    size;
844 {
845 #if !defined(UNIX) && !defined(__EMX__)
846     if (sizeof(int) == 2 && size > 0x7fff)
847     {
848 	/* Don't hide this message */
849 	emsg_silent = 0;
850 	EMSG(_("E340: Line is becoming too long"));
851 	return NULL;
852     }
853 #endif
854     return (lalloc((long_u)size, TRUE));
855 }
856 
857 /*
858  * Allocate memory like lalloc() and set all bytes to zero.
859  */
860     char_u *
861 lalloc_clear(size, message)
862     long_u	size;
863     int		message;
864 {
865     char_u *p;
866 
867     p = (lalloc(size, message));
868     if (p != NULL)
869 	(void)vim_memset(p, 0, (size_t)size);
870     return p;
871 }
872 
873 /*
874  * Low level memory allocation function.
875  * This is used often, KEEP IT FAST!
876  */
877     char_u *
878 lalloc(size, message)
879     long_u	size;
880     int		message;
881 {
882     char_u	*p;		    /* pointer to new storage space */
883     static int	releasing = FALSE;  /* don't do mf_release_all() recursive */
884     int		try_again;
885 #if defined(HAVE_AVAIL_MEM) && !defined(SMALL_MEM)
886     static long_u allocated = 0;    /* allocated since last avail check */
887 #endif
888 
889     /* Safety check for allocating zero bytes */
890     if (size == 0)
891     {
892 	/* Don't hide this message */
893 	emsg_silent = 0;
894 	EMSGN(_("E341: Internal error: lalloc(%ld, )"), size);
895 	return NULL;
896     }
897 
898 #ifdef MEM_PROFILE
899     mem_pre_alloc_l(&size);
900 #endif
901 
902 #if defined(MSDOS) && !defined(DJGPP)
903     if (size >= 0xfff0)		/* in MSDOS we can't deal with >64K blocks */
904 	p = NULL;
905     else
906 #endif
907 
908     /*
909      * Loop when out of memory: Try to release some memfile blocks and
910      * if some blocks are released call malloc again.
911      */
912     for (;;)
913     {
914 	/*
915 	 * Handle three kind of systems:
916 	 * 1. No check for available memory: Just return.
917 	 * 2. Slow check for available memory: call mch_avail_mem() after
918 	 *    allocating KEEP_ROOM amount of memory.
919 	 * 3. Strict check for available memory: call mch_avail_mem()
920 	 */
921 	if ((p = (char_u *)malloc((size_t)size)) != NULL)
922 	{
923 #ifndef HAVE_AVAIL_MEM
924 	    /* 1. No check for available memory: Just return. */
925 	    goto theend;
926 #else
927 # ifndef SMALL_MEM
928 	    /* 2. Slow check for available memory: call mch_avail_mem() after
929 	     *    allocating (KEEP_ROOM / 2) amount of memory. */
930 	    allocated += size;
931 	    if (allocated < KEEP_ROOM / 2)
932 		goto theend;
933 	    allocated = 0;
934 # endif
935 	    /* 3. check for available memory: call mch_avail_mem() */
936 	    if (mch_avail_mem(TRUE) < KEEP_ROOM_KB && !releasing)
937 	    {
938 		free((char *)p);	/* System is low... no go! */
939 		p = NULL;
940 	    }
941 	    else
942 		goto theend;
943 #endif
944 	}
945 	/*
946 	 * Remember that mf_release_all() is being called to avoid an endless
947 	 * loop, because mf_release_all() may call alloc() recursively.
948 	 */
949 	if (releasing)
950 	    break;
951 	releasing = TRUE;
952 
953 	clear_sb_text();	      /* free any scrollback text */
954 	try_again = mf_release_all(); /* release as many blocks as possible */
955 #ifdef FEAT_EVAL
956 	try_again |= garbage_collect(); /* cleanup recursive lists/dicts */
957 #endif
958 
959 	releasing = FALSE;
960 	if (!try_again)
961 	    break;
962     }
963 
964     if (message && p == NULL)
965 	do_outofmem_msg(size);
966 
967 theend:
968 #ifdef MEM_PROFILE
969     mem_post_alloc((void **)&p, (size_t)size);
970 #endif
971     return p;
972 }
973 
974 #if defined(MEM_PROFILE) || defined(PROTO)
975 /*
976  * realloc() with memory profiling.
977  */
978     void *
979 mem_realloc(ptr, size)
980     void *ptr;
981     size_t size;
982 {
983     void *p;
984 
985     mem_pre_free(&ptr);
986     mem_pre_alloc_s(&size);
987 
988     p = realloc(ptr, size);
989 
990     mem_post_alloc(&p, size);
991 
992     return p;
993 }
994 #endif
995 
996 /*
997 * Avoid repeating the error message many times (they take 1 second each).
998 * Did_outofmem_msg is reset when a character is read.
999 */
1000     void
1001 do_outofmem_msg(size)
1002     long_u	size;
1003 {
1004     if (!did_outofmem_msg)
1005     {
1006 	/* Don't hide this message */
1007 	emsg_silent = 0;
1008 
1009 	/* Must come first to avoid coming back here when printing the error
1010 	 * message fails, e.g. when setting v:errmsg. */
1011 	did_outofmem_msg = TRUE;
1012 
1013 	EMSGN(_("E342: Out of memory!  (allocating %lu bytes)"), size);
1014     }
1015 }
1016 
1017 #if defined(EXITFREE) || defined(PROTO)
1018 
1019 # if defined(FEAT_SEARCHPATH)
1020 static void free_findfile __ARGS((void));
1021 # endif
1022 
1023 /*
1024  * Free everything that we allocated.
1025  * Can be used to detect memory leaks, e.g., with ccmalloc.
1026  * NOTE: This is tricky!  Things are freed that functions depend on.  Don't be
1027  * surprised if Vim crashes...
1028  * Some things can't be freed, esp. things local to a library function.
1029  */
1030     void
1031 free_all_mem()
1032 {
1033     buf_T	*buf, *nextbuf;
1034     static int	entered = FALSE;
1035 
1036     /* When we cause a crash here it is caught and Vim tries to exit cleanly.
1037      * Don't try freeing everything again. */
1038     if (entered)
1039 	return;
1040     entered = TRUE;
1041 
1042 # ifdef FEAT_AUTOCMD
1043     block_autocmds();	    /* don't want to trigger autocommands here */
1044 # endif
1045 
1046 # ifdef FEAT_WINDOWS
1047     /* Close all tabs and windows.  Reset 'equalalways' to avoid redraws. */
1048     p_ea = FALSE;
1049     if (first_tabpage->tp_next != NULL)
1050 	do_cmdline_cmd((char_u *)"tabonly!");
1051     if (firstwin != lastwin)
1052 	do_cmdline_cmd((char_u *)"only!");
1053 # endif
1054 
1055 # if defined(FEAT_SPELL)
1056     /* Free all spell info. */
1057     spell_free_all();
1058 # endif
1059 
1060 # if defined(FEAT_USR_CMDS)
1061     /* Clear user commands (before deleting buffers). */
1062     ex_comclear(NULL);
1063 # endif
1064 
1065 # ifdef FEAT_MENU
1066     /* Clear menus. */
1067     do_cmdline_cmd((char_u *)"aunmenu *");
1068 #  ifdef FEAT_MULTI_LANG
1069     do_cmdline_cmd((char_u *)"menutranslate clear");
1070 #  endif
1071 # endif
1072 
1073     /* Clear mappings, abbreviations, breakpoints. */
1074     do_cmdline_cmd((char_u *)"lmapclear");
1075     do_cmdline_cmd((char_u *)"xmapclear");
1076     do_cmdline_cmd((char_u *)"mapclear");
1077     do_cmdline_cmd((char_u *)"mapclear!");
1078     do_cmdline_cmd((char_u *)"abclear");
1079 # if defined(FEAT_EVAL)
1080     do_cmdline_cmd((char_u *)"breakdel *");
1081 # endif
1082 # if defined(FEAT_PROFILE)
1083     do_cmdline_cmd((char_u *)"profdel *");
1084 # endif
1085 # if defined(FEAT_KEYMAP)
1086     do_cmdline_cmd((char_u *)"set keymap=");
1087 #endif
1088 
1089 # ifdef FEAT_TITLE
1090     free_titles();
1091 # endif
1092 # if defined(FEAT_SEARCHPATH)
1093     free_findfile();
1094 # endif
1095 
1096     /* Obviously named calls. */
1097 # if defined(FEAT_AUTOCMD)
1098     free_all_autocmds();
1099 # endif
1100     clear_termcodes();
1101     free_all_options();
1102     free_all_marks();
1103     alist_clear(&global_alist);
1104     free_homedir();
1105 # if defined(FEAT_CMDL_COMPL)
1106     free_users();
1107 # endif
1108     free_search_patterns();
1109     free_old_sub();
1110     free_last_insert();
1111     free_prev_shellcmd();
1112     free_regexp_stuff();
1113     free_tag_stuff();
1114     free_cd_dir();
1115 # ifdef FEAT_SIGNS
1116     free_signs();
1117 # endif
1118 # ifdef FEAT_EVAL
1119     set_expr_line(NULL);
1120 # endif
1121 # ifdef FEAT_DIFF
1122     diff_clear(curtab);
1123 # endif
1124     clear_sb_text();	      /* free any scrollback text */
1125 
1126     /* Free some global vars. */
1127     vim_free(username);
1128 # ifdef FEAT_CLIPBOARD
1129     vim_regfree(clip_exclude_prog);
1130 # endif
1131     vim_free(last_cmdline);
1132 # ifdef FEAT_CMDHIST
1133     vim_free(new_last_cmdline);
1134 # endif
1135     set_keep_msg(NULL, 0);
1136     vim_free(ff_expand_buffer);
1137 
1138     /* Clear cmdline history. */
1139     p_hi = 0;
1140 # ifdef FEAT_CMDHIST
1141     init_history();
1142 # endif
1143 
1144 #ifdef FEAT_QUICKFIX
1145     {
1146 	win_T	    *win;
1147 	tabpage_T   *tab;
1148 
1149 	qf_free_all(NULL);
1150 	/* Free all location lists */
1151 	FOR_ALL_TAB_WINDOWS(tab, win)
1152 	    qf_free_all(win);
1153     }
1154 #endif
1155 
1156     /* Close all script inputs. */
1157     close_all_scripts();
1158 
1159 #if defined(FEAT_WINDOWS)
1160     /* Destroy all windows.  Must come before freeing buffers. */
1161     win_free_all();
1162 #endif
1163 
1164     /* Free all buffers.  Reset 'autochdir' to avoid accessing things that
1165      * were freed already. */
1166 #ifdef FEAT_AUTOCHDIR
1167     p_acd = FALSE;
1168 #endif
1169     for (buf = firstbuf; buf != NULL; )
1170     {
1171 	nextbuf = buf->b_next;
1172 	close_buffer(NULL, buf, DOBUF_WIPE, FALSE);
1173 	if (buf_valid(buf))
1174 	    buf = nextbuf;	/* didn't work, try next one */
1175 	else
1176 	    buf = firstbuf;
1177     }
1178 
1179 #ifdef FEAT_ARABIC
1180     free_cmdline_buf();
1181 #endif
1182 
1183     /* Clear registers. */
1184     clear_registers();
1185     ResetRedobuff();
1186     ResetRedobuff();
1187 
1188 #if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
1189     vim_free(serverDelayedStartName);
1190 #endif
1191 
1192     /* highlight info */
1193     free_highlight();
1194 
1195     reset_last_sourcing();
1196 
1197 #ifdef FEAT_WINDOWS
1198     free_tabpage(first_tabpage);
1199     first_tabpage = NULL;
1200 #endif
1201 
1202 # ifdef UNIX
1203     /* Machine-specific free. */
1204     mch_free_mem();
1205 # endif
1206 
1207     /* message history */
1208     for (;;)
1209 	if (delete_first_msg() == FAIL)
1210 	    break;
1211 
1212 # ifdef FEAT_EVAL
1213     eval_clear();
1214 # endif
1215 
1216     free_termoptions();
1217 
1218     /* screenlines (can't display anything now!) */
1219     free_screenlines();
1220 
1221 #if defined(USE_XSMP)
1222     xsmp_close();
1223 #endif
1224 #ifdef FEAT_GUI_GTK
1225     gui_mch_free_all();
1226 #endif
1227     clear_hl_tables();
1228 
1229     vim_free(IObuff);
1230     vim_free(NameBuff);
1231 }
1232 #endif
1233 
1234 /*
1235  * Copy "string" into newly allocated memory.
1236  */
1237     char_u *
1238 vim_strsave(string)
1239     char_u	*string;
1240 {
1241     char_u	*p;
1242     unsigned	len;
1243 
1244     len = (unsigned)STRLEN(string) + 1;
1245     p = alloc(len);
1246     if (p != NULL)
1247 	mch_memmove(p, string, (size_t)len);
1248     return p;
1249 }
1250 
1251 /*
1252  * Copy up to "len" bytes of "string" into newly allocated memory and
1253  * terminate with a NUL.
1254  * The allocated memory always has size "len + 1", also when "string" is
1255  * shorter.
1256  */
1257     char_u *
1258 vim_strnsave(string, len)
1259     char_u	*string;
1260     int		len;
1261 {
1262     char_u	*p;
1263 
1264     p = alloc((unsigned)(len + 1));
1265     if (p != NULL)
1266     {
1267 	STRNCPY(p, string, len);
1268 	p[len] = NUL;
1269     }
1270     return p;
1271 }
1272 
1273 /*
1274  * Same as vim_strsave(), but any characters found in esc_chars are preceded
1275  * by a backslash.
1276  */
1277     char_u *
1278 vim_strsave_escaped(string, esc_chars)
1279     char_u	*string;
1280     char_u	*esc_chars;
1281 {
1282     return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE);
1283 }
1284 
1285 /*
1286  * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape
1287  * characters where rem_backslash() would remove the backslash.
1288  * Escape the characters with "cc".
1289  */
1290     char_u *
1291 vim_strsave_escaped_ext(string, esc_chars, cc, bsl)
1292     char_u	*string;
1293     char_u	*esc_chars;
1294     int		cc;
1295     int		bsl;
1296 {
1297     char_u	*p;
1298     char_u	*p2;
1299     char_u	*escaped_string;
1300     unsigned	length;
1301 #ifdef FEAT_MBYTE
1302     int		l;
1303 #endif
1304 
1305     /*
1306      * First count the number of backslashes required.
1307      * Then allocate the memory and insert them.
1308      */
1309     length = 1;				/* count the trailing NUL */
1310     for (p = string; *p; p++)
1311     {
1312 #ifdef FEAT_MBYTE
1313 	if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1314 	{
1315 	    length += l;		/* count a multibyte char */
1316 	    p += l - 1;
1317 	    continue;
1318 	}
1319 #endif
1320 	if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1321 	    ++length;			/* count a backslash */
1322 	++length;			/* count an ordinary char */
1323     }
1324     escaped_string = alloc(length);
1325     if (escaped_string != NULL)
1326     {
1327 	p2 = escaped_string;
1328 	for (p = string; *p; p++)
1329 	{
1330 #ifdef FEAT_MBYTE
1331 	    if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1332 	    {
1333 		mch_memmove(p2, p, (size_t)l);
1334 		p2 += l;
1335 		p += l - 1;		/* skip multibyte char  */
1336 		continue;
1337 	    }
1338 #endif
1339 	    if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1340 		*p2++ = cc;
1341 	    *p2++ = *p;
1342 	}
1343 	*p2 = NUL;
1344     }
1345     return escaped_string;
1346 }
1347 
1348 /*
1349  * Return TRUE when 'shell' has "csh" in the tail.
1350  */
1351     int
1352 csh_like_shell()
1353 {
1354     return (strstr((char *)gettail(p_sh), "csh") != NULL);
1355 }
1356 
1357 /*
1358  * Escape "string" for use as a shell argument with system().
1359  * This uses single quotes, except when we know we need to use double quotes
1360  * (MS-DOS and MS-Windows without 'shellslash' set).
1361  * Escape a newline, depending on the 'shell' option.
1362  * When "do_special" is TRUE also replace "!", "%", "#" and things starting
1363  * with "<" like "<cfile>".
1364  * When "do_newline" is FALSE do not escape newline unless it is csh shell.
1365  * Returns the result in allocated memory, NULL if we have run out.
1366  */
1367     char_u *
1368 vim_strsave_shellescape(string, do_special, do_newline)
1369     char_u	*string;
1370     int		do_special;
1371     int		do_newline;
1372 {
1373     unsigned	length;
1374     char_u	*p;
1375     char_u	*d;
1376     char_u	*escaped_string;
1377     int		l;
1378     int		csh_like;
1379 
1380     /* Only csh and similar shells expand '!' within single quotes.  For sh and
1381      * the like we must not put a backslash before it, it will be taken
1382      * literally.  If do_special is set the '!' will be escaped twice.
1383      * Csh also needs to have "\n" escaped twice when do_special is set. */
1384     csh_like = csh_like_shell();
1385 
1386     /* First count the number of extra bytes required. */
1387     length = (unsigned)STRLEN(string) + 3;  /* two quotes and a trailing NUL */
1388     for (p = string; *p != NUL; mb_ptr_adv(p))
1389     {
1390 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1391 	if (!p_ssl)
1392 	{
1393 	    if (*p == '"')
1394 		++length;		/* " -> "" */
1395 	}
1396 	else
1397 # endif
1398 	if (*p == '\'')
1399 	    length += 3;		/* ' => '\'' */
1400 	if ((*p == '\n' && (csh_like || do_newline))
1401 		|| (*p == '!' && (csh_like || do_special)))
1402 	{
1403 	    ++length;			/* insert backslash */
1404 	    if (csh_like && do_special)
1405 		++length;		/* insert backslash */
1406 	}
1407 	if (do_special && find_cmdline_var(p, &l) >= 0)
1408 	{
1409 	    ++length;			/* insert backslash */
1410 	    p += l - 1;
1411 	}
1412     }
1413 
1414     /* Allocate memory for the result and fill it. */
1415     escaped_string = alloc(length);
1416     if (escaped_string != NULL)
1417     {
1418 	d = escaped_string;
1419 
1420 	/* add opening quote */
1421 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1422 	if (!p_ssl)
1423 	    *d++ = '"';
1424 	else
1425 # endif
1426 	    *d++ = '\'';
1427 
1428 	for (p = string; *p != NUL; )
1429 	{
1430 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1431 	    if (!p_ssl)
1432 	    {
1433 		if (*p == '"')
1434 		{
1435 		    *d++ = '"';
1436 		    *d++ = '"';
1437 		    ++p;
1438 		    continue;
1439 		}
1440 	    }
1441 	    else
1442 # endif
1443 	    if (*p == '\'')
1444 	    {
1445 		*d++ = '\'';
1446 		*d++ = '\\';
1447 		*d++ = '\'';
1448 		*d++ = '\'';
1449 		++p;
1450 		continue;
1451 	    }
1452 	    if ((*p == '\n' && (csh_like || do_newline))
1453 		    || (*p == '!' && (csh_like || do_special)))
1454 	    {
1455 		*d++ = '\\';
1456 		if (csh_like && do_special)
1457 		    *d++ = '\\';
1458 		*d++ = *p++;
1459 		continue;
1460 	    }
1461 	    if (do_special && find_cmdline_var(p, &l) >= 0)
1462 	    {
1463 		*d++ = '\\';		/* insert backslash */
1464 		while (--l >= 0)	/* copy the var */
1465 		    *d++ = *p++;
1466 		continue;
1467 	    }
1468 
1469 	    MB_COPY_CHAR(p, d);
1470 	}
1471 
1472 	/* add terminating quote and finish with a NUL */
1473 # if defined(WIN32) || defined(WIN16) || defined(DOS)
1474 	if (!p_ssl)
1475 	    *d++ = '"';
1476 	else
1477 # endif
1478 	    *d++ = '\'';
1479 	*d = NUL;
1480     }
1481 
1482     return escaped_string;
1483 }
1484 
1485 /*
1486  * Like vim_strsave(), but make all characters uppercase.
1487  * This uses ASCII lower-to-upper case translation, language independent.
1488  */
1489     char_u *
1490 vim_strsave_up(string)
1491     char_u	*string;
1492 {
1493     char_u *p1;
1494 
1495     p1 = vim_strsave(string);
1496     vim_strup(p1);
1497     return p1;
1498 }
1499 
1500 /*
1501  * Like vim_strnsave(), but make all characters uppercase.
1502  * This uses ASCII lower-to-upper case translation, language independent.
1503  */
1504     char_u *
1505 vim_strnsave_up(string, len)
1506     char_u	*string;
1507     int		len;
1508 {
1509     char_u *p1;
1510 
1511     p1 = vim_strnsave(string, len);
1512     vim_strup(p1);
1513     return p1;
1514 }
1515 
1516 /*
1517  * ASCII lower-to-upper case translation, language independent.
1518  */
1519     void
1520 vim_strup(p)
1521     char_u	*p;
1522 {
1523     char_u  *p2;
1524     int	    c;
1525 
1526     if (p != NULL)
1527     {
1528 	p2 = p;
1529 	while ((c = *p2) != NUL)
1530 #ifdef EBCDIC
1531 	    *p2++ = isalpha(c) ? toupper(c) : c;
1532 #else
1533 	    *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20);
1534 #endif
1535     }
1536 }
1537 
1538 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
1539 /*
1540  * Make string "s" all upper-case and return it in allocated memory.
1541  * Handles multi-byte characters as well as possible.
1542  * Returns NULL when out of memory.
1543  */
1544     char_u *
1545 strup_save(orig)
1546     char_u	*orig;
1547 {
1548     char_u	*p;
1549     char_u	*res;
1550 
1551     res = p = vim_strsave(orig);
1552 
1553     if (res != NULL)
1554 	while (*p != NUL)
1555 	{
1556 # ifdef FEAT_MBYTE
1557 	    int		l;
1558 
1559 	    if (enc_utf8)
1560 	    {
1561 		int	c, uc;
1562 		int	newl;
1563 		char_u	*s;
1564 
1565 		c = utf_ptr2char(p);
1566 		uc = utf_toupper(c);
1567 
1568 		/* Reallocate string when byte count changes.  This is rare,
1569 		 * thus it's OK to do another malloc()/free(). */
1570 		l = utf_ptr2len(p);
1571 		newl = utf_char2len(uc);
1572 		if (newl != l)
1573 		{
1574 		    s = alloc((unsigned)STRLEN(res) + 1 + newl - l);
1575 		    if (s == NULL)
1576 			break;
1577 		    mch_memmove(s, res, p - res);
1578 		    STRCPY(s + (p - res) + newl, p + l);
1579 		    p = s + (p - res);
1580 		    vim_free(res);
1581 		    res = s;
1582 		}
1583 
1584 		utf_char2bytes(uc, p);
1585 		p += newl;
1586 	    }
1587 	    else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1588 		p += l;		/* skip multi-byte character */
1589 	    else
1590 # endif
1591 	    {
1592 		*p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */
1593 		p++;
1594 	    }
1595 	}
1596 
1597     return res;
1598 }
1599 #endif
1600 
1601 /*
1602  * copy a space a number of times
1603  */
1604     void
1605 copy_spaces(ptr, count)
1606     char_u	*ptr;
1607     size_t	count;
1608 {
1609     size_t	i = count;
1610     char_u	*p = ptr;
1611 
1612     while (i--)
1613 	*p++ = ' ';
1614 }
1615 
1616 #if defined(FEAT_VISUALEXTRA) || defined(PROTO)
1617 /*
1618  * Copy a character a number of times.
1619  * Does not work for multi-byte characters!
1620  */
1621     void
1622 copy_chars(ptr, count, c)
1623     char_u	*ptr;
1624     size_t	count;
1625     int		c;
1626 {
1627     size_t	i = count;
1628     char_u	*p = ptr;
1629 
1630     while (i--)
1631 	*p++ = c;
1632 }
1633 #endif
1634 
1635 /*
1636  * delete spaces at the end of a string
1637  */
1638     void
1639 del_trailing_spaces(ptr)
1640     char_u	*ptr;
1641 {
1642     char_u	*q;
1643 
1644     q = ptr + STRLEN(ptr);
1645     while (--q > ptr && vim_iswhite(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1646 	*q = NUL;
1647 }
1648 
1649 /*
1650  * Like strncpy(), but always terminate the result with one NUL.
1651  * "to" must be "len + 1" long!
1652  */
1653     void
1654 vim_strncpy(to, from, len)
1655     char_u	*to;
1656     char_u	*from;
1657     size_t	len;
1658 {
1659     STRNCPY(to, from, len);
1660     to[len] = NUL;
1661 }
1662 
1663 /*
1664  * Like strcat(), but make sure the result fits in "tosize" bytes and is
1665  * always NUL terminated.
1666  */
1667     void
1668 vim_strcat(to, from, tosize)
1669     char_u	*to;
1670     char_u	*from;
1671     size_t	tosize;
1672 {
1673     size_t tolen = STRLEN(to);
1674     size_t fromlen = STRLEN(from);
1675 
1676     if (tolen + fromlen + 1 > tosize)
1677     {
1678 	mch_memmove(to + tolen, from, tosize - tolen - 1);
1679 	to[tosize - 1] = NUL;
1680     }
1681     else
1682 	STRCPY(to + tolen, from);
1683 }
1684 
1685 /*
1686  * Isolate one part of a string option where parts are separated with
1687  * "sep_chars".
1688  * The part is copied into "buf[maxlen]".
1689  * "*option" is advanced to the next part.
1690  * The length is returned.
1691  */
1692     int
1693 copy_option_part(option, buf, maxlen, sep_chars)
1694     char_u	**option;
1695     char_u	*buf;
1696     int		maxlen;
1697     char	*sep_chars;
1698 {
1699     int	    len = 0;
1700     char_u  *p = *option;
1701 
1702     /* skip '.' at start of option part, for 'suffixes' */
1703     if (*p == '.')
1704 	buf[len++] = *p++;
1705     while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1706     {
1707 	/*
1708 	 * Skip backslash before a separator character and space.
1709 	 */
1710 	if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1711 	    ++p;
1712 	if (len < maxlen - 1)
1713 	    buf[len++] = *p;
1714 	++p;
1715     }
1716     buf[len] = NUL;
1717 
1718     if (*p != NUL && *p != ',')	/* skip non-standard separator */
1719 	++p;
1720     p = skip_to_option_part(p);	/* p points to next file name */
1721 
1722     *option = p;
1723     return len;
1724 }
1725 
1726 /*
1727  * Replacement for free() that ignores NULL pointers.
1728  * Also skip free() when exiting for sure, this helps when we caught a deadly
1729  * signal that was caused by a crash in free().
1730  */
1731     void
1732 vim_free(x)
1733     void *x;
1734 {
1735     if (x != NULL && !really_exiting)
1736     {
1737 #ifdef MEM_PROFILE
1738 	mem_pre_free(&x);
1739 #endif
1740 	free(x);
1741     }
1742 }
1743 
1744 #ifndef HAVE_MEMSET
1745     void *
1746 vim_memset(ptr, c, size)
1747     void    *ptr;
1748     int	    c;
1749     size_t  size;
1750 {
1751     char *p = ptr;
1752 
1753     while (size-- > 0)
1754 	*p++ = c;
1755     return ptr;
1756 }
1757 #endif
1758 
1759 #ifdef VIM_MEMCMP
1760 /*
1761  * Return zero when "b1" and "b2" are the same for "len" bytes.
1762  * Return non-zero otherwise.
1763  */
1764     int
1765 vim_memcmp(b1, b2, len)
1766     void    *b1;
1767     void    *b2;
1768     size_t  len;
1769 {
1770     char_u  *p1 = (char_u *)b1, *p2 = (char_u *)b2;
1771 
1772     for ( ; len > 0; --len)
1773     {
1774 	if (*p1 != *p2)
1775 	    return 1;
1776 	++p1;
1777 	++p2;
1778     }
1779     return 0;
1780 }
1781 #endif
1782 
1783 #ifdef VIM_MEMMOVE
1784 /*
1785  * Version of memmove() that handles overlapping source and destination.
1786  * For systems that don't have a function that is guaranteed to do that (SYSV).
1787  */
1788     void
1789 mch_memmove(dst_arg, src_arg, len)
1790     void    *src_arg, *dst_arg;
1791     size_t  len;
1792 {
1793     /*
1794      * A void doesn't have a size, we use char pointers.
1795      */
1796     char *dst = dst_arg, *src = src_arg;
1797 
1798 					/* overlap, copy backwards */
1799     if (dst > src && dst < src + len)
1800     {
1801 	src += len;
1802 	dst += len;
1803 	while (len-- > 0)
1804 	    *--dst = *--src;
1805     }
1806     else				/* copy forwards */
1807 	while (len-- > 0)
1808 	    *dst++ = *src++;
1809 }
1810 #endif
1811 
1812 #if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1813 /*
1814  * Compare two strings, ignoring case, using current locale.
1815  * Doesn't work for multi-byte characters.
1816  * return 0 for match, < 0 for smaller, > 0 for bigger
1817  */
1818     int
1819 vim_stricmp(s1, s2)
1820     char	*s1;
1821     char	*s2;
1822 {
1823     int		i;
1824 
1825     for (;;)
1826     {
1827 	i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1828 	if (i != 0)
1829 	    return i;			    /* this character different */
1830 	if (*s1 == NUL)
1831 	    break;			    /* strings match until NUL */
1832 	++s1;
1833 	++s2;
1834     }
1835     return 0;				    /* strings match */
1836 }
1837 #endif
1838 
1839 #if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1840 /*
1841  * Compare two strings, for length "len", ignoring case, using current locale.
1842  * Doesn't work for multi-byte characters.
1843  * return 0 for match, < 0 for smaller, > 0 for bigger
1844  */
1845     int
1846 vim_strnicmp(s1, s2, len)
1847     char	*s1;
1848     char	*s2;
1849     size_t	len;
1850 {
1851     int		i;
1852 
1853     while (len > 0)
1854     {
1855 	i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1856 	if (i != 0)
1857 	    return i;			    /* this character different */
1858 	if (*s1 == NUL)
1859 	    break;			    /* strings match until NUL */
1860 	++s1;
1861 	++s2;
1862 	--len;
1863     }
1864     return 0;				    /* strings match */
1865 }
1866 #endif
1867 
1868 /*
1869  * Version of strchr() and strrchr() that handle unsigned char strings
1870  * with characters from 128 to 255 correctly.  It also doesn't return a
1871  * pointer to the NUL at the end of the string.
1872  */
1873     char_u  *
1874 vim_strchr(string, c)
1875     char_u	*string;
1876     int		c;
1877 {
1878     char_u	*p;
1879     int		b;
1880 
1881     p = string;
1882 #ifdef FEAT_MBYTE
1883     if (enc_utf8 && c >= 0x80)
1884     {
1885 	while (*p != NUL)
1886 	{
1887 	    if (utf_ptr2char(p) == c)
1888 		return p;
1889 	    p += (*mb_ptr2len)(p);
1890 	}
1891 	return NULL;
1892     }
1893     if (enc_dbcs != 0 && c > 255)
1894     {
1895 	int	n2 = c & 0xff;
1896 
1897 	c = ((unsigned)c >> 8) & 0xff;
1898 	while ((b = *p) != NUL)
1899 	{
1900 	    if (b == c && p[1] == n2)
1901 		return p;
1902 	    p += (*mb_ptr2len)(p);
1903 	}
1904 	return NULL;
1905     }
1906     if (has_mbyte)
1907     {
1908 	while ((b = *p) != NUL)
1909 	{
1910 	    if (b == c)
1911 		return p;
1912 	    p += (*mb_ptr2len)(p);
1913 	}
1914 	return NULL;
1915     }
1916 #endif
1917     while ((b = *p) != NUL)
1918     {
1919 	if (b == c)
1920 	    return p;
1921 	++p;
1922     }
1923     return NULL;
1924 }
1925 
1926 /*
1927  * Version of strchr() that only works for bytes and handles unsigned char
1928  * strings with characters above 128 correctly. It also doesn't return a
1929  * pointer to the NUL at the end of the string.
1930  */
1931     char_u  *
1932 vim_strbyte(string, c)
1933     char_u	*string;
1934     int		c;
1935 {
1936     char_u	*p = string;
1937 
1938     while (*p != NUL)
1939     {
1940 	if (*p == c)
1941 	    return p;
1942 	++p;
1943     }
1944     return NULL;
1945 }
1946 
1947 /*
1948  * Search for last occurrence of "c" in "string".
1949  * Return NULL if not found.
1950  * Does not handle multi-byte char for "c"!
1951  */
1952     char_u  *
1953 vim_strrchr(string, c)
1954     char_u	*string;
1955     int		c;
1956 {
1957     char_u	*retval = NULL;
1958     char_u	*p = string;
1959 
1960     while (*p)
1961     {
1962 	if (*p == c)
1963 	    retval = p;
1964 	mb_ptr_adv(p);
1965     }
1966     return retval;
1967 }
1968 
1969 /*
1970  * Vim's version of strpbrk(), in case it's missing.
1971  * Don't generate a prototype for this, causes problems when it's not used.
1972  */
1973 #ifndef PROTO
1974 # ifndef HAVE_STRPBRK
1975 #  ifdef vim_strpbrk
1976 #   undef vim_strpbrk
1977 #  endif
1978     char_u *
1979 vim_strpbrk(s, charset)
1980     char_u	*s;
1981     char_u	*charset;
1982 {
1983     while (*s)
1984     {
1985 	if (vim_strchr(charset, *s) != NULL)
1986 	    return s;
1987 	mb_ptr_adv(s);
1988     }
1989     return NULL;
1990 }
1991 # endif
1992 #endif
1993 
1994 /*
1995  * Vim has its own isspace() function, because on some machines isspace()
1996  * can't handle characters above 128.
1997  */
1998     int
1999 vim_isspace(x)
2000     int	    x;
2001 {
2002     return ((x >= 9 && x <= 13) || x == ' ');
2003 }
2004 
2005 /************************************************************************
2006  * Functions for handling growing arrays.
2007  */
2008 
2009 /*
2010  * Clear an allocated growing array.
2011  */
2012     void
2013 ga_clear(gap)
2014     garray_T *gap;
2015 {
2016     vim_free(gap->ga_data);
2017     ga_init(gap);
2018 }
2019 
2020 /*
2021  * Clear a growing array that contains a list of strings.
2022  */
2023     void
2024 ga_clear_strings(gap)
2025     garray_T *gap;
2026 {
2027     int		i;
2028 
2029     for (i = 0; i < gap->ga_len; ++i)
2030 	vim_free(((char_u **)(gap->ga_data))[i]);
2031     ga_clear(gap);
2032 }
2033 
2034 /*
2035  * Initialize a growing array.	Don't forget to set ga_itemsize and
2036  * ga_growsize!  Or use ga_init2().
2037  */
2038     void
2039 ga_init(gap)
2040     garray_T *gap;
2041 {
2042     gap->ga_data = NULL;
2043     gap->ga_maxlen = 0;
2044     gap->ga_len = 0;
2045 }
2046 
2047     void
2048 ga_init2(gap, itemsize, growsize)
2049     garray_T	*gap;
2050     int		itemsize;
2051     int		growsize;
2052 {
2053     ga_init(gap);
2054     gap->ga_itemsize = itemsize;
2055     gap->ga_growsize = growsize;
2056 }
2057 
2058 /*
2059  * Make room in growing array "gap" for at least "n" items.
2060  * Return FAIL for failure, OK otherwise.
2061  */
2062     int
2063 ga_grow(gap, n)
2064     garray_T	*gap;
2065     int		n;
2066 {
2067     size_t	old_len;
2068     size_t	new_len;
2069     char_u	*pp;
2070 
2071     if (gap->ga_maxlen - gap->ga_len < n)
2072     {
2073 	if (n < gap->ga_growsize)
2074 	    n = gap->ga_growsize;
2075 	new_len = gap->ga_itemsize * (gap->ga_len + n);
2076 	pp = (gap->ga_data == NULL)
2077 	      ? alloc((unsigned)new_len) : vim_realloc(gap->ga_data, new_len);
2078 	if (pp == NULL)
2079 	    return FAIL;
2080 	old_len = gap->ga_itemsize * gap->ga_maxlen;
2081 	vim_memset(pp + old_len, 0, new_len - old_len);
2082 	gap->ga_maxlen = gap->ga_len + n;
2083 	gap->ga_data = pp;
2084     }
2085     return OK;
2086 }
2087 
2088 /*
2089  * For a growing array that contains a list of strings: concatenate all the
2090  * strings with a separating "sep".
2091  * Returns NULL when out of memory.
2092  */
2093     char_u *
2094 ga_concat_strings(gap, sep)
2095     garray_T *gap;
2096     char     *sep;
2097 {
2098     int		i;
2099     int		len = 0;
2100     int		sep_len = (int)STRLEN(sep);
2101     char_u	*s;
2102     char_u	*p;
2103 
2104     for (i = 0; i < gap->ga_len; ++i)
2105 	len += (int)STRLEN(((char_u **)(gap->ga_data))[i]) + sep_len;
2106 
2107     s = alloc(len + 1);
2108     if (s != NULL)
2109     {
2110 	*s = NUL;
2111 	p = s;
2112 	for (i = 0; i < gap->ga_len; ++i)
2113 	{
2114 	    if (p != s)
2115 	    {
2116 		STRCPY(p, sep);
2117 		p += sep_len;
2118 	    }
2119 	    STRCPY(p, ((char_u **)(gap->ga_data))[i]);
2120 	    p += STRLEN(p);
2121 	}
2122     }
2123     return s;
2124 }
2125 
2126 /*
2127  * Concatenate a string to a growarray which contains characters.
2128  * Note: Does NOT copy the NUL at the end!
2129  */
2130     void
2131 ga_concat(gap, s)
2132     garray_T	*gap;
2133     char_u	*s;
2134 {
2135     int    len = (int)STRLEN(s);
2136 
2137     if (ga_grow(gap, len) == OK)
2138     {
2139 	mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
2140 	gap->ga_len += len;
2141     }
2142 }
2143 
2144 /*
2145  * Append one byte to a growarray which contains bytes.
2146  */
2147     void
2148 ga_append(gap, c)
2149     garray_T	*gap;
2150     int		c;
2151 {
2152     if (ga_grow(gap, 1) == OK)
2153     {
2154 	*((char *)gap->ga_data + gap->ga_len) = c;
2155 	++gap->ga_len;
2156     }
2157 }
2158 
2159 #if (defined(UNIX) && !defined(USE_SYSTEM)) || defined(WIN3264)
2160 /*
2161  * Append the text in "gap" below the cursor line and clear "gap".
2162  */
2163     void
2164 append_ga_line(gap)
2165     garray_T	*gap;
2166 {
2167     /* Remove trailing CR. */
2168     if (gap->ga_len > 0
2169 	    && !curbuf->b_p_bin
2170 	    && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR)
2171 	--gap->ga_len;
2172     ga_append(gap, NUL);
2173     ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE);
2174     gap->ga_len = 0;
2175 }
2176 #endif
2177 
2178 /************************************************************************
2179  * functions that use lookup tables for various things, generally to do with
2180  * special key codes.
2181  */
2182 
2183 /*
2184  * Some useful tables.
2185  */
2186 
2187 static struct modmasktable
2188 {
2189     short	mod_mask;	/* Bit-mask for particular key modifier */
2190     short	mod_flag;	/* Bit(s) for particular key modifier */
2191     char_u	name;		/* Single letter name of modifier */
2192 } mod_mask_table[] =
2193 {
2194     {MOD_MASK_ALT,		MOD_MASK_ALT,		(char_u)'M'},
2195     {MOD_MASK_META,		MOD_MASK_META,		(char_u)'T'},
2196     {MOD_MASK_CTRL,		MOD_MASK_CTRL,		(char_u)'C'},
2197     {MOD_MASK_SHIFT,		MOD_MASK_SHIFT,		(char_u)'S'},
2198     {MOD_MASK_MULTI_CLICK,	MOD_MASK_2CLICK,	(char_u)'2'},
2199     {MOD_MASK_MULTI_CLICK,	MOD_MASK_3CLICK,	(char_u)'3'},
2200     {MOD_MASK_MULTI_CLICK,	MOD_MASK_4CLICK,	(char_u)'4'},
2201 #ifdef MACOS
2202     {MOD_MASK_CMD,		MOD_MASK_CMD,		(char_u)'D'},
2203 #endif
2204     /* 'A' must be the last one */
2205     {MOD_MASK_ALT,		MOD_MASK_ALT,		(char_u)'A'},
2206     {0, 0, NUL}
2207 };
2208 
2209 /*
2210  * Shifted key terminal codes and their unshifted equivalent.
2211  * Don't add mouse codes here, they are handled separately!
2212  */
2213 #define MOD_KEYS_ENTRY_SIZE 5
2214 
2215 static char_u modifier_keys_table[] =
2216 {
2217 /*  mod mask	    with modifier		without modifier */
2218     MOD_MASK_SHIFT, '&', '9',			'@', '1',	/* begin */
2219     MOD_MASK_SHIFT, '&', '0',			'@', '2',	/* cancel */
2220     MOD_MASK_SHIFT, '*', '1',			'@', '4',	/* command */
2221     MOD_MASK_SHIFT, '*', '2',			'@', '5',	/* copy */
2222     MOD_MASK_SHIFT, '*', '3',			'@', '6',	/* create */
2223     MOD_MASK_SHIFT, '*', '4',			'k', 'D',	/* delete char */
2224     MOD_MASK_SHIFT, '*', '5',			'k', 'L',	/* delete line */
2225     MOD_MASK_SHIFT, '*', '7',			'@', '7',	/* end */
2226     MOD_MASK_CTRL,  KS_EXTRA, (int)KE_C_END,	'@', '7',	/* end */
2227     MOD_MASK_SHIFT, '*', '9',			'@', '9',	/* exit */
2228     MOD_MASK_SHIFT, '*', '0',			'@', '0',	/* find */
2229     MOD_MASK_SHIFT, '#', '1',			'%', '1',	/* help */
2230     MOD_MASK_SHIFT, '#', '2',			'k', 'h',	/* home */
2231     MOD_MASK_CTRL,  KS_EXTRA, (int)KE_C_HOME,	'k', 'h',	/* home */
2232     MOD_MASK_SHIFT, '#', '3',			'k', 'I',	/* insert */
2233     MOD_MASK_SHIFT, '#', '4',			'k', 'l',	/* left arrow */
2234     MOD_MASK_CTRL,  KS_EXTRA, (int)KE_C_LEFT,	'k', 'l',	/* left arrow */
2235     MOD_MASK_SHIFT, '%', 'a',			'%', '3',	/* message */
2236     MOD_MASK_SHIFT, '%', 'b',			'%', '4',	/* move */
2237     MOD_MASK_SHIFT, '%', 'c',			'%', '5',	/* next */
2238     MOD_MASK_SHIFT, '%', 'd',			'%', '7',	/* options */
2239     MOD_MASK_SHIFT, '%', 'e',			'%', '8',	/* previous */
2240     MOD_MASK_SHIFT, '%', 'f',			'%', '9',	/* print */
2241     MOD_MASK_SHIFT, '%', 'g',			'%', '0',	/* redo */
2242     MOD_MASK_SHIFT, '%', 'h',			'&', '3',	/* replace */
2243     MOD_MASK_SHIFT, '%', 'i',			'k', 'r',	/* right arr. */
2244     MOD_MASK_CTRL,  KS_EXTRA, (int)KE_C_RIGHT,	'k', 'r',	/* right arr. */
2245     MOD_MASK_SHIFT, '%', 'j',			'&', '5',	/* resume */
2246     MOD_MASK_SHIFT, '!', '1',			'&', '6',	/* save */
2247     MOD_MASK_SHIFT, '!', '2',			'&', '7',	/* suspend */
2248     MOD_MASK_SHIFT, '!', '3',			'&', '8',	/* undo */
2249     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP,	'k', 'u',	/* up arrow */
2250     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN,	'k', 'd',	/* down arrow */
2251 
2252 								/* vt100 F1 */
2253     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1,	KS_EXTRA, (int)KE_XF1,
2254     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2,	KS_EXTRA, (int)KE_XF2,
2255     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3,	KS_EXTRA, (int)KE_XF3,
2256     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4,	KS_EXTRA, (int)KE_XF4,
2257 
2258     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1,	'k', '1',	/* F1 */
2259     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2,	'k', '2',
2260     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3,	'k', '3',
2261     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4,	'k', '4',
2262     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5,	'k', '5',
2263     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6,	'k', '6',
2264     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7,	'k', '7',
2265     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8,	'k', '8',
2266     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9,	'k', '9',
2267     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10,	'k', ';',	/* F10 */
2268 
2269     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11,	'F', '1',
2270     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12,	'F', '2',
2271     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13,	'F', '3',
2272     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14,	'F', '4',
2273     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15,	'F', '5',
2274     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16,	'F', '6',
2275     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17,	'F', '7',
2276     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18,	'F', '8',
2277     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19,	'F', '9',
2278     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20,	'F', 'A',
2279 
2280     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21,	'F', 'B',
2281     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22,	'F', 'C',
2282     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23,	'F', 'D',
2283     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24,	'F', 'E',
2284     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25,	'F', 'F',
2285     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26,	'F', 'G',
2286     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27,	'F', 'H',
2287     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28,	'F', 'I',
2288     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29,	'F', 'J',
2289     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30,	'F', 'K',
2290 
2291     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31,	'F', 'L',
2292     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32,	'F', 'M',
2293     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33,	'F', 'N',
2294     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34,	'F', 'O',
2295     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35,	'F', 'P',
2296     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36,	'F', 'Q',
2297     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37,	'F', 'R',
2298 
2299 							    /* TAB pseudo code*/
2300     MOD_MASK_SHIFT, 'k', 'B',			KS_EXTRA, (int)KE_TAB,
2301 
2302     NUL
2303 };
2304 
2305 static struct key_name_entry
2306 {
2307     int	    key;	/* Special key code or ascii value */
2308     char_u  *name;	/* Name of key */
2309 } key_names_table[] =
2310 {
2311     {' ',		(char_u *)"Space"},
2312     {TAB,		(char_u *)"Tab"},
2313     {K_TAB,		(char_u *)"Tab"},
2314     {NL,		(char_u *)"NL"},
2315     {NL,		(char_u *)"NewLine"},	/* Alternative name */
2316     {NL,		(char_u *)"LineFeed"},	/* Alternative name */
2317     {NL,		(char_u *)"LF"},	/* Alternative name */
2318     {CAR,		(char_u *)"CR"},
2319     {CAR,		(char_u *)"Return"},	/* Alternative name */
2320     {CAR,		(char_u *)"Enter"},	/* Alternative name */
2321     {K_BS,		(char_u *)"BS"},
2322     {K_BS,		(char_u *)"BackSpace"},	/* Alternative name */
2323     {ESC,		(char_u *)"Esc"},
2324     {CSI,		(char_u *)"CSI"},
2325     {K_CSI,		(char_u *)"xCSI"},
2326     {'|',		(char_u *)"Bar"},
2327     {'\\',		(char_u *)"Bslash"},
2328     {K_DEL,		(char_u *)"Del"},
2329     {K_DEL,		(char_u *)"Delete"},	/* Alternative name */
2330     {K_KDEL,		(char_u *)"kDel"},
2331     {K_UP,		(char_u *)"Up"},
2332     {K_DOWN,		(char_u *)"Down"},
2333     {K_LEFT,		(char_u *)"Left"},
2334     {K_RIGHT,		(char_u *)"Right"},
2335     {K_XUP,		(char_u *)"xUp"},
2336     {K_XDOWN,		(char_u *)"xDown"},
2337     {K_XLEFT,		(char_u *)"xLeft"},
2338     {K_XRIGHT,		(char_u *)"xRight"},
2339 
2340     {K_F1,		(char_u *)"F1"},
2341     {K_F2,		(char_u *)"F2"},
2342     {K_F3,		(char_u *)"F3"},
2343     {K_F4,		(char_u *)"F4"},
2344     {K_F5,		(char_u *)"F5"},
2345     {K_F6,		(char_u *)"F6"},
2346     {K_F7,		(char_u *)"F7"},
2347     {K_F8,		(char_u *)"F8"},
2348     {K_F9,		(char_u *)"F9"},
2349     {K_F10,		(char_u *)"F10"},
2350 
2351     {K_F11,		(char_u *)"F11"},
2352     {K_F12,		(char_u *)"F12"},
2353     {K_F13,		(char_u *)"F13"},
2354     {K_F14,		(char_u *)"F14"},
2355     {K_F15,		(char_u *)"F15"},
2356     {K_F16,		(char_u *)"F16"},
2357     {K_F17,		(char_u *)"F17"},
2358     {K_F18,		(char_u *)"F18"},
2359     {K_F19,		(char_u *)"F19"},
2360     {K_F20,		(char_u *)"F20"},
2361 
2362     {K_F21,		(char_u *)"F21"},
2363     {K_F22,		(char_u *)"F22"},
2364     {K_F23,		(char_u *)"F23"},
2365     {K_F24,		(char_u *)"F24"},
2366     {K_F25,		(char_u *)"F25"},
2367     {K_F26,		(char_u *)"F26"},
2368     {K_F27,		(char_u *)"F27"},
2369     {K_F28,		(char_u *)"F28"},
2370     {K_F29,		(char_u *)"F29"},
2371     {K_F30,		(char_u *)"F30"},
2372 
2373     {K_F31,		(char_u *)"F31"},
2374     {K_F32,		(char_u *)"F32"},
2375     {K_F33,		(char_u *)"F33"},
2376     {K_F34,		(char_u *)"F34"},
2377     {K_F35,		(char_u *)"F35"},
2378     {K_F36,		(char_u *)"F36"},
2379     {K_F37,		(char_u *)"F37"},
2380 
2381     {K_XF1,		(char_u *)"xF1"},
2382     {K_XF2,		(char_u *)"xF2"},
2383     {K_XF3,		(char_u *)"xF3"},
2384     {K_XF4,		(char_u *)"xF4"},
2385 
2386     {K_HELP,		(char_u *)"Help"},
2387     {K_UNDO,		(char_u *)"Undo"},
2388     {K_INS,		(char_u *)"Insert"},
2389     {K_INS,		(char_u *)"Ins"},	/* Alternative name */
2390     {K_KINS,		(char_u *)"kInsert"},
2391     {K_HOME,		(char_u *)"Home"},
2392     {K_KHOME,		(char_u *)"kHome"},
2393     {K_XHOME,		(char_u *)"xHome"},
2394     {K_ZHOME,		(char_u *)"zHome"},
2395     {K_END,		(char_u *)"End"},
2396     {K_KEND,		(char_u *)"kEnd"},
2397     {K_XEND,		(char_u *)"xEnd"},
2398     {K_ZEND,		(char_u *)"zEnd"},
2399     {K_PAGEUP,		(char_u *)"PageUp"},
2400     {K_PAGEDOWN,	(char_u *)"PageDown"},
2401     {K_KPAGEUP,		(char_u *)"kPageUp"},
2402     {K_KPAGEDOWN,	(char_u *)"kPageDown"},
2403 
2404     {K_KPLUS,		(char_u *)"kPlus"},
2405     {K_KMINUS,		(char_u *)"kMinus"},
2406     {K_KDIVIDE,		(char_u *)"kDivide"},
2407     {K_KMULTIPLY,	(char_u *)"kMultiply"},
2408     {K_KENTER,		(char_u *)"kEnter"},
2409     {K_KPOINT,		(char_u *)"kPoint"},
2410 
2411     {K_K0,		(char_u *)"k0"},
2412     {K_K1,		(char_u *)"k1"},
2413     {K_K2,		(char_u *)"k2"},
2414     {K_K3,		(char_u *)"k3"},
2415     {K_K4,		(char_u *)"k4"},
2416     {K_K5,		(char_u *)"k5"},
2417     {K_K6,		(char_u *)"k6"},
2418     {K_K7,		(char_u *)"k7"},
2419     {K_K8,		(char_u *)"k8"},
2420     {K_K9,		(char_u *)"k9"},
2421 
2422     {'<',		(char_u *)"lt"},
2423 
2424     {K_MOUSE,		(char_u *)"Mouse"},
2425 #ifdef FEAT_MOUSE_NET
2426     {K_NETTERM_MOUSE,	(char_u *)"NetMouse"},
2427 #endif
2428 #ifdef FEAT_MOUSE_DEC
2429     {K_DEC_MOUSE,	(char_u *)"DecMouse"},
2430 #endif
2431 #ifdef FEAT_MOUSE_JSB
2432     {K_JSBTERM_MOUSE,	(char_u *)"JsbMouse"},
2433 #endif
2434 #ifdef FEAT_MOUSE_PTERM
2435     {K_PTERM_MOUSE,	(char_u *)"PtermMouse"},
2436 #endif
2437 #ifdef FEAT_MOUSE_URXVT
2438     {K_URXVT_MOUSE,	(char_u *)"UrxvtMouse"},
2439 #endif
2440 #ifdef FEAT_MOUSE_SGR
2441     {K_SGR_MOUSE,	(char_u *)"SgrMouse"},
2442 #endif
2443     {K_LEFTMOUSE,	(char_u *)"LeftMouse"},
2444     {K_LEFTMOUSE_NM,	(char_u *)"LeftMouseNM"},
2445     {K_LEFTDRAG,	(char_u *)"LeftDrag"},
2446     {K_LEFTRELEASE,	(char_u *)"LeftRelease"},
2447     {K_LEFTRELEASE_NM,	(char_u *)"LeftReleaseNM"},
2448     {K_MIDDLEMOUSE,	(char_u *)"MiddleMouse"},
2449     {K_MIDDLEDRAG,	(char_u *)"MiddleDrag"},
2450     {K_MIDDLERELEASE,	(char_u *)"MiddleRelease"},
2451     {K_RIGHTMOUSE,	(char_u *)"RightMouse"},
2452     {K_RIGHTDRAG,	(char_u *)"RightDrag"},
2453     {K_RIGHTRELEASE,	(char_u *)"RightRelease"},
2454     {K_MOUSEDOWN,	(char_u *)"ScrollWheelUp"},
2455     {K_MOUSEUP,		(char_u *)"ScrollWheelDown"},
2456     {K_MOUSELEFT,	(char_u *)"ScrollWheelRight"},
2457     {K_MOUSERIGHT,	(char_u *)"ScrollWheelLeft"},
2458     {K_MOUSEDOWN,	(char_u *)"MouseDown"}, /* OBSOLETE: Use	  */
2459     {K_MOUSEUP,		(char_u *)"MouseUp"},	/* ScrollWheelXXX instead */
2460     {K_X1MOUSE,		(char_u *)"X1Mouse"},
2461     {K_X1DRAG,		(char_u *)"X1Drag"},
2462     {K_X1RELEASE,		(char_u *)"X1Release"},
2463     {K_X2MOUSE,		(char_u *)"X2Mouse"},
2464     {K_X2DRAG,		(char_u *)"X2Drag"},
2465     {K_X2RELEASE,		(char_u *)"X2Release"},
2466     {K_DROP,		(char_u *)"Drop"},
2467     {K_ZERO,		(char_u *)"Nul"},
2468 #ifdef FEAT_EVAL
2469     {K_SNR,		(char_u *)"SNR"},
2470 #endif
2471     {K_PLUG,		(char_u *)"Plug"},
2472     {0,			NULL}
2473 };
2474 
2475 #define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
2476 
2477 #ifdef FEAT_MOUSE
2478 static struct mousetable
2479 {
2480     int	    pseudo_code;	/* Code for pseudo mouse event */
2481     int	    button;		/* Which mouse button is it? */
2482     int	    is_click;		/* Is it a mouse button click event? */
2483     int	    is_drag;		/* Is it a mouse drag event? */
2484 } mouse_table[] =
2485 {
2486     {(int)KE_LEFTMOUSE,		MOUSE_LEFT,	TRUE,	FALSE},
2487 #ifdef FEAT_GUI
2488     {(int)KE_LEFTMOUSE_NM,	MOUSE_LEFT,	TRUE,	FALSE},
2489 #endif
2490     {(int)KE_LEFTDRAG,		MOUSE_LEFT,	FALSE,	TRUE},
2491     {(int)KE_LEFTRELEASE,	MOUSE_LEFT,	FALSE,	FALSE},
2492 #ifdef FEAT_GUI
2493     {(int)KE_LEFTRELEASE_NM,	MOUSE_LEFT,	FALSE,	FALSE},
2494 #endif
2495     {(int)KE_MIDDLEMOUSE,	MOUSE_MIDDLE,	TRUE,	FALSE},
2496     {(int)KE_MIDDLEDRAG,	MOUSE_MIDDLE,	FALSE,	TRUE},
2497     {(int)KE_MIDDLERELEASE,	MOUSE_MIDDLE,	FALSE,	FALSE},
2498     {(int)KE_RIGHTMOUSE,	MOUSE_RIGHT,	TRUE,	FALSE},
2499     {(int)KE_RIGHTDRAG,		MOUSE_RIGHT,	FALSE,	TRUE},
2500     {(int)KE_RIGHTRELEASE,	MOUSE_RIGHT,	FALSE,	FALSE},
2501     {(int)KE_X1MOUSE,		MOUSE_X1,	TRUE,	FALSE},
2502     {(int)KE_X1DRAG,		MOUSE_X1,	FALSE,	TRUE},
2503     {(int)KE_X1RELEASE,		MOUSE_X1,	FALSE,	FALSE},
2504     {(int)KE_X2MOUSE,		MOUSE_X2,	TRUE,	FALSE},
2505     {(int)KE_X2DRAG,		MOUSE_X2,	FALSE,	TRUE},
2506     {(int)KE_X2RELEASE,		MOUSE_X2,	FALSE,	FALSE},
2507     /* DRAG without CLICK */
2508     {(int)KE_IGNORE,		MOUSE_RELEASE,	FALSE,	TRUE},
2509     /* RELEASE without CLICK */
2510     {(int)KE_IGNORE,		MOUSE_RELEASE,	FALSE,	FALSE},
2511     {0,				0,		0,	0},
2512 };
2513 #endif /* FEAT_MOUSE */
2514 
2515 /*
2516  * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
2517  * modifier name ('S' for Shift, 'C' for Ctrl etc).
2518  */
2519     int
2520 name_to_mod_mask(c)
2521     int	    c;
2522 {
2523     int	    i;
2524 
2525     c = TOUPPER_ASC(c);
2526     for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
2527 	if (c == mod_mask_table[i].name)
2528 	    return mod_mask_table[i].mod_flag;
2529     return 0;
2530 }
2531 
2532 /*
2533  * Check if if there is a special key code for "key" that includes the
2534  * modifiers specified.
2535  */
2536     int
2537 simplify_key(key, modifiers)
2538     int	    key;
2539     int	    *modifiers;
2540 {
2541     int	    i;
2542     int	    key0;
2543     int	    key1;
2544 
2545     if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2546     {
2547 	/* TAB is a special case */
2548 	if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2549 	{
2550 	    *modifiers &= ~MOD_MASK_SHIFT;
2551 	    return K_S_TAB;
2552 	}
2553 	key0 = KEY2TERMCAP0(key);
2554 	key1 = KEY2TERMCAP1(key);
2555 	for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2556 	    if (key0 == modifier_keys_table[i + 3]
2557 		    && key1 == modifier_keys_table[i + 4]
2558 		    && (*modifiers & modifier_keys_table[i]))
2559 	    {
2560 		*modifiers &= ~modifier_keys_table[i];
2561 		return TERMCAP2KEY(modifier_keys_table[i + 1],
2562 						   modifier_keys_table[i + 2]);
2563 	    }
2564     }
2565     return key;
2566 }
2567 
2568 /*
2569  * Change <xHome> to <Home>, <xUp> to <Up>, etc.
2570  */
2571     int
2572 handle_x_keys(key)
2573     int	    key;
2574 {
2575     switch (key)
2576     {
2577 	case K_XUP:	return K_UP;
2578 	case K_XDOWN:	return K_DOWN;
2579 	case K_XLEFT:	return K_LEFT;
2580 	case K_XRIGHT:	return K_RIGHT;
2581 	case K_XHOME:	return K_HOME;
2582 	case K_ZHOME:	return K_HOME;
2583 	case K_XEND:	return K_END;
2584 	case K_ZEND:	return K_END;
2585 	case K_XF1:	return K_F1;
2586 	case K_XF2:	return K_F2;
2587 	case K_XF3:	return K_F3;
2588 	case K_XF4:	return K_F4;
2589 	case K_S_XF1:	return K_S_F1;
2590 	case K_S_XF2:	return K_S_F2;
2591 	case K_S_XF3:	return K_S_F3;
2592 	case K_S_XF4:	return K_S_F4;
2593     }
2594     return key;
2595 }
2596 
2597 /*
2598  * Return a string which contains the name of the given key when the given
2599  * modifiers are down.
2600  */
2601     char_u *
2602 get_special_key_name(c, modifiers)
2603     int	    c;
2604     int	    modifiers;
2605 {
2606     static char_u string[MAX_KEY_NAME_LEN + 1];
2607 
2608     int	    i, idx;
2609     int	    table_idx;
2610     char_u  *s;
2611 
2612     string[0] = '<';
2613     idx = 1;
2614 
2615     /* Key that stands for a normal character. */
2616     if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2617 	c = KEY2TERMCAP1(c);
2618 
2619     /*
2620      * Translate shifted special keys into unshifted keys and set modifier.
2621      * Same for CTRL and ALT modifiers.
2622      */
2623     if (IS_SPECIAL(c))
2624     {
2625 	for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2626 	    if (       KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2627 		    && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2628 	    {
2629 		modifiers |= modifier_keys_table[i];
2630 		c = TERMCAP2KEY(modifier_keys_table[i + 3],
2631 						   modifier_keys_table[i + 4]);
2632 		break;
2633 	    }
2634     }
2635 
2636     /* try to find the key in the special key table */
2637     table_idx = find_special_key_in_table(c);
2638 
2639     /*
2640      * When not a known special key, and not a printable character, try to
2641      * extract modifiers.
2642      */
2643     if (c > 0
2644 #ifdef FEAT_MBYTE
2645 	    && (*mb_char2len)(c) == 1
2646 #endif
2647        )
2648     {
2649 	if (table_idx < 0
2650 		&& (!vim_isprintc(c) || (c & 0x7f) == ' ')
2651 		&& (c & 0x80))
2652 	{
2653 	    c &= 0x7f;
2654 	    modifiers |= MOD_MASK_ALT;
2655 	    /* try again, to find the un-alted key in the special key table */
2656 	    table_idx = find_special_key_in_table(c);
2657 	}
2658 	if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2659 	{
2660 #ifdef EBCDIC
2661 	    c = CtrlChar(c);
2662 #else
2663 	    c += '@';
2664 #endif
2665 	    modifiers |= MOD_MASK_CTRL;
2666 	}
2667     }
2668 
2669     /* translate the modifier into a string */
2670     for (i = 0; mod_mask_table[i].name != 'A'; i++)
2671 	if ((modifiers & mod_mask_table[i].mod_mask)
2672 						== mod_mask_table[i].mod_flag)
2673 	{
2674 	    string[idx++] = mod_mask_table[i].name;
2675 	    string[idx++] = (char_u)'-';
2676 	}
2677 
2678     if (table_idx < 0)		/* unknown special key, may output t_xx */
2679     {
2680 	if (IS_SPECIAL(c))
2681 	{
2682 	    string[idx++] = 't';
2683 	    string[idx++] = '_';
2684 	    string[idx++] = KEY2TERMCAP0(c);
2685 	    string[idx++] = KEY2TERMCAP1(c);
2686 	}
2687 	/* Not a special key, only modifiers, output directly */
2688 	else
2689 	{
2690 #ifdef FEAT_MBYTE
2691 	    if (has_mbyte && (*mb_char2len)(c) > 1)
2692 		idx += (*mb_char2bytes)(c, string + idx);
2693 	    else
2694 #endif
2695 	    if (vim_isprintc(c))
2696 		string[idx++] = c;
2697 	    else
2698 	    {
2699 		s = transchar(c);
2700 		while (*s)
2701 		    string[idx++] = *s++;
2702 	    }
2703 	}
2704     }
2705     else		/* use name of special key */
2706     {
2707 	STRCPY(string + idx, key_names_table[table_idx].name);
2708 	idx = (int)STRLEN(string);
2709     }
2710     string[idx++] = '>';
2711     string[idx] = NUL;
2712     return string;
2713 }
2714 
2715 /*
2716  * Try translating a <> name at (*srcp)[] to dst[].
2717  * Return the number of characters added to dst[], zero for no match.
2718  * If there is a match, srcp is advanced to after the <> name.
2719  * dst[] must be big enough to hold the result (up to six characters)!
2720  */
2721     int
2722 trans_special(srcp, dst, keycode)
2723     char_u	**srcp;
2724     char_u	*dst;
2725     int		keycode; /* prefer key code, e.g. K_DEL instead of DEL */
2726 {
2727     int		modifiers = 0;
2728     int		key;
2729     int		dlen = 0;
2730 
2731     key = find_special_key(srcp, &modifiers, keycode, FALSE);
2732     if (key == 0)
2733 	return 0;
2734 
2735     /* Put the appropriate modifier in a string */
2736     if (modifiers != 0)
2737     {
2738 	dst[dlen++] = K_SPECIAL;
2739 	dst[dlen++] = KS_MODIFIER;
2740 	dst[dlen++] = modifiers;
2741     }
2742 
2743     if (IS_SPECIAL(key))
2744     {
2745 	dst[dlen++] = K_SPECIAL;
2746 	dst[dlen++] = KEY2TERMCAP0(key);
2747 	dst[dlen++] = KEY2TERMCAP1(key);
2748     }
2749 #ifdef FEAT_MBYTE
2750     else if (has_mbyte && !keycode)
2751 	dlen += (*mb_char2bytes)(key, dst + dlen);
2752 #endif
2753     else if (keycode)
2754 	dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2755     else
2756 	dst[dlen++] = key;
2757 
2758     return dlen;
2759 }
2760 
2761 /*
2762  * Try translating a <> name at (*srcp)[], return the key and modifiers.
2763  * srcp is advanced to after the <> name.
2764  * returns 0 if there is no match.
2765  */
2766     int
2767 find_special_key(srcp, modp, keycode, keep_x_key)
2768     char_u	**srcp;
2769     int		*modp;
2770     int		keycode;     /* prefer key code, e.g. K_DEL instead of DEL */
2771     int		keep_x_key;  /* don't translate xHome to Home key */
2772 {
2773     char_u	*last_dash;
2774     char_u	*end_of_name;
2775     char_u	*src;
2776     char_u	*bp;
2777     int		modifiers;
2778     int		bit;
2779     int		key;
2780     unsigned long n;
2781     int		l;
2782 
2783     src = *srcp;
2784     if (src[0] != '<')
2785 	return 0;
2786 
2787     /* Find end of modifier list */
2788     last_dash = src;
2789     for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2790     {
2791 	if (*bp == '-')
2792 	{
2793 	    last_dash = bp;
2794 	    if (bp[1] != NUL)
2795 	    {
2796 #ifdef FEAT_MBYTE
2797 		if (has_mbyte)
2798 		    l = mb_ptr2len(bp + 1);
2799 		else
2800 #endif
2801 		    l = 1;
2802 		if (bp[l + 1] == '>')
2803 		    bp += l;	/* anything accepted, like <C-?> */
2804 	    }
2805 	}
2806 	if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2807 	    bp += 3;	/* skip t_xx, xx may be '-' or '>' */
2808 	else if (STRNICMP(bp, "char-", 5) == 0)
2809 	{
2810 	    vim_str2nr(bp + 5, NULL, &l, TRUE, TRUE, NULL, NULL);
2811 	    bp += l + 5;
2812 	    break;
2813 	}
2814     }
2815 
2816     if (*bp == '>')	/* found matching '>' */
2817     {
2818 	end_of_name = bp + 1;
2819 
2820 	/* Which modifiers are given? */
2821 	modifiers = 0x0;
2822 	for (bp = src + 1; bp < last_dash; bp++)
2823 	{
2824 	    if (*bp != '-')
2825 	    {
2826 		bit = name_to_mod_mask(*bp);
2827 		if (bit == 0x0)
2828 		    break;	/* Illegal modifier name */
2829 		modifiers |= bit;
2830 	    }
2831 	}
2832 
2833 	/*
2834 	 * Legal modifier name.
2835 	 */
2836 	if (bp >= last_dash)
2837 	{
2838 	    if (STRNICMP(last_dash + 1, "char-", 5) == 0
2839 						 && VIM_ISDIGIT(last_dash[6]))
2840 	    {
2841 		/* <Char-123> or <Char-033> or <Char-0x33> */
2842 		vim_str2nr(last_dash + 6, NULL, NULL, TRUE, TRUE, NULL, &n);
2843 		key = (int)n;
2844 	    }
2845 	    else
2846 	    {
2847 		/*
2848 		 * Modifier with single letter, or special key name.
2849 		 */
2850 #ifdef FEAT_MBYTE
2851 		if (has_mbyte)
2852 		    l = mb_ptr2len(last_dash + 1);
2853 		else
2854 #endif
2855 		    l = 1;
2856 		if (modifiers != 0 && last_dash[l + 1] == '>')
2857 		    key = PTR2CHAR(last_dash + 1);
2858 		else
2859 		{
2860 		    key = get_special_key_code(last_dash + 1);
2861 		    if (!keep_x_key)
2862 			key = handle_x_keys(key);
2863 		}
2864 	    }
2865 
2866 	    /*
2867 	     * get_special_key_code() may return NUL for invalid
2868 	     * special key name.
2869 	     */
2870 	    if (key != NUL)
2871 	    {
2872 		/*
2873 		 * Only use a modifier when there is no special key code that
2874 		 * includes the modifier.
2875 		 */
2876 		key = simplify_key(key, &modifiers);
2877 
2878 		if (!keycode)
2879 		{
2880 		    /* don't want keycode, use single byte code */
2881 		    if (key == K_BS)
2882 			key = BS;
2883 		    else if (key == K_DEL || key == K_KDEL)
2884 			key = DEL;
2885 		}
2886 
2887 		/*
2888 		 * Normal Key with modifier: Try to make a single byte code.
2889 		 */
2890 		if (!IS_SPECIAL(key))
2891 		    key = extract_modifiers(key, &modifiers);
2892 
2893 		*modp = modifiers;
2894 		*srcp = end_of_name;
2895 		return key;
2896 	    }
2897 	}
2898     }
2899     return 0;
2900 }
2901 
2902 /*
2903  * Try to include modifiers in the key.
2904  * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2905  */
2906     int
2907 extract_modifiers(key, modp)
2908     int	    key;
2909     int	    *modp;
2910 {
2911     int	modifiers = *modp;
2912 
2913 #ifdef MACOS
2914     /* Command-key really special, no fancynest */
2915     if (!(modifiers & MOD_MASK_CMD))
2916 #endif
2917     if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2918     {
2919 	key = TOUPPER_ASC(key);
2920 	modifiers &= ~MOD_MASK_SHIFT;
2921     }
2922     if ((modifiers & MOD_MASK_CTRL)
2923 #ifdef EBCDIC
2924 	    /* * TODO: EBCDIC Better use:
2925 	     * && (Ctrl_chr(key) || key == '?')
2926 	     * ???  */
2927 	    && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2928 						       != NULL
2929 #else
2930 	    && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2931 #endif
2932 	    )
2933     {
2934 	key = Ctrl_chr(key);
2935 	modifiers &= ~MOD_MASK_CTRL;
2936 	/* <C-@> is <Nul> */
2937 	if (key == 0)
2938 	    key = K_ZERO;
2939     }
2940 #ifdef MACOS
2941     /* Command-key really special, no fancynest */
2942     if (!(modifiers & MOD_MASK_CMD))
2943 #endif
2944     if ((modifiers & MOD_MASK_ALT) && key < 0x80
2945 #ifdef FEAT_MBYTE
2946 	    && !enc_dbcs		/* avoid creating a lead byte */
2947 #endif
2948 	    )
2949     {
2950 	key |= 0x80;
2951 	modifiers &= ~MOD_MASK_ALT;	/* remove the META modifier */
2952     }
2953 
2954     *modp = modifiers;
2955     return key;
2956 }
2957 
2958 /*
2959  * Try to find key "c" in the special key table.
2960  * Return the index when found, -1 when not found.
2961  */
2962     int
2963 find_special_key_in_table(c)
2964     int	    c;
2965 {
2966     int	    i;
2967 
2968     for (i = 0; key_names_table[i].name != NULL; i++)
2969 	if (c == key_names_table[i].key)
2970 	    break;
2971     if (key_names_table[i].name == NULL)
2972 	i = -1;
2973     return i;
2974 }
2975 
2976 /*
2977  * Find the special key with the given name (the given string does not have to
2978  * end with NUL, the name is assumed to end before the first non-idchar).
2979  * If the name starts with "t_" the next two characters are interpreted as a
2980  * termcap name.
2981  * Return the key code, or 0 if not found.
2982  */
2983     int
2984 get_special_key_code(name)
2985     char_u  *name;
2986 {
2987     char_u  *table_name;
2988     char_u  string[3];
2989     int	    i, j;
2990 
2991     /*
2992      * If it's <t_xx> we get the code for xx from the termcap
2993      */
2994     if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
2995     {
2996 	string[0] = name[2];
2997 	string[1] = name[3];
2998 	string[2] = NUL;
2999 	if (add_termcap_entry(string, FALSE) == OK)
3000 	    return TERMCAP2KEY(name[2], name[3]);
3001     }
3002     else
3003 	for (i = 0; key_names_table[i].name != NULL; i++)
3004 	{
3005 	    table_name = key_names_table[i].name;
3006 	    for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
3007 		if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
3008 		    break;
3009 	    if (!vim_isIDc(name[j]) && table_name[j] == NUL)
3010 		return key_names_table[i].key;
3011 	}
3012     return 0;
3013 }
3014 
3015 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3016     char_u *
3017 get_key_name(i)
3018     int	    i;
3019 {
3020     if (i >= (int)KEY_NAMES_TABLE_LEN)
3021 	return NULL;
3022     return  key_names_table[i].name;
3023 }
3024 #endif
3025 
3026 #if defined(FEAT_MOUSE) || defined(PROTO)
3027 /*
3028  * Look up the given mouse code to return the relevant information in the other
3029  * arguments.  Return which button is down or was released.
3030  */
3031     int
3032 get_mouse_button(code, is_click, is_drag)
3033     int	    code;
3034     int	    *is_click;
3035     int	    *is_drag;
3036 {
3037     int	    i;
3038 
3039     for (i = 0; mouse_table[i].pseudo_code; i++)
3040 	if (code == mouse_table[i].pseudo_code)
3041 	{
3042 	    *is_click = mouse_table[i].is_click;
3043 	    *is_drag = mouse_table[i].is_drag;
3044 	    return mouse_table[i].button;
3045 	}
3046     return 0;	    /* Shouldn't get here */
3047 }
3048 
3049 /*
3050  * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
3051  * the given information about which mouse button is down, and whether the
3052  * mouse was clicked, dragged or released.
3053  */
3054     int
3055 get_pseudo_mouse_code(button, is_click, is_drag)
3056     int	    button;	/* eg MOUSE_LEFT */
3057     int	    is_click;
3058     int	    is_drag;
3059 {
3060     int	    i;
3061 
3062     for (i = 0; mouse_table[i].pseudo_code; i++)
3063 	if (button == mouse_table[i].button
3064 	    && is_click == mouse_table[i].is_click
3065 	    && is_drag == mouse_table[i].is_drag)
3066 	{
3067 #ifdef FEAT_GUI
3068 	    /* Trick: a non mappable left click and release has mouse_col -1
3069 	     * or added MOUSE_COLOFF.  Used for 'mousefocus' in
3070 	     * gui_mouse_moved() */
3071 	    if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
3072 	    {
3073 		if (mouse_col < 0)
3074 		    mouse_col = 0;
3075 		else
3076 		    mouse_col -= MOUSE_COLOFF;
3077 		if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
3078 		    return (int)KE_LEFTMOUSE_NM;
3079 		if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
3080 		    return (int)KE_LEFTRELEASE_NM;
3081 	    }
3082 #endif
3083 	    return mouse_table[i].pseudo_code;
3084 	}
3085     return (int)KE_IGNORE;	    /* not recognized, ignore it */
3086 }
3087 #endif /* FEAT_MOUSE */
3088 
3089 /*
3090  * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
3091  */
3092     int
3093 get_fileformat(buf)
3094     buf_T	*buf;
3095 {
3096     int		c = *buf->b_p_ff;
3097 
3098     if (buf->b_p_bin || c == 'u')
3099 	return EOL_UNIX;
3100     if (c == 'm')
3101 	return EOL_MAC;
3102     return EOL_DOS;
3103 }
3104 
3105 /*
3106  * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
3107  * argument.
3108  */
3109     int
3110 get_fileformat_force(buf, eap)
3111     buf_T	*buf;
3112     exarg_T	*eap;	    /* can be NULL! */
3113 {
3114     int		c;
3115 
3116     if (eap != NULL && eap->force_ff != 0)
3117 	c = eap->cmd[eap->force_ff];
3118     else
3119     {
3120 	if ((eap != NULL && eap->force_bin != 0)
3121 			       ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
3122 	    return EOL_UNIX;
3123 	c = *buf->b_p_ff;
3124     }
3125     if (c == 'u')
3126 	return EOL_UNIX;
3127     if (c == 'm')
3128 	return EOL_MAC;
3129     return EOL_DOS;
3130 }
3131 
3132 /*
3133  * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
3134  * Sets both 'textmode' and 'fileformat'.
3135  * Note: Does _not_ set global value of 'textmode'!
3136  */
3137     void
3138 set_fileformat(t, opt_flags)
3139     int		t;
3140     int		opt_flags;	/* OPT_LOCAL and/or OPT_GLOBAL */
3141 {
3142     char	*p = NULL;
3143 
3144     switch (t)
3145     {
3146     case EOL_DOS:
3147 	p = FF_DOS;
3148 	curbuf->b_p_tx = TRUE;
3149 	break;
3150     case EOL_UNIX:
3151 	p = FF_UNIX;
3152 	curbuf->b_p_tx = FALSE;
3153 	break;
3154     case EOL_MAC:
3155 	p = FF_MAC;
3156 	curbuf->b_p_tx = FALSE;
3157 	break;
3158     }
3159     if (p != NULL)
3160 	set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
3161 						     OPT_FREE | opt_flags, 0);
3162 
3163 #ifdef FEAT_WINDOWS
3164     /* This may cause the buffer to become (un)modified. */
3165     check_status(curbuf);
3166     redraw_tabline = TRUE;
3167 #endif
3168 #ifdef FEAT_TITLE
3169     need_maketitle = TRUE;	    /* set window title later */
3170 #endif
3171 }
3172 
3173 /*
3174  * Return the default fileformat from 'fileformats'.
3175  */
3176     int
3177 default_fileformat()
3178 {
3179     switch (*p_ffs)
3180     {
3181 	case 'm':   return EOL_MAC;
3182 	case 'd':   return EOL_DOS;
3183     }
3184     return EOL_UNIX;
3185 }
3186 
3187 /*
3188  * Call shell.	Calls mch_call_shell, with 'shellxquote' added.
3189  */
3190     int
3191 call_shell(cmd, opt)
3192     char_u	*cmd;
3193     int		opt;
3194 {
3195     char_u	*ncmd;
3196     int		retval;
3197 #ifdef FEAT_PROFILE
3198     proftime_T	wait_time;
3199 #endif
3200 
3201     if (p_verbose > 3)
3202     {
3203 	verbose_enter();
3204 	smsg((char_u *)_("Calling shell to execute: \"%s\""),
3205 						    cmd == NULL ? p_sh : cmd);
3206 	out_char('\n');
3207 	cursor_on();
3208 	verbose_leave();
3209     }
3210 
3211 #ifdef FEAT_PROFILE
3212     if (do_profiling == PROF_YES)
3213 	prof_child_enter(&wait_time);
3214 #endif
3215 
3216     if (*p_sh == NUL)
3217     {
3218 	EMSG(_(e_shellempty));
3219 	retval = -1;
3220     }
3221     else
3222     {
3223 #ifdef FEAT_GUI_MSWIN
3224 	/* Don't hide the pointer while executing a shell command. */
3225 	gui_mch_mousehide(FALSE);
3226 #endif
3227 #ifdef FEAT_GUI
3228 	++hold_gui_events;
3229 #endif
3230 	/* The external command may update a tags file, clear cached tags. */
3231 	tag_freematch();
3232 
3233 	if (cmd == NULL || *p_sxq == NUL)
3234 	    retval = mch_call_shell(cmd, opt);
3235 	else
3236 	{
3237 	    char_u *ecmd = cmd;
3238 
3239 	    if (*p_sxe != NUL && STRCMP(p_sxq, "(") == 0)
3240 	    {
3241 		ecmd = vim_strsave_escaped_ext(cmd, p_sxe, '^', FALSE);
3242 		if (ecmd == NULL)
3243 		    ecmd = cmd;
3244 	    }
3245 	    ncmd = alloc((unsigned)(STRLEN(ecmd) + STRLEN(p_sxq) * 2 + 1));
3246 	    if (ncmd != NULL)
3247 	    {
3248 		STRCPY(ncmd, p_sxq);
3249 		STRCAT(ncmd, ecmd);
3250 		/* When 'shellxquote' is ( append ).
3251 		 * When 'shellxquote' is "( append )". */
3252 		STRCAT(ncmd, STRCMP(p_sxq, "(") == 0 ? (char_u *)")"
3253 			   : STRCMP(p_sxq, "\"(") == 0 ? (char_u *)")\""
3254 			   : p_sxq);
3255 		retval = mch_call_shell(ncmd, opt);
3256 		vim_free(ncmd);
3257 	    }
3258 	    else
3259 		retval = -1;
3260 	    if (ecmd != cmd)
3261 		vim_free(ecmd);
3262 	}
3263 #ifdef FEAT_GUI
3264 	--hold_gui_events;
3265 #endif
3266 	/*
3267 	 * Check the window size, in case it changed while executing the
3268 	 * external command.
3269 	 */
3270 	shell_resized_check();
3271     }
3272 
3273 #ifdef FEAT_EVAL
3274     set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
3275 # ifdef FEAT_PROFILE
3276     if (do_profiling == PROF_YES)
3277 	prof_child_exit(&wait_time);
3278 # endif
3279 #endif
3280 
3281     return retval;
3282 }
3283 
3284 /*
3285  * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to
3286  * NORMAL State with a condition.  This function returns the real State.
3287  */
3288     int
3289 get_real_state()
3290 {
3291     if (State & NORMAL)
3292     {
3293 	if (VIsual_active)
3294 	{
3295 	    if (VIsual_select)
3296 		return SELECTMODE;
3297 	    return VISUAL;
3298 	}
3299 	else if (finish_op)
3300 	    return OP_PENDING;
3301     }
3302     return State;
3303 }
3304 
3305 #if defined(FEAT_MBYTE) || defined(PROTO)
3306 /*
3307  * Return TRUE if "p" points to just after a path separator.
3308  * Takes care of multi-byte characters.
3309  * "b" must point to the start of the file name
3310  */
3311     int
3312 after_pathsep(b, p)
3313     char_u	*b;
3314     char_u	*p;
3315 {
3316     return p > b && vim_ispathsep(p[-1])
3317 			     && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
3318 }
3319 #endif
3320 
3321 /*
3322  * Return TRUE if file names "f1" and "f2" are in the same directory.
3323  * "f1" may be a short name, "f2" must be a full path.
3324  */
3325     int
3326 same_directory(f1, f2)
3327     char_u	*f1;
3328     char_u	*f2;
3329 {
3330     char_u	ffname[MAXPATHL];
3331     char_u	*t1;
3332     char_u	*t2;
3333 
3334     /* safety check */
3335     if (f1 == NULL || f2 == NULL)
3336 	return FALSE;
3337 
3338     (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
3339     t1 = gettail_sep(ffname);
3340     t2 = gettail_sep(f2);
3341     return (t1 - ffname == t2 - f2
3342 	     && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
3343 }
3344 
3345 #if defined(FEAT_SESSION) || defined(MSWIN) || defined(FEAT_GUI_MAC) \
3346 	|| ((defined(FEAT_GUI_GTK)) \
3347 			&& ( defined(FEAT_WINDOWS) || defined(FEAT_DND)) ) \
3348 	|| defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) \
3349 	|| defined(PROTO)
3350 /*
3351  * Change to a file's directory.
3352  * Caller must call shorten_fnames()!
3353  * Return OK or FAIL.
3354  */
3355     int
3356 vim_chdirfile(fname)
3357     char_u	*fname;
3358 {
3359     char_u	dir[MAXPATHL];
3360 
3361     vim_strncpy(dir, fname, MAXPATHL - 1);
3362     *gettail_sep(dir) = NUL;
3363     return mch_chdir((char *)dir) == 0 ? OK : FAIL;
3364 }
3365 #endif
3366 
3367 #if defined(STAT_IGNORES_SLASH) || defined(PROTO)
3368 /*
3369  * Check if "name" ends in a slash and is not a directory.
3370  * Used for systems where stat() ignores a trailing slash on a file name.
3371  * The Vim code assumes a trailing slash is only ignored for a directory.
3372  */
3373     int
3374 illegal_slash(name)
3375     char *name;
3376 {
3377     if (name[0] == NUL)
3378 	return FALSE;	    /* no file name is not illegal */
3379     if (name[strlen(name) - 1] != '/')
3380 	return FALSE;	    /* no trailing slash */
3381     if (mch_isdir((char_u *)name))
3382 	return FALSE;	    /* trailing slash for a directory */
3383     return TRUE;
3384 }
3385 #endif
3386 
3387 #if defined(CURSOR_SHAPE) || defined(PROTO)
3388 
3389 /*
3390  * Handling of cursor and mouse pointer shapes in various modes.
3391  */
3392 
3393 cursorentry_T shape_table[SHAPE_IDX_COUNT] =
3394 {
3395     /* The values will be filled in from the 'guicursor' and 'mouseshape'
3396      * defaults when Vim starts.
3397      * Adjust the SHAPE_IDX_ defines when making changes! */
3398     {0,	0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
3399     {0,	0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
3400     {0,	0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
3401     {0,	0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
3402     {0,	0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
3403     {0,	0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
3404     {0,	0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
3405     {0,	0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
3406     {0,	0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
3407     {0,	0, 0,   0L,   0L,   0L, 0, 0, "e", SHAPE_MOUSE},
3408     {0,	0, 0,   0L,   0L,   0L, 0, 0, "s", SHAPE_MOUSE},
3409     {0,	0, 0,   0L,   0L,   0L, 0, 0, "sd", SHAPE_MOUSE},
3410     {0,	0, 0,   0L,   0L,   0L, 0, 0, "vs", SHAPE_MOUSE},
3411     {0,	0, 0,   0L,   0L,   0L, 0, 0, "vd", SHAPE_MOUSE},
3412     {0,	0, 0,   0L,   0L,   0L, 0, 0, "m", SHAPE_MOUSE},
3413     {0,	0, 0,   0L,   0L,   0L, 0, 0, "ml", SHAPE_MOUSE},
3414     {0,	0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
3415 };
3416 
3417 #ifdef FEAT_MOUSESHAPE
3418 /*
3419  * Table with names for mouse shapes.  Keep in sync with all the tables for
3420  * mch_set_mouse_shape()!.
3421  */
3422 static char * mshape_names[] =
3423 {
3424     "arrow",	/* default, must be the first one */
3425     "blank",	/* hidden */
3426     "beam",
3427     "updown",
3428     "udsizing",
3429     "leftright",
3430     "lrsizing",
3431     "busy",
3432     "no",
3433     "crosshair",
3434     "hand1",
3435     "hand2",
3436     "pencil",
3437     "question",
3438     "rightup-arrow",
3439     "up-arrow",
3440     NULL
3441 };
3442 #endif
3443 
3444 /*
3445  * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
3446  * ("what" is SHAPE_MOUSE).
3447  * Returns error message for an illegal option, NULL otherwise.
3448  */
3449     char_u *
3450 parse_shape_opt(what)
3451     int		what;
3452 {
3453     char_u	*modep;
3454     char_u	*colonp;
3455     char_u	*commap;
3456     char_u	*slashp;
3457     char_u	*p, *endp;
3458     int		idx = 0;		/* init for GCC */
3459     int		all_idx;
3460     int		len;
3461     int		i;
3462     long	n;
3463     int		found_ve = FALSE;	/* found "ve" flag */
3464     int		round;
3465 
3466     /*
3467      * First round: check for errors; second round: do it for real.
3468      */
3469     for (round = 1; round <= 2; ++round)
3470     {
3471 	/*
3472 	 * Repeat for all comma separated parts.
3473 	 */
3474 #ifdef FEAT_MOUSESHAPE
3475 	if (what == SHAPE_MOUSE)
3476 	    modep = p_mouseshape;
3477 	else
3478 #endif
3479 	    modep = p_guicursor;
3480 	while (*modep != NUL)
3481 	{
3482 	    colonp = vim_strchr(modep, ':');
3483 	    if (colonp == NULL)
3484 		return (char_u *)N_("E545: Missing colon");
3485 	    if (colonp == modep)
3486 		return (char_u *)N_("E546: Illegal mode");
3487 	    commap = vim_strchr(modep, ',');
3488 
3489 	    /*
3490 	     * Repeat for all mode's before the colon.
3491 	     * For the 'a' mode, we loop to handle all the modes.
3492 	     */
3493 	    all_idx = -1;
3494 	    while (modep < colonp || all_idx >= 0)
3495 	    {
3496 		if (all_idx < 0)
3497 		{
3498 		    /* Find the mode. */
3499 		    if (modep[1] == '-' || modep[1] == ':')
3500 			len = 1;
3501 		    else
3502 			len = 2;
3503 		    if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
3504 			all_idx = SHAPE_IDX_COUNT - 1;
3505 		    else
3506 		    {
3507 			for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
3508 			    if (STRNICMP(modep, shape_table[idx].name, len)
3509 									 == 0)
3510 				break;
3511 			if (idx == SHAPE_IDX_COUNT
3512 				   || (shape_table[idx].used_for & what) == 0)
3513 			    return (char_u *)N_("E546: Illegal mode");
3514 			if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
3515 			    found_ve = TRUE;
3516 		    }
3517 		    modep += len + 1;
3518 		}
3519 
3520 		if (all_idx >= 0)
3521 		    idx = all_idx--;
3522 		else if (round == 2)
3523 		{
3524 #ifdef FEAT_MOUSESHAPE
3525 		    if (what == SHAPE_MOUSE)
3526 		    {
3527 			/* Set the default, for the missing parts */
3528 			shape_table[idx].mshape = 0;
3529 		    }
3530 		    else
3531 #endif
3532 		    {
3533 			/* Set the defaults, for the missing parts */
3534 			shape_table[idx].shape = SHAPE_BLOCK;
3535 			shape_table[idx].blinkwait = 700L;
3536 			shape_table[idx].blinkon = 400L;
3537 			shape_table[idx].blinkoff = 250L;
3538 		    }
3539 		}
3540 
3541 		/* Parse the part after the colon */
3542 		for (p = colonp + 1; *p && *p != ','; )
3543 		{
3544 #ifdef FEAT_MOUSESHAPE
3545 		    if (what == SHAPE_MOUSE)
3546 		    {
3547 			for (i = 0; ; ++i)
3548 			{
3549 			    if (mshape_names[i] == NULL)
3550 			    {
3551 				if (!VIM_ISDIGIT(*p))
3552 				    return (char_u *)N_("E547: Illegal mouseshape");
3553 				if (round == 2)
3554 				    shape_table[idx].mshape =
3555 					      getdigits(&p) + MSHAPE_NUMBERED;
3556 				else
3557 				    (void)getdigits(&p);
3558 				break;
3559 			    }
3560 			    len = (int)STRLEN(mshape_names[i]);
3561 			    if (STRNICMP(p, mshape_names[i], len) == 0)
3562 			    {
3563 				if (round == 2)
3564 				    shape_table[idx].mshape = i;
3565 				p += len;
3566 				break;
3567 			    }
3568 			}
3569 		    }
3570 		    else /* if (what == SHAPE_MOUSE) */
3571 #endif
3572 		    {
3573 			/*
3574 			 * First handle the ones with a number argument.
3575 			 */
3576 			i = *p;
3577 			len = 0;
3578 			if (STRNICMP(p, "ver", 3) == 0)
3579 			    len = 3;
3580 			else if (STRNICMP(p, "hor", 3) == 0)
3581 			    len = 3;
3582 			else if (STRNICMP(p, "blinkwait", 9) == 0)
3583 			    len = 9;
3584 			else if (STRNICMP(p, "blinkon", 7) == 0)
3585 			    len = 7;
3586 			else if (STRNICMP(p, "blinkoff", 8) == 0)
3587 			    len = 8;
3588 			if (len != 0)
3589 			{
3590 			    p += len;
3591 			    if (!VIM_ISDIGIT(*p))
3592 				return (char_u *)N_("E548: digit expected");
3593 			    n = getdigits(&p);
3594 			    if (len == 3)   /* "ver" or "hor" */
3595 			    {
3596 				if (n == 0)
3597 				    return (char_u *)N_("E549: Illegal percentage");
3598 				if (round == 2)
3599 				{
3600 				    if (TOLOWER_ASC(i) == 'v')
3601 					shape_table[idx].shape = SHAPE_VER;
3602 				    else
3603 					shape_table[idx].shape = SHAPE_HOR;
3604 				    shape_table[idx].percentage = n;
3605 				}
3606 			    }
3607 			    else if (round == 2)
3608 			    {
3609 				if (len == 9)
3610 				    shape_table[idx].blinkwait = n;
3611 				else if (len == 7)
3612 				    shape_table[idx].blinkon = n;
3613 				else
3614 				    shape_table[idx].blinkoff = n;
3615 			    }
3616 			}
3617 			else if (STRNICMP(p, "block", 5) == 0)
3618 			{
3619 			    if (round == 2)
3620 				shape_table[idx].shape = SHAPE_BLOCK;
3621 			    p += 5;
3622 			}
3623 			else	/* must be a highlight group name then */
3624 			{
3625 			    endp = vim_strchr(p, '-');
3626 			    if (commap == NULL)		    /* last part */
3627 			    {
3628 				if (endp == NULL)
3629 				    endp = p + STRLEN(p);   /* find end of part */
3630 			    }
3631 			    else if (endp > commap || endp == NULL)
3632 				endp = commap;
3633 			    slashp = vim_strchr(p, '/');
3634 			    if (slashp != NULL && slashp < endp)
3635 			    {
3636 				/* "group/langmap_group" */
3637 				i = syn_check_group(p, (int)(slashp - p));
3638 				p = slashp + 1;
3639 			    }
3640 			    if (round == 2)
3641 			    {
3642 				shape_table[idx].id = syn_check_group(p,
3643 							     (int)(endp - p));
3644 				shape_table[idx].id_lm = shape_table[idx].id;
3645 				if (slashp != NULL && slashp < endp)
3646 				    shape_table[idx].id = i;
3647 			    }
3648 			    p = endp;
3649 			}
3650 		    } /* if (what != SHAPE_MOUSE) */
3651 
3652 		    if (*p == '-')
3653 			++p;
3654 		}
3655 	    }
3656 	    modep = p;
3657 	    if (*modep == ',')
3658 		++modep;
3659 	}
3660     }
3661 
3662     /* If the 's' flag is not given, use the 'v' cursor for 's' */
3663     if (!found_ve)
3664     {
3665 #ifdef FEAT_MOUSESHAPE
3666 	if (what == SHAPE_MOUSE)
3667 	{
3668 	    shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3669 	}
3670 	else
3671 #endif
3672 	{
3673 	    shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3674 	    shape_table[SHAPE_IDX_VE].percentage =
3675 					 shape_table[SHAPE_IDX_V].percentage;
3676 	    shape_table[SHAPE_IDX_VE].blinkwait =
3677 					  shape_table[SHAPE_IDX_V].blinkwait;
3678 	    shape_table[SHAPE_IDX_VE].blinkon =
3679 					    shape_table[SHAPE_IDX_V].blinkon;
3680 	    shape_table[SHAPE_IDX_VE].blinkoff =
3681 					   shape_table[SHAPE_IDX_V].blinkoff;
3682 	    shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3683 	    shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3684 	}
3685     }
3686 
3687     return NULL;
3688 }
3689 
3690 # if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
3691 	|| defined(FEAT_MOUSESHAPE) || defined(PROTO)
3692 /*
3693  * Return the index into shape_table[] for the current mode.
3694  * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3695  */
3696     int
3697 get_shape_idx(mouse)
3698     int	mouse;
3699 {
3700 #ifdef FEAT_MOUSESHAPE
3701     if (mouse && (State == HITRETURN || State == ASKMORE))
3702     {
3703 # ifdef FEAT_GUI
3704 	int x, y;
3705 	gui_mch_getmouse(&x, &y);
3706 	if (Y_2_ROW(y) == Rows - 1)
3707 	    return SHAPE_IDX_MOREL;
3708 # endif
3709 	return SHAPE_IDX_MORE;
3710     }
3711     if (mouse && drag_status_line)
3712 	return SHAPE_IDX_SDRAG;
3713 # ifdef FEAT_VERTSPLIT
3714     if (mouse && drag_sep_line)
3715 	return SHAPE_IDX_VDRAG;
3716 # endif
3717 #endif
3718     if (!mouse && State == SHOWMATCH)
3719 	return SHAPE_IDX_SM;
3720 #ifdef FEAT_VREPLACE
3721     if (State & VREPLACE_FLAG)
3722 	return SHAPE_IDX_R;
3723 #endif
3724     if (State & REPLACE_FLAG)
3725 	return SHAPE_IDX_R;
3726     if (State & INSERT)
3727 	return SHAPE_IDX_I;
3728     if (State & CMDLINE)
3729     {
3730 	if (cmdline_at_end())
3731 	    return SHAPE_IDX_C;
3732 	if (cmdline_overstrike())
3733 	    return SHAPE_IDX_CR;
3734 	return SHAPE_IDX_CI;
3735     }
3736     if (finish_op)
3737 	return SHAPE_IDX_O;
3738     if (VIsual_active)
3739     {
3740 	if (*p_sel == 'e')
3741 	    return SHAPE_IDX_VE;
3742 	else
3743 	    return SHAPE_IDX_V;
3744     }
3745     return SHAPE_IDX_N;
3746 }
3747 #endif
3748 
3749 # if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3750 static int old_mouse_shape = 0;
3751 
3752 /*
3753  * Set the mouse shape:
3754  * If "shape" is -1, use shape depending on the current mode,
3755  * depending on the current state.
3756  * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3757  * when the mouse moves off the status or command line).
3758  */
3759     void
3760 update_mouseshape(shape_idx)
3761     int	shape_idx;
3762 {
3763     int new_mouse_shape;
3764 
3765     /* Only works in GUI mode. */
3766     if (!gui.in_use || gui.starting)
3767 	return;
3768 
3769     /* Postpone the updating when more is to come.  Speeds up executing of
3770      * mappings. */
3771     if (shape_idx == -1 && char_avail())
3772     {
3773 	postponed_mouseshape = TRUE;
3774 	return;
3775     }
3776 
3777     /* When ignoring the mouse don't change shape on the statusline. */
3778     if (*p_mouse == NUL
3779 	    && (shape_idx == SHAPE_IDX_CLINE
3780 		|| shape_idx == SHAPE_IDX_STATUS
3781 		|| shape_idx == SHAPE_IDX_VSEP))
3782 	shape_idx = -2;
3783 
3784     if (shape_idx == -2
3785 	    && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3786 	    && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3787 	    && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3788 	return;
3789     if (shape_idx < 0)
3790 	new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3791     else
3792 	new_mouse_shape = shape_table[shape_idx].mshape;
3793     if (new_mouse_shape != old_mouse_shape)
3794     {
3795 	mch_set_mouse_shape(new_mouse_shape);
3796 	old_mouse_shape = new_mouse_shape;
3797     }
3798     postponed_mouseshape = FALSE;
3799 }
3800 # endif
3801 
3802 #endif /* CURSOR_SHAPE */
3803 
3804 
3805 #ifdef FEAT_CRYPT
3806 /*
3807  * Optional encryption support.
3808  * Mohsin Ahmed, [email protected], 98-09-24
3809  * Based on zip/crypt sources.
3810  *
3811  * NOTE FOR USA: Since 2000 exporting this code from the USA is allowed to
3812  * most countries.  There are a few exceptions, but that still should not be a
3813  * problem since this code was originally created in Europe and India.
3814  *
3815  * Blowfish addition originally made by Mohsin Ahmed,
3816  * http://www.cs.albany.edu/~mosh 2010-03-14
3817  * Based on blowfish by Bruce Schneier (http://www.schneier.com/blowfish.html)
3818  * and sha256 by Christophe Devine.
3819  */
3820 
3821 /* from zip.h */
3822 
3823 typedef unsigned short ush;	/* unsigned 16-bit value */
3824 typedef unsigned long  ulg;	/* unsigned 32-bit value */
3825 
3826 static void make_crc_tab __ARGS((void));
3827 
3828 static ulg crc_32_tab[256];
3829 
3830 /*
3831  * Fill the CRC table.
3832  */
3833     static void
3834 make_crc_tab()
3835 {
3836     ulg		s,t,v;
3837     static int	done = FALSE;
3838 
3839     if (done)
3840 	return;
3841     for (t = 0; t < 256; t++)
3842     {
3843 	v = t;
3844 	for (s = 0; s < 8; s++)
3845 	    v = (v >> 1) ^ ((v & 1) * (ulg)0xedb88320L);
3846 	crc_32_tab[t] = v;
3847     }
3848     done = TRUE;
3849 }
3850 
3851 #define CRC32(c, b) (crc_32_tab[((int)(c) ^ (b)) & 0xff] ^ ((c) >> 8))
3852 
3853 static ulg keys[3]; /* keys defining the pseudo-random sequence */
3854 
3855 /*
3856  * Return the next byte in the pseudo-random sequence.
3857  */
3858 #define DECRYPT_BYTE_ZIP(t) { \
3859     ush temp; \
3860  \
3861     temp = (ush)keys[2] | 2; \
3862     t = (int)(((unsigned)(temp * (temp ^ 1U)) >> 8) & 0xff); \
3863 }
3864 
3865 /*
3866  * Update the encryption keys with the next byte of plain text.
3867  */
3868 #define UPDATE_KEYS_ZIP(c) { \
3869     keys[0] = CRC32(keys[0], (c)); \
3870     keys[1] += keys[0] & 0xff; \
3871     keys[1] = keys[1] * 134775813L + 1; \
3872     keys[2] = CRC32(keys[2], (int)(keys[1] >> 24)); \
3873 }
3874 
3875 static int crypt_busy = 0;
3876 static ulg saved_keys[3];
3877 static int saved_crypt_method;
3878 
3879 /*
3880  * Return int value for crypt method string:
3881  * 0 for "zip", the old method.  Also for any non-valid value.
3882  * 1 for "blowfish".
3883  */
3884     int
3885 crypt_method_from_string(s)
3886     char_u  *s;
3887 {
3888     return *s == 'b' ? 1 : 0;
3889 }
3890 
3891 /*
3892  * Get the crypt method for buffer "buf" as a number.
3893  */
3894     int
3895 get_crypt_method(buf)
3896     buf_T *buf;
3897 {
3898     return crypt_method_from_string(*buf->b_p_cm == NUL ? p_cm : buf->b_p_cm);
3899 }
3900 
3901 /*
3902  * Set the crypt method for buffer "buf" to "method" using the int value as
3903  * returned by crypt_method_from_string().
3904  */
3905     void
3906 set_crypt_method(buf, method)
3907     buf_T   *buf;
3908     int	    method;
3909 {
3910     free_string_option(buf->b_p_cm);
3911     buf->b_p_cm = vim_strsave((char_u *)(method == 0 ? "zip" : "blowfish"));
3912 }
3913 
3914 /*
3915  * Prepare for initializing encryption.  If already doing encryption then save
3916  * the state.
3917  * Must always be called symmetrically with crypt_pop_state().
3918  */
3919     void
3920 crypt_push_state()
3921 {
3922     if (crypt_busy == 1)
3923     {
3924 	/* save the state */
3925 	if (use_crypt_method == 0)
3926 	{
3927 	    saved_keys[0] = keys[0];
3928 	    saved_keys[1] = keys[1];
3929 	    saved_keys[2] = keys[2];
3930 	}
3931 	else
3932 	    bf_crypt_save();
3933 	saved_crypt_method = use_crypt_method;
3934     }
3935     else if (crypt_busy > 1)
3936 	EMSG2(_(e_intern2), "crypt_push_state()");
3937     ++crypt_busy;
3938 }
3939 
3940 /*
3941  * End encryption.  If doing encryption before crypt_push_state() then restore
3942  * the saved state.
3943  * Must always be called symmetrically with crypt_push_state().
3944  */
3945     void
3946 crypt_pop_state()
3947 {
3948     --crypt_busy;
3949     if (crypt_busy == 1)
3950     {
3951 	use_crypt_method = saved_crypt_method;
3952 	if (use_crypt_method == 0)
3953 	{
3954 	    keys[0] = saved_keys[0];
3955 	    keys[1] = saved_keys[1];
3956 	    keys[2] = saved_keys[2];
3957 	}
3958 	else
3959 	    bf_crypt_restore();
3960     }
3961 }
3962 
3963 /*
3964  * Encrypt "from[len]" into "to[len]".
3965  * "from" and "to" can be equal to encrypt in place.
3966  */
3967     void
3968 crypt_encode(from, len, to)
3969     char_u	*from;
3970     size_t	len;
3971     char_u	*to;
3972 {
3973     size_t	i;
3974     int		ztemp, t;
3975 
3976     if (use_crypt_method == 0)
3977 	for (i = 0; i < len; ++i)
3978 	{
3979 	    ztemp = from[i];
3980 	    DECRYPT_BYTE_ZIP(t);
3981 	    UPDATE_KEYS_ZIP(ztemp);
3982 	    to[i] = t ^ ztemp;
3983 	}
3984     else
3985 	bf_crypt_encode(from, len, to);
3986 }
3987 
3988 /*
3989  * Decrypt "ptr[len]" in place.
3990  */
3991     void
3992 crypt_decode(ptr, len)
3993     char_u	*ptr;
3994     long	len;
3995 {
3996     char_u *p;
3997 
3998     if (use_crypt_method == 0)
3999 	for (p = ptr; p < ptr + len; ++p)
4000 	{
4001 	    ush temp;
4002 
4003 	    temp = (ush)keys[2] | 2;
4004 	    temp = (int)(((unsigned)(temp * (temp ^ 1U)) >> 8) & 0xff);
4005 	    UPDATE_KEYS_ZIP(*p ^= temp);
4006 	}
4007     else
4008 	bf_crypt_decode(ptr, len);
4009 }
4010 
4011 /*
4012  * Initialize the encryption keys and the random header according to
4013  * the given password.
4014  * If "passwd" is NULL or empty, don't do anything.
4015  */
4016     void
4017 crypt_init_keys(passwd)
4018     char_u *passwd;		/* password string with which to modify keys */
4019 {
4020     if (passwd != NULL && *passwd != NUL)
4021     {
4022 	if (use_crypt_method == 0)
4023 	{
4024 	    char_u *p;
4025 
4026 	    make_crc_tab();
4027 	    keys[0] = 305419896L;
4028 	    keys[1] = 591751049L;
4029 	    keys[2] = 878082192L;
4030 	    for (p = passwd; *p!= NUL; ++p)
4031 	    {
4032 		UPDATE_KEYS_ZIP((int)*p);
4033 	    }
4034 	}
4035 	else
4036 	    bf_crypt_init_keys(passwd);
4037     }
4038 }
4039 
4040 /*
4041  * Free an allocated crypt key.  Clear the text to make sure it doesn't stay
4042  * in memory anywhere.
4043  */
4044     void
4045 free_crypt_key(key)
4046     char_u *key;
4047 {
4048     char_u *p;
4049 
4050     if (key != NULL)
4051     {
4052 	for (p = key; *p != NUL; ++p)
4053 	    *p = 0;
4054 	vim_free(key);
4055     }
4056 }
4057 
4058 /*
4059  * Ask the user for a crypt key.
4060  * When "store" is TRUE, the new key is stored in the 'key' option, and the
4061  * 'key' option value is returned: Don't free it.
4062  * When "store" is FALSE, the typed key is returned in allocated memory.
4063  * Returns NULL on failure.
4064  */
4065     char_u *
4066 get_crypt_key(store, twice)
4067     int		store;
4068     int		twice;	    /* Ask for the key twice. */
4069 {
4070     char_u	*p1, *p2 = NULL;
4071     int		round;
4072 
4073     for (round = 0; ; ++round)
4074     {
4075 	cmdline_star = TRUE;
4076 	cmdline_row = msg_row;
4077 	p1 = getcmdline_prompt(NUL, round == 0
4078 		? (char_u *)_("Enter encryption key: ")
4079 		: (char_u *)_("Enter same key again: "), 0, EXPAND_NOTHING,
4080 		NULL);
4081 	cmdline_star = FALSE;
4082 
4083 	if (p1 == NULL)
4084 	    break;
4085 
4086 	if (round == twice)
4087 	{
4088 	    if (p2 != NULL && STRCMP(p1, p2) != 0)
4089 	    {
4090 		MSG(_("Keys don't match!"));
4091 		free_crypt_key(p1);
4092 		free_crypt_key(p2);
4093 		p2 = NULL;
4094 		round = -1;		/* do it again */
4095 		continue;
4096 	    }
4097 
4098 	    if (store)
4099 	    {
4100 		set_option_value((char_u *)"key", 0L, p1, OPT_LOCAL);
4101 		free_crypt_key(p1);
4102 		p1 = curbuf->b_p_key;
4103 	    }
4104 	    break;
4105 	}
4106 	p2 = p1;
4107     }
4108 
4109     /* since the user typed this, no need to wait for return */
4110     if (msg_didout)
4111 	msg_putchar('\n');
4112     need_wait_return = FALSE;
4113     msg_didout = FALSE;
4114 
4115     free_crypt_key(p2);
4116     return p1;
4117 }
4118 
4119 #endif /* FEAT_CRYPT */
4120 
4121 /* TODO: make some #ifdef for this */
4122 /*--------[ file searching ]-------------------------------------------------*/
4123 /*
4124  * File searching functions for 'path', 'tags' and 'cdpath' options.
4125  * External visible functions:
4126  * vim_findfile_init()		creates/initialises the search context
4127  * vim_findfile_free_visited()	free list of visited files/dirs of search
4128  *				context
4129  * vim_findfile()		find a file in the search context
4130  * vim_findfile_cleanup()	cleanup/free search context created by
4131  *				vim_findfile_init()
4132  *
4133  * All static functions and variables start with 'ff_'
4134  *
4135  * In general it works like this:
4136  * First you create yourself a search context by calling vim_findfile_init().
4137  * It is possible to give a search context from a previous call to
4138  * vim_findfile_init(), so it can be reused. After this you call vim_findfile()
4139  * until you are satisfied with the result or it returns NULL. On every call it
4140  * returns the next file which matches the conditions given to
4141  * vim_findfile_init(). If it doesn't find a next file it returns NULL.
4142  *
4143  * It is possible to call vim_findfile_init() again to reinitialise your search
4144  * with some new parameters. Don't forget to pass your old search context to
4145  * it, so it can reuse it and especially reuse the list of already visited
4146  * directories. If you want to delete the list of already visited directories
4147  * simply call vim_findfile_free_visited().
4148  *
4149  * When you are done call vim_findfile_cleanup() to free the search context.
4150  *
4151  * The function vim_findfile_init() has a long comment, which describes the
4152  * needed parameters.
4153  *
4154  *
4155  *
4156  * ATTENTION:
4157  * ==========
4158  *	Also we use an allocated search context here, this functions are NOT
4159  *	thread-safe!!!!!
4160  *
4161  *	To minimize parameter passing (or because I'm to lazy), only the
4162  *	external visible functions get a search context as a parameter. This is
4163  *	then assigned to a static global, which is used throughout the local
4164  *	functions.
4165  */
4166 
4167 /*
4168  * type for the directory search stack
4169  */
4170 typedef struct ff_stack
4171 {
4172     struct ff_stack	*ffs_prev;
4173 
4174     /* the fix part (no wildcards) and the part containing the wildcards
4175      * of the search path
4176      */
4177     char_u		*ffs_fix_path;
4178 #ifdef FEAT_PATH_EXTRA
4179     char_u		*ffs_wc_path;
4180 #endif
4181 
4182     /* files/dirs found in the above directory, matched by the first wildcard
4183      * of wc_part
4184      */
4185     char_u		**ffs_filearray;
4186     int			ffs_filearray_size;
4187     char_u		ffs_filearray_cur;   /* needed for partly handled dirs */
4188 
4189     /* to store status of partly handled directories
4190      * 0: we work on this directory for the first time
4191      * 1: this directory was partly searched in an earlier step
4192      */
4193     int			ffs_stage;
4194 
4195     /* How deep are we in the directory tree?
4196      * Counts backward from value of level parameter to vim_findfile_init
4197      */
4198     int			ffs_level;
4199 
4200     /* Did we already expand '**' to an empty string? */
4201     int			ffs_star_star_empty;
4202 } ff_stack_T;
4203 
4204 /*
4205  * type for already visited directories or files.
4206  */
4207 typedef struct ff_visited
4208 {
4209     struct ff_visited	*ffv_next;
4210 
4211 #ifdef FEAT_PATH_EXTRA
4212     /* Visited directories are different if the wildcard string are
4213      * different. So we have to save it.
4214      */
4215     char_u		*ffv_wc_path;
4216 #endif
4217     /* for unix use inode etc for comparison (needed because of links), else
4218      * use filename.
4219      */
4220 #ifdef UNIX
4221     int			ffv_dev_valid;	/* ffv_dev and ffv_ino were set */
4222     dev_t		ffv_dev;	/* device number */
4223     ino_t		ffv_ino;	/* inode number */
4224 #endif
4225     /* The memory for this struct is allocated according to the length of
4226      * ffv_fname.
4227      */
4228     char_u		ffv_fname[1];	/* actually longer */
4229 } ff_visited_T;
4230 
4231 /*
4232  * We might have to manage several visited lists during a search.
4233  * This is especially needed for the tags option. If tags is set to:
4234  *      "./++/tags,./++/TAGS,++/tags"  (replace + with *)
4235  * So we have to do 3 searches:
4236  *   1) search from the current files directory downward for the file "tags"
4237  *   2) search from the current files directory downward for the file "TAGS"
4238  *   3) search from Vims current directory downwards for the file "tags"
4239  * As you can see, the first and the third search are for the same file, so for
4240  * the third search we can use the visited list of the first search. For the
4241  * second search we must start from a empty visited list.
4242  * The struct ff_visited_list_hdr is used to manage a linked list of already
4243  * visited lists.
4244  */
4245 typedef struct ff_visited_list_hdr
4246 {
4247     struct ff_visited_list_hdr	*ffvl_next;
4248 
4249     /* the filename the attached visited list is for */
4250     char_u			*ffvl_filename;
4251 
4252     ff_visited_T		*ffvl_visited_list;
4253 
4254 } ff_visited_list_hdr_T;
4255 
4256 
4257 /*
4258  * '**' can be expanded to several directory levels.
4259  * Set the default maximum depth.
4260  */
4261 #define FF_MAX_STAR_STAR_EXPAND ((char_u)30)
4262 
4263 /*
4264  * The search context:
4265  *   ffsc_stack_ptr:	the stack for the dirs to search
4266  *   ffsc_visited_list: the currently active visited list
4267  *   ffsc_dir_visited_list: the currently active visited list for search dirs
4268  *   ffsc_visited_lists_list: the list of all visited lists
4269  *   ffsc_dir_visited_lists_list: the list of all visited lists for search dirs
4270  *   ffsc_file_to_search:     the file to search for
4271  *   ffsc_start_dir:	the starting directory, if search path was relative
4272  *   ffsc_fix_path:	the fix part of the given path (without wildcards)
4273  *			Needed for upward search.
4274  *   ffsc_wc_path:	the part of the given path containing wildcards
4275  *   ffsc_level:	how many levels of dirs to search downwards
4276  *   ffsc_stopdirs_v:	array of stop directories for upward search
4277  *   ffsc_find_what:	FINDFILE_BOTH, FINDFILE_DIR or FINDFILE_FILE
4278  *   ffsc_tagfile:	searching for tags file, don't use 'suffixesadd'
4279  */
4280 typedef struct ff_search_ctx_T
4281 {
4282      ff_stack_T			*ffsc_stack_ptr;
4283      ff_visited_list_hdr_T	*ffsc_visited_list;
4284      ff_visited_list_hdr_T	*ffsc_dir_visited_list;
4285      ff_visited_list_hdr_T	*ffsc_visited_lists_list;
4286      ff_visited_list_hdr_T	*ffsc_dir_visited_lists_list;
4287      char_u			*ffsc_file_to_search;
4288      char_u			*ffsc_start_dir;
4289      char_u			*ffsc_fix_path;
4290 #ifdef FEAT_PATH_EXTRA
4291      char_u			*ffsc_wc_path;
4292      int			ffsc_level;
4293      char_u			**ffsc_stopdirs_v;
4294 #endif
4295      int			ffsc_find_what;
4296      int			ffsc_tagfile;
4297 } ff_search_ctx_T;
4298 
4299 /* locally needed functions */
4300 #ifdef FEAT_PATH_EXTRA
4301 static int ff_check_visited __ARGS((ff_visited_T **, char_u *, char_u *));
4302 #else
4303 static int ff_check_visited __ARGS((ff_visited_T **, char_u *));
4304 #endif
4305 static void vim_findfile_free_visited_list __ARGS((ff_visited_list_hdr_T **list_headp));
4306 static void ff_free_visited_list __ARGS((ff_visited_T *vl));
4307 static ff_visited_list_hdr_T* ff_get_visited_list __ARGS((char_u *, ff_visited_list_hdr_T **list_headp));
4308 #ifdef FEAT_PATH_EXTRA
4309 static int ff_wc_equal __ARGS((char_u *s1, char_u *s2));
4310 #endif
4311 
4312 static void ff_push __ARGS((ff_search_ctx_T *search_ctx, ff_stack_T *stack_ptr));
4313 static ff_stack_T *ff_pop __ARGS((ff_search_ctx_T *search_ctx));
4314 static void ff_clear __ARGS((ff_search_ctx_T *search_ctx));
4315 static void ff_free_stack_element __ARGS((ff_stack_T *stack_ptr));
4316 #ifdef FEAT_PATH_EXTRA
4317 static ff_stack_T *ff_create_stack_element __ARGS((char_u *, char_u *, int, int));
4318 #else
4319 static ff_stack_T *ff_create_stack_element __ARGS((char_u *, int, int));
4320 #endif
4321 #ifdef FEAT_PATH_EXTRA
4322 static int ff_path_in_stoplist __ARGS((char_u *, int, char_u **));
4323 #endif
4324 
4325 static char_u e_pathtoolong[] = N_("E854: path too long for completion");
4326 
4327 #if 0
4328 /*
4329  * if someone likes findfirst/findnext, here are the functions
4330  * NOT TESTED!!
4331  */
4332 
4333 static void *ff_fn_search_context = NULL;
4334 
4335     char_u *
4336 vim_findfirst(path, filename, level)
4337     char_u	*path;
4338     char_u	*filename;
4339     int		level;
4340 {
4341     ff_fn_search_context =
4342 	vim_findfile_init(path, filename, NULL, level, TRUE, FALSE,
4343 		ff_fn_search_context, rel_fname);
4344     if (NULL == ff_fn_search_context)
4345 	return NULL;
4346     else
4347 	return vim_findnext()
4348 }
4349 
4350     char_u *
4351 vim_findnext()
4352 {
4353     char_u *ret = vim_findfile(ff_fn_search_context);
4354 
4355     if (NULL == ret)
4356     {
4357 	vim_findfile_cleanup(ff_fn_search_context);
4358 	ff_fn_search_context = NULL;
4359     }
4360     return ret;
4361 }
4362 #endif
4363 
4364 /*
4365  * Initialization routine for vim_findfile().
4366  *
4367  * Returns the newly allocated search context or NULL if an error occurred.
4368  *
4369  * Don't forget to clean up by calling vim_findfile_cleanup() if you are done
4370  * with the search context.
4371  *
4372  * Find the file 'filename' in the directory 'path'.
4373  * The parameter 'path' may contain wildcards. If so only search 'level'
4374  * directories deep. The parameter 'level' is the absolute maximum and is
4375  * not related to restricts given to the '**' wildcard. If 'level' is 100
4376  * and you use '**200' vim_findfile() will stop after 100 levels.
4377  *
4378  * 'filename' cannot contain wildcards!  It is used as-is, no backslashes to
4379  * escape special characters.
4380  *
4381  * If 'stopdirs' is not NULL and nothing is found downward, the search is
4382  * restarted on the next higher directory level. This is repeated until the
4383  * start-directory of a search is contained in 'stopdirs'. 'stopdirs' has the
4384  * format ";*<dirname>*\(;<dirname>\)*;\=$".
4385  *
4386  * If the 'path' is relative, the starting dir for the search is either VIM's
4387  * current dir or if the path starts with "./" the current files dir.
4388  * If the 'path' is absolute, the starting dir is that part of the path before
4389  * the first wildcard.
4390  *
4391  * Upward search is only done on the starting dir.
4392  *
4393  * If 'free_visited' is TRUE the list of already visited files/directories is
4394  * cleared. Set this to FALSE if you just want to search from another
4395  * directory, but want to be sure that no directory from a previous search is
4396  * searched again. This is useful if you search for a file at different places.
4397  * The list of visited files/dirs can also be cleared with the function
4398  * vim_findfile_free_visited().
4399  *
4400  * Set the parameter 'find_what' to FINDFILE_DIR if you want to search for
4401  * directories only, FINDFILE_FILE for files only, FINDFILE_BOTH for both.
4402  *
4403  * A search context returned by a previous call to vim_findfile_init() can be
4404  * passed in the parameter "search_ctx_arg".  This context is reused and
4405  * reinitialized with the new parameters.  The list of already visited
4406  * directories from this context is only deleted if the parameter
4407  * "free_visited" is true.  Be aware that the passed "search_ctx_arg" is freed
4408  * if the reinitialization fails.
4409  *
4410  * If you don't have a search context from a previous call "search_ctx_arg"
4411  * must be NULL.
4412  *
4413  * This function silently ignores a few errors, vim_findfile() will have
4414  * limited functionality then.
4415  */
4416     void *
4417 vim_findfile_init(path, filename, stopdirs, level, free_visited, find_what,
4418 					   search_ctx_arg, tagfile, rel_fname)
4419     char_u	*path;
4420     char_u	*filename;
4421     char_u	*stopdirs UNUSED;
4422     int		level;
4423     int		free_visited;
4424     int		find_what;
4425     void	*search_ctx_arg;
4426     int		tagfile;	/* expanding names of tags files */
4427     char_u	*rel_fname;	/* file name to use for "." */
4428 {
4429 #ifdef FEAT_PATH_EXTRA
4430     char_u		*wc_part;
4431 #endif
4432     ff_stack_T		*sptr;
4433     ff_search_ctx_T	*search_ctx;
4434 
4435     /* If a search context is given by the caller, reuse it, else allocate a
4436      * new one.
4437      */
4438     if (search_ctx_arg != NULL)
4439 	search_ctx = search_ctx_arg;
4440     else
4441     {
4442 	search_ctx = (ff_search_ctx_T*)alloc((unsigned)sizeof(ff_search_ctx_T));
4443 	if (search_ctx == NULL)
4444 	    goto error_return;
4445 	vim_memset(search_ctx, 0, sizeof(ff_search_ctx_T));
4446     }
4447     search_ctx->ffsc_find_what = find_what;
4448     search_ctx->ffsc_tagfile = tagfile;
4449 
4450     /* clear the search context, but NOT the visited lists */
4451     ff_clear(search_ctx);
4452 
4453     /* clear visited list if wanted */
4454     if (free_visited == TRUE)
4455 	vim_findfile_free_visited(search_ctx);
4456     else
4457     {
4458 	/* Reuse old visited lists. Get the visited list for the given
4459 	 * filename. If no list for the current filename exists, creates a new
4460 	 * one. */
4461 	search_ctx->ffsc_visited_list = ff_get_visited_list(filename,
4462 					&search_ctx->ffsc_visited_lists_list);
4463 	if (search_ctx->ffsc_visited_list == NULL)
4464 	    goto error_return;
4465 	search_ctx->ffsc_dir_visited_list = ff_get_visited_list(filename,
4466 				    &search_ctx->ffsc_dir_visited_lists_list);
4467 	if (search_ctx->ffsc_dir_visited_list == NULL)
4468 	    goto error_return;
4469     }
4470 
4471     if (ff_expand_buffer == NULL)
4472     {
4473 	ff_expand_buffer = (char_u*)alloc(MAXPATHL);
4474 	if (ff_expand_buffer == NULL)
4475 	    goto error_return;
4476     }
4477 
4478     /* Store information on starting dir now if path is relative.
4479      * If path is absolute, we do that later.  */
4480     if (path[0] == '.'
4481 	    && (vim_ispathsep(path[1]) || path[1] == NUL)
4482 	    && (!tagfile || vim_strchr(p_cpo, CPO_DOTTAG) == NULL)
4483 	    && rel_fname != NULL)
4484     {
4485 	int	len = (int)(gettail(rel_fname) - rel_fname);
4486 
4487 	if (!vim_isAbsName(rel_fname) && len + 1 < MAXPATHL)
4488 	{
4489 	    /* Make the start dir an absolute path name. */
4490 	    vim_strncpy(ff_expand_buffer, rel_fname, len);
4491 	    search_ctx->ffsc_start_dir = FullName_save(ff_expand_buffer, FALSE);
4492 	}
4493 	else
4494 	    search_ctx->ffsc_start_dir = vim_strnsave(rel_fname, len);
4495 	if (search_ctx->ffsc_start_dir == NULL)
4496 	    goto error_return;
4497 	if (*++path != NUL)
4498 	    ++path;
4499     }
4500     else if (*path == NUL || !vim_isAbsName(path))
4501     {
4502 #ifdef BACKSLASH_IN_FILENAME
4503 	/* "c:dir" needs "c:" to be expanded, otherwise use current dir */
4504 	if (*path != NUL && path[1] == ':')
4505 	{
4506 	    char_u  drive[3];
4507 
4508 	    drive[0] = path[0];
4509 	    drive[1] = ':';
4510 	    drive[2] = NUL;
4511 	    if (vim_FullName(drive, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
4512 		goto error_return;
4513 	    path += 2;
4514 	}
4515 	else
4516 #endif
4517 	if (mch_dirname(ff_expand_buffer, MAXPATHL) == FAIL)
4518 	    goto error_return;
4519 
4520 	search_ctx->ffsc_start_dir = vim_strsave(ff_expand_buffer);
4521 	if (search_ctx->ffsc_start_dir == NULL)
4522 	    goto error_return;
4523 
4524 #ifdef BACKSLASH_IN_FILENAME
4525 	/* A path that starts with "/dir" is relative to the drive, not to the
4526 	 * directory (but not for "//machine/dir").  Only use the drive name. */
4527 	if ((*path == '/' || *path == '\\')
4528 		&& path[1] != path[0]
4529 		&& search_ctx->ffsc_start_dir[1] == ':')
4530 	    search_ctx->ffsc_start_dir[2] = NUL;
4531 #endif
4532     }
4533 
4534 #ifdef FEAT_PATH_EXTRA
4535     /*
4536      * If stopdirs are given, split them into an array of pointers.
4537      * If this fails (mem allocation), there is no upward search at all or a
4538      * stop directory is not recognized -> continue silently.
4539      * If stopdirs just contains a ";" or is empty,
4540      * search_ctx->ffsc_stopdirs_v will only contain a  NULL pointer. This
4541      * is handled as unlimited upward search.  See function
4542      * ff_path_in_stoplist() for details.
4543      */
4544     if (stopdirs != NULL)
4545     {
4546 	char_u	*walker = stopdirs;
4547 	int	dircount;
4548 
4549 	while (*walker == ';')
4550 	    walker++;
4551 
4552 	dircount = 1;
4553 	search_ctx->ffsc_stopdirs_v =
4554 				 (char_u **)alloc((unsigned)sizeof(char_u *));
4555 
4556 	if (search_ctx->ffsc_stopdirs_v != NULL)
4557 	{
4558 	    do
4559 	    {
4560 		char_u	*helper;
4561 		void	*ptr;
4562 
4563 		helper = walker;
4564 		ptr = vim_realloc(search_ctx->ffsc_stopdirs_v,
4565 					   (dircount + 1) * sizeof(char_u *));
4566 		if (ptr)
4567 		    search_ctx->ffsc_stopdirs_v = ptr;
4568 		else
4569 		    /* ignore, keep what we have and continue */
4570 		    break;
4571 		walker = vim_strchr(walker, ';');
4572 		if (walker)
4573 		{
4574 		    search_ctx->ffsc_stopdirs_v[dircount-1] =
4575 				 vim_strnsave(helper, (int)(walker - helper));
4576 		    walker++;
4577 		}
4578 		else
4579 		    /* this might be "", which means ascent till top
4580 		     * of directory tree.
4581 		     */
4582 		    search_ctx->ffsc_stopdirs_v[dircount-1] =
4583 							  vim_strsave(helper);
4584 
4585 		dircount++;
4586 
4587 	    } while (walker != NULL);
4588 	    search_ctx->ffsc_stopdirs_v[dircount-1] = NULL;
4589 	}
4590     }
4591 #endif
4592 
4593 #ifdef FEAT_PATH_EXTRA
4594     search_ctx->ffsc_level = level;
4595 
4596     /* split into:
4597      *  -fix path
4598      *  -wildcard_stuff (might be NULL)
4599      */
4600     wc_part = vim_strchr(path, '*');
4601     if (wc_part != NULL)
4602     {
4603 	int	llevel;
4604 	int	len;
4605 	char	*errpt;
4606 
4607 	/* save the fix part of the path */
4608 	search_ctx->ffsc_fix_path = vim_strnsave(path, (int)(wc_part - path));
4609 
4610 	/*
4611 	 * copy wc_path and add restricts to the '**' wildcard.
4612 	 * The octet after a '**' is used as a (binary) counter.
4613 	 * So '**3' is transposed to '**^C' ('^C' is ASCII value 3)
4614 	 * or '**76' is transposed to '**N'( 'N' is ASCII value 76).
4615 	 * For EBCDIC you get different character values.
4616 	 * If no restrict is given after '**' the default is used.
4617 	 * Due to this technique the path looks awful if you print it as a
4618 	 * string.
4619 	 */
4620 	len = 0;
4621 	while (*wc_part != NUL)
4622 	{
4623 	    if (len + 5 >= MAXPATHL)
4624 	    {
4625 		EMSG(_(e_pathtoolong));
4626 		break;
4627 	    }
4628 	    if (STRNCMP(wc_part, "**", 2) == 0)
4629 	    {
4630 		ff_expand_buffer[len++] = *wc_part++;
4631 		ff_expand_buffer[len++] = *wc_part++;
4632 
4633 		llevel = strtol((char *)wc_part, &errpt, 10);
4634 		if ((char_u *)errpt != wc_part && llevel > 0 && llevel < 255)
4635 		    ff_expand_buffer[len++] = llevel;
4636 		else if ((char_u *)errpt != wc_part && llevel == 0)
4637 		    /* restrict is 0 -> remove already added '**' */
4638 		    len -= 2;
4639 		else
4640 		    ff_expand_buffer[len++] = FF_MAX_STAR_STAR_EXPAND;
4641 		wc_part = (char_u *)errpt;
4642 		if (*wc_part != NUL && !vim_ispathsep(*wc_part))
4643 		{
4644 		    EMSG2(_("E343: Invalid path: '**[number]' must be at the end of the path or be followed by '%s'."), PATHSEPSTR);
4645 		    goto error_return;
4646 		}
4647 	    }
4648 	    else
4649 		ff_expand_buffer[len++] = *wc_part++;
4650 	}
4651 	ff_expand_buffer[len] = NUL;
4652 	search_ctx->ffsc_wc_path = vim_strsave(ff_expand_buffer);
4653 
4654 	if (search_ctx->ffsc_wc_path == NULL)
4655 	    goto error_return;
4656     }
4657     else
4658 #endif
4659 	search_ctx->ffsc_fix_path = vim_strsave(path);
4660 
4661     if (search_ctx->ffsc_start_dir == NULL)
4662     {
4663 	/* store the fix part as startdir.
4664 	 * This is needed if the parameter path is fully qualified.
4665 	 */
4666 	search_ctx->ffsc_start_dir = vim_strsave(search_ctx->ffsc_fix_path);
4667 	if (search_ctx->ffsc_start_dir == NULL)
4668 	    goto error_return;
4669 	search_ctx->ffsc_fix_path[0] = NUL;
4670     }
4671 
4672     /* create an absolute path */
4673     if (STRLEN(search_ctx->ffsc_start_dir)
4674 			  + STRLEN(search_ctx->ffsc_fix_path) + 3 >= MAXPATHL)
4675     {
4676 	EMSG(_(e_pathtoolong));
4677 	goto error_return;
4678     }
4679     STRCPY(ff_expand_buffer, search_ctx->ffsc_start_dir);
4680     add_pathsep(ff_expand_buffer);
4681     {
4682 	int    eb_len = (int)STRLEN(ff_expand_buffer);
4683 	char_u *buf = alloc(eb_len
4684 				+ (int)STRLEN(search_ctx->ffsc_fix_path) + 1);
4685 
4686 	STRCPY(buf, ff_expand_buffer);
4687 	STRCPY(buf + eb_len, search_ctx->ffsc_fix_path);
4688 	if (mch_isdir(buf))
4689 	{
4690 	    STRCAT(ff_expand_buffer, search_ctx->ffsc_fix_path);
4691 	    add_pathsep(ff_expand_buffer);
4692 	}
4693 #ifdef FEAT_PATH_EXTRA
4694 	else
4695 	{
4696 	    char_u *p =  gettail(search_ctx->ffsc_fix_path);
4697 	    char_u *wc_path = NULL;
4698 	    char_u *temp = NULL;
4699 	    int    len = 0;
4700 
4701 	    if (p > search_ctx->ffsc_fix_path)
4702 	    {
4703 		len = (int)(p - search_ctx->ffsc_fix_path) - 1;
4704 		STRNCAT(ff_expand_buffer, search_ctx->ffsc_fix_path, len);
4705 		add_pathsep(ff_expand_buffer);
4706 	    }
4707 	    else
4708 		len = (int)STRLEN(search_ctx->ffsc_fix_path);
4709 
4710 	    if (search_ctx->ffsc_wc_path != NULL)
4711 	    {
4712 		wc_path = vim_strsave(search_ctx->ffsc_wc_path);
4713 		temp = alloc((int)(STRLEN(search_ctx->ffsc_wc_path)
4714 				 + STRLEN(search_ctx->ffsc_fix_path + len)
4715 				 + 1));
4716 	    }
4717 
4718 	    if (temp == NULL || wc_path == NULL)
4719 	    {
4720 		vim_free(buf);
4721 		vim_free(temp);
4722 		vim_free(wc_path);
4723 		goto error_return;
4724 	    }
4725 
4726 	    STRCPY(temp, search_ctx->ffsc_fix_path + len);
4727 	    STRCAT(temp, search_ctx->ffsc_wc_path);
4728 	    vim_free(search_ctx->ffsc_wc_path);
4729 	    vim_free(wc_path);
4730 	    search_ctx->ffsc_wc_path = temp;
4731 	}
4732 #endif
4733 	vim_free(buf);
4734     }
4735 
4736     sptr = ff_create_stack_element(ff_expand_buffer,
4737 #ifdef FEAT_PATH_EXTRA
4738 	    search_ctx->ffsc_wc_path,
4739 #endif
4740 	    level, 0);
4741 
4742     if (sptr == NULL)
4743 	goto error_return;
4744 
4745     ff_push(search_ctx, sptr);
4746 
4747     search_ctx->ffsc_file_to_search = vim_strsave(filename);
4748     if (search_ctx->ffsc_file_to_search == NULL)
4749 	goto error_return;
4750 
4751     return search_ctx;
4752 
4753 error_return:
4754     /*
4755      * We clear the search context now!
4756      * Even when the caller gave us a (perhaps valid) context we free it here,
4757      * as we might have already destroyed it.
4758      */
4759     vim_findfile_cleanup(search_ctx);
4760     return NULL;
4761 }
4762 
4763 #if defined(FEAT_PATH_EXTRA) || defined(PROTO)
4764 /*
4765  * Get the stopdir string.  Check that ';' is not escaped.
4766  */
4767     char_u *
4768 vim_findfile_stopdir(buf)
4769     char_u	*buf;
4770 {
4771     char_u	*r_ptr = buf;
4772 
4773     while (*r_ptr != NUL && *r_ptr != ';')
4774     {
4775 	if (r_ptr[0] == '\\' && r_ptr[1] == ';')
4776 	{
4777 	    /* Overwrite the escape char,
4778 	     * use STRLEN(r_ptr) to move the trailing '\0'. */
4779 	    STRMOVE(r_ptr, r_ptr + 1);
4780 	    r_ptr++;
4781 	}
4782 	r_ptr++;
4783     }
4784     if (*r_ptr == ';')
4785     {
4786 	*r_ptr = 0;
4787 	r_ptr++;
4788     }
4789     else if (*r_ptr == NUL)
4790 	r_ptr = NULL;
4791     return r_ptr;
4792 }
4793 #endif
4794 
4795 /*
4796  * Clean up the given search context. Can handle a NULL pointer.
4797  */
4798     void
4799 vim_findfile_cleanup(ctx)
4800     void	*ctx;
4801 {
4802     if (ctx == NULL)
4803 	return;
4804 
4805     vim_findfile_free_visited(ctx);
4806     ff_clear(ctx);
4807     vim_free(ctx);
4808 }
4809 
4810 /*
4811  * Find a file in a search context.
4812  * The search context was created with vim_findfile_init() above.
4813  * Return a pointer to an allocated file name or NULL if nothing found.
4814  * To get all matching files call this function until you get NULL.
4815  *
4816  * If the passed search_context is NULL, NULL is returned.
4817  *
4818  * The search algorithm is depth first. To change this replace the
4819  * stack with a list (don't forget to leave partly searched directories on the
4820  * top of the list).
4821  */
4822     char_u *
4823 vim_findfile(search_ctx_arg)
4824     void	*search_ctx_arg;
4825 {
4826     char_u	*file_path;
4827 #ifdef FEAT_PATH_EXTRA
4828     char_u	*rest_of_wildcards;
4829     char_u	*path_end = NULL;
4830 #endif
4831     ff_stack_T	*stackp;
4832 #if defined(FEAT_SEARCHPATH) || defined(FEAT_PATH_EXTRA)
4833     int		len;
4834 #endif
4835     int		i;
4836     char_u	*p;
4837 #ifdef FEAT_SEARCHPATH
4838     char_u	*suf;
4839 #endif
4840     ff_search_ctx_T *search_ctx;
4841 
4842     if (search_ctx_arg == NULL)
4843 	return NULL;
4844 
4845     search_ctx = (ff_search_ctx_T *)search_ctx_arg;
4846 
4847     /*
4848      * filepath is used as buffer for various actions and as the storage to
4849      * return a found filename.
4850      */
4851     if ((file_path = alloc((int)MAXPATHL)) == NULL)
4852 	return NULL;
4853 
4854 #ifdef FEAT_PATH_EXTRA
4855     /* store the end of the start dir -- needed for upward search */
4856     if (search_ctx->ffsc_start_dir != NULL)
4857 	path_end = &search_ctx->ffsc_start_dir[
4858 					  STRLEN(search_ctx->ffsc_start_dir)];
4859 #endif
4860 
4861 #ifdef FEAT_PATH_EXTRA
4862     /* upward search loop */
4863     for (;;)
4864     {
4865 #endif
4866 	/* downward search loop */
4867 	for (;;)
4868 	{
4869 	    /* check if user user wants to stop the search*/
4870 	    ui_breakcheck();
4871 	    if (got_int)
4872 		break;
4873 
4874 	    /* get directory to work on from stack */
4875 	    stackp = ff_pop(search_ctx);
4876 	    if (stackp == NULL)
4877 		break;
4878 
4879 	    /*
4880 	     * TODO: decide if we leave this test in
4881 	     *
4882 	     * GOOD: don't search a directory(-tree) twice.
4883 	     * BAD:  - check linked list for every new directory entered.
4884 	     *       - check for double files also done below
4885 	     *
4886 	     * Here we check if we already searched this directory.
4887 	     * We already searched a directory if:
4888 	     * 1) The directory is the same.
4889 	     * 2) We would use the same wildcard string.
4890 	     *
4891 	     * Good if you have links on same directory via several ways
4892 	     *  or you have selfreferences in directories (e.g. SuSE Linux 6.3:
4893 	     *  /etc/rc.d/init.d is linked to /etc/rc.d -> endless loop)
4894 	     *
4895 	     * This check is only needed for directories we work on for the
4896 	     * first time (hence stackp->ff_filearray == NULL)
4897 	     */
4898 	    if (stackp->ffs_filearray == NULL
4899 		    && ff_check_visited(&search_ctx->ffsc_dir_visited_list
4900 							  ->ffvl_visited_list,
4901 			stackp->ffs_fix_path
4902 #ifdef FEAT_PATH_EXTRA
4903 			, stackp->ffs_wc_path
4904 #endif
4905 			) == FAIL)
4906 	    {
4907 #ifdef FF_VERBOSE
4908 		if (p_verbose >= 5)
4909 		{
4910 		    verbose_enter_scroll();
4911 		    smsg((char_u *)"Already Searched: %s (%s)",
4912 				   stackp->ffs_fix_path, stackp->ffs_wc_path);
4913 		    /* don't overwrite this either */
4914 		    msg_puts((char_u *)"\n");
4915 		    verbose_leave_scroll();
4916 		}
4917 #endif
4918 		ff_free_stack_element(stackp);
4919 		continue;
4920 	    }
4921 #ifdef FF_VERBOSE
4922 	    else if (p_verbose >= 5)
4923 	    {
4924 		verbose_enter_scroll();
4925 		smsg((char_u *)"Searching: %s (%s)",
4926 				   stackp->ffs_fix_path, stackp->ffs_wc_path);
4927 		/* don't overwrite this either */
4928 		msg_puts((char_u *)"\n");
4929 		verbose_leave_scroll();
4930 	    }
4931 #endif
4932 
4933 	    /* check depth */
4934 	    if (stackp->ffs_level <= 0)
4935 	    {
4936 		ff_free_stack_element(stackp);
4937 		continue;
4938 	    }
4939 
4940 	    file_path[0] = NUL;
4941 
4942 	    /*
4943 	     * If no filearray till now expand wildcards
4944 	     * The function expand_wildcards() can handle an array of paths
4945 	     * and all possible expands are returned in one array. We use this
4946 	     * to handle the expansion of '**' into an empty string.
4947 	     */
4948 	    if (stackp->ffs_filearray == NULL)
4949 	    {
4950 		char_u *dirptrs[2];
4951 
4952 		/* we use filepath to build the path expand_wildcards() should
4953 		 * expand.
4954 		 */
4955 		dirptrs[0] = file_path;
4956 		dirptrs[1] = NULL;
4957 
4958 		/* if we have a start dir copy it in */
4959 		if (!vim_isAbsName(stackp->ffs_fix_path)
4960 						&& search_ctx->ffsc_start_dir)
4961 		{
4962 		    STRCPY(file_path, search_ctx->ffsc_start_dir);
4963 		    add_pathsep(file_path);
4964 		}
4965 
4966 		/* append the fix part of the search path */
4967 		STRCAT(file_path, stackp->ffs_fix_path);
4968 		add_pathsep(file_path);
4969 
4970 #ifdef FEAT_PATH_EXTRA
4971 		rest_of_wildcards = stackp->ffs_wc_path;
4972 		if (*rest_of_wildcards != NUL)
4973 		{
4974 		    len = (int)STRLEN(file_path);
4975 		    if (STRNCMP(rest_of_wildcards, "**", 2) == 0)
4976 		    {
4977 			/* pointer to the restrict byte
4978 			 * The restrict byte is not a character!
4979 			 */
4980 			p = rest_of_wildcards + 2;
4981 
4982 			if (*p > 0)
4983 			{
4984 			    (*p)--;
4985 			    file_path[len++] = '*';
4986 			}
4987 
4988 			if (*p == 0)
4989 			{
4990 			    /* remove '**<numb> from wildcards */
4991 			    STRMOVE(rest_of_wildcards, rest_of_wildcards + 3);
4992 			}
4993 			else
4994 			    rest_of_wildcards += 3;
4995 
4996 			if (stackp->ffs_star_star_empty == 0)
4997 			{
4998 			    /* if not done before, expand '**' to empty */
4999 			    stackp->ffs_star_star_empty = 1;
5000 			    dirptrs[1] = stackp->ffs_fix_path;
5001 			}
5002 		    }
5003 
5004 		    /*
5005 		     * Here we copy until the next path separator or the end of
5006 		     * the path. If we stop at a path separator, there is
5007 		     * still something else left. This is handled below by
5008 		     * pushing every directory returned from expand_wildcards()
5009 		     * on the stack again for further search.
5010 		     */
5011 		    while (*rest_of_wildcards
5012 			    && !vim_ispathsep(*rest_of_wildcards))
5013 			file_path[len++] = *rest_of_wildcards++;
5014 
5015 		    file_path[len] = NUL;
5016 		    if (vim_ispathsep(*rest_of_wildcards))
5017 			rest_of_wildcards++;
5018 		}
5019 #endif
5020 
5021 		/*
5022 		 * Expand wildcards like "*" and "$VAR".
5023 		 * If the path is a URL don't try this.
5024 		 */
5025 		if (path_with_url(dirptrs[0]))
5026 		{
5027 		    stackp->ffs_filearray = (char_u **)
5028 					      alloc((unsigned)sizeof(char *));
5029 		    if (stackp->ffs_filearray != NULL
5030 			    && (stackp->ffs_filearray[0]
5031 				= vim_strsave(dirptrs[0])) != NULL)
5032 			stackp->ffs_filearray_size = 1;
5033 		    else
5034 			stackp->ffs_filearray_size = 0;
5035 		}
5036 		else
5037 		    /* Add EW_NOTWILD because the expanded path may contain
5038 		     * wildcard characters that are to be taken literally.
5039 		     * This is a bit of a hack. */
5040 		    expand_wildcards((dirptrs[1] == NULL) ? 1 : 2, dirptrs,
5041 			    &stackp->ffs_filearray_size,
5042 			    &stackp->ffs_filearray,
5043 			    EW_DIR|EW_ADDSLASH|EW_SILENT|EW_NOTWILD);
5044 
5045 		stackp->ffs_filearray_cur = 0;
5046 		stackp->ffs_stage = 0;
5047 	    }
5048 #ifdef FEAT_PATH_EXTRA
5049 	    else
5050 		rest_of_wildcards = &stackp->ffs_wc_path[
5051 						 STRLEN(stackp->ffs_wc_path)];
5052 #endif
5053 
5054 	    if (stackp->ffs_stage == 0)
5055 	    {
5056 		/* this is the first time we work on this directory */
5057 #ifdef FEAT_PATH_EXTRA
5058 		if (*rest_of_wildcards == NUL)
5059 #endif
5060 		{
5061 		    /*
5062 		     * We don't have further wildcards to expand, so we have to
5063 		     * check for the final file now.
5064 		     */
5065 		    for (i = stackp->ffs_filearray_cur;
5066 					  i < stackp->ffs_filearray_size; ++i)
5067 		    {
5068 			if (!path_with_url(stackp->ffs_filearray[i])
5069 				      && !mch_isdir(stackp->ffs_filearray[i]))
5070 			    continue;   /* not a directory */
5071 
5072 			/* prepare the filename to be checked for existence
5073 			 * below */
5074 			STRCPY(file_path, stackp->ffs_filearray[i]);
5075 			add_pathsep(file_path);
5076 			STRCAT(file_path, search_ctx->ffsc_file_to_search);
5077 
5078 			/*
5079 			 * Try without extra suffix and then with suffixes
5080 			 * from 'suffixesadd'.
5081 			 */
5082 #ifdef FEAT_SEARCHPATH
5083 			len = (int)STRLEN(file_path);
5084 			if (search_ctx->ffsc_tagfile)
5085 			    suf = (char_u *)"";
5086 			else
5087 			    suf = curbuf->b_p_sua;
5088 			for (;;)
5089 #endif
5090 			{
5091 			    /* if file exists and we didn't already find it */
5092 			    if ((path_with_url(file_path)
5093 				  || (mch_getperm(file_path) >= 0
5094 				      && (search_ctx->ffsc_find_what
5095 							      == FINDFILE_BOTH
5096 					  || ((search_ctx->ffsc_find_what
5097 							      == FINDFILE_DIR)
5098 						   == mch_isdir(file_path)))))
5099 #ifndef FF_VERBOSE
5100 				    && (ff_check_visited(
5101 					    &search_ctx->ffsc_visited_list->ffvl_visited_list,
5102 					    file_path
5103 #ifdef FEAT_PATH_EXTRA
5104 					    , (char_u *)""
5105 #endif
5106 					    ) == OK)
5107 #endif
5108 			       )
5109 			    {
5110 #ifdef FF_VERBOSE
5111 				if (ff_check_visited(
5112 					    &search_ctx->ffsc_visited_list->ffvl_visited_list,
5113 					    file_path
5114 #ifdef FEAT_PATH_EXTRA
5115 					    , (char_u *)""
5116 #endif
5117 						    ) == FAIL)
5118 				{
5119 				    if (p_verbose >= 5)
5120 				    {
5121 					verbose_enter_scroll();
5122 					smsg((char_u *)"Already: %s",
5123 								   file_path);
5124 					/* don't overwrite this either */
5125 					msg_puts((char_u *)"\n");
5126 					verbose_leave_scroll();
5127 				    }
5128 				    continue;
5129 				}
5130 #endif
5131 
5132 				/* push dir to examine rest of subdirs later */
5133 				stackp->ffs_filearray_cur = i + 1;
5134 				ff_push(search_ctx, stackp);
5135 
5136 				if (!path_with_url(file_path))
5137 				    simplify_filename(file_path);
5138 				if (mch_dirname(ff_expand_buffer, MAXPATHL)
5139 									== OK)
5140 				{
5141 				    p = shorten_fname(file_path,
5142 							    ff_expand_buffer);
5143 				    if (p != NULL)
5144 					STRMOVE(file_path, p);
5145 				}
5146 #ifdef FF_VERBOSE
5147 				if (p_verbose >= 5)
5148 				{
5149 				    verbose_enter_scroll();
5150 				    smsg((char_u *)"HIT: %s", file_path);
5151 				    /* don't overwrite this either */
5152 				    msg_puts((char_u *)"\n");
5153 				    verbose_leave_scroll();
5154 				}
5155 #endif
5156 				return file_path;
5157 			    }
5158 
5159 #ifdef FEAT_SEARCHPATH
5160 			    /* Not found or found already, try next suffix. */
5161 			    if (*suf == NUL)
5162 				break;
5163 			    copy_option_part(&suf, file_path + len,
5164 							 MAXPATHL - len, ",");
5165 #endif
5166 			}
5167 		    }
5168 		}
5169 #ifdef FEAT_PATH_EXTRA
5170 		else
5171 		{
5172 		    /*
5173 		     * still wildcards left, push the directories for further
5174 		     * search
5175 		     */
5176 		    for (i = stackp->ffs_filearray_cur;
5177 					  i < stackp->ffs_filearray_size; ++i)
5178 		    {
5179 			if (!mch_isdir(stackp->ffs_filearray[i]))
5180 			    continue;	/* not a directory */
5181 
5182 			ff_push(search_ctx,
5183 				ff_create_stack_element(
5184 						     stackp->ffs_filearray[i],
5185 						     rest_of_wildcards,
5186 						     stackp->ffs_level - 1, 0));
5187 		    }
5188 		}
5189 #endif
5190 		stackp->ffs_filearray_cur = 0;
5191 		stackp->ffs_stage = 1;
5192 	    }
5193 
5194 #ifdef FEAT_PATH_EXTRA
5195 	    /*
5196 	     * if wildcards contains '**' we have to descent till we reach the
5197 	     * leaves of the directory tree.
5198 	     */
5199 	    if (STRNCMP(stackp->ffs_wc_path, "**", 2) == 0)
5200 	    {
5201 		for (i = stackp->ffs_filearray_cur;
5202 					  i < stackp->ffs_filearray_size; ++i)
5203 		{
5204 		    if (fnamecmp(stackp->ffs_filearray[i],
5205 						   stackp->ffs_fix_path) == 0)
5206 			continue; /* don't repush same directory */
5207 		    if (!mch_isdir(stackp->ffs_filearray[i]))
5208 			continue;   /* not a directory */
5209 		    ff_push(search_ctx,
5210 			    ff_create_stack_element(stackp->ffs_filearray[i],
5211 				stackp->ffs_wc_path, stackp->ffs_level - 1, 1));
5212 		}
5213 	    }
5214 #endif
5215 
5216 	    /* we are done with the current directory */
5217 	    ff_free_stack_element(stackp);
5218 
5219 	}
5220 
5221 #ifdef FEAT_PATH_EXTRA
5222 	/* If we reached this, we didn't find anything downwards.
5223 	 * Let's check if we should do an upward search.
5224 	 */
5225 	if (search_ctx->ffsc_start_dir
5226 		&& search_ctx->ffsc_stopdirs_v != NULL && !got_int)
5227 	{
5228 	    ff_stack_T  *sptr;
5229 
5230 	    /* is the last starting directory in the stop list? */
5231 	    if (ff_path_in_stoplist(search_ctx->ffsc_start_dir,
5232 		       (int)(path_end - search_ctx->ffsc_start_dir),
5233 		       search_ctx->ffsc_stopdirs_v) == TRUE)
5234 		break;
5235 
5236 	    /* cut of last dir */
5237 	    while (path_end > search_ctx->ffsc_start_dir
5238 						  && vim_ispathsep(*path_end))
5239 		path_end--;
5240 	    while (path_end > search_ctx->ffsc_start_dir
5241 					      && !vim_ispathsep(path_end[-1]))
5242 		path_end--;
5243 	    *path_end = 0;
5244 	    path_end--;
5245 
5246 	    if (*search_ctx->ffsc_start_dir == 0)
5247 		break;
5248 
5249 	    STRCPY(file_path, search_ctx->ffsc_start_dir);
5250 	    add_pathsep(file_path);
5251 	    STRCAT(file_path, search_ctx->ffsc_fix_path);
5252 
5253 	    /* create a new stack entry */
5254 	    sptr = ff_create_stack_element(file_path,
5255 		    search_ctx->ffsc_wc_path, search_ctx->ffsc_level, 0);
5256 	    if (sptr == NULL)
5257 		break;
5258 	    ff_push(search_ctx, sptr);
5259 	}
5260 	else
5261 	    break;
5262     }
5263 #endif
5264 
5265     vim_free(file_path);
5266     return NULL;
5267 }
5268 
5269 /*
5270  * Free the list of lists of visited files and directories
5271  * Can handle it if the passed search_context is NULL;
5272  */
5273     void
5274 vim_findfile_free_visited(search_ctx_arg)
5275     void	*search_ctx_arg;
5276 {
5277     ff_search_ctx_T *search_ctx;
5278 
5279     if (search_ctx_arg == NULL)
5280 	return;
5281 
5282     search_ctx = (ff_search_ctx_T *)search_ctx_arg;
5283     vim_findfile_free_visited_list(&search_ctx->ffsc_visited_lists_list);
5284     vim_findfile_free_visited_list(&search_ctx->ffsc_dir_visited_lists_list);
5285 }
5286 
5287     static void
5288 vim_findfile_free_visited_list(list_headp)
5289     ff_visited_list_hdr_T	**list_headp;
5290 {
5291     ff_visited_list_hdr_T *vp;
5292 
5293     while (*list_headp != NULL)
5294     {
5295 	vp = (*list_headp)->ffvl_next;
5296 	ff_free_visited_list((*list_headp)->ffvl_visited_list);
5297 
5298 	vim_free((*list_headp)->ffvl_filename);
5299 	vim_free(*list_headp);
5300 	*list_headp = vp;
5301     }
5302     *list_headp = NULL;
5303 }
5304 
5305     static void
5306 ff_free_visited_list(vl)
5307     ff_visited_T *vl;
5308 {
5309     ff_visited_T *vp;
5310 
5311     while (vl != NULL)
5312     {
5313 	vp = vl->ffv_next;
5314 #ifdef FEAT_PATH_EXTRA
5315 	vim_free(vl->ffv_wc_path);
5316 #endif
5317 	vim_free(vl);
5318 	vl = vp;
5319     }
5320     vl = NULL;
5321 }
5322 
5323 /*
5324  * Returns the already visited list for the given filename. If none is found it
5325  * allocates a new one.
5326  */
5327     static ff_visited_list_hdr_T*
5328 ff_get_visited_list(filename, list_headp)
5329     char_u			*filename;
5330     ff_visited_list_hdr_T	**list_headp;
5331 {
5332     ff_visited_list_hdr_T  *retptr = NULL;
5333 
5334     /* check if a visited list for the given filename exists */
5335     if (*list_headp != NULL)
5336     {
5337 	retptr = *list_headp;
5338 	while (retptr != NULL)
5339 	{
5340 	    if (fnamecmp(filename, retptr->ffvl_filename) == 0)
5341 	    {
5342 #ifdef FF_VERBOSE
5343 		if (p_verbose >= 5)
5344 		{
5345 		    verbose_enter_scroll();
5346 		    smsg((char_u *)"ff_get_visited_list: FOUND list for %s",
5347 								    filename);
5348 		    /* don't overwrite this either */
5349 		    msg_puts((char_u *)"\n");
5350 		    verbose_leave_scroll();
5351 		}
5352 #endif
5353 		return retptr;
5354 	    }
5355 	    retptr = retptr->ffvl_next;
5356 	}
5357     }
5358 
5359 #ifdef FF_VERBOSE
5360     if (p_verbose >= 5)
5361     {
5362 	verbose_enter_scroll();
5363 	smsg((char_u *)"ff_get_visited_list: new list for %s", filename);
5364 	/* don't overwrite this either */
5365 	msg_puts((char_u *)"\n");
5366 	verbose_leave_scroll();
5367     }
5368 #endif
5369 
5370     /*
5371      * if we reach this we didn't find a list and we have to allocate new list
5372      */
5373     retptr = (ff_visited_list_hdr_T*)alloc((unsigned)sizeof(*retptr));
5374     if (retptr == NULL)
5375 	return NULL;
5376 
5377     retptr->ffvl_visited_list = NULL;
5378     retptr->ffvl_filename = vim_strsave(filename);
5379     if (retptr->ffvl_filename == NULL)
5380     {
5381 	vim_free(retptr);
5382 	return NULL;
5383     }
5384     retptr->ffvl_next = *list_headp;
5385     *list_headp = retptr;
5386 
5387     return retptr;
5388 }
5389 
5390 #ifdef FEAT_PATH_EXTRA
5391 /*
5392  * check if two wildcard paths are equal. Returns TRUE or FALSE.
5393  * They are equal if:
5394  *  - both paths are NULL
5395  *  - they have the same length
5396  *  - char by char comparison is OK
5397  *  - the only differences are in the counters behind a '**', so
5398  *    '**\20' is equal to '**\24'
5399  */
5400     static int
5401 ff_wc_equal(s1, s2)
5402     char_u	*s1;
5403     char_u	*s2;
5404 {
5405     int		i;
5406     int		prev1 = NUL;
5407     int		prev2 = NUL;
5408 
5409     if (s1 == s2)
5410 	return TRUE;
5411 
5412     if (s1 == NULL || s2 == NULL)
5413 	return FALSE;
5414 
5415     if (STRLEN(s1) != STRLEN(s2))
5416 	return FAIL;
5417 
5418     for (i = 0; s1[i] != NUL && s2[i] != NUL; i += MB_PTR2LEN(s1 + i))
5419     {
5420 	int c1 = PTR2CHAR(s1 + i);
5421 	int c2 = PTR2CHAR(s2 + i);
5422 
5423 	if ((p_fic ? MB_TOLOWER(c1) != MB_TOLOWER(c2) : c1 != c2)
5424 		&& (prev1 != '*' || prev2 != '*'))
5425 	    return FAIL;
5426 	prev2 = prev1;
5427 	prev1 = c1;
5428     }
5429     return TRUE;
5430 }
5431 #endif
5432 
5433 /*
5434  * maintains the list of already visited files and dirs
5435  * returns FAIL if the given file/dir is already in the list
5436  * returns OK if it is newly added
5437  *
5438  * TODO: What to do on memory allocation problems?
5439  *	 -> return TRUE - Better the file is found several times instead of
5440  *	    never.
5441  */
5442     static int
5443 ff_check_visited(visited_list, fname
5444 #ifdef FEAT_PATH_EXTRA
5445 	, wc_path
5446 #endif
5447 	)
5448     ff_visited_T	**visited_list;
5449     char_u		*fname;
5450 #ifdef FEAT_PATH_EXTRA
5451     char_u		*wc_path;
5452 #endif
5453 {
5454     ff_visited_T	*vp;
5455 #ifdef UNIX
5456     struct stat		st;
5457     int			url = FALSE;
5458 #endif
5459 
5460     /* For an URL we only compare the name, otherwise we compare the
5461      * device/inode (unix) or the full path name (not Unix). */
5462     if (path_with_url(fname))
5463     {
5464 	vim_strncpy(ff_expand_buffer, fname, MAXPATHL - 1);
5465 #ifdef UNIX
5466 	url = TRUE;
5467 #endif
5468     }
5469     else
5470     {
5471 	ff_expand_buffer[0] = NUL;
5472 #ifdef UNIX
5473 	if (mch_stat((char *)fname, &st) < 0)
5474 #else
5475 	if (vim_FullName(fname, ff_expand_buffer, MAXPATHL, TRUE) == FAIL)
5476 #endif
5477 	    return FAIL;
5478     }
5479 
5480     /* check against list of already visited files */
5481     for (vp = *visited_list; vp != NULL; vp = vp->ffv_next)
5482     {
5483 	if (
5484 #ifdef UNIX
5485 		!url ? (vp->ffv_dev_valid && vp->ffv_dev == st.st_dev
5486 						  && vp->ffv_ino == st.st_ino)
5487 		     :
5488 #endif
5489 		fnamecmp(vp->ffv_fname, ff_expand_buffer) == 0
5490 	   )
5491 	{
5492 #ifdef FEAT_PATH_EXTRA
5493 	    /* are the wildcard parts equal */
5494 	    if (ff_wc_equal(vp->ffv_wc_path, wc_path) == TRUE)
5495 #endif
5496 		/* already visited */
5497 		return FAIL;
5498 	}
5499     }
5500 
5501     /*
5502      * New file/dir.  Add it to the list of visited files/dirs.
5503      */
5504     vp = (ff_visited_T *)alloc((unsigned)(sizeof(ff_visited_T)
5505 						 + STRLEN(ff_expand_buffer)));
5506 
5507     if (vp != NULL)
5508     {
5509 #ifdef UNIX
5510 	if (!url)
5511 	{
5512 	    vp->ffv_dev_valid = TRUE;
5513 	    vp->ffv_ino = st.st_ino;
5514 	    vp->ffv_dev = st.st_dev;
5515 	    vp->ffv_fname[0] = NUL;
5516 	}
5517 	else
5518 	{
5519 	    vp->ffv_dev_valid = FALSE;
5520 #endif
5521 	    STRCPY(vp->ffv_fname, ff_expand_buffer);
5522 #ifdef UNIX
5523 	}
5524 #endif
5525 #ifdef FEAT_PATH_EXTRA
5526 	if (wc_path != NULL)
5527 	    vp->ffv_wc_path = vim_strsave(wc_path);
5528 	else
5529 	    vp->ffv_wc_path = NULL;
5530 #endif
5531 
5532 	vp->ffv_next = *visited_list;
5533 	*visited_list = vp;
5534     }
5535 
5536     return OK;
5537 }
5538 
5539 /*
5540  * create stack element from given path pieces
5541  */
5542     static ff_stack_T *
5543 ff_create_stack_element(fix_part,
5544 #ifdef FEAT_PATH_EXTRA
5545 	wc_part,
5546 #endif
5547 	level, star_star_empty)
5548     char_u	*fix_part;
5549 #ifdef FEAT_PATH_EXTRA
5550     char_u	*wc_part;
5551 #endif
5552     int		level;
5553     int		star_star_empty;
5554 {
5555     ff_stack_T	*new;
5556 
5557     new = (ff_stack_T *)alloc((unsigned)sizeof(ff_stack_T));
5558     if (new == NULL)
5559 	return NULL;
5560 
5561     new->ffs_prev	   = NULL;
5562     new->ffs_filearray	   = NULL;
5563     new->ffs_filearray_size = 0;
5564     new->ffs_filearray_cur  = 0;
5565     new->ffs_stage	   = 0;
5566     new->ffs_level	   = level;
5567     new->ffs_star_star_empty = star_star_empty;;
5568 
5569     /* the following saves NULL pointer checks in vim_findfile */
5570     if (fix_part == NULL)
5571 	fix_part = (char_u *)"";
5572     new->ffs_fix_path = vim_strsave(fix_part);
5573 
5574 #ifdef FEAT_PATH_EXTRA
5575     if (wc_part == NULL)
5576 	wc_part  = (char_u *)"";
5577     new->ffs_wc_path = vim_strsave(wc_part);
5578 #endif
5579 
5580     if (new->ffs_fix_path == NULL
5581 #ifdef FEAT_PATH_EXTRA
5582 	    || new->ffs_wc_path == NULL
5583 #endif
5584 	    )
5585     {
5586 	ff_free_stack_element(new);
5587 	new = NULL;
5588     }
5589 
5590     return new;
5591 }
5592 
5593 /*
5594  * Push a dir on the directory stack.
5595  */
5596     static void
5597 ff_push(search_ctx, stack_ptr)
5598     ff_search_ctx_T *search_ctx;
5599     ff_stack_T	    *stack_ptr;
5600 {
5601     /* check for NULL pointer, not to return an error to the user, but
5602      * to prevent a crash */
5603     if (stack_ptr != NULL)
5604     {
5605 	stack_ptr->ffs_prev = search_ctx->ffsc_stack_ptr;
5606 	search_ctx->ffsc_stack_ptr = stack_ptr;
5607     }
5608 }
5609 
5610 /*
5611  * Pop a dir from the directory stack.
5612  * Returns NULL if stack is empty.
5613  */
5614     static ff_stack_T *
5615 ff_pop(search_ctx)
5616     ff_search_ctx_T *search_ctx;
5617 {
5618     ff_stack_T  *sptr;
5619 
5620     sptr = search_ctx->ffsc_stack_ptr;
5621     if (search_ctx->ffsc_stack_ptr != NULL)
5622 	search_ctx->ffsc_stack_ptr = search_ctx->ffsc_stack_ptr->ffs_prev;
5623 
5624     return sptr;
5625 }
5626 
5627 /*
5628  * free the given stack element
5629  */
5630     static void
5631 ff_free_stack_element(stack_ptr)
5632     ff_stack_T  *stack_ptr;
5633 {
5634     /* vim_free handles possible NULL pointers */
5635     vim_free(stack_ptr->ffs_fix_path);
5636 #ifdef FEAT_PATH_EXTRA
5637     vim_free(stack_ptr->ffs_wc_path);
5638 #endif
5639 
5640     if (stack_ptr->ffs_filearray != NULL)
5641 	FreeWild(stack_ptr->ffs_filearray_size, stack_ptr->ffs_filearray);
5642 
5643     vim_free(stack_ptr);
5644 }
5645 
5646 /*
5647  * Clear the search context, but NOT the visited list.
5648  */
5649     static void
5650 ff_clear(search_ctx)
5651     ff_search_ctx_T *search_ctx;
5652 {
5653     ff_stack_T   *sptr;
5654 
5655     /* clear up stack */
5656     while ((sptr = ff_pop(search_ctx)) != NULL)
5657 	ff_free_stack_element(sptr);
5658 
5659     vim_free(search_ctx->ffsc_file_to_search);
5660     vim_free(search_ctx->ffsc_start_dir);
5661     vim_free(search_ctx->ffsc_fix_path);
5662 #ifdef FEAT_PATH_EXTRA
5663     vim_free(search_ctx->ffsc_wc_path);
5664 #endif
5665 
5666 #ifdef FEAT_PATH_EXTRA
5667     if (search_ctx->ffsc_stopdirs_v != NULL)
5668     {
5669 	int  i = 0;
5670 
5671 	while (search_ctx->ffsc_stopdirs_v[i] != NULL)
5672 	{
5673 	    vim_free(search_ctx->ffsc_stopdirs_v[i]);
5674 	    i++;
5675 	}
5676 	vim_free(search_ctx->ffsc_stopdirs_v);
5677     }
5678     search_ctx->ffsc_stopdirs_v = NULL;
5679 #endif
5680 
5681     /* reset everything */
5682     search_ctx->ffsc_file_to_search = NULL;
5683     search_ctx->ffsc_start_dir = NULL;
5684     search_ctx->ffsc_fix_path = NULL;
5685 #ifdef FEAT_PATH_EXTRA
5686     search_ctx->ffsc_wc_path = NULL;
5687     search_ctx->ffsc_level = 0;
5688 #endif
5689 }
5690 
5691 #ifdef FEAT_PATH_EXTRA
5692 /*
5693  * check if the given path is in the stopdirs
5694  * returns TRUE if yes else FALSE
5695  */
5696     static int
5697 ff_path_in_stoplist(path, path_len, stopdirs_v)
5698     char_u	*path;
5699     int		path_len;
5700     char_u	**stopdirs_v;
5701 {
5702     int		i = 0;
5703 
5704     /* eat up trailing path separators, except the first */
5705     while (path_len > 1 && vim_ispathsep(path[path_len - 1]))
5706 	path_len--;
5707 
5708     /* if no path consider it as match */
5709     if (path_len == 0)
5710 	return TRUE;
5711 
5712     for (i = 0; stopdirs_v[i] != NULL; i++)
5713     {
5714 	if ((int)STRLEN(stopdirs_v[i]) > path_len)
5715 	{
5716 	    /* match for parent directory. So '/home' also matches
5717 	     * '/home/rks'. Check for PATHSEP in stopdirs_v[i], else
5718 	     * '/home/r' would also match '/home/rks'
5719 	     */
5720 	    if (fnamencmp(stopdirs_v[i], path, path_len) == 0
5721 		    && vim_ispathsep(stopdirs_v[i][path_len]))
5722 		return TRUE;
5723 	}
5724 	else
5725 	{
5726 	    if (fnamecmp(stopdirs_v[i], path) == 0)
5727 		return TRUE;
5728 	}
5729     }
5730     return FALSE;
5731 }
5732 #endif
5733 
5734 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
5735 /*
5736  * Find the file name "ptr[len]" in the path.  Also finds directory names.
5737  *
5738  * On the first call set the parameter 'first' to TRUE to initialize
5739  * the search.  For repeating calls to FALSE.
5740  *
5741  * Repeating calls will return other files called 'ptr[len]' from the path.
5742  *
5743  * Only on the first call 'ptr' and 'len' are used.  For repeating calls they
5744  * don't need valid values.
5745  *
5746  * If nothing found on the first call the option FNAME_MESS will issue the
5747  * message:
5748  *	    'Can't find file "<file>" in path'
5749  * On repeating calls:
5750  *	    'No more file "<file>" found in path'
5751  *
5752  * options:
5753  * FNAME_MESS	    give error message when not found
5754  *
5755  * Uses NameBuff[]!
5756  *
5757  * Returns an allocated string for the file name.  NULL for error.
5758  *
5759  */
5760     char_u *
5761 find_file_in_path(ptr, len, options, first, rel_fname)
5762     char_u	*ptr;		/* file name */
5763     int		len;		/* length of file name */
5764     int		options;
5765     int		first;		/* use count'th matching file name */
5766     char_u	*rel_fname;	/* file name searching relative to */
5767 {
5768     return find_file_in_path_option(ptr, len, options, first,
5769 	    *curbuf->b_p_path == NUL ? p_path : curbuf->b_p_path,
5770 	    FINDFILE_BOTH, rel_fname, curbuf->b_p_sua);
5771 }
5772 
5773 static char_u	*ff_file_to_find = NULL;
5774 static void	*fdip_search_ctx = NULL;
5775 
5776 #if defined(EXITFREE)
5777     static void
5778 free_findfile()
5779 {
5780     vim_free(ff_file_to_find);
5781     vim_findfile_cleanup(fdip_search_ctx);
5782 }
5783 #endif
5784 
5785 /*
5786  * Find the directory name "ptr[len]" in the path.
5787  *
5788  * options:
5789  * FNAME_MESS	    give error message when not found
5790  *
5791  * Uses NameBuff[]!
5792  *
5793  * Returns an allocated string for the file name.  NULL for error.
5794  */
5795     char_u *
5796 find_directory_in_path(ptr, len, options, rel_fname)
5797     char_u	*ptr;		/* file name */
5798     int		len;		/* length of file name */
5799     int		options;
5800     char_u	*rel_fname;	/* file name searching relative to */
5801 {
5802     return find_file_in_path_option(ptr, len, options, TRUE, p_cdpath,
5803 				       FINDFILE_DIR, rel_fname, (char_u *)"");
5804 }
5805 
5806     char_u *
5807 find_file_in_path_option(ptr, len, options, first, path_option, find_what, rel_fname, suffixes)
5808     char_u	*ptr;		/* file name */
5809     int		len;		/* length of file name */
5810     int		options;
5811     int		first;		/* use count'th matching file name */
5812     char_u	*path_option;	/* p_path or p_cdpath */
5813     int		find_what;	/* FINDFILE_FILE, _DIR or _BOTH */
5814     char_u	*rel_fname;	/* file name we are looking relative to. */
5815     char_u	*suffixes;	/* list of suffixes, 'suffixesadd' option */
5816 {
5817     static char_u	*dir;
5818     static int		did_findfile_init = FALSE;
5819     char_u		save_char;
5820     char_u		*file_name = NULL;
5821     char_u		*buf = NULL;
5822     int			rel_to_curdir;
5823 #ifdef AMIGA
5824     struct Process	*proc = (struct Process *)FindTask(0L);
5825     APTR		save_winptr = proc->pr_WindowPtr;
5826 
5827     /* Avoid a requester here for a volume that doesn't exist. */
5828     proc->pr_WindowPtr = (APTR)-1L;
5829 #endif
5830 
5831     if (first == TRUE)
5832     {
5833 	/* copy file name into NameBuff, expanding environment variables */
5834 	save_char = ptr[len];
5835 	ptr[len] = NUL;
5836 	expand_env(ptr, NameBuff, MAXPATHL);
5837 	ptr[len] = save_char;
5838 
5839 	vim_free(ff_file_to_find);
5840 	ff_file_to_find = vim_strsave(NameBuff);
5841 	if (ff_file_to_find == NULL)	/* out of memory */
5842 	{
5843 	    file_name = NULL;
5844 	    goto theend;
5845 	}
5846     }
5847 
5848     rel_to_curdir = (ff_file_to_find[0] == '.'
5849 		    && (ff_file_to_find[1] == NUL
5850 			|| vim_ispathsep(ff_file_to_find[1])
5851 			|| (ff_file_to_find[1] == '.'
5852 			    && (ff_file_to_find[2] == NUL
5853 				|| vim_ispathsep(ff_file_to_find[2])))));
5854     if (vim_isAbsName(ff_file_to_find)
5855 	    /* "..", "../path", "." and "./path": don't use the path_option */
5856 	    || rel_to_curdir
5857 #if defined(MSWIN) || defined(MSDOS) || defined(OS2)
5858 	    /* handle "\tmp" as absolute path */
5859 	    || vim_ispathsep(ff_file_to_find[0])
5860 	    /* handle "c:name" as absolute path */
5861 	    || (ff_file_to_find[0] != NUL && ff_file_to_find[1] == ':')
5862 #endif
5863 #ifdef AMIGA
5864 	    /* handle ":tmp" as absolute path */
5865 	    || ff_file_to_find[0] == ':'
5866 #endif
5867        )
5868     {
5869 	/*
5870 	 * Absolute path, no need to use "path_option".
5871 	 * If this is not a first call, return NULL.  We already returned a
5872 	 * filename on the first call.
5873 	 */
5874 	if (first == TRUE)
5875 	{
5876 	    int		l;
5877 	    int		run;
5878 
5879 	    if (path_with_url(ff_file_to_find))
5880 	    {
5881 		file_name = vim_strsave(ff_file_to_find);
5882 		goto theend;
5883 	    }
5884 
5885 	    /* When FNAME_REL flag given first use the directory of the file.
5886 	     * Otherwise or when this fails use the current directory. */
5887 	    for (run = 1; run <= 2; ++run)
5888 	    {
5889 		l = (int)STRLEN(ff_file_to_find);
5890 		if (run == 1
5891 			&& rel_to_curdir
5892 			&& (options & FNAME_REL)
5893 			&& rel_fname != NULL
5894 			&& STRLEN(rel_fname) + l < MAXPATHL)
5895 		{
5896 		    STRCPY(NameBuff, rel_fname);
5897 		    STRCPY(gettail(NameBuff), ff_file_to_find);
5898 		    l = (int)STRLEN(NameBuff);
5899 		}
5900 		else
5901 		{
5902 		    STRCPY(NameBuff, ff_file_to_find);
5903 		    run = 2;
5904 		}
5905 
5906 		/* When the file doesn't exist, try adding parts of
5907 		 * 'suffixesadd'. */
5908 		buf = suffixes;
5909 		for (;;)
5910 		{
5911 		    if (
5912 #ifdef DJGPP
5913 			    /* "C:" by itself will fail for mch_getperm(),
5914 			     * assume it's always valid. */
5915 			    (find_what != FINDFILE_FILE && NameBuff[0] != NUL
5916 				  && NameBuff[1] == ':'
5917 				  && NameBuff[2] == NUL) ||
5918 #endif
5919 			    (mch_getperm(NameBuff) >= 0
5920 			     && (find_what == FINDFILE_BOTH
5921 				 || ((find_what == FINDFILE_DIR)
5922 						    == mch_isdir(NameBuff)))))
5923 		    {
5924 			file_name = vim_strsave(NameBuff);
5925 			goto theend;
5926 		    }
5927 		    if (*buf == NUL)
5928 			break;
5929 		    copy_option_part(&buf, NameBuff + l, MAXPATHL - l, ",");
5930 		}
5931 	    }
5932 	}
5933     }
5934     else
5935     {
5936 	/*
5937 	 * Loop over all paths in the 'path' or 'cdpath' option.
5938 	 * When "first" is set, first setup to the start of the option.
5939 	 * Otherwise continue to find the next match.
5940 	 */
5941 	if (first == TRUE)
5942 	{
5943 	    /* vim_findfile_free_visited can handle a possible NULL pointer */
5944 	    vim_findfile_free_visited(fdip_search_ctx);
5945 	    dir = path_option;
5946 	    did_findfile_init = FALSE;
5947 	}
5948 
5949 	for (;;)
5950 	{
5951 	    if (did_findfile_init)
5952 	    {
5953 		file_name = vim_findfile(fdip_search_ctx);
5954 		if (file_name != NULL)
5955 		    break;
5956 
5957 		did_findfile_init = FALSE;
5958 	    }
5959 	    else
5960 	    {
5961 		char_u  *r_ptr;
5962 
5963 		if (dir == NULL || *dir == NUL)
5964 		{
5965 		    /* We searched all paths of the option, now we can
5966 		     * free the search context. */
5967 		    vim_findfile_cleanup(fdip_search_ctx);
5968 		    fdip_search_ctx = NULL;
5969 		    break;
5970 		}
5971 
5972 		if ((buf = alloc((int)(MAXPATHL))) == NULL)
5973 		    break;
5974 
5975 		/* copy next path */
5976 		buf[0] = 0;
5977 		copy_option_part(&dir, buf, MAXPATHL, " ,");
5978 
5979 #ifdef FEAT_PATH_EXTRA
5980 		/* get the stopdir string */
5981 		r_ptr = vim_findfile_stopdir(buf);
5982 #else
5983 		r_ptr = NULL;
5984 #endif
5985 		fdip_search_ctx = vim_findfile_init(buf, ff_file_to_find,
5986 					    r_ptr, 100, FALSE, find_what,
5987 					   fdip_search_ctx, FALSE, rel_fname);
5988 		if (fdip_search_ctx != NULL)
5989 		    did_findfile_init = TRUE;
5990 		vim_free(buf);
5991 	    }
5992 	}
5993     }
5994     if (file_name == NULL && (options & FNAME_MESS))
5995     {
5996 	if (first == TRUE)
5997 	{
5998 	    if (find_what == FINDFILE_DIR)
5999 		EMSG2(_("E344: Can't find directory \"%s\" in cdpath"),
6000 			ff_file_to_find);
6001 	    else
6002 		EMSG2(_("E345: Can't find file \"%s\" in path"),
6003 			ff_file_to_find);
6004 	}
6005 	else
6006 	{
6007 	    if (find_what == FINDFILE_DIR)
6008 		EMSG2(_("E346: No more directory \"%s\" found in cdpath"),
6009 			ff_file_to_find);
6010 	    else
6011 		EMSG2(_("E347: No more file \"%s\" found in path"),
6012 			ff_file_to_find);
6013 	}
6014     }
6015 
6016 theend:
6017 #ifdef AMIGA
6018     proc->pr_WindowPtr = save_winptr;
6019 #endif
6020     return file_name;
6021 }
6022 
6023 #endif /* FEAT_SEARCHPATH */
6024 
6025 /*
6026  * Change directory to "new_dir".  If FEAT_SEARCHPATH is defined, search
6027  * 'cdpath' for relative directory names, otherwise just mch_chdir().
6028  */
6029     int
6030 vim_chdir(new_dir)
6031     char_u	*new_dir;
6032 {
6033 #ifndef FEAT_SEARCHPATH
6034     return mch_chdir((char *)new_dir);
6035 #else
6036     char_u	*dir_name;
6037     int		r;
6038 
6039     dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
6040 						FNAME_MESS, curbuf->b_ffname);
6041     if (dir_name == NULL)
6042 	return -1;
6043     r = mch_chdir((char *)dir_name);
6044     vim_free(dir_name);
6045     return r;
6046 #endif
6047 }
6048 
6049 /*
6050  * Get user name from machine-specific function.
6051  * Returns the user name in "buf[len]".
6052  * Some systems are quite slow in obtaining the user name (Windows NT), thus
6053  * cache the result.
6054  * Returns OK or FAIL.
6055  */
6056     int
6057 get_user_name(buf, len)
6058     char_u	*buf;
6059     int		len;
6060 {
6061     if (username == NULL)
6062     {
6063 	if (mch_get_user_name(buf, len) == FAIL)
6064 	    return FAIL;
6065 	username = vim_strsave(buf);
6066     }
6067     else
6068 	vim_strncpy(buf, username, len - 1);
6069     return OK;
6070 }
6071 
6072 #ifndef HAVE_QSORT
6073 /*
6074  * Our own qsort(), for systems that don't have it.
6075  * It's simple and slow.  From the K&R C book.
6076  */
6077     void
6078 qsort(base, elm_count, elm_size, cmp)
6079     void	*base;
6080     size_t	elm_count;
6081     size_t	elm_size;
6082     int (*cmp) __ARGS((const void *, const void *));
6083 {
6084     char_u	*buf;
6085     char_u	*p1;
6086     char_u	*p2;
6087     int		i, j;
6088     int		gap;
6089 
6090     buf = alloc((unsigned)elm_size);
6091     if (buf == NULL)
6092 	return;
6093 
6094     for (gap = elm_count / 2; gap > 0; gap /= 2)
6095 	for (i = gap; i < elm_count; ++i)
6096 	    for (j = i - gap; j >= 0; j -= gap)
6097 	    {
6098 		/* Compare the elements. */
6099 		p1 = (char_u *)base + j * elm_size;
6100 		p2 = (char_u *)base + (j + gap) * elm_size;
6101 		if ((*cmp)((void *)p1, (void *)p2) <= 0)
6102 		    break;
6103 		/* Exchange the elements. */
6104 		mch_memmove(buf, p1, elm_size);
6105 		mch_memmove(p1, p2, elm_size);
6106 		mch_memmove(p2, buf, elm_size);
6107 	    }
6108 
6109     vim_free(buf);
6110 }
6111 #endif
6112 
6113 /*
6114  * Sort an array of strings.
6115  */
6116 static int
6117 #ifdef __BORLANDC__
6118 _RTLENTRYF
6119 #endif
6120 sort_compare __ARGS((const void *s1, const void *s2));
6121 
6122     static int
6123 #ifdef __BORLANDC__
6124 _RTLENTRYF
6125 #endif
6126 sort_compare(s1, s2)
6127     const void	*s1;
6128     const void	*s2;
6129 {
6130     return STRCMP(*(char **)s1, *(char **)s2);
6131 }
6132 
6133     void
6134 sort_strings(files, count)
6135     char_u	**files;
6136     int		count;
6137 {
6138     qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
6139 }
6140 
6141 #if !defined(NO_EXPANDPATH) || defined(PROTO)
6142 /*
6143  * Compare path "p[]" to "q[]".
6144  * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
6145  * Return value like strcmp(p, q), but consider path separators.
6146  */
6147     int
6148 pathcmp(p, q, maxlen)
6149     const char *p, *q;
6150     int maxlen;
6151 {
6152     int		i;
6153     int		c1, c2;
6154     const char	*s = NULL;
6155 
6156     for (i = 0; maxlen < 0 || i < maxlen; i += MB_PTR2LEN((char_u *)p + i))
6157     {
6158 	c1 = PTR2CHAR((char_u *)p + i);
6159 	c2 = PTR2CHAR((char_u *)q + i);
6160 
6161 	/* End of "p": check if "q" also ends or just has a slash. */
6162 	if (c1 == NUL)
6163 	{
6164 	    if (c2 == NUL)  /* full match */
6165 		return 0;
6166 	    s = q;
6167 	    break;
6168 	}
6169 
6170 	/* End of "q": check if "p" just has a slash. */
6171 	if (c2 == NUL)
6172 	{
6173 	    s = p;
6174 	    break;
6175 	}
6176 
6177 	if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
6178 #ifdef BACKSLASH_IN_FILENAME
6179 		/* consider '/' and '\\' to be equal */
6180 		&& !((c1 == '/' && c2 == '\\')
6181 		    || (c1 == '\\' && c2 == '/'))
6182 #endif
6183 		)
6184 	{
6185 	    if (vim_ispathsep(c1))
6186 		return -1;
6187 	    if (vim_ispathsep(c2))
6188 		return 1;
6189 	    return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
6190 		    : c1 - c2;  /* no match */
6191 	}
6192     }
6193     if (s == NULL)	/* "i" ran into "maxlen" */
6194 	return 0;
6195 
6196     c1 = PTR2CHAR((char_u *)s + i);
6197     c2 = PTR2CHAR((char_u *)s + i + MB_PTR2LEN((char_u *)s + i));
6198     /* ignore a trailing slash, but not "//" or ":/" */
6199     if (c2 == NUL
6200 	    && i > 0
6201 	    && !after_pathsep((char_u *)s, (char_u *)s + i)
6202 #ifdef BACKSLASH_IN_FILENAME
6203 	    && (c1 == '/' || c1 == '\\')
6204 #else
6205 	    && c1 == '/'
6206 #endif
6207        )
6208 	return 0;   /* match with trailing slash */
6209     if (s == q)
6210 	return -1;	    /* no match */
6211     return 1;
6212 }
6213 #endif
6214 
6215 /*
6216  * The putenv() implementation below comes from the "screen" program.
6217  * Included with permission from Juergen Weigert.
6218  * See pty.c for the copyright notice.
6219  */
6220 
6221 /*
6222  *  putenv  --	put value into environment
6223  *
6224  *  Usage:  i = putenv (string)
6225  *    int i;
6226  *    char  *string;
6227  *
6228  *  where string is of the form <name>=<value>.
6229  *  Putenv returns 0 normally, -1 on error (not enough core for malloc).
6230  *
6231  *  Putenv may need to add a new name into the environment, or to
6232  *  associate a value longer than the current value with a particular
6233  *  name.  So, to make life simpler, putenv() copies your entire
6234  *  environment into the heap (i.e. malloc()) from the stack
6235  *  (i.e. where it resides when your process is initiated) the first
6236  *  time you call it.
6237  *
6238  *  (history removed, not very interesting.  See the "screen" sources.)
6239  */
6240 
6241 #if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
6242 
6243 #define EXTRASIZE 5		/* increment to add to env. size */
6244 
6245 static int  envsize = -1;	/* current size of environment */
6246 #ifndef MACOS_CLASSIC
6247 extern
6248 #endif
6249        char **environ;		/* the global which is your env. */
6250 
6251 static int  findenv __ARGS((char *name)); /* look for a name in the env. */
6252 static int  newenv __ARGS((void));	/* copy env. from stack to heap */
6253 static int  moreenv __ARGS((void));	/* incr. size of env. */
6254 
6255     int
6256 putenv(string)
6257     const char *string;
6258 {
6259     int	    i;
6260     char    *p;
6261 
6262     if (envsize < 0)
6263     {				/* first time putenv called */
6264 	if (newenv() < 0)	/* copy env. to heap */
6265 	    return -1;
6266     }
6267 
6268     i = findenv((char *)string); /* look for name in environment */
6269 
6270     if (i < 0)
6271     {				/* name must be added */
6272 	for (i = 0; environ[i]; i++);
6273 	if (i >= (envsize - 1))
6274 	{			/* need new slot */
6275 	    if (moreenv() < 0)
6276 		return -1;
6277 	}
6278 	p = (char *)alloc((unsigned)(strlen(string) + 1));
6279 	if (p == NULL)		/* not enough core */
6280 	    return -1;
6281 	environ[i + 1] = 0;	/* new end of env. */
6282     }
6283     else
6284     {				/* name already in env. */
6285 	p = vim_realloc(environ[i], strlen(string) + 1);
6286 	if (p == NULL)
6287 	    return -1;
6288     }
6289     sprintf(p, "%s", string);	/* copy into env. */
6290     environ[i] = p;
6291 
6292     return 0;
6293 }
6294 
6295     static int
6296 findenv(name)
6297     char *name;
6298 {
6299     char    *namechar, *envchar;
6300     int	    i, found;
6301 
6302     found = 0;
6303     for (i = 0; environ[i] && !found; i++)
6304     {
6305 	envchar = environ[i];
6306 	namechar = name;
6307 	while (*namechar && *namechar != '=' && (*namechar == *envchar))
6308 	{
6309 	    namechar++;
6310 	    envchar++;
6311 	}
6312 	found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
6313     }
6314     return found ? i - 1 : -1;
6315 }
6316 
6317     static int
6318 newenv()
6319 {
6320     char    **env, *elem;
6321     int	    i, esize;
6322 
6323 #ifdef MACOS
6324     /* for Mac a new, empty environment is created */
6325     i = 0;
6326 #else
6327     for (i = 0; environ[i]; i++)
6328 	;
6329 #endif
6330     esize = i + EXTRASIZE + 1;
6331     env = (char **)alloc((unsigned)(esize * sizeof (elem)));
6332     if (env == NULL)
6333 	return -1;
6334 
6335 #ifndef MACOS
6336     for (i = 0; environ[i]; i++)
6337     {
6338 	elem = (char *)alloc((unsigned)(strlen(environ[i]) + 1));
6339 	if (elem == NULL)
6340 	    return -1;
6341 	env[i] = elem;
6342 	strcpy(elem, environ[i]);
6343     }
6344 #endif
6345 
6346     env[i] = 0;
6347     environ = env;
6348     envsize = esize;
6349     return 0;
6350 }
6351 
6352     static int
6353 moreenv()
6354 {
6355     int	    esize;
6356     char    **env;
6357 
6358     esize = envsize + EXTRASIZE;
6359     env = (char **)vim_realloc((char *)environ, esize * sizeof (*env));
6360     if (env == 0)
6361 	return -1;
6362     environ = env;
6363     envsize = esize;
6364     return 0;
6365 }
6366 
6367 # ifdef USE_VIMPTY_GETENV
6368     char_u *
6369 vimpty_getenv(string)
6370     const char_u *string;
6371 {
6372     int i;
6373     char_u *p;
6374 
6375     if (envsize < 0)
6376 	return NULL;
6377 
6378     i = findenv((char *)string);
6379 
6380     if (i < 0)
6381 	return NULL;
6382 
6383     p = vim_strchr((char_u *)environ[i], '=');
6384     return (p + 1);
6385 }
6386 # endif
6387 
6388 #endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
6389 
6390 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
6391 /*
6392  * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
6393  * rights to write into.
6394  */
6395     int
6396 filewritable(fname)
6397     char_u	*fname;
6398 {
6399     int		retval = 0;
6400 #if defined(UNIX) || defined(VMS)
6401     int		perm = 0;
6402 #endif
6403 
6404 #if defined(UNIX) || defined(VMS)
6405     perm = mch_getperm(fname);
6406 #endif
6407 #ifndef MACOS_CLASSIC /* TODO: get either mch_writable or mch_access */
6408     if (
6409 # ifdef WIN3264
6410 	    mch_writable(fname) &&
6411 # else
6412 # if defined(UNIX) || defined(VMS)
6413 	    (perm & 0222) &&
6414 #  endif
6415 # endif
6416 	    mch_access((char *)fname, W_OK) == 0
6417        )
6418 #endif
6419     {
6420 	++retval;
6421 	if (mch_isdir(fname))
6422 	    ++retval;
6423     }
6424     return retval;
6425 }
6426 #endif
6427 
6428 /*
6429  * Print an error message with one or two "%s" and one or two string arguments.
6430  * This is not in message.c to avoid a warning for prototypes.
6431  */
6432     int
6433 emsg3(s, a1, a2)
6434     char_u *s, *a1, *a2;
6435 {
6436     if (emsg_not_now())
6437 	return TRUE;		/* no error messages at the moment */
6438 #ifdef HAVE_STDARG_H
6439     vim_snprintf((char *)IObuff, IOSIZE, (char *)s, a1, a2);
6440 #else
6441     vim_snprintf((char *)IObuff, IOSIZE, (char *)s, (long_u)a1, (long_u)a2);
6442 #endif
6443     return emsg(IObuff);
6444 }
6445 
6446 /*
6447  * Print an error message with one "%ld" and one long int argument.
6448  * This is not in message.c to avoid a warning for prototypes.
6449  */
6450     int
6451 emsgn(s, n)
6452     char_u	*s;
6453     long	n;
6454 {
6455     if (emsg_not_now())
6456 	return TRUE;		/* no error messages at the moment */
6457     vim_snprintf((char *)IObuff, IOSIZE, (char *)s, n);
6458     return emsg(IObuff);
6459 }
6460 
6461 #if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
6462 /*
6463  * Read 2 bytes from "fd" and turn them into an int, MSB first.
6464  */
6465     int
6466 get2c(fd)
6467     FILE	*fd;
6468 {
6469     int		n;
6470 
6471     n = getc(fd);
6472     n = (n << 8) + getc(fd);
6473     return n;
6474 }
6475 
6476 /*
6477  * Read 3 bytes from "fd" and turn them into an int, MSB first.
6478  */
6479     int
6480 get3c(fd)
6481     FILE	*fd;
6482 {
6483     int		n;
6484 
6485     n = getc(fd);
6486     n = (n << 8) + getc(fd);
6487     n = (n << 8) + getc(fd);
6488     return n;
6489 }
6490 
6491 /*
6492  * Read 4 bytes from "fd" and turn them into an int, MSB first.
6493  */
6494     int
6495 get4c(fd)
6496     FILE	*fd;
6497 {
6498     /* Use unsigned rather than int otherwise result is undefined
6499      * when left-shift sets the MSB. */
6500     unsigned	n;
6501 
6502     n = (unsigned)getc(fd);
6503     n = (n << 8) + (unsigned)getc(fd);
6504     n = (n << 8) + (unsigned)getc(fd);
6505     n = (n << 8) + (unsigned)getc(fd);
6506     return (int)n;
6507 }
6508 
6509 /*
6510  * Read 8 bytes from "fd" and turn them into a time_t, MSB first.
6511  */
6512     time_t
6513 get8ctime(fd)
6514     FILE	*fd;
6515 {
6516     time_t	n = 0;
6517     int		i;
6518 
6519     for (i = 0; i < 8; ++i)
6520 	n = (n << 8) + getc(fd);
6521     return n;
6522 }
6523 
6524 /*
6525  * Read a string of length "cnt" from "fd" into allocated memory.
6526  * Returns NULL when out of memory or unable to read that many bytes.
6527  */
6528     char_u *
6529 read_string(fd, cnt)
6530     FILE	*fd;
6531     int		cnt;
6532 {
6533     char_u	*str;
6534     int		i;
6535     int		c;
6536 
6537     /* allocate memory */
6538     str = alloc((unsigned)cnt + 1);
6539     if (str != NULL)
6540     {
6541 	/* Read the string.  Quit when running into the EOF. */
6542 	for (i = 0; i < cnt; ++i)
6543 	{
6544 	    c = getc(fd);
6545 	    if (c == EOF)
6546 	    {
6547 		vim_free(str);
6548 		return NULL;
6549 	    }
6550 	    str[i] = c;
6551 	}
6552 	str[i] = NUL;
6553     }
6554     return str;
6555 }
6556 
6557 /*
6558  * Write a number to file "fd", MSB first, in "len" bytes.
6559  */
6560     int
6561 put_bytes(fd, nr, len)
6562     FILE    *fd;
6563     long_u  nr;
6564     int	    len;
6565 {
6566     int	    i;
6567 
6568     for (i = len - 1; i >= 0; --i)
6569 	if (putc((int)(nr >> (i * 8)), fd) == EOF)
6570 	    return FAIL;
6571     return OK;
6572 }
6573 
6574 #ifdef _MSC_VER
6575 # if (_MSC_VER <= 1200)
6576 /* This line is required for VC6 without the service pack.  Also see the
6577  * matching #pragma below. */
6578  #  pragma optimize("", off)
6579 # endif
6580 #endif
6581 
6582 /*
6583  * Write time_t to file "fd" in 8 bytes.
6584  */
6585     void
6586 put_time(fd, the_time)
6587     FILE	*fd;
6588     time_t	the_time;
6589 {
6590     int		c;
6591     int		i;
6592     time_t	wtime = the_time;
6593 
6594     /* time_t can be up to 8 bytes in size, more than long_u, thus we
6595      * can't use put_bytes() here.
6596      * Another problem is that ">>" may do an arithmetic shift that keeps the
6597      * sign.  This happens for large values of wtime.  A cast to long_u may
6598      * truncate if time_t is 8 bytes.  So only use a cast when it is 4 bytes,
6599      * it's safe to assume that long_u is 4 bytes or more and when using 8
6600      * bytes the top bit won't be set. */
6601     for (i = 7; i >= 0; --i)
6602     {
6603 	if (i + 1 > (int)sizeof(time_t))
6604 	    /* ">>" doesn't work well when shifting more bits than avail */
6605 	    putc(0, fd);
6606 	else
6607 	{
6608 #if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
6609 	    c = (int)(wtime >> (i * 8));
6610 #else
6611 	    c = (int)((long_u)wtime >> (i * 8));
6612 #endif
6613 	    putc(c, fd);
6614 	}
6615     }
6616 }
6617 
6618 #ifdef _MSC_VER
6619 # if (_MSC_VER <= 1200)
6620  #  pragma optimize("", on)
6621 # endif
6622 #endif
6623 
6624 #endif
6625 
6626 #if (defined(FEAT_MBYTE) && defined(FEAT_QUICKFIX)) \
6627 	|| defined(FEAT_SPELL) || defined(PROTO)
6628 /*
6629  * Return TRUE if string "s" contains a non-ASCII character (128 or higher).
6630  * When "s" is NULL FALSE is returned.
6631  */
6632     int
6633 has_non_ascii(s)
6634     char_u	*s;
6635 {
6636     char_u	*p;
6637 
6638     if (s != NULL)
6639 	for (p = s; *p != NUL; ++p)
6640 	    if (*p >= 128)
6641 		return TRUE;
6642     return FALSE;
6643 }
6644 #endif
6645