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