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