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