xref: /vim-8.2.3635/src/misc2.c (revision 06fe74ae)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * misc2.c: Various functions.
12  */
13 #include "vim.h"
14 
15 static char_u	*username = NULL; /* cached result of mch_get_user_name() */
16 
17 static int coladvance2(pos_T *pos, int addspaces, int finetune, colnr_T wcol);
18 
19 /*
20  * Return TRUE if in the current mode we need to use virtual.
21  */
22     int
23 virtual_active(void)
24 {
25     /* While an operator is being executed we return "virtual_op", because
26      * VIsual_active has already been reset, thus we can't check for "block"
27      * being used. */
28     if (virtual_op != MAYBE)
29 	return virtual_op;
30     return (ve_flags == VE_ALL
31 	    || ((ve_flags & VE_BLOCK) && VIsual_active && VIsual_mode == Ctrl_V)
32 	    || ((ve_flags & VE_INSERT) && (State & INSERT)));
33 }
34 
35 /*
36  * Get the screen position of the cursor.
37  */
38     int
39 getviscol(void)
40 {
41     colnr_T	x;
42 
43     getvvcol(curwin, &curwin->w_cursor, &x, NULL, NULL);
44     return (int)x;
45 }
46 
47 /*
48  * Go to column "wcol", and add/insert white space as necessary to get the
49  * cursor in that column.
50  * The caller must have saved the cursor line for undo!
51  */
52     int
53 coladvance_force(colnr_T wcol)
54 {
55     int rc = coladvance2(&curwin->w_cursor, TRUE, FALSE, wcol);
56 
57     if (wcol == MAXCOL)
58 	curwin->w_valid &= ~VALID_VIRTCOL;
59     else
60     {
61 	/* Virtcol is valid */
62 	curwin->w_valid |= VALID_VIRTCOL;
63 	curwin->w_virtcol = wcol;
64     }
65     return rc;
66 }
67 
68 /*
69  * Get the screen position of character col with a coladd in the cursor line.
70  */
71     int
72 getviscol2(colnr_T col, colnr_T coladd UNUSED)
73 {
74     colnr_T	x;
75     pos_T	pos;
76 
77     pos.lnum = curwin->w_cursor.lnum;
78     pos.col = col;
79     pos.coladd = coladd;
80     getvvcol(curwin, &pos, &x, NULL, NULL);
81     return (int)x;
82 }
83 
84 /*
85  * Try to advance the Cursor to the specified screen column.
86  * If virtual editing: fine tune the cursor position.
87  * Note that all virtual positions off the end of a line should share
88  * a curwin->w_cursor.col value (n.b. this is equal to STRLEN(line)),
89  * beginning at coladd 0.
90  *
91  * return OK if desired column is reached, FAIL if not
92  */
93     int
94 coladvance(colnr_T wcol)
95 {
96     int rc = getvpos(&curwin->w_cursor, wcol);
97 
98     if (wcol == MAXCOL || rc == FAIL)
99 	curwin->w_valid &= ~VALID_VIRTCOL;
100     else if (*ml_get_cursor() != TAB)
101     {
102 	/* Virtcol is valid when not on a TAB */
103 	curwin->w_valid |= VALID_VIRTCOL;
104 	curwin->w_virtcol = wcol;
105     }
106     return rc;
107 }
108 
109 /*
110  * Return in "pos" the position of the cursor advanced to screen column "wcol".
111  * return OK if desired column is reached, FAIL if not
112  */
113     int
114 getvpos(pos_T *pos, colnr_T wcol)
115 {
116     return coladvance2(pos, FALSE, virtual_active(), wcol);
117 }
118 
119     static int
120 coladvance2(
121     pos_T	*pos,
122     int		addspaces,	/* change the text to achieve our goal? */
123     int		finetune,	/* change char offset for the exact column */
124     colnr_T	wcol)		/* column to move to */
125 {
126     int		idx;
127     char_u	*ptr;
128     char_u	*line;
129     colnr_T	col = 0;
130     int		csize = 0;
131     int		one_more;
132 #ifdef FEAT_LINEBREAK
133     int		head = 0;
134 #endif
135 
136     one_more = (State & INSERT)
137 		    || restart_edit != NUL
138 		    || (VIsual_active && *p_sel != 'o')
139 		    || ((ve_flags & VE_ONEMORE) && wcol < MAXCOL) ;
140     line = ml_get_buf(curbuf, pos->lnum, FALSE);
141 
142     if (wcol >= MAXCOL)
143     {
144 	    idx = (int)STRLEN(line) - 1 + one_more;
145 	    col = wcol;
146 
147 	    if ((addspaces || finetune) && !VIsual_active)
148 	    {
149 		curwin->w_curswant = linetabsize(line) + one_more;
150 		if (curwin->w_curswant > 0)
151 		    --curwin->w_curswant;
152 	    }
153     }
154     else
155     {
156 	int width = curwin->w_width - win_col_off(curwin);
157 
158 	if (finetune
159 		&& curwin->w_p_wrap
160 		&& curwin->w_width != 0
161 		&& wcol >= (colnr_T)width)
162 	{
163 	    csize = linetabsize(line);
164 	    if (csize > 0)
165 		csize--;
166 
167 	    if (wcol / width > (colnr_T)csize / width
168 		    && ((State & INSERT) == 0 || (int)wcol > csize + 1))
169 	    {
170 		/* In case of line wrapping don't move the cursor beyond the
171 		 * right screen edge.  In Insert mode allow going just beyond
172 		 * the last character (like what happens when typing and
173 		 * reaching the right window edge). */
174 		wcol = (csize / width + 1) * width - 1;
175 	    }
176 	}
177 
178 	ptr = line;
179 	while (col <= wcol && *ptr != NUL)
180 	{
181 	    /* Count a tab for what it's worth (if list mode not on) */
182 #ifdef FEAT_LINEBREAK
183 	    csize = win_lbr_chartabsize(curwin, line, ptr, col, &head);
184 	    MB_PTR_ADV(ptr);
185 #else
186 	    csize = lbr_chartabsize_adv(line, &ptr, col);
187 #endif
188 	    col += csize;
189 	}
190 	idx = (int)(ptr - line);
191 	/*
192 	 * Handle all the special cases.  The virtual_active() check
193 	 * is needed to ensure that a virtual position off the end of
194 	 * a line has the correct indexing.  The one_more comparison
195 	 * replaces an explicit add of one_more later on.
196 	 */
197 	if (col > wcol || (!virtual_active() && one_more == 0))
198 	{
199 	    idx -= 1;
200 # ifdef FEAT_LINEBREAK
201 	    /* Don't count the chars from 'showbreak'. */
202 	    csize -= head;
203 # endif
204 	    col -= csize;
205 	}
206 
207 	if (virtual_active()
208 		&& addspaces
209 		&& ((col != wcol && col != wcol + 1) || csize > 1))
210 	{
211 	    /* 'virtualedit' is set: The difference between wcol and col is
212 	     * filled with spaces. */
213 
214 	    if (line[idx] == NUL)
215 	    {
216 		/* Append spaces */
217 		int	correct = wcol - col;
218 		char_u	*newline = alloc(idx + correct + 1);
219 		int	t;
220 
221 		if (newline == NULL)
222 		    return FAIL;
223 
224 		for (t = 0; t < idx; ++t)
225 		    newline[t] = line[t];
226 
227 		for (t = 0; t < correct; ++t)
228 		    newline[t + idx] = ' ';
229 
230 		newline[idx + correct] = NUL;
231 
232 		ml_replace(pos->lnum, newline, FALSE);
233 		changed_bytes(pos->lnum, (colnr_T)idx);
234 		idx += correct;
235 		col = wcol;
236 	    }
237 	    else
238 	    {
239 		/* Break a tab */
240 		int	linelen = (int)STRLEN(line);
241 		int	correct = wcol - col - csize + 1; /* negative!! */
242 		char_u	*newline;
243 		int	t, s = 0;
244 		int	v;
245 
246 		if (-correct > csize)
247 		    return FAIL;
248 
249 		newline = alloc(linelen + csize);
250 		if (newline == NULL)
251 		    return FAIL;
252 
253 		for (t = 0; t < linelen; t++)
254 		{
255 		    if (t != idx)
256 			newline[s++] = line[t];
257 		    else
258 			for (v = 0; v < csize; v++)
259 			    newline[s++] = ' ';
260 		}
261 
262 		newline[linelen + csize - 1] = NUL;
263 
264 		ml_replace(pos->lnum, newline, FALSE);
265 		changed_bytes(pos->lnum, idx);
266 		idx += (csize - 1 + correct);
267 		col += correct;
268 	    }
269 	}
270     }
271 
272     if (idx < 0)
273 	pos->col = 0;
274     else
275 	pos->col = idx;
276 
277     pos->coladd = 0;
278 
279     if (finetune)
280     {
281 	if (wcol == MAXCOL)
282 	{
283 	    /* The width of the last character is used to set coladd. */
284 	    if (!one_more)
285 	    {
286 		colnr_T	    scol, ecol;
287 
288 		getvcol(curwin, pos, &scol, NULL, &ecol);
289 		pos->coladd = ecol - scol;
290 	    }
291 	}
292 	else
293 	{
294 	    int b = (int)wcol - (int)col;
295 
296 	    /* The difference between wcol and col is used to set coladd. */
297 	    if (b > 0 && b < (MAXCOL - 2 * curwin->w_width))
298 		pos->coladd = b;
299 
300 	    col += b;
301 	}
302     }
303 
304     /* prevent from moving onto a trail byte */
305     if (has_mbyte)
306 	mb_adjustpos(curbuf, pos);
307 
308     if (col < wcol)
309 	return FAIL;
310     return OK;
311 }
312 
313 /*
314  * Increment the cursor position.  See inc() for return values.
315  */
316     int
317 inc_cursor(void)
318 {
319     return inc(&curwin->w_cursor);
320 }
321 
322 /*
323  * Increment the line pointer "lp" crossing line boundaries as necessary.
324  * Return 1 when going to the next line.
325  * Return 2 when moving forward onto a NUL at the end of the line).
326  * Return -1 when at the end of file.
327  * Return 0 otherwise.
328  */
329     int
330 inc(pos_T *lp)
331 {
332     char_u  *p;
333 
334     /* when searching position may be set to end of a line */
335     if (lp->col != MAXCOL)
336     {
337 	p = ml_get_pos(lp);
338 	if (*p != NUL)	/* still within line, move to next char (may be NUL) */
339 	{
340 	    if (has_mbyte)
341 	    {
342 		int l = (*mb_ptr2len)(p);
343 
344 		lp->col += l;
345 		return ((p[l] != NUL) ? 0 : 2);
346 	    }
347 	    lp->col++;
348 	    lp->coladd = 0;
349 	    return ((p[1] != NUL) ? 0 : 2);
350 	}
351     }
352     if (lp->lnum != curbuf->b_ml.ml_line_count)     /* there is a next line */
353     {
354 	lp->col = 0;
355 	lp->lnum++;
356 	lp->coladd = 0;
357 	return 1;
358     }
359     return -1;
360 }
361 
362 /*
363  * incl(lp): same as inc(), but skip the NUL at the end of non-empty lines
364  */
365     int
366 incl(pos_T *lp)
367 {
368     int	    r;
369 
370     if ((r = inc(lp)) >= 1 && lp->col)
371 	r = inc(lp);
372     return r;
373 }
374 
375 /*
376  * dec(p)
377  *
378  * Decrement the line pointer 'p' crossing line boundaries as necessary.
379  * Return 1 when crossing a line, -1 when at start of file, 0 otherwise.
380  */
381     int
382 dec_cursor(void)
383 {
384     return dec(&curwin->w_cursor);
385 }
386 
387     int
388 dec(pos_T *lp)
389 {
390     char_u	*p;
391 
392     lp->coladd = 0;
393     if (lp->col == MAXCOL)
394     {
395 	/* past end of line */
396 	p = ml_get(lp->lnum);
397 	lp->col = (colnr_T)STRLEN(p);
398 	if (has_mbyte)
399 	    lp->col -= (*mb_head_off)(p, p + lp->col);
400 	return 0;
401     }
402 
403     if (lp->col > 0)
404     {
405 	/* still within line */
406 	lp->col--;
407 	if (has_mbyte)
408 	{
409 	    p = ml_get(lp->lnum);
410 	    lp->col -= (*mb_head_off)(p, p + lp->col);
411 	}
412 	return 0;
413     }
414 
415     if (lp->lnum > 1)
416     {
417 	/* there is a prior line */
418 	lp->lnum--;
419 	p = ml_get(lp->lnum);
420 	lp->col = (colnr_T)STRLEN(p);
421 	if (has_mbyte)
422 	    lp->col -= (*mb_head_off)(p, p + lp->col);
423 	return 1;
424     }
425 
426     /* at start of file */
427     return -1;
428 }
429 
430 /*
431  * decl(lp): same as dec(), but skip the NUL at the end of non-empty lines
432  */
433     int
434 decl(pos_T *lp)
435 {
436     int	    r;
437 
438     if ((r = dec(lp)) == 1 && lp->col)
439 	r = dec(lp);
440     return r;
441 }
442 
443 /*
444  * Get the line number relative to the current cursor position, i.e. the
445  * difference between line number and cursor position. Only look for lines that
446  * can be visible, folded lines don't count.
447  */
448     linenr_T
449 get_cursor_rel_lnum(
450     win_T	*wp,
451     linenr_T	lnum)		    /* line number to get the result for */
452 {
453     linenr_T	cursor = wp->w_cursor.lnum;
454     linenr_T	retval = 0;
455 
456 #ifdef FEAT_FOLDING
457     if (hasAnyFolding(wp))
458     {
459 	if (lnum > cursor)
460 	{
461 	    while (lnum > cursor)
462 	    {
463 		(void)hasFoldingWin(wp, lnum, &lnum, NULL, TRUE, NULL);
464 		/* if lnum and cursor are in the same fold,
465 		 * now lnum <= cursor */
466 		if (lnum > cursor)
467 		    retval++;
468 		lnum--;
469 	    }
470 	}
471 	else if (lnum < cursor)
472 	{
473 	    while (lnum < cursor)
474 	    {
475 		(void)hasFoldingWin(wp, lnum, NULL, &lnum, TRUE, NULL);
476 		/* if lnum and cursor are in the same fold,
477 		 * now lnum >= cursor */
478 		if (lnum < cursor)
479 		    retval--;
480 		lnum++;
481 	    }
482 	}
483 	/* else if (lnum == cursor)
484 	 *     retval = 0;
485 	 */
486     }
487     else
488 #endif
489 	retval = lnum - cursor;
490 
491     return retval;
492 }
493 
494 /*
495  * Make sure "pos.lnum" and "pos.col" are valid in "buf".
496  * This allows for the col to be on the NUL byte.
497  */
498     void
499 check_pos(buf_T *buf, pos_T *pos)
500 {
501     char_u *line;
502     colnr_T len;
503 
504     if (pos->lnum > buf->b_ml.ml_line_count)
505 	pos->lnum = buf->b_ml.ml_line_count;
506 
507     if (pos->col > 0)
508     {
509 	line = ml_get_buf(buf, pos->lnum, FALSE);
510 	len = (colnr_T)STRLEN(line);
511 	if (pos->col > len)
512 	    pos->col = len;
513     }
514 }
515 
516 /*
517  * Make sure curwin->w_cursor.lnum is valid.
518  */
519     void
520 check_cursor_lnum(void)
521 {
522     if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
523     {
524 #ifdef FEAT_FOLDING
525 	/* If there is a closed fold at the end of the file, put the cursor in
526 	 * its first line.  Otherwise in the last line. */
527 	if (!hasFolding(curbuf->b_ml.ml_line_count,
528 						&curwin->w_cursor.lnum, NULL))
529 #endif
530 	    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
531     }
532     if (curwin->w_cursor.lnum <= 0)
533 	curwin->w_cursor.lnum = 1;
534 }
535 
536 /*
537  * Make sure curwin->w_cursor.col is valid.
538  */
539     void
540 check_cursor_col(void)
541 {
542     check_cursor_col_win(curwin);
543 }
544 
545 /*
546  * Make sure win->w_cursor.col is valid.
547  */
548     void
549 check_cursor_col_win(win_T *win)
550 {
551     colnr_T len;
552     colnr_T oldcol = win->w_cursor.col;
553     colnr_T oldcoladd = win->w_cursor.col + win->w_cursor.coladd;
554 
555     len = (colnr_T)STRLEN(ml_get_buf(win->w_buffer, win->w_cursor.lnum, FALSE));
556     if (len == 0)
557 	win->w_cursor.col = 0;
558     else if (win->w_cursor.col >= len)
559     {
560 	/* Allow cursor past end-of-line when:
561 	 * - in Insert mode or restarting Insert mode
562 	 * - in Visual mode and 'selection' isn't "old"
563 	 * - 'virtualedit' is set */
564 	if ((State & INSERT) || restart_edit
565 		|| (VIsual_active && *p_sel != 'o')
566 		|| (ve_flags & VE_ONEMORE)
567 		|| virtual_active())
568 	    win->w_cursor.col = len;
569 	else
570 	{
571 	    win->w_cursor.col = len - 1;
572 	    /* Move the cursor to the head byte. */
573 	    if (has_mbyte)
574 		mb_adjustpos(win->w_buffer, &win->w_cursor);
575 	}
576     }
577     else if (win->w_cursor.col < 0)
578 	win->w_cursor.col = 0;
579 
580     /* If virtual editing is on, we can leave the cursor on the old position,
581      * only we must set it to virtual.  But don't do it when at the end of the
582      * line. */
583     if (oldcol == MAXCOL)
584 	win->w_cursor.coladd = 0;
585     else if (ve_flags == VE_ALL)
586     {
587 	if (oldcoladd > win->w_cursor.col)
588 	{
589 	    win->w_cursor.coladd = oldcoladd - win->w_cursor.col;
590 
591 	    /* Make sure that coladd is not more than the char width.
592 	     * Not for the last character, coladd is then used when the cursor
593 	     * is actually after the last character. */
594 	    if (win->w_cursor.col + 1 < len && win->w_cursor.coladd > 0)
595 	    {
596 		int cs, ce;
597 
598 		getvcol(win, &win->w_cursor, &cs, NULL, &ce);
599 		if (win->w_cursor.coladd > ce - cs)
600 		    win->w_cursor.coladd = ce - cs;
601 	    }
602 	}
603 	else
604 	    /* avoid weird number when there is a miscalculation or overflow */
605 	    win->w_cursor.coladd = 0;
606     }
607 }
608 
609 /*
610  * make sure curwin->w_cursor in on a valid character
611  */
612     void
613 check_cursor(void)
614 {
615     check_cursor_lnum();
616     check_cursor_col();
617 }
618 
619 #if defined(FEAT_TEXTOBJ) || defined(PROTO)
620 /*
621  * Make sure curwin->w_cursor is not on the NUL at the end of the line.
622  * Allow it when in Visual mode and 'selection' is not "old".
623  */
624     void
625 adjust_cursor_col(void)
626 {
627     if (curwin->w_cursor.col > 0
628 	    && (!VIsual_active || *p_sel == 'o')
629 	    && gchar_cursor() == NUL)
630 	--curwin->w_cursor.col;
631 }
632 #endif
633 
634 /*
635  * When curwin->w_leftcol has changed, adjust the cursor position.
636  * Return TRUE if the cursor was moved.
637  */
638     int
639 leftcol_changed(void)
640 {
641     long	lastcol;
642     colnr_T	s, e;
643     int		retval = FALSE;
644     long        siso = get_sidescrolloff_value();
645 
646     changed_cline_bef_curs();
647     lastcol = curwin->w_leftcol + curwin->w_width - curwin_col_off() - 1;
648     validate_virtcol();
649 
650     /*
651      * If the cursor is right or left of the screen, move it to last or first
652      * character.
653      */
654     if (curwin->w_virtcol > (colnr_T)(lastcol - siso))
655     {
656 	retval = TRUE;
657 	coladvance((colnr_T)(lastcol - siso));
658     }
659     else if (curwin->w_virtcol < curwin->w_leftcol + siso)
660     {
661 	retval = TRUE;
662 	(void)coladvance((colnr_T)(curwin->w_leftcol + siso));
663     }
664 
665     /*
666      * If the start of the character under the cursor is not on the screen,
667      * advance the cursor one more char.  If this fails (last char of the
668      * line) adjust the scrolling.
669      */
670     getvvcol(curwin, &curwin->w_cursor, &s, NULL, &e);
671     if (e > (colnr_T)lastcol)
672     {
673 	retval = TRUE;
674 	coladvance(s - 1);
675     }
676     else if (s < curwin->w_leftcol)
677     {
678 	retval = TRUE;
679 	if (coladvance(e + 1) == FAIL)	/* there isn't another character */
680 	{
681 	    curwin->w_leftcol = s;	/* adjust w_leftcol instead */
682 	    changed_cline_bef_curs();
683 	}
684     }
685 
686     if (retval)
687 	curwin->w_set_curswant = TRUE;
688     redraw_later(NOT_VALID);
689     return retval;
690 }
691 
692 /**********************************************************************
693  * Various routines dealing with allocation and deallocation of memory.
694  */
695 
696 #if defined(MEM_PROFILE) || defined(PROTO)
697 
698 # define MEM_SIZES  8200
699 static long_u mem_allocs[MEM_SIZES];
700 static long_u mem_frees[MEM_SIZES];
701 static long_u mem_allocated;
702 static long_u mem_freed;
703 static long_u mem_peak;
704 static long_u num_alloc;
705 static long_u num_freed;
706 
707     static void
708 mem_pre_alloc_s(size_t *sizep)
709 {
710     *sizep += sizeof(size_t);
711 }
712 
713     static void
714 mem_pre_alloc_l(size_t *sizep)
715 {
716     *sizep += sizeof(size_t);
717 }
718 
719     static void
720 mem_post_alloc(
721     void **pp,
722     size_t size)
723 {
724     if (*pp == NULL)
725 	return;
726     size -= sizeof(size_t);
727     *(long_u *)*pp = size;
728     if (size <= MEM_SIZES-1)
729 	mem_allocs[size-1]++;
730     else
731 	mem_allocs[MEM_SIZES-1]++;
732     mem_allocated += size;
733     if (mem_allocated - mem_freed > mem_peak)
734 	mem_peak = mem_allocated - mem_freed;
735     num_alloc++;
736     *pp = (void *)((char *)*pp + sizeof(size_t));
737 }
738 
739     static void
740 mem_pre_free(void **pp)
741 {
742     long_u size;
743 
744     *pp = (void *)((char *)*pp - sizeof(size_t));
745     size = *(size_t *)*pp;
746     if (size <= MEM_SIZES-1)
747 	mem_frees[size-1]++;
748     else
749 	mem_frees[MEM_SIZES-1]++;
750     mem_freed += size;
751     num_freed++;
752 }
753 
754 /*
755  * called on exit via atexit()
756  */
757     void
758 vim_mem_profile_dump(void)
759 {
760     int i, j;
761 
762     printf("\r\n");
763     j = 0;
764     for (i = 0; i < MEM_SIZES - 1; i++)
765     {
766 	if (mem_allocs[i] || mem_frees[i])
767 	{
768 	    if (mem_frees[i] > mem_allocs[i])
769 		printf("\r\n%s", _("ERROR: "));
770 	    printf("[%4d / %4lu-%-4lu] ", i + 1, mem_allocs[i], mem_frees[i]);
771 	    j++;
772 	    if (j > 3)
773 	    {
774 		j = 0;
775 		printf("\r\n");
776 	    }
777 	}
778     }
779 
780     i = MEM_SIZES - 1;
781     if (mem_allocs[i])
782     {
783 	printf("\r\n");
784 	if (mem_frees[i] > mem_allocs[i])
785 	    puts(_("ERROR: "));
786 	printf("[>%d / %4lu-%-4lu]", i, mem_allocs[i], mem_frees[i]);
787     }
788 
789     printf(_("\n[bytes] total alloc-freed %lu-%lu, in use %lu, peak use %lu\n"),
790 	    mem_allocated, mem_freed, mem_allocated - mem_freed, mem_peak);
791     printf(_("[calls] total re/malloc()'s %lu, total free()'s %lu\n\n"),
792 	    num_alloc, num_freed);
793 }
794 
795 #endif /* MEM_PROFILE */
796 
797 #ifdef FEAT_EVAL
798     int
799 alloc_does_fail(size_t size)
800 {
801     if (alloc_fail_countdown == 0)
802     {
803 	if (--alloc_fail_repeat <= 0)
804 	    alloc_fail_id = 0;
805 	do_outofmem_msg(size);
806 	return TRUE;
807     }
808     --alloc_fail_countdown;
809     return FALSE;
810 }
811 #endif
812 
813 /*
814  * Some memory is reserved for error messages and for being able to
815  * call mf_release_all(), which needs some memory for mf_trans_add().
816  */
817 #define KEEP_ROOM (2 * 8192L)
818 #define KEEP_ROOM_KB (KEEP_ROOM / 1024L)
819 
820 /*
821  * The normal way to allocate memory.  This handles an out-of-memory situation
822  * as well as possible, still returns NULL when we're completely out.
823  */
824     void *
825 alloc(size_t size)
826 {
827     return lalloc(size, TRUE);
828 }
829 
830 /*
831  * alloc() with an ID for alloc_fail().
832  */
833     void *
834 alloc_id(size_t size, alloc_id_T id UNUSED)
835 {
836 #ifdef FEAT_EVAL
837     if (alloc_fail_id == id && alloc_does_fail(size))
838 	return NULL;
839 #endif
840     return lalloc(size, TRUE);
841 }
842 
843 /*
844  * Allocate memory and set all bytes to zero.
845  */
846     void *
847 alloc_clear(size_t size)
848 {
849     void *p;
850 
851     p = lalloc(size, TRUE);
852     if (p != NULL)
853 	(void)vim_memset(p, 0, size);
854     return p;
855 }
856 
857 /*
858  * Same as alloc_clear() but with allocation id for testing
859  */
860     void *
861 alloc_clear_id(size_t size, alloc_id_T id UNUSED)
862 {
863 #ifdef FEAT_EVAL
864     if (alloc_fail_id == id && alloc_does_fail(size))
865 	return NULL;
866 #endif
867     return alloc_clear(size);
868 }
869 
870 /*
871  * Allocate memory like lalloc() and set all bytes to zero.
872  */
873     void *
874 lalloc_clear(size_t size, int message)
875 {
876     void *p;
877 
878     p = lalloc(size, message);
879     if (p != NULL)
880 	(void)vim_memset(p, 0, size);
881     return p;
882 }
883 
884 /*
885  * Low level memory allocation function.
886  * This is used often, KEEP IT FAST!
887  */
888     void *
889 lalloc(size_t size, int message)
890 {
891     void	*p;		    /* pointer to new storage space */
892     static int	releasing = FALSE;  /* don't do mf_release_all() recursive */
893     int		try_again;
894 #if defined(HAVE_AVAIL_MEM)
895     static size_t allocated = 0;    /* allocated since last avail check */
896 #endif
897 
898     // Safety check for allocating zero bytes
899     if (size == 0)
900     {
901 	// Don't hide this message
902 	emsg_silent = 0;
903 	iemsg(_("E341: Internal error: lalloc(0, )"));
904 	return NULL;
905     }
906 
907 #ifdef MEM_PROFILE
908     mem_pre_alloc_l(&size);
909 #endif
910 
911     /*
912      * Loop when out of memory: Try to release some memfile blocks and
913      * if some blocks are released call malloc again.
914      */
915     for (;;)
916     {
917 	/*
918 	 * Handle three kind of systems:
919 	 * 1. No check for available memory: Just return.
920 	 * 2. Slow check for available memory: call mch_avail_mem() after
921 	 *    allocating KEEP_ROOM amount of memory.
922 	 * 3. Strict check for available memory: call mch_avail_mem()
923 	 */
924 	if ((p = malloc(size)) != NULL)
925 	{
926 #ifndef HAVE_AVAIL_MEM
927 	    /* 1. No check for available memory: Just return. */
928 	    goto theend;
929 #else
930 	    /* 2. Slow check for available memory: call mch_avail_mem() after
931 	     *    allocating (KEEP_ROOM / 2) amount of memory. */
932 	    allocated += size;
933 	    if (allocated < KEEP_ROOM / 2)
934 		goto theend;
935 	    allocated = 0;
936 
937 	    /* 3. check for available memory: call mch_avail_mem() */
938 	    if (mch_avail_mem(TRUE) < KEEP_ROOM_KB && !releasing)
939 	    {
940 		free(p);	/* System is low... no go! */
941 		p = NULL;
942 	    }
943 	    else
944 		goto theend;
945 #endif
946 	}
947 	/*
948 	 * Remember that mf_release_all() is being called to avoid an endless
949 	 * loop, because mf_release_all() may call alloc() recursively.
950 	 */
951 	if (releasing)
952 	    break;
953 	releasing = TRUE;
954 
955 	clear_sb_text(TRUE);	      /* free any scrollback text */
956 	try_again = mf_release_all(); /* release as many blocks as possible */
957 
958 	releasing = FALSE;
959 	if (!try_again)
960 	    break;
961     }
962 
963     if (message && p == NULL)
964 	do_outofmem_msg(size);
965 
966 theend:
967 #ifdef MEM_PROFILE
968     mem_post_alloc(&p, size);
969 #endif
970     return p;
971 }
972 
973 /*
974  * lalloc() with an ID for alloc_fail().
975  */
976 #if defined(FEAT_SIGNS) || defined(PROTO)
977     void *
978 lalloc_id(size_t size, int message, alloc_id_T id UNUSED)
979 {
980 #ifdef FEAT_EVAL
981     if (alloc_fail_id == id && alloc_does_fail(size))
982 	return NULL;
983 #endif
984     return (lalloc(size, message));
985 }
986 #endif
987 
988 #if defined(MEM_PROFILE) || defined(PROTO)
989 /*
990  * realloc() with memory profiling.
991  */
992     void *
993 mem_realloc(void *ptr, size_t size)
994 {
995     void *p;
996 
997     mem_pre_free(&ptr);
998     mem_pre_alloc_s(&size);
999 
1000     p = realloc(ptr, size);
1001 
1002     mem_post_alloc(&p, size);
1003 
1004     return p;
1005 }
1006 #endif
1007 
1008 /*
1009 * Avoid repeating the error message many times (they take 1 second each).
1010 * Did_outofmem_msg is reset when a character is read.
1011 */
1012     void
1013 do_outofmem_msg(size_t size)
1014 {
1015     if (!did_outofmem_msg)
1016     {
1017 	// Don't hide this message
1018 	emsg_silent = 0;
1019 
1020 	// Must come first to avoid coming back here when printing the error
1021 	// message fails, e.g. when setting v:errmsg.
1022 	did_outofmem_msg = TRUE;
1023 
1024 	semsg(_("E342: Out of memory!  (allocating %lu bytes)"), (long_u)size);
1025 
1026 	if (starting == NO_SCREEN)
1027 	    // Not even finished with initializations and already out of
1028 	    // memory?  Then nothing is going to work, exit.
1029 	    mch_exit(123);
1030     }
1031 }
1032 
1033 #if defined(EXITFREE) || defined(PROTO)
1034 
1035 /*
1036  * Free everything that we allocated.
1037  * Can be used to detect memory leaks, e.g., with ccmalloc.
1038  * NOTE: This is tricky!  Things are freed that functions depend on.  Don't be
1039  * surprised if Vim crashes...
1040  * Some things can't be freed, esp. things local to a library function.
1041  */
1042     void
1043 free_all_mem(void)
1044 {
1045     buf_T	*buf, *nextbuf;
1046 
1047     /* When we cause a crash here it is caught and Vim tries to exit cleanly.
1048      * Don't try freeing everything again. */
1049     if (entered_free_all_mem)
1050 	return;
1051     entered_free_all_mem = TRUE;
1052 
1053     /* Don't want to trigger autocommands from here on. */
1054     block_autocmds();
1055 
1056     /* Close all tabs and windows.  Reset 'equalalways' to avoid redraws. */
1057     p_ea = FALSE;
1058     if (first_tabpage != NULL && first_tabpage->tp_next != NULL)
1059 	do_cmdline_cmd((char_u *)"tabonly!");
1060     if (!ONE_WINDOW)
1061 	do_cmdline_cmd((char_u *)"only!");
1062 
1063 # if defined(FEAT_SPELL)
1064     /* Free all spell info. */
1065     spell_free_all();
1066 # endif
1067 
1068 # if defined(FEAT_BEVAL_TERM)
1069     ui_remove_balloon();
1070 # endif
1071 
1072     // Clear user commands (before deleting buffers).
1073     ex_comclear(NULL);
1074 
1075     // When exiting from mainerr_arg_missing curbuf has not been initialized,
1076     // and not much else.
1077     if (curbuf != NULL)
1078     {
1079 # ifdef FEAT_MENU
1080 	// Clear menus.
1081 	do_cmdline_cmd((char_u *)"aunmenu *");
1082 #  ifdef FEAT_MULTI_LANG
1083 	do_cmdline_cmd((char_u *)"menutranslate clear");
1084 #  endif
1085 # endif
1086 	// Clear mappings, abbreviations, breakpoints.
1087 	do_cmdline_cmd((char_u *)"lmapclear");
1088 	do_cmdline_cmd((char_u *)"xmapclear");
1089 	do_cmdline_cmd((char_u *)"mapclear");
1090 	do_cmdline_cmd((char_u *)"mapclear!");
1091 	do_cmdline_cmd((char_u *)"abclear");
1092 # if defined(FEAT_EVAL)
1093 	do_cmdline_cmd((char_u *)"breakdel *");
1094 # endif
1095 # if defined(FEAT_PROFILE)
1096 	do_cmdline_cmd((char_u *)"profdel *");
1097 # endif
1098 # if defined(FEAT_KEYMAP)
1099 	do_cmdline_cmd((char_u *)"set keymap=");
1100 # endif
1101     }
1102 
1103 # ifdef FEAT_TITLE
1104     free_titles();
1105 # endif
1106 # if defined(FEAT_SEARCHPATH)
1107     free_findfile();
1108 # endif
1109 
1110     /* Obviously named calls. */
1111     free_all_autocmds();
1112     clear_termcodes();
1113     free_all_marks();
1114     alist_clear(&global_alist);
1115     free_homedir();
1116     free_users();
1117     free_search_patterns();
1118     free_old_sub();
1119     free_last_insert();
1120     free_insexpand_stuff();
1121     free_prev_shellcmd();
1122     free_regexp_stuff();
1123     free_tag_stuff();
1124     free_cd_dir();
1125 # ifdef FEAT_SIGNS
1126     free_signs();
1127 # endif
1128 # ifdef FEAT_EVAL
1129     set_expr_line(NULL);
1130 # endif
1131 # ifdef FEAT_DIFF
1132     if (curtab != NULL)
1133 	diff_clear(curtab);
1134 # endif
1135     clear_sb_text(TRUE);	      /* free any scrollback text */
1136 
1137     /* Free some global vars. */
1138     vim_free(username);
1139 # ifdef FEAT_CLIPBOARD
1140     vim_regfree(clip_exclude_prog);
1141 # endif
1142     vim_free(last_cmdline);
1143     vim_free(new_last_cmdline);
1144     set_keep_msg(NULL, 0);
1145 
1146     /* Clear cmdline history. */
1147     p_hi = 0;
1148     init_history();
1149 # ifdef FEAT_TEXT_PROP
1150     clear_global_prop_types();
1151 # endif
1152 
1153 # ifdef FEAT_QUICKFIX
1154     {
1155 	win_T	    *win;
1156 	tabpage_T   *tab;
1157 
1158 	qf_free_all(NULL);
1159 	// Free all location lists
1160 	FOR_ALL_TAB_WINDOWS(tab, win)
1161 	    qf_free_all(win);
1162     }
1163 # endif
1164 
1165     // Close all script inputs.
1166     close_all_scripts();
1167 
1168     if (curwin != NULL)
1169 	// Destroy all windows.  Must come before freeing buffers.
1170 	win_free_all();
1171 
1172     /* Free all option values.  Must come after closing windows. */
1173     free_all_options();
1174 
1175     /* Free all buffers.  Reset 'autochdir' to avoid accessing things that
1176      * were freed already. */
1177 # ifdef FEAT_AUTOCHDIR
1178     p_acd = FALSE;
1179 # endif
1180     for (buf = firstbuf; buf != NULL; )
1181     {
1182 	bufref_T    bufref;
1183 
1184 	set_bufref(&bufref, buf);
1185 	nextbuf = buf->b_next;
1186 	close_buffer(NULL, buf, DOBUF_WIPE, FALSE);
1187 	if (bufref_valid(&bufref))
1188 	    buf = nextbuf;	/* didn't work, try next one */
1189 	else
1190 	    buf = firstbuf;
1191     }
1192 
1193 # ifdef FEAT_ARABIC
1194     free_arshape_buf();
1195 # endif
1196 
1197     /* Clear registers. */
1198     clear_registers();
1199     ResetRedobuff();
1200     ResetRedobuff();
1201 
1202 # if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
1203     vim_free(serverDelayedStartName);
1204 # endif
1205 
1206     /* highlight info */
1207     free_highlight();
1208 
1209     reset_last_sourcing();
1210 
1211     if (first_tabpage != NULL)
1212     {
1213 	free_tabpage(first_tabpage);
1214 	first_tabpage = NULL;
1215     }
1216 
1217 # ifdef UNIX
1218     /* Machine-specific free. */
1219     mch_free_mem();
1220 # endif
1221 
1222     /* message history */
1223     for (;;)
1224 	if (delete_first_msg() == FAIL)
1225 	    break;
1226 
1227 # ifdef FEAT_JOB_CHANNEL
1228     channel_free_all();
1229 # endif
1230 # ifdef FEAT_TIMERS
1231     timer_free_all();
1232 # endif
1233 # ifdef FEAT_EVAL
1234     /* must be after channel_free_all() with unrefs partials */
1235     eval_clear();
1236 # endif
1237 # ifdef FEAT_JOB_CHANNEL
1238     /* must be after eval_clear() with unrefs jobs */
1239     job_free_all();
1240 # endif
1241 
1242     free_termoptions();
1243 
1244     /* screenlines (can't display anything now!) */
1245     free_screenlines();
1246 
1247 # if defined(FEAT_SOUND)
1248     sound_free();
1249 # endif
1250 # if defined(USE_XSMP)
1251     xsmp_close();
1252 # endif
1253 # ifdef FEAT_GUI_GTK
1254     gui_mch_free_all();
1255 # endif
1256     clear_hl_tables();
1257 
1258     vim_free(IObuff);
1259     vim_free(NameBuff);
1260 # ifdef FEAT_QUICKFIX
1261     check_quickfix_busy();
1262 # endif
1263 }
1264 #endif
1265 
1266 /*
1267  * Copy "string" into newly allocated memory.
1268  */
1269     char_u *
1270 vim_strsave(char_u *string)
1271 {
1272     char_u	*p;
1273     size_t	len;
1274 
1275     len = STRLEN(string) + 1;
1276     p = alloc(len);
1277     if (p != NULL)
1278 	mch_memmove(p, string, len);
1279     return p;
1280 }
1281 
1282 /*
1283  * Copy up to "len" bytes of "string" into newly allocated memory and
1284  * terminate with a NUL.
1285  * The allocated memory always has size "len + 1", also when "string" is
1286  * shorter.
1287  */
1288     char_u *
1289 vim_strnsave(char_u *string, int len)
1290 {
1291     char_u	*p;
1292 
1293     p = alloc(len + 1);
1294     if (p != NULL)
1295     {
1296 	STRNCPY(p, string, len);
1297 	p[len] = NUL;
1298     }
1299     return p;
1300 }
1301 
1302 /*
1303  * Copy "p[len]" into allocated memory, ignoring NUL characters.
1304  * Returns NULL when out of memory.
1305  */
1306     char_u *
1307 vim_memsave(char_u *p, size_t len)
1308 {
1309     char_u *ret = alloc(len);
1310 
1311     if (ret != NULL)
1312 	mch_memmove(ret, p, len);
1313     return ret;
1314 }
1315 
1316 /*
1317  * Same as vim_strsave(), but any characters found in esc_chars are preceded
1318  * by a backslash.
1319  */
1320     char_u *
1321 vim_strsave_escaped(char_u *string, char_u *esc_chars)
1322 {
1323     return vim_strsave_escaped_ext(string, esc_chars, '\\', FALSE);
1324 }
1325 
1326 /*
1327  * Same as vim_strsave_escaped(), but when "bsl" is TRUE also escape
1328  * characters where rem_backslash() would remove the backslash.
1329  * Escape the characters with "cc".
1330  */
1331     char_u *
1332 vim_strsave_escaped_ext(
1333     char_u	*string,
1334     char_u	*esc_chars,
1335     int		cc,
1336     int		bsl)
1337 {
1338     char_u	*p;
1339     char_u	*p2;
1340     char_u	*escaped_string;
1341     unsigned	length;
1342     int		l;
1343 
1344     /*
1345      * First count the number of backslashes required.
1346      * Then allocate the memory and insert them.
1347      */
1348     length = 1;				/* count the trailing NUL */
1349     for (p = string; *p; p++)
1350     {
1351 	if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1352 	{
1353 	    length += l;		/* count a multibyte char */
1354 	    p += l - 1;
1355 	    continue;
1356 	}
1357 	if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1358 	    ++length;			/* count a backslash */
1359 	++length;			/* count an ordinary char */
1360     }
1361     escaped_string = alloc(length);
1362     if (escaped_string != NULL)
1363     {
1364 	p2 = escaped_string;
1365 	for (p = string; *p; p++)
1366 	{
1367 	    if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1368 	    {
1369 		mch_memmove(p2, p, (size_t)l);
1370 		p2 += l;
1371 		p += l - 1;		/* skip multibyte char  */
1372 		continue;
1373 	    }
1374 	    if (vim_strchr(esc_chars, *p) != NULL || (bsl && rem_backslash(p)))
1375 		*p2++ = cc;
1376 	    *p2++ = *p;
1377 	}
1378 	*p2 = NUL;
1379     }
1380     return escaped_string;
1381 }
1382 
1383 /*
1384  * Return TRUE when 'shell' has "csh" in the tail.
1385  */
1386     int
1387 csh_like_shell(void)
1388 {
1389     return (strstr((char *)gettail(p_sh), "csh") != NULL);
1390 }
1391 
1392 /*
1393  * Escape "string" for use as a shell argument with system().
1394  * This uses single quotes, except when we know we need to use double quotes
1395  * (MS-DOS and MS-Windows without 'shellslash' set).
1396  * Escape a newline, depending on the 'shell' option.
1397  * When "do_special" is TRUE also replace "!", "%", "#" and things starting
1398  * with "<" like "<cfile>".
1399  * When "do_newline" is FALSE do not escape newline unless it is csh shell.
1400  * Returns the result in allocated memory, NULL if we have run out.
1401  */
1402     char_u *
1403 vim_strsave_shellescape(char_u *string, int do_special, int do_newline)
1404 {
1405     unsigned	length;
1406     char_u	*p;
1407     char_u	*d;
1408     char_u	*escaped_string;
1409     int		l;
1410     int		csh_like;
1411 
1412     /* Only csh and similar shells expand '!' within single quotes.  For sh and
1413      * the like we must not put a backslash before it, it will be taken
1414      * literally.  If do_special is set the '!' will be escaped twice.
1415      * Csh also needs to have "\n" escaped twice when do_special is set. */
1416     csh_like = csh_like_shell();
1417 
1418     /* First count the number of extra bytes required. */
1419     length = (unsigned)STRLEN(string) + 3;  /* two quotes and a trailing NUL */
1420     for (p = string; *p != NUL; MB_PTR_ADV(p))
1421     {
1422 # ifdef MSWIN
1423 	if (!p_ssl)
1424 	{
1425 	    if (*p == '"')
1426 		++length;		/* " -> "" */
1427 	}
1428 	else
1429 # endif
1430 	if (*p == '\'')
1431 	    length += 3;		/* ' => '\'' */
1432 	if ((*p == '\n' && (csh_like || do_newline))
1433 		|| (*p == '!' && (csh_like || do_special)))
1434 	{
1435 	    ++length;			/* insert backslash */
1436 	    if (csh_like && do_special)
1437 		++length;		/* insert backslash */
1438 	}
1439 	if (do_special && find_cmdline_var(p, &l) >= 0)
1440 	{
1441 	    ++length;			/* insert backslash */
1442 	    p += l - 1;
1443 	}
1444     }
1445 
1446     /* Allocate memory for the result and fill it. */
1447     escaped_string = alloc(length);
1448     if (escaped_string != NULL)
1449     {
1450 	d = escaped_string;
1451 
1452 	/* add opening quote */
1453 # ifdef MSWIN
1454 	if (!p_ssl)
1455 	    *d++ = '"';
1456 	else
1457 # endif
1458 	    *d++ = '\'';
1459 
1460 	for (p = string; *p != NUL; )
1461 	{
1462 # ifdef MSWIN
1463 	    if (!p_ssl)
1464 	    {
1465 		if (*p == '"')
1466 		{
1467 		    *d++ = '"';
1468 		    *d++ = '"';
1469 		    ++p;
1470 		    continue;
1471 		}
1472 	    }
1473 	    else
1474 # endif
1475 	    if (*p == '\'')
1476 	    {
1477 		*d++ = '\'';
1478 		*d++ = '\\';
1479 		*d++ = '\'';
1480 		*d++ = '\'';
1481 		++p;
1482 		continue;
1483 	    }
1484 	    if ((*p == '\n' && (csh_like || do_newline))
1485 		    || (*p == '!' && (csh_like || do_special)))
1486 	    {
1487 		*d++ = '\\';
1488 		if (csh_like && do_special)
1489 		    *d++ = '\\';
1490 		*d++ = *p++;
1491 		continue;
1492 	    }
1493 	    if (do_special && find_cmdline_var(p, &l) >= 0)
1494 	    {
1495 		*d++ = '\\';		/* insert backslash */
1496 		while (--l >= 0)	/* copy the var */
1497 		    *d++ = *p++;
1498 		continue;
1499 	    }
1500 
1501 	    MB_COPY_CHAR(p, d);
1502 	}
1503 
1504 	/* add terminating quote and finish with a NUL */
1505 # ifdef MSWIN
1506 	if (!p_ssl)
1507 	    *d++ = '"';
1508 	else
1509 # endif
1510 	    *d++ = '\'';
1511 	*d = NUL;
1512     }
1513 
1514     return escaped_string;
1515 }
1516 
1517 /*
1518  * Like vim_strsave(), but make all characters uppercase.
1519  * This uses ASCII lower-to-upper case translation, language independent.
1520  */
1521     char_u *
1522 vim_strsave_up(char_u *string)
1523 {
1524     char_u *p1;
1525 
1526     p1 = vim_strsave(string);
1527     vim_strup(p1);
1528     return p1;
1529 }
1530 
1531 /*
1532  * Like vim_strnsave(), but make all characters uppercase.
1533  * This uses ASCII lower-to-upper case translation, language independent.
1534  */
1535     char_u *
1536 vim_strnsave_up(char_u *string, int len)
1537 {
1538     char_u *p1;
1539 
1540     p1 = vim_strnsave(string, len);
1541     vim_strup(p1);
1542     return p1;
1543 }
1544 
1545 /*
1546  * ASCII lower-to-upper case translation, language independent.
1547  */
1548     void
1549 vim_strup(
1550     char_u	*p)
1551 {
1552     char_u  *p2;
1553     int	    c;
1554 
1555     if (p != NULL)
1556     {
1557 	p2 = p;
1558 	while ((c = *p2) != NUL)
1559 #ifdef EBCDIC
1560 	    *p2++ = isalpha(c) ? toupper(c) : c;
1561 #else
1562 	    *p2++ = (c < 'a' || c > 'z') ? c : (c - 0x20);
1563 #endif
1564     }
1565 }
1566 
1567 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
1568 /*
1569  * Make string "s" all upper-case and return it in allocated memory.
1570  * Handles multi-byte characters as well as possible.
1571  * Returns NULL when out of memory.
1572  */
1573     char_u *
1574 strup_save(char_u *orig)
1575 {
1576     char_u	*p;
1577     char_u	*res;
1578 
1579     res = p = vim_strsave(orig);
1580 
1581     if (res != NULL)
1582 	while (*p != NUL)
1583 	{
1584 	    int		l;
1585 
1586 	    if (enc_utf8)
1587 	    {
1588 		int	c, uc;
1589 		int	newl;
1590 		char_u	*s;
1591 
1592 		c = utf_ptr2char(p);
1593 		l = utf_ptr2len(p);
1594 		if (c == 0)
1595 		{
1596 		    /* overlong sequence, use only the first byte */
1597 		    c = *p;
1598 		    l = 1;
1599 		}
1600 		uc = utf_toupper(c);
1601 
1602 		/* Reallocate string when byte count changes.  This is rare,
1603 		 * thus it's OK to do another malloc()/free(). */
1604 		newl = utf_char2len(uc);
1605 		if (newl != l)
1606 		{
1607 		    s = alloc(STRLEN(res) + 1 + newl - l);
1608 		    if (s == NULL)
1609 		    {
1610 			vim_free(res);
1611 			return NULL;
1612 		    }
1613 		    mch_memmove(s, res, p - res);
1614 		    STRCPY(s + (p - res) + newl, p + l);
1615 		    p = s + (p - res);
1616 		    vim_free(res);
1617 		    res = s;
1618 		}
1619 
1620 		utf_char2bytes(uc, p);
1621 		p += newl;
1622 	    }
1623 	    else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1624 		p += l;		/* skip multi-byte character */
1625 	    else
1626 	    {
1627 		*p = TOUPPER_LOC(*p); /* note that toupper() can be a macro */
1628 		p++;
1629 	    }
1630 	}
1631 
1632     return res;
1633 }
1634 
1635 /*
1636  * Make string "s" all lower-case and return it in allocated memory.
1637  * Handles multi-byte characters as well as possible.
1638  * Returns NULL when out of memory.
1639  */
1640     char_u *
1641 strlow_save(char_u *orig)
1642 {
1643     char_u	*p;
1644     char_u	*res;
1645 
1646     res = p = vim_strsave(orig);
1647 
1648     if (res != NULL)
1649 	while (*p != NUL)
1650 	{
1651 	    int		l;
1652 
1653 	    if (enc_utf8)
1654 	    {
1655 		int	c, lc;
1656 		int	newl;
1657 		char_u	*s;
1658 
1659 		c = utf_ptr2char(p);
1660 		l = utf_ptr2len(p);
1661 		if (c == 0)
1662 		{
1663 		    /* overlong sequence, use only the first byte */
1664 		    c = *p;
1665 		    l = 1;
1666 		}
1667 		lc = utf_tolower(c);
1668 
1669 		/* Reallocate string when byte count changes.  This is rare,
1670 		 * thus it's OK to do another malloc()/free(). */
1671 		newl = utf_char2len(lc);
1672 		if (newl != l)
1673 		{
1674 		    s = alloc(STRLEN(res) + 1 + newl - l);
1675 		    if (s == NULL)
1676 		    {
1677 			vim_free(res);
1678 			return NULL;
1679 		    }
1680 		    mch_memmove(s, res, p - res);
1681 		    STRCPY(s + (p - res) + newl, p + l);
1682 		    p = s + (p - res);
1683 		    vim_free(res);
1684 		    res = s;
1685 		}
1686 
1687 		utf_char2bytes(lc, p);
1688 		p += newl;
1689 	    }
1690 	    else if (has_mbyte && (l = (*mb_ptr2len)(p)) > 1)
1691 		p += l;		/* skip multi-byte character */
1692 	    else
1693 	    {
1694 		*p = TOLOWER_LOC(*p); /* note that tolower() can be a macro */
1695 		p++;
1696 	    }
1697 	}
1698 
1699     return res;
1700 }
1701 #endif
1702 
1703 /*
1704  * delete spaces at the end of a string
1705  */
1706     void
1707 del_trailing_spaces(char_u *ptr)
1708 {
1709     char_u	*q;
1710 
1711     q = ptr + STRLEN(ptr);
1712     while (--q > ptr && VIM_ISWHITE(q[0]) && q[-1] != '\\' && q[-1] != Ctrl_V)
1713 	*q = NUL;
1714 }
1715 
1716 /*
1717  * Like strncpy(), but always terminate the result with one NUL.
1718  * "to" must be "len + 1" long!
1719  */
1720     void
1721 vim_strncpy(char_u *to, char_u *from, size_t len)
1722 {
1723     STRNCPY(to, from, len);
1724     to[len] = NUL;
1725 }
1726 
1727 /*
1728  * Like strcat(), but make sure the result fits in "tosize" bytes and is
1729  * always NUL terminated. "from" and "to" may overlap.
1730  */
1731     void
1732 vim_strcat(char_u *to, char_u *from, size_t tosize)
1733 {
1734     size_t tolen = STRLEN(to);
1735     size_t fromlen = STRLEN(from);
1736 
1737     if (tolen + fromlen + 1 > tosize)
1738     {
1739 	mch_memmove(to + tolen, from, tosize - tolen - 1);
1740 	to[tosize - 1] = NUL;
1741     }
1742     else
1743 	mch_memmove(to + tolen, from, fromlen + 1);
1744 }
1745 
1746 /*
1747  * Isolate one part of a string option where parts are separated with
1748  * "sep_chars".
1749  * The part is copied into "buf[maxlen]".
1750  * "*option" is advanced to the next part.
1751  * The length is returned.
1752  */
1753     int
1754 copy_option_part(
1755     char_u	**option,
1756     char_u	*buf,
1757     int		maxlen,
1758     char	*sep_chars)
1759 {
1760     int	    len = 0;
1761     char_u  *p = *option;
1762 
1763     /* skip '.' at start of option part, for 'suffixes' */
1764     if (*p == '.')
1765 	buf[len++] = *p++;
1766     while (*p != NUL && vim_strchr((char_u *)sep_chars, *p) == NULL)
1767     {
1768 	/*
1769 	 * Skip backslash before a separator character and space.
1770 	 */
1771 	if (p[0] == '\\' && vim_strchr((char_u *)sep_chars, p[1]) != NULL)
1772 	    ++p;
1773 	if (len < maxlen - 1)
1774 	    buf[len++] = *p;
1775 	++p;
1776     }
1777     buf[len] = NUL;
1778 
1779     if (*p != NUL && *p != ',')	/* skip non-standard separator */
1780 	++p;
1781     p = skip_to_option_part(p);	/* p points to next file name */
1782 
1783     *option = p;
1784     return len;
1785 }
1786 
1787 /*
1788  * Replacement for free() that ignores NULL pointers.
1789  * Also skip free() when exiting for sure, this helps when we caught a deadly
1790  * signal that was caused by a crash in free().
1791  * If you want to set NULL after calling this function, you should use
1792  * VIM_CLEAR() instead.
1793  */
1794     void
1795 vim_free(void *x)
1796 {
1797     if (x != NULL && !really_exiting)
1798     {
1799 #ifdef MEM_PROFILE
1800 	mem_pre_free(&x);
1801 #endif
1802 	free(x);
1803     }
1804 }
1805 
1806 #ifndef HAVE_MEMSET
1807     void *
1808 vim_memset(void *ptr, int c, size_t size)
1809 {
1810     char *p = ptr;
1811 
1812     while (size-- > 0)
1813 	*p++ = c;
1814     return ptr;
1815 }
1816 #endif
1817 
1818 #if (!defined(HAVE_STRCASECMP) && !defined(HAVE_STRICMP)) || defined(PROTO)
1819 /*
1820  * Compare two strings, ignoring case, using current locale.
1821  * Doesn't work for multi-byte characters.
1822  * return 0 for match, < 0 for smaller, > 0 for bigger
1823  */
1824     int
1825 vim_stricmp(char *s1, char *s2)
1826 {
1827     int		i;
1828 
1829     for (;;)
1830     {
1831 	i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1832 	if (i != 0)
1833 	    return i;			    /* this character different */
1834 	if (*s1 == NUL)
1835 	    break;			    /* strings match until NUL */
1836 	++s1;
1837 	++s2;
1838     }
1839     return 0;				    /* strings match */
1840 }
1841 #endif
1842 
1843 #if (!defined(HAVE_STRNCASECMP) && !defined(HAVE_STRNICMP)) || defined(PROTO)
1844 /*
1845  * Compare two strings, for length "len", ignoring case, using current locale.
1846  * Doesn't work for multi-byte characters.
1847  * return 0 for match, < 0 for smaller, > 0 for bigger
1848  */
1849     int
1850 vim_strnicmp(char *s1, char *s2, size_t len)
1851 {
1852     int		i;
1853 
1854     while (len > 0)
1855     {
1856 	i = (int)TOLOWER_LOC(*s1) - (int)TOLOWER_LOC(*s2);
1857 	if (i != 0)
1858 	    return i;			    /* this character different */
1859 	if (*s1 == NUL)
1860 	    break;			    /* strings match until NUL */
1861 	++s1;
1862 	++s2;
1863 	--len;
1864     }
1865     return 0;				    /* strings match */
1866 }
1867 #endif
1868 
1869 /*
1870  * Version of strchr() and strrchr() that handle unsigned char strings
1871  * with characters from 128 to 255 correctly.  It also doesn't return a
1872  * pointer to the NUL at the end of the string.
1873  */
1874     char_u  *
1875 vim_strchr(char_u *string, int c)
1876 {
1877     char_u	*p;
1878     int		b;
1879 
1880     p = string;
1881     if (enc_utf8 && c >= 0x80)
1882     {
1883 	while (*p != NUL)
1884 	{
1885 	    int l = utfc_ptr2len(p);
1886 
1887 	    /* Avoid matching an illegal byte here. */
1888 	    if (utf_ptr2char(p) == c && l > 1)
1889 		return p;
1890 	    p += l;
1891 	}
1892 	return NULL;
1893     }
1894     if (enc_dbcs != 0 && c > 255)
1895     {
1896 	int	n2 = c & 0xff;
1897 
1898 	c = ((unsigned)c >> 8) & 0xff;
1899 	while ((b = *p) != NUL)
1900 	{
1901 	    if (b == c && p[1] == n2)
1902 		return p;
1903 	    p += (*mb_ptr2len)(p);
1904 	}
1905 	return NULL;
1906     }
1907     if (has_mbyte)
1908     {
1909 	while ((b = *p) != NUL)
1910 	{
1911 	    if (b == c)
1912 		return p;
1913 	    p += (*mb_ptr2len)(p);
1914 	}
1915 	return NULL;
1916     }
1917     while ((b = *p) != NUL)
1918     {
1919 	if (b == c)
1920 	    return p;
1921 	++p;
1922     }
1923     return NULL;
1924 }
1925 
1926 /*
1927  * Version of strchr() that only works for bytes and handles unsigned char
1928  * strings with characters above 128 correctly. It also doesn't return a
1929  * pointer to the NUL at the end of the string.
1930  */
1931     char_u  *
1932 vim_strbyte(char_u *string, int c)
1933 {
1934     char_u	*p = string;
1935 
1936     while (*p != NUL)
1937     {
1938 	if (*p == c)
1939 	    return p;
1940 	++p;
1941     }
1942     return NULL;
1943 }
1944 
1945 /*
1946  * Search for last occurrence of "c" in "string".
1947  * Return NULL if not found.
1948  * Does not handle multi-byte char for "c"!
1949  */
1950     char_u  *
1951 vim_strrchr(char_u *string, int c)
1952 {
1953     char_u	*retval = NULL;
1954     char_u	*p = string;
1955 
1956     while (*p)
1957     {
1958 	if (*p == c)
1959 	    retval = p;
1960 	MB_PTR_ADV(p);
1961     }
1962     return retval;
1963 }
1964 
1965 /*
1966  * Vim's version of strpbrk(), in case it's missing.
1967  * Don't generate a prototype for this, causes problems when it's not used.
1968  */
1969 #ifndef PROTO
1970 # ifndef HAVE_STRPBRK
1971 #  ifdef vim_strpbrk
1972 #   undef vim_strpbrk
1973 #  endif
1974     char_u *
1975 vim_strpbrk(char_u *s, char_u *charset)
1976 {
1977     while (*s)
1978     {
1979 	if (vim_strchr(charset, *s) != NULL)
1980 	    return s;
1981 	MB_PTR_ADV(s);
1982     }
1983     return NULL;
1984 }
1985 # endif
1986 #endif
1987 
1988 /*
1989  * Vim has its own isspace() function, because on some machines isspace()
1990  * can't handle characters above 128.
1991  */
1992     int
1993 vim_isspace(int x)
1994 {
1995     return ((x >= 9 && x <= 13) || x == ' ');
1996 }
1997 
1998 /************************************************************************
1999  * Functions for handling growing arrays.
2000  */
2001 
2002 /*
2003  * Clear an allocated growing array.
2004  */
2005     void
2006 ga_clear(garray_T *gap)
2007 {
2008     vim_free(gap->ga_data);
2009     ga_init(gap);
2010 }
2011 
2012 /*
2013  * Clear a growing array that contains a list of strings.
2014  */
2015     void
2016 ga_clear_strings(garray_T *gap)
2017 {
2018     int		i;
2019 
2020     for (i = 0; i < gap->ga_len; ++i)
2021 	vim_free(((char_u **)(gap->ga_data))[i]);
2022     ga_clear(gap);
2023 }
2024 
2025 /*
2026  * Initialize a growing array.	Don't forget to set ga_itemsize and
2027  * ga_growsize!  Or use ga_init2().
2028  */
2029     void
2030 ga_init(garray_T *gap)
2031 {
2032     gap->ga_data = NULL;
2033     gap->ga_maxlen = 0;
2034     gap->ga_len = 0;
2035 }
2036 
2037     void
2038 ga_init2(garray_T *gap, int itemsize, int growsize)
2039 {
2040     ga_init(gap);
2041     gap->ga_itemsize = itemsize;
2042     gap->ga_growsize = growsize;
2043 }
2044 
2045 /*
2046  * Make room in growing array "gap" for at least "n" items.
2047  * Return FAIL for failure, OK otherwise.
2048  */
2049     int
2050 ga_grow(garray_T *gap, int n)
2051 {
2052     size_t	old_len;
2053     size_t	new_len;
2054     char_u	*pp;
2055 
2056     if (gap->ga_maxlen - gap->ga_len < n)
2057     {
2058 	if (n < gap->ga_growsize)
2059 	    n = gap->ga_growsize;
2060 
2061 	// A linear growth is very inefficient when the array grows big.  This
2062 	// is a compromise between allocating memory that won't be used and too
2063 	// many copy operations. A factor of 1.5 seems reasonable.
2064 	if (n < gap->ga_len / 2)
2065 	    n = gap->ga_len / 2;
2066 
2067 	new_len = gap->ga_itemsize * (gap->ga_len + n);
2068 	pp = vim_realloc(gap->ga_data, new_len);
2069 	if (pp == NULL)
2070 	    return FAIL;
2071 	old_len = gap->ga_itemsize * gap->ga_maxlen;
2072 	vim_memset(pp + old_len, 0, new_len - old_len);
2073 	gap->ga_maxlen = gap->ga_len + n;
2074 	gap->ga_data = pp;
2075     }
2076     return OK;
2077 }
2078 
2079 #if defined(FEAT_EVAL) || defined(FEAT_SEARCHPATH) || defined(PROTO)
2080 /*
2081  * For a growing array that contains a list of strings: concatenate all the
2082  * strings with a separating "sep".
2083  * Returns NULL when out of memory.
2084  */
2085     char_u *
2086 ga_concat_strings(garray_T *gap, char *sep)
2087 {
2088     int		i;
2089     int		len = 0;
2090     int		sep_len = (int)STRLEN(sep);
2091     char_u	*s;
2092     char_u	*p;
2093 
2094     for (i = 0; i < gap->ga_len; ++i)
2095 	len += (int)STRLEN(((char_u **)(gap->ga_data))[i]) + sep_len;
2096 
2097     s = alloc(len + 1);
2098     if (s != NULL)
2099     {
2100 	*s = NUL;
2101 	p = s;
2102 	for (i = 0; i < gap->ga_len; ++i)
2103 	{
2104 	    if (p != s)
2105 	    {
2106 		STRCPY(p, sep);
2107 		p += sep_len;
2108 	    }
2109 	    STRCPY(p, ((char_u **)(gap->ga_data))[i]);
2110 	    p += STRLEN(p);
2111 	}
2112     }
2113     return s;
2114 }
2115 #endif
2116 
2117 #if defined(FEAT_VIMINFO) || defined(FEAT_EVAL) || defined(PROTO)
2118 /*
2119  * Make a copy of string "p" and add it to "gap".
2120  * When out of memory nothing changes.
2121  */
2122     void
2123 ga_add_string(garray_T *gap, char_u *p)
2124 {
2125     char_u *cp = vim_strsave(p);
2126 
2127     if (cp != NULL)
2128     {
2129 	if (ga_grow(gap, 1) == OK)
2130 	    ((char_u **)(gap->ga_data))[gap->ga_len++] = cp;
2131 	else
2132 	    vim_free(cp);
2133     }
2134 }
2135 #endif
2136 
2137 /*
2138  * Concatenate a string to a growarray which contains bytes.
2139  * When "s" is NULL does not do anything.
2140  * Note: Does NOT copy the NUL at the end!
2141  */
2142     void
2143 ga_concat(garray_T *gap, char_u *s)
2144 {
2145     int    len;
2146 
2147     if (s == NULL || *s == NUL)
2148 	return;
2149     len = (int)STRLEN(s);
2150     if (ga_grow(gap, len) == OK)
2151     {
2152 	mch_memmove((char *)gap->ga_data + gap->ga_len, s, (size_t)len);
2153 	gap->ga_len += len;
2154     }
2155 }
2156 
2157 /*
2158  * Append one byte to a growarray which contains bytes.
2159  */
2160     void
2161 ga_append(garray_T *gap, int c)
2162 {
2163     if (ga_grow(gap, 1) == OK)
2164     {
2165 	*((char *)gap->ga_data + gap->ga_len) = c;
2166 	++gap->ga_len;
2167     }
2168 }
2169 
2170 #if (defined(UNIX) && !defined(USE_SYSTEM)) || defined(MSWIN) \
2171 	|| defined(PROTO)
2172 /*
2173  * Append the text in "gap" below the cursor line and clear "gap".
2174  */
2175     void
2176 append_ga_line(garray_T *gap)
2177 {
2178     /* Remove trailing CR. */
2179     if (gap->ga_len > 0
2180 	    && !curbuf->b_p_bin
2181 	    && ((char_u *)gap->ga_data)[gap->ga_len - 1] == CAR)
2182 	--gap->ga_len;
2183     ga_append(gap, NUL);
2184     ml_append(curwin->w_cursor.lnum++, gap->ga_data, 0, FALSE);
2185     gap->ga_len = 0;
2186 }
2187 #endif
2188 
2189 /************************************************************************
2190  * functions that use lookup tables for various things, generally to do with
2191  * special key codes.
2192  */
2193 
2194 /*
2195  * Some useful tables.
2196  */
2197 
2198 static struct modmasktable
2199 {
2200     short	mod_mask;	/* Bit-mask for particular key modifier */
2201     short	mod_flag;	/* Bit(s) for particular key modifier */
2202     char_u	name;		/* Single letter name of modifier */
2203 } mod_mask_table[] =
2204 {
2205     {MOD_MASK_ALT,		MOD_MASK_ALT,		(char_u)'M'},
2206     {MOD_MASK_META,		MOD_MASK_META,		(char_u)'T'},
2207     {MOD_MASK_CTRL,		MOD_MASK_CTRL,		(char_u)'C'},
2208     {MOD_MASK_SHIFT,		MOD_MASK_SHIFT,		(char_u)'S'},
2209     {MOD_MASK_MULTI_CLICK,	MOD_MASK_2CLICK,	(char_u)'2'},
2210     {MOD_MASK_MULTI_CLICK,	MOD_MASK_3CLICK,	(char_u)'3'},
2211     {MOD_MASK_MULTI_CLICK,	MOD_MASK_4CLICK,	(char_u)'4'},
2212 #ifdef MACOS_X
2213     {MOD_MASK_CMD,		MOD_MASK_CMD,		(char_u)'D'},
2214 #endif
2215     /* 'A' must be the last one */
2216     {MOD_MASK_ALT,		MOD_MASK_ALT,		(char_u)'A'},
2217     {0, 0, NUL}
2218     /* NOTE: when adding an entry, update MAX_KEY_NAME_LEN! */
2219 };
2220 
2221 /*
2222  * Shifted key terminal codes and their unshifted equivalent.
2223  * Don't add mouse codes here, they are handled separately!
2224  */
2225 #define MOD_KEYS_ENTRY_SIZE 5
2226 
2227 static char_u modifier_keys_table[] =
2228 {
2229 /*  mod mask	    with modifier		without modifier */
2230     MOD_MASK_SHIFT, '&', '9',			'@', '1',	/* begin */
2231     MOD_MASK_SHIFT, '&', '0',			'@', '2',	/* cancel */
2232     MOD_MASK_SHIFT, '*', '1',			'@', '4',	/* command */
2233     MOD_MASK_SHIFT, '*', '2',			'@', '5',	/* copy */
2234     MOD_MASK_SHIFT, '*', '3',			'@', '6',	/* create */
2235     MOD_MASK_SHIFT, '*', '4',			'k', 'D',	/* delete char */
2236     MOD_MASK_SHIFT, '*', '5',			'k', 'L',	/* delete line */
2237     MOD_MASK_SHIFT, '*', '7',			'@', '7',	/* end */
2238     MOD_MASK_CTRL,  KS_EXTRA, (int)KE_C_END,	'@', '7',	/* end */
2239     MOD_MASK_SHIFT, '*', '9',			'@', '9',	/* exit */
2240     MOD_MASK_SHIFT, '*', '0',			'@', '0',	/* find */
2241     MOD_MASK_SHIFT, '#', '1',			'%', '1',	/* help */
2242     MOD_MASK_SHIFT, '#', '2',			'k', 'h',	/* home */
2243     MOD_MASK_CTRL,  KS_EXTRA, (int)KE_C_HOME,	'k', 'h',	/* home */
2244     MOD_MASK_SHIFT, '#', '3',			'k', 'I',	/* insert */
2245     MOD_MASK_SHIFT, '#', '4',			'k', 'l',	/* left arrow */
2246     MOD_MASK_CTRL,  KS_EXTRA, (int)KE_C_LEFT,	'k', 'l',	/* left arrow */
2247     MOD_MASK_SHIFT, '%', 'a',			'%', '3',	/* message */
2248     MOD_MASK_SHIFT, '%', 'b',			'%', '4',	/* move */
2249     MOD_MASK_SHIFT, '%', 'c',			'%', '5',	/* next */
2250     MOD_MASK_SHIFT, '%', 'd',			'%', '7',	/* options */
2251     MOD_MASK_SHIFT, '%', 'e',			'%', '8',	/* previous */
2252     MOD_MASK_SHIFT, '%', 'f',			'%', '9',	/* print */
2253     MOD_MASK_SHIFT, '%', 'g',			'%', '0',	/* redo */
2254     MOD_MASK_SHIFT, '%', 'h',			'&', '3',	/* replace */
2255     MOD_MASK_SHIFT, '%', 'i',			'k', 'r',	/* right arr. */
2256     MOD_MASK_CTRL,  KS_EXTRA, (int)KE_C_RIGHT,	'k', 'r',	/* right arr. */
2257     MOD_MASK_SHIFT, '%', 'j',			'&', '5',	/* resume */
2258     MOD_MASK_SHIFT, '!', '1',			'&', '6',	/* save */
2259     MOD_MASK_SHIFT, '!', '2',			'&', '7',	/* suspend */
2260     MOD_MASK_SHIFT, '!', '3',			'&', '8',	/* undo */
2261     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_UP,	'k', 'u',	/* up arrow */
2262     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_DOWN,	'k', 'd',	/* down arrow */
2263 
2264 								/* vt100 F1 */
2265     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF1,	KS_EXTRA, (int)KE_XF1,
2266     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF2,	KS_EXTRA, (int)KE_XF2,
2267     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF3,	KS_EXTRA, (int)KE_XF3,
2268     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_XF4,	KS_EXTRA, (int)KE_XF4,
2269 
2270     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F1,	'k', '1',	/* F1 */
2271     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F2,	'k', '2',
2272     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F3,	'k', '3',
2273     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F4,	'k', '4',
2274     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F5,	'k', '5',
2275     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F6,	'k', '6',
2276     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F7,	'k', '7',
2277     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F8,	'k', '8',
2278     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F9,	'k', '9',
2279     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F10,	'k', ';',	/* F10 */
2280 
2281     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F11,	'F', '1',
2282     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F12,	'F', '2',
2283     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F13,	'F', '3',
2284     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F14,	'F', '4',
2285     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F15,	'F', '5',
2286     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F16,	'F', '6',
2287     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F17,	'F', '7',
2288     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F18,	'F', '8',
2289     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F19,	'F', '9',
2290     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F20,	'F', 'A',
2291 
2292     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F21,	'F', 'B',
2293     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F22,	'F', 'C',
2294     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F23,	'F', 'D',
2295     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F24,	'F', 'E',
2296     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F25,	'F', 'F',
2297     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F26,	'F', 'G',
2298     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F27,	'F', 'H',
2299     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F28,	'F', 'I',
2300     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F29,	'F', 'J',
2301     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F30,	'F', 'K',
2302 
2303     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F31,	'F', 'L',
2304     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F32,	'F', 'M',
2305     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F33,	'F', 'N',
2306     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F34,	'F', 'O',
2307     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F35,	'F', 'P',
2308     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F36,	'F', 'Q',
2309     MOD_MASK_SHIFT, KS_EXTRA, (int)KE_S_F37,	'F', 'R',
2310 
2311 							    /* TAB pseudo code*/
2312     MOD_MASK_SHIFT, 'k', 'B',			KS_EXTRA, (int)KE_TAB,
2313 
2314     NUL
2315 };
2316 
2317 static struct key_name_entry
2318 {
2319     int	    key;	/* Special key code or ascii value */
2320     char_u  *name;	/* Name of key */
2321 } key_names_table[] =
2322 {
2323     {' ',		(char_u *)"Space"},
2324     {TAB,		(char_u *)"Tab"},
2325     {K_TAB,		(char_u *)"Tab"},
2326     {NL,		(char_u *)"NL"},
2327     {NL,		(char_u *)"NewLine"},	/* Alternative name */
2328     {NL,		(char_u *)"LineFeed"},	/* Alternative name */
2329     {NL,		(char_u *)"LF"},	/* Alternative name */
2330     {CAR,		(char_u *)"CR"},
2331     {CAR,		(char_u *)"Return"},	/* Alternative name */
2332     {CAR,		(char_u *)"Enter"},	/* Alternative name */
2333     {K_BS,		(char_u *)"BS"},
2334     {K_BS,		(char_u *)"BackSpace"},	/* Alternative name */
2335     {ESC,		(char_u *)"Esc"},
2336     {CSI,		(char_u *)"CSI"},
2337     {K_CSI,		(char_u *)"xCSI"},
2338     {'|',		(char_u *)"Bar"},
2339     {'\\',		(char_u *)"Bslash"},
2340     {K_DEL,		(char_u *)"Del"},
2341     {K_DEL,		(char_u *)"Delete"},	/* Alternative name */
2342     {K_KDEL,		(char_u *)"kDel"},
2343     {K_UP,		(char_u *)"Up"},
2344     {K_DOWN,		(char_u *)"Down"},
2345     {K_LEFT,		(char_u *)"Left"},
2346     {K_RIGHT,		(char_u *)"Right"},
2347     {K_XUP,		(char_u *)"xUp"},
2348     {K_XDOWN,		(char_u *)"xDown"},
2349     {K_XLEFT,		(char_u *)"xLeft"},
2350     {K_XRIGHT,		(char_u *)"xRight"},
2351     {K_PS,		(char_u *)"PasteStart"},
2352     {K_PE,		(char_u *)"PasteEnd"},
2353 
2354     {K_F1,		(char_u *)"F1"},
2355     {K_F2,		(char_u *)"F2"},
2356     {K_F3,		(char_u *)"F3"},
2357     {K_F4,		(char_u *)"F4"},
2358     {K_F5,		(char_u *)"F5"},
2359     {K_F6,		(char_u *)"F6"},
2360     {K_F7,		(char_u *)"F7"},
2361     {K_F8,		(char_u *)"F8"},
2362     {K_F9,		(char_u *)"F9"},
2363     {K_F10,		(char_u *)"F10"},
2364 
2365     {K_F11,		(char_u *)"F11"},
2366     {K_F12,		(char_u *)"F12"},
2367     {K_F13,		(char_u *)"F13"},
2368     {K_F14,		(char_u *)"F14"},
2369     {K_F15,		(char_u *)"F15"},
2370     {K_F16,		(char_u *)"F16"},
2371     {K_F17,		(char_u *)"F17"},
2372     {K_F18,		(char_u *)"F18"},
2373     {K_F19,		(char_u *)"F19"},
2374     {K_F20,		(char_u *)"F20"},
2375 
2376     {K_F21,		(char_u *)"F21"},
2377     {K_F22,		(char_u *)"F22"},
2378     {K_F23,		(char_u *)"F23"},
2379     {K_F24,		(char_u *)"F24"},
2380     {K_F25,		(char_u *)"F25"},
2381     {K_F26,		(char_u *)"F26"},
2382     {K_F27,		(char_u *)"F27"},
2383     {K_F28,		(char_u *)"F28"},
2384     {K_F29,		(char_u *)"F29"},
2385     {K_F30,		(char_u *)"F30"},
2386 
2387     {K_F31,		(char_u *)"F31"},
2388     {K_F32,		(char_u *)"F32"},
2389     {K_F33,		(char_u *)"F33"},
2390     {K_F34,		(char_u *)"F34"},
2391     {K_F35,		(char_u *)"F35"},
2392     {K_F36,		(char_u *)"F36"},
2393     {K_F37,		(char_u *)"F37"},
2394 
2395     {K_XF1,		(char_u *)"xF1"},
2396     {K_XF2,		(char_u *)"xF2"},
2397     {K_XF3,		(char_u *)"xF3"},
2398     {K_XF4,		(char_u *)"xF4"},
2399 
2400     {K_HELP,		(char_u *)"Help"},
2401     {K_UNDO,		(char_u *)"Undo"},
2402     {K_INS,		(char_u *)"Insert"},
2403     {K_INS,		(char_u *)"Ins"},	/* Alternative name */
2404     {K_KINS,		(char_u *)"kInsert"},
2405     {K_HOME,		(char_u *)"Home"},
2406     {K_KHOME,		(char_u *)"kHome"},
2407     {K_XHOME,		(char_u *)"xHome"},
2408     {K_ZHOME,		(char_u *)"zHome"},
2409     {K_END,		(char_u *)"End"},
2410     {K_KEND,		(char_u *)"kEnd"},
2411     {K_XEND,		(char_u *)"xEnd"},
2412     {K_ZEND,		(char_u *)"zEnd"},
2413     {K_PAGEUP,		(char_u *)"PageUp"},
2414     {K_PAGEDOWN,	(char_u *)"PageDown"},
2415     {K_KPAGEUP,		(char_u *)"kPageUp"},
2416     {K_KPAGEDOWN,	(char_u *)"kPageDown"},
2417 
2418     {K_KPLUS,		(char_u *)"kPlus"},
2419     {K_KMINUS,		(char_u *)"kMinus"},
2420     {K_KDIVIDE,		(char_u *)"kDivide"},
2421     {K_KMULTIPLY,	(char_u *)"kMultiply"},
2422     {K_KENTER,		(char_u *)"kEnter"},
2423     {K_KPOINT,		(char_u *)"kPoint"},
2424 
2425     {K_K0,		(char_u *)"k0"},
2426     {K_K1,		(char_u *)"k1"},
2427     {K_K2,		(char_u *)"k2"},
2428     {K_K3,		(char_u *)"k3"},
2429     {K_K4,		(char_u *)"k4"},
2430     {K_K5,		(char_u *)"k5"},
2431     {K_K6,		(char_u *)"k6"},
2432     {K_K7,		(char_u *)"k7"},
2433     {K_K8,		(char_u *)"k8"},
2434     {K_K9,		(char_u *)"k9"},
2435 
2436     {'<',		(char_u *)"lt"},
2437 
2438     {K_MOUSE,		(char_u *)"Mouse"},
2439 #ifdef FEAT_MOUSE_NET
2440     {K_NETTERM_MOUSE,	(char_u *)"NetMouse"},
2441 #endif
2442 #ifdef FEAT_MOUSE_DEC
2443     {K_DEC_MOUSE,	(char_u *)"DecMouse"},
2444 #endif
2445 #ifdef FEAT_MOUSE_JSB
2446     {K_JSBTERM_MOUSE,	(char_u *)"JsbMouse"},
2447 #endif
2448 #ifdef FEAT_MOUSE_PTERM
2449     {K_PTERM_MOUSE,	(char_u *)"PtermMouse"},
2450 #endif
2451 #ifdef FEAT_MOUSE_URXVT
2452     {K_URXVT_MOUSE,	(char_u *)"UrxvtMouse"},
2453 #endif
2454     {K_SGR_MOUSE,	(char_u *)"SgrMouse"},
2455     {K_SGR_MOUSERELEASE, (char_u *)"SgrMouseRelelase"},
2456     {K_LEFTMOUSE,	(char_u *)"LeftMouse"},
2457     {K_LEFTMOUSE_NM,	(char_u *)"LeftMouseNM"},
2458     {K_LEFTDRAG,	(char_u *)"LeftDrag"},
2459     {K_LEFTRELEASE,	(char_u *)"LeftRelease"},
2460     {K_LEFTRELEASE_NM,	(char_u *)"LeftReleaseNM"},
2461     {K_MOUSEMOVE,	(char_u *)"MouseMove"},
2462     {K_MIDDLEMOUSE,	(char_u *)"MiddleMouse"},
2463     {K_MIDDLEDRAG,	(char_u *)"MiddleDrag"},
2464     {K_MIDDLERELEASE,	(char_u *)"MiddleRelease"},
2465     {K_RIGHTMOUSE,	(char_u *)"RightMouse"},
2466     {K_RIGHTDRAG,	(char_u *)"RightDrag"},
2467     {K_RIGHTRELEASE,	(char_u *)"RightRelease"},
2468     {K_MOUSEDOWN,	(char_u *)"ScrollWheelUp"},
2469     {K_MOUSEUP,		(char_u *)"ScrollWheelDown"},
2470     {K_MOUSELEFT,	(char_u *)"ScrollWheelRight"},
2471     {K_MOUSERIGHT,	(char_u *)"ScrollWheelLeft"},
2472     {K_MOUSEDOWN,	(char_u *)"MouseDown"}, /* OBSOLETE: Use	  */
2473     {K_MOUSEUP,		(char_u *)"MouseUp"},	/* ScrollWheelXXX instead */
2474     {K_X1MOUSE,		(char_u *)"X1Mouse"},
2475     {K_X1DRAG,		(char_u *)"X1Drag"},
2476     {K_X1RELEASE,		(char_u *)"X1Release"},
2477     {K_X2MOUSE,		(char_u *)"X2Mouse"},
2478     {K_X2DRAG,		(char_u *)"X2Drag"},
2479     {K_X2RELEASE,		(char_u *)"X2Release"},
2480     {K_DROP,		(char_u *)"Drop"},
2481     {K_ZERO,		(char_u *)"Nul"},
2482 #ifdef FEAT_EVAL
2483     {K_SNR,		(char_u *)"SNR"},
2484 #endif
2485     {K_PLUG,		(char_u *)"Plug"},
2486     {K_CURSORHOLD,	(char_u *)"CursorHold"},
2487     {K_IGNORE,		(char_u *)"Ignore"},
2488     {0,			NULL}
2489     /* NOTE: When adding a long name update MAX_KEY_NAME_LEN. */
2490 };
2491 
2492 #define KEY_NAMES_TABLE_LEN (sizeof(key_names_table) / sizeof(struct key_name_entry))
2493 
2494 #ifdef FEAT_MOUSE
2495 static struct mousetable
2496 {
2497     int	    pseudo_code;	/* Code for pseudo mouse event */
2498     int	    button;		/* Which mouse button is it? */
2499     int	    is_click;		/* Is it a mouse button click event? */
2500     int	    is_drag;		/* Is it a mouse drag event? */
2501 } mouse_table[] =
2502 {
2503     {(int)KE_LEFTMOUSE,		MOUSE_LEFT,	TRUE,	FALSE},
2504 #ifdef FEAT_GUI
2505     {(int)KE_LEFTMOUSE_NM,	MOUSE_LEFT,	TRUE,	FALSE},
2506 #endif
2507     {(int)KE_LEFTDRAG,		MOUSE_LEFT,	FALSE,	TRUE},
2508     {(int)KE_LEFTRELEASE,	MOUSE_LEFT,	FALSE,	FALSE},
2509 #ifdef FEAT_GUI
2510     {(int)KE_LEFTRELEASE_NM,	MOUSE_LEFT,	FALSE,	FALSE},
2511 #endif
2512     {(int)KE_MIDDLEMOUSE,	MOUSE_MIDDLE,	TRUE,	FALSE},
2513     {(int)KE_MIDDLEDRAG,	MOUSE_MIDDLE,	FALSE,	TRUE},
2514     {(int)KE_MIDDLERELEASE,	MOUSE_MIDDLE,	FALSE,	FALSE},
2515     {(int)KE_RIGHTMOUSE,	MOUSE_RIGHT,	TRUE,	FALSE},
2516     {(int)KE_RIGHTDRAG,		MOUSE_RIGHT,	FALSE,	TRUE},
2517     {(int)KE_RIGHTRELEASE,	MOUSE_RIGHT,	FALSE,	FALSE},
2518     {(int)KE_X1MOUSE,		MOUSE_X1,	TRUE,	FALSE},
2519     {(int)KE_X1DRAG,		MOUSE_X1,	FALSE,	TRUE},
2520     {(int)KE_X1RELEASE,		MOUSE_X1,	FALSE,	FALSE},
2521     {(int)KE_X2MOUSE,		MOUSE_X2,	TRUE,	FALSE},
2522     {(int)KE_X2DRAG,		MOUSE_X2,	FALSE,	TRUE},
2523     {(int)KE_X2RELEASE,		MOUSE_X2,	FALSE,	FALSE},
2524     /* DRAG without CLICK */
2525     {(int)KE_MOUSEMOVE,		MOUSE_RELEASE,	FALSE,	TRUE},
2526     /* RELEASE without CLICK */
2527     {(int)KE_IGNORE,		MOUSE_RELEASE,	FALSE,	FALSE},
2528     {0,				0,		0,	0},
2529 };
2530 #endif /* FEAT_MOUSE */
2531 
2532 /*
2533  * Return the modifier mask bit (MOD_MASK_*) which corresponds to the given
2534  * modifier name ('S' for Shift, 'C' for Ctrl etc).
2535  */
2536     static int
2537 name_to_mod_mask(int c)
2538 {
2539     int	    i;
2540 
2541     c = TOUPPER_ASC(c);
2542     for (i = 0; mod_mask_table[i].mod_mask != 0; i++)
2543 	if (c == mod_mask_table[i].name)
2544 	    return mod_mask_table[i].mod_flag;
2545     return 0;
2546 }
2547 
2548 /*
2549  * Check if if there is a special key code for "key" that includes the
2550  * modifiers specified.
2551  */
2552     int
2553 simplify_key(int key, int *modifiers)
2554 {
2555     int	    i;
2556     int	    key0;
2557     int	    key1;
2558 
2559     if (*modifiers & (MOD_MASK_SHIFT | MOD_MASK_CTRL | MOD_MASK_ALT))
2560     {
2561 	/* TAB is a special case */
2562 	if (key == TAB && (*modifiers & MOD_MASK_SHIFT))
2563 	{
2564 	    *modifiers &= ~MOD_MASK_SHIFT;
2565 	    return K_S_TAB;
2566 	}
2567 	key0 = KEY2TERMCAP0(key);
2568 	key1 = KEY2TERMCAP1(key);
2569 	for (i = 0; modifier_keys_table[i] != NUL; i += MOD_KEYS_ENTRY_SIZE)
2570 	    if (key0 == modifier_keys_table[i + 3]
2571 		    && key1 == modifier_keys_table[i + 4]
2572 		    && (*modifiers & modifier_keys_table[i]))
2573 	    {
2574 		*modifiers &= ~modifier_keys_table[i];
2575 		return TERMCAP2KEY(modifier_keys_table[i + 1],
2576 						   modifier_keys_table[i + 2]);
2577 	    }
2578     }
2579     return key;
2580 }
2581 
2582 /*
2583  * Change <xHome> to <Home>, <xUp> to <Up>, etc.
2584  */
2585     int
2586 handle_x_keys(int key)
2587 {
2588     switch (key)
2589     {
2590 	case K_XUP:	return K_UP;
2591 	case K_XDOWN:	return K_DOWN;
2592 	case K_XLEFT:	return K_LEFT;
2593 	case K_XRIGHT:	return K_RIGHT;
2594 	case K_XHOME:	return K_HOME;
2595 	case K_ZHOME:	return K_HOME;
2596 	case K_XEND:	return K_END;
2597 	case K_ZEND:	return K_END;
2598 	case K_XF1:	return K_F1;
2599 	case K_XF2:	return K_F2;
2600 	case K_XF3:	return K_F3;
2601 	case K_XF4:	return K_F4;
2602 	case K_S_XF1:	return K_S_F1;
2603 	case K_S_XF2:	return K_S_F2;
2604 	case K_S_XF3:	return K_S_F3;
2605 	case K_S_XF4:	return K_S_F4;
2606     }
2607     return key;
2608 }
2609 
2610 /*
2611  * Return a string which contains the name of the given key when the given
2612  * modifiers are down.
2613  */
2614     char_u *
2615 get_special_key_name(int c, int modifiers)
2616 {
2617     static char_u string[MAX_KEY_NAME_LEN + 1];
2618 
2619     int	    i, idx;
2620     int	    table_idx;
2621     char_u  *s;
2622 
2623     string[0] = '<';
2624     idx = 1;
2625 
2626     /* Key that stands for a normal character. */
2627     if (IS_SPECIAL(c) && KEY2TERMCAP0(c) == KS_KEY)
2628 	c = KEY2TERMCAP1(c);
2629 
2630     /*
2631      * Translate shifted special keys into unshifted keys and set modifier.
2632      * Same for CTRL and ALT modifiers.
2633      */
2634     if (IS_SPECIAL(c))
2635     {
2636 	for (i = 0; modifier_keys_table[i] != 0; i += MOD_KEYS_ENTRY_SIZE)
2637 	    if (       KEY2TERMCAP0(c) == (int)modifier_keys_table[i + 1]
2638 		    && (int)KEY2TERMCAP1(c) == (int)modifier_keys_table[i + 2])
2639 	    {
2640 		modifiers |= modifier_keys_table[i];
2641 		c = TERMCAP2KEY(modifier_keys_table[i + 3],
2642 						   modifier_keys_table[i + 4]);
2643 		break;
2644 	    }
2645     }
2646 
2647     /* try to find the key in the special key table */
2648     table_idx = find_special_key_in_table(c);
2649 
2650     /*
2651      * When not a known special key, and not a printable character, try to
2652      * extract modifiers.
2653      */
2654     if (c > 0 && (*mb_char2len)(c) == 1)
2655     {
2656 	if (table_idx < 0
2657 		&& (!vim_isprintc(c) || (c & 0x7f) == ' ')
2658 		&& (c & 0x80))
2659 	{
2660 	    c &= 0x7f;
2661 	    modifiers |= MOD_MASK_ALT;
2662 	    /* try again, to find the un-alted key in the special key table */
2663 	    table_idx = find_special_key_in_table(c);
2664 	}
2665 	if (table_idx < 0 && !vim_isprintc(c) && c < ' ')
2666 	{
2667 #ifdef EBCDIC
2668 	    c = CtrlChar(c);
2669 #else
2670 	    c += '@';
2671 #endif
2672 	    modifiers |= MOD_MASK_CTRL;
2673 	}
2674     }
2675 
2676     /* translate the modifier into a string */
2677     for (i = 0; mod_mask_table[i].name != 'A'; i++)
2678 	if ((modifiers & mod_mask_table[i].mod_mask)
2679 						== mod_mask_table[i].mod_flag)
2680 	{
2681 	    string[idx++] = mod_mask_table[i].name;
2682 	    string[idx++] = (char_u)'-';
2683 	}
2684 
2685     if (table_idx < 0)		/* unknown special key, may output t_xx */
2686     {
2687 	if (IS_SPECIAL(c))
2688 	{
2689 	    string[idx++] = 't';
2690 	    string[idx++] = '_';
2691 	    string[idx++] = KEY2TERMCAP0(c);
2692 	    string[idx++] = KEY2TERMCAP1(c);
2693 	}
2694 	/* Not a special key, only modifiers, output directly */
2695 	else
2696 	{
2697 	    if (has_mbyte && (*mb_char2len)(c) > 1)
2698 		idx += (*mb_char2bytes)(c, string + idx);
2699 	    else if (vim_isprintc(c))
2700 		string[idx++] = c;
2701 	    else
2702 	    {
2703 		s = transchar(c);
2704 		while (*s)
2705 		    string[idx++] = *s++;
2706 	    }
2707 	}
2708     }
2709     else		/* use name of special key */
2710     {
2711 	size_t len = STRLEN(key_names_table[table_idx].name);
2712 
2713 	if (len + idx + 2 <= MAX_KEY_NAME_LEN)
2714 	{
2715 	    STRCPY(string + idx, key_names_table[table_idx].name);
2716 	    idx += (int)len;
2717 	}
2718     }
2719     string[idx++] = '>';
2720     string[idx] = NUL;
2721     return string;
2722 }
2723 
2724 /*
2725  * Try translating a <> name at (*srcp)[] to dst[].
2726  * Return the number of characters added to dst[], zero for no match.
2727  * If there is a match, srcp is advanced to after the <> name.
2728  * dst[] must be big enough to hold the result (up to six characters)!
2729  */
2730     int
2731 trans_special(
2732     char_u	**srcp,
2733     char_u	*dst,
2734     int		keycode,    // prefer key code, e.g. K_DEL instead of DEL
2735     int		in_string)  // TRUE when inside a double quoted string
2736 {
2737     int		modifiers = 0;
2738     int		key;
2739 
2740     key = find_special_key(srcp, &modifiers, keycode, FALSE, in_string);
2741     if (key == 0)
2742 	return 0;
2743 
2744     return special_to_buf(key, modifiers, keycode, dst);
2745 }
2746 
2747 /*
2748  * Put the character sequence for "key" with "modifiers" into "dst" and return
2749  * the resulting length.
2750  * When "keycode" is TRUE prefer key code, e.g. K_DEL instead of DEL.
2751  * The sequence is not NUL terminated.
2752  * This is how characters in a string are encoded.
2753  */
2754     int
2755 special_to_buf(int key, int modifiers, int keycode, char_u *dst)
2756 {
2757     int		dlen = 0;
2758 
2759     /* Put the appropriate modifier in a string */
2760     if (modifiers != 0)
2761     {
2762 	dst[dlen++] = K_SPECIAL;
2763 	dst[dlen++] = KS_MODIFIER;
2764 	dst[dlen++] = modifiers;
2765     }
2766 
2767     if (IS_SPECIAL(key))
2768     {
2769 	dst[dlen++] = K_SPECIAL;
2770 	dst[dlen++] = KEY2TERMCAP0(key);
2771 	dst[dlen++] = KEY2TERMCAP1(key);
2772     }
2773     else if (has_mbyte && !keycode)
2774 	dlen += (*mb_char2bytes)(key, dst + dlen);
2775     else if (keycode)
2776 	dlen = (int)(add_char2buf(key, dst + dlen) - dst);
2777     else
2778 	dst[dlen++] = key;
2779 
2780     return dlen;
2781 }
2782 
2783 /*
2784  * Try translating a <> name at (*srcp)[], return the key and modifiers.
2785  * srcp is advanced to after the <> name.
2786  * returns 0 if there is no match.
2787  */
2788     int
2789 find_special_key(
2790     char_u	**srcp,
2791     int		*modp,
2792     int		keycode,     /* prefer key code, e.g. K_DEL instead of DEL */
2793     int		keep_x_key,  /* don't translate xHome to Home key */
2794     int		in_string)   /* TRUE in string, double quote is escaped */
2795 {
2796     char_u	*last_dash;
2797     char_u	*end_of_name;
2798     char_u	*src;
2799     char_u	*bp;
2800     int		modifiers;
2801     int		bit;
2802     int		key;
2803     uvarnumber_T	n;
2804     int		l;
2805 
2806     src = *srcp;
2807     if (src[0] != '<')
2808 	return 0;
2809 
2810     /* Find end of modifier list */
2811     last_dash = src;
2812     for (bp = src + 1; *bp == '-' || vim_isIDc(*bp); bp++)
2813     {
2814 	if (*bp == '-')
2815 	{
2816 	    last_dash = bp;
2817 	    if (bp[1] != NUL)
2818 	    {
2819 		if (has_mbyte)
2820 		    l = mb_ptr2len(bp + 1);
2821 		else
2822 		    l = 1;
2823 		// Anything accepted, like <C-?>.
2824 		// <C-"> or <M-"> are not special in strings as " is
2825 		// the string delimiter. With a backslash it works: <M-\">
2826 		if (!(in_string && bp[1] == '"') && bp[l + 1] == '>')
2827 		    bp += l;
2828 		else if (in_string && bp[1] == '\\' && bp[2] == '"'
2829 							       && bp[3] == '>')
2830 		    bp += 2;
2831 	    }
2832 	}
2833 	if (bp[0] == 't' && bp[1] == '_' && bp[2] && bp[3])
2834 	    bp += 3;	/* skip t_xx, xx may be '-' or '>' */
2835 	else if (STRNICMP(bp, "char-", 5) == 0)
2836 	{
2837 	    vim_str2nr(bp + 5, NULL, &l, STR2NR_ALL, NULL, NULL, 0, TRUE);
2838 	    if (l == 0)
2839 	    {
2840 		emsg(_(e_invarg));
2841 		return 0;
2842 	    }
2843 	    bp += l + 5;
2844 	    break;
2845 	}
2846     }
2847 
2848     if (*bp == '>')	/* found matching '>' */
2849     {
2850 	end_of_name = bp + 1;
2851 
2852 	/* Which modifiers are given? */
2853 	modifiers = 0x0;
2854 	for (bp = src + 1; bp < last_dash; bp++)
2855 	{
2856 	    if (*bp != '-')
2857 	    {
2858 		bit = name_to_mod_mask(*bp);
2859 		if (bit == 0x0)
2860 		    break;	/* Illegal modifier name */
2861 		modifiers |= bit;
2862 	    }
2863 	}
2864 
2865 	/*
2866 	 * Legal modifier name.
2867 	 */
2868 	if (bp >= last_dash)
2869 	{
2870 	    if (STRNICMP(last_dash + 1, "char-", 5) == 0
2871 						 && VIM_ISDIGIT(last_dash[6]))
2872 	    {
2873 		/* <Char-123> or <Char-033> or <Char-0x33> */
2874 		vim_str2nr(last_dash + 6, NULL, &l, STR2NR_ALL, NULL, &n, 0, TRUE);
2875 		if (l == 0)
2876 		{
2877 		    emsg(_(e_invarg));
2878 		    return 0;
2879 		}
2880 		key = (int)n;
2881 	    }
2882 	    else
2883 	    {
2884 		int off = 1;
2885 
2886 		/* Modifier with single letter, or special key name.  */
2887 		if (in_string && last_dash[1] == '\\' && last_dash[2] == '"')
2888 		    off = 2;
2889 		if (has_mbyte)
2890 		    l = mb_ptr2len(last_dash + off);
2891 		else
2892 		    l = 1;
2893 		if (modifiers != 0 && last_dash[l + off] == '>')
2894 		    key = PTR2CHAR(last_dash + off);
2895 		else
2896 		{
2897 		    key = get_special_key_code(last_dash + off);
2898 		    if (!keep_x_key)
2899 			key = handle_x_keys(key);
2900 		}
2901 	    }
2902 
2903 	    /*
2904 	     * get_special_key_code() may return NUL for invalid
2905 	     * special key name.
2906 	     */
2907 	    if (key != NUL)
2908 	    {
2909 		/*
2910 		 * Only use a modifier when there is no special key code that
2911 		 * includes the modifier.
2912 		 */
2913 		key = simplify_key(key, &modifiers);
2914 
2915 		if (!keycode)
2916 		{
2917 		    /* don't want keycode, use single byte code */
2918 		    if (key == K_BS)
2919 			key = BS;
2920 		    else if (key == K_DEL || key == K_KDEL)
2921 			key = DEL;
2922 		}
2923 
2924 		/*
2925 		 * Normal Key with modifier: Try to make a single byte code.
2926 		 */
2927 		if (!IS_SPECIAL(key))
2928 		    key = extract_modifiers(key, &modifiers);
2929 
2930 		*modp = modifiers;
2931 		*srcp = end_of_name;
2932 		return key;
2933 	    }
2934 	}
2935     }
2936     return 0;
2937 }
2938 
2939 /*
2940  * Try to include modifiers in the key.
2941  * Changes "Shift-a" to 'A', "Alt-A" to 0xc0, etc.
2942  */
2943     int
2944 extract_modifiers(int key, int *modp)
2945 {
2946     int	modifiers = *modp;
2947 
2948 #ifdef MACOS_X
2949     /* Command-key really special, no fancynest */
2950     if (!(modifiers & MOD_MASK_CMD))
2951 #endif
2952     if ((modifiers & MOD_MASK_SHIFT) && ASCII_ISALPHA(key))
2953     {
2954 	key = TOUPPER_ASC(key);
2955 	modifiers &= ~MOD_MASK_SHIFT;
2956     }
2957     if ((modifiers & MOD_MASK_CTRL)
2958 #ifdef EBCDIC
2959 	    /* * TODO: EBCDIC Better use:
2960 	     * && (Ctrl_chr(key) || key == '?')
2961 	     * ???  */
2962 	    && strchr("?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_", key)
2963 						       != NULL
2964 #else
2965 	    && ((key >= '?' && key <= '_') || ASCII_ISALPHA(key))
2966 #endif
2967 	    )
2968     {
2969 	key = Ctrl_chr(key);
2970 	modifiers &= ~MOD_MASK_CTRL;
2971 	/* <C-@> is <Nul> */
2972 	if (key == 0)
2973 	    key = K_ZERO;
2974     }
2975 #ifdef MACOS_X
2976     /* Command-key really special, no fancynest */
2977     if (!(modifiers & MOD_MASK_CMD))
2978 #endif
2979     if ((modifiers & MOD_MASK_ALT) && key < 0x80
2980 	    && !enc_dbcs)		// avoid creating a lead byte
2981     {
2982 	key |= 0x80;
2983 	modifiers &= ~MOD_MASK_ALT;	/* remove the META modifier */
2984     }
2985 
2986     *modp = modifiers;
2987     return key;
2988 }
2989 
2990 /*
2991  * Try to find key "c" in the special key table.
2992  * Return the index when found, -1 when not found.
2993  */
2994     int
2995 find_special_key_in_table(int c)
2996 {
2997     int	    i;
2998 
2999     for (i = 0; key_names_table[i].name != NULL; i++)
3000 	if (c == key_names_table[i].key)
3001 	    break;
3002     if (key_names_table[i].name == NULL)
3003 	i = -1;
3004     return i;
3005 }
3006 
3007 /*
3008  * Find the special key with the given name (the given string does not have to
3009  * end with NUL, the name is assumed to end before the first non-idchar).
3010  * If the name starts with "t_" the next two characters are interpreted as a
3011  * termcap name.
3012  * Return the key code, or 0 if not found.
3013  */
3014     int
3015 get_special_key_code(char_u *name)
3016 {
3017     char_u  *table_name;
3018     char_u  string[3];
3019     int	    i, j;
3020 
3021     /*
3022      * If it's <t_xx> we get the code for xx from the termcap
3023      */
3024     if (name[0] == 't' && name[1] == '_' && name[2] != NUL && name[3] != NUL)
3025     {
3026 	string[0] = name[2];
3027 	string[1] = name[3];
3028 	string[2] = NUL;
3029 	if (add_termcap_entry(string, FALSE) == OK)
3030 	    return TERMCAP2KEY(name[2], name[3]);
3031     }
3032     else
3033 	for (i = 0; key_names_table[i].name != NULL; i++)
3034 	{
3035 	    table_name = key_names_table[i].name;
3036 	    for (j = 0; vim_isIDc(name[j]) && table_name[j] != NUL; j++)
3037 		if (TOLOWER_ASC(table_name[j]) != TOLOWER_ASC(name[j]))
3038 		    break;
3039 	    if (!vim_isIDc(name[j]) && table_name[j] == NUL)
3040 		return key_names_table[i].key;
3041 	}
3042     return 0;
3043 }
3044 
3045     char_u *
3046 get_key_name(int i)
3047 {
3048     if (i >= (int)KEY_NAMES_TABLE_LEN)
3049 	return NULL;
3050     return  key_names_table[i].name;
3051 }
3052 
3053 #if defined(FEAT_MOUSE) || defined(PROTO)
3054 /*
3055  * Look up the given mouse code to return the relevant information in the other
3056  * arguments.  Return which button is down or was released.
3057  */
3058     int
3059 get_mouse_button(int code, int *is_click, int *is_drag)
3060 {
3061     int	    i;
3062 
3063     for (i = 0; mouse_table[i].pseudo_code; i++)
3064 	if (code == mouse_table[i].pseudo_code)
3065 	{
3066 	    *is_click = mouse_table[i].is_click;
3067 	    *is_drag = mouse_table[i].is_drag;
3068 	    return mouse_table[i].button;
3069 	}
3070     return 0;	    /* Shouldn't get here */
3071 }
3072 
3073 /*
3074  * Return the appropriate pseudo mouse event token (KE_LEFTMOUSE etc) based on
3075  * the given information about which mouse button is down, and whether the
3076  * mouse was clicked, dragged or released.
3077  */
3078     int
3079 get_pseudo_mouse_code(
3080     int	    button,	/* eg MOUSE_LEFT */
3081     int	    is_click,
3082     int	    is_drag)
3083 {
3084     int	    i;
3085 
3086     for (i = 0; mouse_table[i].pseudo_code; i++)
3087 	if (button == mouse_table[i].button
3088 	    && is_click == mouse_table[i].is_click
3089 	    && is_drag == mouse_table[i].is_drag)
3090 	{
3091 #ifdef FEAT_GUI
3092 	    /* Trick: a non mappable left click and release has mouse_col -1
3093 	     * or added MOUSE_COLOFF.  Used for 'mousefocus' in
3094 	     * gui_mouse_moved() */
3095 	    if (mouse_col < 0 || mouse_col > MOUSE_COLOFF)
3096 	    {
3097 		if (mouse_col < 0)
3098 		    mouse_col = 0;
3099 		else
3100 		    mouse_col -= MOUSE_COLOFF;
3101 		if (mouse_table[i].pseudo_code == (int)KE_LEFTMOUSE)
3102 		    return (int)KE_LEFTMOUSE_NM;
3103 		if (mouse_table[i].pseudo_code == (int)KE_LEFTRELEASE)
3104 		    return (int)KE_LEFTRELEASE_NM;
3105 	    }
3106 #endif
3107 	    return mouse_table[i].pseudo_code;
3108 	}
3109     return (int)KE_IGNORE;	    /* not recognized, ignore it */
3110 }
3111 #endif /* FEAT_MOUSE */
3112 
3113 /*
3114  * Return the current end-of-line type: EOL_DOS, EOL_UNIX or EOL_MAC.
3115  */
3116     int
3117 get_fileformat(buf_T *buf)
3118 {
3119     int		c = *buf->b_p_ff;
3120 
3121     if (buf->b_p_bin || c == 'u')
3122 	return EOL_UNIX;
3123     if (c == 'm')
3124 	return EOL_MAC;
3125     return EOL_DOS;
3126 }
3127 
3128 /*
3129  * Like get_fileformat(), but override 'fileformat' with "p" for "++opt=val"
3130  * argument.
3131  */
3132     int
3133 get_fileformat_force(
3134     buf_T	*buf,
3135     exarg_T	*eap)	    /* can be NULL! */
3136 {
3137     int		c;
3138 
3139     if (eap != NULL && eap->force_ff != 0)
3140 	c = eap->force_ff;
3141     else
3142     {
3143 	if ((eap != NULL && eap->force_bin != 0)
3144 			       ? (eap->force_bin == FORCE_BIN) : buf->b_p_bin)
3145 	    return EOL_UNIX;
3146 	c = *buf->b_p_ff;
3147     }
3148     if (c == 'u')
3149 	return EOL_UNIX;
3150     if (c == 'm')
3151 	return EOL_MAC;
3152     return EOL_DOS;
3153 }
3154 
3155 /*
3156  * Set the current end-of-line type to EOL_DOS, EOL_UNIX or EOL_MAC.
3157  * Sets both 'textmode' and 'fileformat'.
3158  * Note: Does _not_ set global value of 'textmode'!
3159  */
3160     void
3161 set_fileformat(
3162     int		t,
3163     int		opt_flags)	/* OPT_LOCAL and/or OPT_GLOBAL */
3164 {
3165     char	*p = NULL;
3166 
3167     switch (t)
3168     {
3169     case EOL_DOS:
3170 	p = FF_DOS;
3171 	curbuf->b_p_tx = TRUE;
3172 	break;
3173     case EOL_UNIX:
3174 	p = FF_UNIX;
3175 	curbuf->b_p_tx = FALSE;
3176 	break;
3177     case EOL_MAC:
3178 	p = FF_MAC;
3179 	curbuf->b_p_tx = FALSE;
3180 	break;
3181     }
3182     if (p != NULL)
3183 	set_string_option_direct((char_u *)"ff", -1, (char_u *)p,
3184 						     OPT_FREE | opt_flags, 0);
3185 
3186     /* This may cause the buffer to become (un)modified. */
3187     check_status(curbuf);
3188     redraw_tabline = TRUE;
3189 #ifdef FEAT_TITLE
3190     need_maketitle = TRUE;	    /* set window title later */
3191 #endif
3192 }
3193 
3194 /*
3195  * Return the default fileformat from 'fileformats'.
3196  */
3197     int
3198 default_fileformat(void)
3199 {
3200     switch (*p_ffs)
3201     {
3202 	case 'm':   return EOL_MAC;
3203 	case 'd':   return EOL_DOS;
3204     }
3205     return EOL_UNIX;
3206 }
3207 
3208 /*
3209  * Call shell.	Calls mch_call_shell, with 'shellxquote' added.
3210  */
3211     int
3212 call_shell(char_u *cmd, int opt)
3213 {
3214     char_u	*ncmd;
3215     int		retval;
3216 #ifdef FEAT_PROFILE
3217     proftime_T	wait_time;
3218 #endif
3219 
3220     if (p_verbose > 3)
3221     {
3222 	verbose_enter();
3223 	smsg(_("Calling shell to execute: \"%s\""),
3224 						    cmd == NULL ? p_sh : cmd);
3225 	out_char('\n');
3226 	cursor_on();
3227 	verbose_leave();
3228     }
3229 
3230 #ifdef FEAT_PROFILE
3231     if (do_profiling == PROF_YES)
3232 	prof_child_enter(&wait_time);
3233 #endif
3234 
3235     if (*p_sh == NUL)
3236     {
3237 	emsg(_(e_shellempty));
3238 	retval = -1;
3239     }
3240     else
3241     {
3242 #ifdef FEAT_GUI_MSWIN
3243 	/* Don't hide the pointer while executing a shell command. */
3244 	gui_mch_mousehide(FALSE);
3245 #endif
3246 #ifdef FEAT_GUI
3247 	++hold_gui_events;
3248 #endif
3249 	/* The external command may update a tags file, clear cached tags. */
3250 	tag_freematch();
3251 
3252 	if (cmd == NULL || *p_sxq == NUL)
3253 	    retval = mch_call_shell(cmd, opt);
3254 	else
3255 	{
3256 	    char_u *ecmd = cmd;
3257 
3258 	    if (*p_sxe != NUL && STRCMP(p_sxq, "(") == 0)
3259 	    {
3260 		ecmd = vim_strsave_escaped_ext(cmd, p_sxe, '^', FALSE);
3261 		if (ecmd == NULL)
3262 		    ecmd = cmd;
3263 	    }
3264 	    ncmd = alloc(STRLEN(ecmd) + STRLEN(p_sxq) * 2 + 1);
3265 	    if (ncmd != NULL)
3266 	    {
3267 		STRCPY(ncmd, p_sxq);
3268 		STRCAT(ncmd, ecmd);
3269 		/* When 'shellxquote' is ( append ).
3270 		 * When 'shellxquote' is "( append )". */
3271 		STRCAT(ncmd, STRCMP(p_sxq, "(") == 0 ? (char_u *)")"
3272 			   : STRCMP(p_sxq, "\"(") == 0 ? (char_u *)")\""
3273 			   : p_sxq);
3274 		retval = mch_call_shell(ncmd, opt);
3275 		vim_free(ncmd);
3276 	    }
3277 	    else
3278 		retval = -1;
3279 	    if (ecmd != cmd)
3280 		vim_free(ecmd);
3281 	}
3282 #ifdef FEAT_GUI
3283 	--hold_gui_events;
3284 #endif
3285 	/*
3286 	 * Check the window size, in case it changed while executing the
3287 	 * external command.
3288 	 */
3289 	shell_resized_check();
3290     }
3291 
3292 #ifdef FEAT_EVAL
3293     set_vim_var_nr(VV_SHELL_ERROR, (long)retval);
3294 # ifdef FEAT_PROFILE
3295     if (do_profiling == PROF_YES)
3296 	prof_child_exit(&wait_time);
3297 # endif
3298 #endif
3299 
3300     return retval;
3301 }
3302 
3303 /*
3304  * VISUAL, SELECTMODE and OP_PENDING State are never set, they are equal to
3305  * NORMAL State with a condition.  This function returns the real State.
3306  */
3307     int
3308 get_real_state(void)
3309 {
3310     if (State & NORMAL)
3311     {
3312 	if (VIsual_active)
3313 	{
3314 	    if (VIsual_select)
3315 		return SELECTMODE;
3316 	    return VISUAL;
3317 	}
3318 	else if (finish_op)
3319 	    return OP_PENDING;
3320     }
3321     return State;
3322 }
3323 
3324 /*
3325  * Return TRUE if "p" points to just after a path separator.
3326  * Takes care of multi-byte characters.
3327  * "b" must point to the start of the file name
3328  */
3329     int
3330 after_pathsep(char_u *b, char_u *p)
3331 {
3332     return p > b && vim_ispathsep(p[-1])
3333 			     && (!has_mbyte || (*mb_head_off)(b, p - 1) == 0);
3334 }
3335 
3336 /*
3337  * Return TRUE if file names "f1" and "f2" are in the same directory.
3338  * "f1" may be a short name, "f2" must be a full path.
3339  */
3340     int
3341 same_directory(char_u *f1, char_u *f2)
3342 {
3343     char_u	ffname[MAXPATHL];
3344     char_u	*t1;
3345     char_u	*t2;
3346 
3347     /* safety check */
3348     if (f1 == NULL || f2 == NULL)
3349 	return FALSE;
3350 
3351     (void)vim_FullName(f1, ffname, MAXPATHL, FALSE);
3352     t1 = gettail_sep(ffname);
3353     t2 = gettail_sep(f2);
3354     return (t1 - ffname == t2 - f2
3355 	     && pathcmp((char *)ffname, (char *)f2, (int)(t1 - ffname)) == 0);
3356 }
3357 
3358 #if defined(FEAT_SESSION) || defined(FEAT_AUTOCHDIR) \
3359 	|| defined(MSWIN) || defined(FEAT_GUI_MAC) || defined(FEAT_GUI_GTK) \
3360 	|| defined(FEAT_NETBEANS_INTG) \
3361 	|| defined(PROTO)
3362 /*
3363  * Change to a file's directory.
3364  * Caller must call shorten_fnames()!
3365  * Return OK or FAIL.
3366  */
3367     int
3368 vim_chdirfile(char_u *fname, char *trigger_autocmd)
3369 {
3370     char_u	old_dir[MAXPATHL];
3371     char_u	new_dir[MAXPATHL];
3372     int		res;
3373 
3374     if (mch_dirname(old_dir, MAXPATHL) != OK)
3375 	*old_dir = NUL;
3376 
3377     vim_strncpy(new_dir, fname, MAXPATHL - 1);
3378     *gettail_sep(new_dir) = NUL;
3379 
3380     if (pathcmp((char *)old_dir, (char *)new_dir, -1) == 0)
3381 	// nothing to do
3382 	res = OK;
3383     else
3384     {
3385 	res = mch_chdir((char *)new_dir) == 0 ? OK : FAIL;
3386 
3387 	if (res == OK && trigger_autocmd != NULL)
3388 	    apply_autocmds(EVENT_DIRCHANGED, (char_u *)trigger_autocmd,
3389 						       new_dir, FALSE, curbuf);
3390     }
3391     return res;
3392 }
3393 #endif
3394 
3395 #if defined(STAT_IGNORES_SLASH) || defined(PROTO)
3396 /*
3397  * Check if "name" ends in a slash and is not a directory.
3398  * Used for systems where stat() ignores a trailing slash on a file name.
3399  * The Vim code assumes a trailing slash is only ignored for a directory.
3400  */
3401     static int
3402 illegal_slash(const char *name)
3403 {
3404     if (name[0] == NUL)
3405 	return FALSE;	    /* no file name is not illegal */
3406     if (name[strlen(name) - 1] != '/')
3407 	return FALSE;	    /* no trailing slash */
3408     if (mch_isdir((char_u *)name))
3409 	return FALSE;	    /* trailing slash for a directory */
3410     return TRUE;
3411 }
3412 
3413 /*
3414  * Special implementation of mch_stat() for Solaris.
3415  */
3416     int
3417 vim_stat(const char *name, stat_T *stp)
3418 {
3419     /* On Solaris stat() accepts "file/" as if it was "file".  Return -1 if
3420      * the name ends in "/" and it's not a directory. */
3421     return illegal_slash(name) ? -1 : stat(name, stp);
3422 }
3423 #endif
3424 
3425 #if defined(CURSOR_SHAPE) || defined(PROTO)
3426 
3427 /*
3428  * Handling of cursor and mouse pointer shapes in various modes.
3429  */
3430 
3431 cursorentry_T shape_table[SHAPE_IDX_COUNT] =
3432 {
3433     /* The values will be filled in from the 'guicursor' and 'mouseshape'
3434      * defaults when Vim starts.
3435      * Adjust the SHAPE_IDX_ defines when making changes! */
3436     {0,	0, 0, 700L, 400L, 250L, 0, 0, "n", SHAPE_CURSOR+SHAPE_MOUSE},
3437     {0,	0, 0, 700L, 400L, 250L, 0, 0, "v", SHAPE_CURSOR+SHAPE_MOUSE},
3438     {0,	0, 0, 700L, 400L, 250L, 0, 0, "i", SHAPE_CURSOR+SHAPE_MOUSE},
3439     {0,	0, 0, 700L, 400L, 250L, 0, 0, "r", SHAPE_CURSOR+SHAPE_MOUSE},
3440     {0,	0, 0, 700L, 400L, 250L, 0, 0, "c", SHAPE_CURSOR+SHAPE_MOUSE},
3441     {0,	0, 0, 700L, 400L, 250L, 0, 0, "ci", SHAPE_CURSOR+SHAPE_MOUSE},
3442     {0,	0, 0, 700L, 400L, 250L, 0, 0, "cr", SHAPE_CURSOR+SHAPE_MOUSE},
3443     {0,	0, 0, 700L, 400L, 250L, 0, 0, "o", SHAPE_CURSOR+SHAPE_MOUSE},
3444     {0,	0, 0, 700L, 400L, 250L, 0, 0, "ve", SHAPE_CURSOR+SHAPE_MOUSE},
3445     {0,	0, 0,   0L,   0L,   0L, 0, 0, "e", SHAPE_MOUSE},
3446     {0,	0, 0,   0L,   0L,   0L, 0, 0, "s", SHAPE_MOUSE},
3447     {0,	0, 0,   0L,   0L,   0L, 0, 0, "sd", SHAPE_MOUSE},
3448     {0,	0, 0,   0L,   0L,   0L, 0, 0, "vs", SHAPE_MOUSE},
3449     {0,	0, 0,   0L,   0L,   0L, 0, 0, "vd", SHAPE_MOUSE},
3450     {0,	0, 0,   0L,   0L,   0L, 0, 0, "m", SHAPE_MOUSE},
3451     {0,	0, 0,   0L,   0L,   0L, 0, 0, "ml", SHAPE_MOUSE},
3452     {0,	0, 0, 100L, 100L, 100L, 0, 0, "sm", SHAPE_CURSOR},
3453 };
3454 
3455 #ifdef FEAT_MOUSESHAPE
3456 /*
3457  * Table with names for mouse shapes.  Keep in sync with all the tables for
3458  * mch_set_mouse_shape()!.
3459  */
3460 static char * mshape_names[] =
3461 {
3462     "arrow",	/* default, must be the first one */
3463     "blank",	/* hidden */
3464     "beam",
3465     "updown",
3466     "udsizing",
3467     "leftright",
3468     "lrsizing",
3469     "busy",
3470     "no",
3471     "crosshair",
3472     "hand1",
3473     "hand2",
3474     "pencil",
3475     "question",
3476     "rightup-arrow",
3477     "up-arrow",
3478     NULL
3479 };
3480 #endif
3481 
3482 /*
3483  * Parse the 'guicursor' option ("what" is SHAPE_CURSOR) or 'mouseshape'
3484  * ("what" is SHAPE_MOUSE).
3485  * Returns error message for an illegal option, NULL otherwise.
3486  */
3487     char *
3488 parse_shape_opt(int what)
3489 {
3490     char_u	*modep;
3491     char_u	*colonp;
3492     char_u	*commap;
3493     char_u	*slashp;
3494     char_u	*p, *endp;
3495     int		idx = 0;		/* init for GCC */
3496     int		all_idx;
3497     int		len;
3498     int		i;
3499     long	n;
3500     int		found_ve = FALSE;	/* found "ve" flag */
3501     int		round;
3502 
3503     /*
3504      * First round: check for errors; second round: do it for real.
3505      */
3506     for (round = 1; round <= 2; ++round)
3507     {
3508 	/*
3509 	 * Repeat for all comma separated parts.
3510 	 */
3511 #ifdef FEAT_MOUSESHAPE
3512 	if (what == SHAPE_MOUSE)
3513 	    modep = p_mouseshape;
3514 	else
3515 #endif
3516 	    modep = p_guicursor;
3517 	while (*modep != NUL)
3518 	{
3519 	    colonp = vim_strchr(modep, ':');
3520 	    commap = vim_strchr(modep, ',');
3521 
3522 	    if (colonp == NULL || (commap != NULL && commap < colonp))
3523 		return N_("E545: Missing colon");
3524 	    if (colonp == modep)
3525 		return N_("E546: Illegal mode");
3526 
3527 	    /*
3528 	     * Repeat for all mode's before the colon.
3529 	     * For the 'a' mode, we loop to handle all the modes.
3530 	     */
3531 	    all_idx = -1;
3532 	    while (modep < colonp || all_idx >= 0)
3533 	    {
3534 		if (all_idx < 0)
3535 		{
3536 		    /* Find the mode. */
3537 		    if (modep[1] == '-' || modep[1] == ':')
3538 			len = 1;
3539 		    else
3540 			len = 2;
3541 		    if (len == 1 && TOLOWER_ASC(modep[0]) == 'a')
3542 			all_idx = SHAPE_IDX_COUNT - 1;
3543 		    else
3544 		    {
3545 			for (idx = 0; idx < SHAPE_IDX_COUNT; ++idx)
3546 			    if (STRNICMP(modep, shape_table[idx].name, len)
3547 									 == 0)
3548 				break;
3549 			if (idx == SHAPE_IDX_COUNT
3550 				   || (shape_table[idx].used_for & what) == 0)
3551 			    return N_("E546: Illegal mode");
3552 			if (len == 2 && modep[0] == 'v' && modep[1] == 'e')
3553 			    found_ve = TRUE;
3554 		    }
3555 		    modep += len + 1;
3556 		}
3557 
3558 		if (all_idx >= 0)
3559 		    idx = all_idx--;
3560 		else if (round == 2)
3561 		{
3562 #ifdef FEAT_MOUSESHAPE
3563 		    if (what == SHAPE_MOUSE)
3564 		    {
3565 			/* Set the default, for the missing parts */
3566 			shape_table[idx].mshape = 0;
3567 		    }
3568 		    else
3569 #endif
3570 		    {
3571 			/* Set the defaults, for the missing parts */
3572 			shape_table[idx].shape = SHAPE_BLOCK;
3573 			shape_table[idx].blinkwait = 700L;
3574 			shape_table[idx].blinkon = 400L;
3575 			shape_table[idx].blinkoff = 250L;
3576 		    }
3577 		}
3578 
3579 		/* Parse the part after the colon */
3580 		for (p = colonp + 1; *p && *p != ','; )
3581 		{
3582 #ifdef FEAT_MOUSESHAPE
3583 		    if (what == SHAPE_MOUSE)
3584 		    {
3585 			for (i = 0; ; ++i)
3586 			{
3587 			    if (mshape_names[i] == NULL)
3588 			    {
3589 				if (!VIM_ISDIGIT(*p))
3590 				    return N_("E547: Illegal mouseshape");
3591 				if (round == 2)
3592 				    shape_table[idx].mshape =
3593 					      getdigits(&p) + MSHAPE_NUMBERED;
3594 				else
3595 				    (void)getdigits(&p);
3596 				break;
3597 			    }
3598 			    len = (int)STRLEN(mshape_names[i]);
3599 			    if (STRNICMP(p, mshape_names[i], len) == 0)
3600 			    {
3601 				if (round == 2)
3602 				    shape_table[idx].mshape = i;
3603 				p += len;
3604 				break;
3605 			    }
3606 			}
3607 		    }
3608 		    else /* if (what == SHAPE_MOUSE) */
3609 #endif
3610 		    {
3611 			/*
3612 			 * First handle the ones with a number argument.
3613 			 */
3614 			i = *p;
3615 			len = 0;
3616 			if (STRNICMP(p, "ver", 3) == 0)
3617 			    len = 3;
3618 			else if (STRNICMP(p, "hor", 3) == 0)
3619 			    len = 3;
3620 			else if (STRNICMP(p, "blinkwait", 9) == 0)
3621 			    len = 9;
3622 			else if (STRNICMP(p, "blinkon", 7) == 0)
3623 			    len = 7;
3624 			else if (STRNICMP(p, "blinkoff", 8) == 0)
3625 			    len = 8;
3626 			if (len != 0)
3627 			{
3628 			    p += len;
3629 			    if (!VIM_ISDIGIT(*p))
3630 				return N_("E548: digit expected");
3631 			    n = getdigits(&p);
3632 			    if (len == 3)   /* "ver" or "hor" */
3633 			    {
3634 				if (n == 0)
3635 				    return N_("E549: Illegal percentage");
3636 				if (round == 2)
3637 				{
3638 				    if (TOLOWER_ASC(i) == 'v')
3639 					shape_table[idx].shape = SHAPE_VER;
3640 				    else
3641 					shape_table[idx].shape = SHAPE_HOR;
3642 				    shape_table[idx].percentage = n;
3643 				}
3644 			    }
3645 			    else if (round == 2)
3646 			    {
3647 				if (len == 9)
3648 				    shape_table[idx].blinkwait = n;
3649 				else if (len == 7)
3650 				    shape_table[idx].blinkon = n;
3651 				else
3652 				    shape_table[idx].blinkoff = n;
3653 			    }
3654 			}
3655 			else if (STRNICMP(p, "block", 5) == 0)
3656 			{
3657 			    if (round == 2)
3658 				shape_table[idx].shape = SHAPE_BLOCK;
3659 			    p += 5;
3660 			}
3661 			else	/* must be a highlight group name then */
3662 			{
3663 			    endp = vim_strchr(p, '-');
3664 			    if (commap == NULL)		    /* last part */
3665 			    {
3666 				if (endp == NULL)
3667 				    endp = p + STRLEN(p);   /* find end of part */
3668 			    }
3669 			    else if (endp > commap || endp == NULL)
3670 				endp = commap;
3671 			    slashp = vim_strchr(p, '/');
3672 			    if (slashp != NULL && slashp < endp)
3673 			    {
3674 				/* "group/langmap_group" */
3675 				i = syn_check_group(p, (int)(slashp - p));
3676 				p = slashp + 1;
3677 			    }
3678 			    if (round == 2)
3679 			    {
3680 				shape_table[idx].id = syn_check_group(p,
3681 							     (int)(endp - p));
3682 				shape_table[idx].id_lm = shape_table[idx].id;
3683 				if (slashp != NULL && slashp < endp)
3684 				    shape_table[idx].id = i;
3685 			    }
3686 			    p = endp;
3687 			}
3688 		    } /* if (what != SHAPE_MOUSE) */
3689 
3690 		    if (*p == '-')
3691 			++p;
3692 		}
3693 	    }
3694 	    modep = p;
3695 	    if (*modep == ',')
3696 		++modep;
3697 	}
3698     }
3699 
3700     /* If the 's' flag is not given, use the 'v' cursor for 's' */
3701     if (!found_ve)
3702     {
3703 #ifdef FEAT_MOUSESHAPE
3704 	if (what == SHAPE_MOUSE)
3705 	{
3706 	    shape_table[SHAPE_IDX_VE].mshape = shape_table[SHAPE_IDX_V].mshape;
3707 	}
3708 	else
3709 #endif
3710 	{
3711 	    shape_table[SHAPE_IDX_VE].shape = shape_table[SHAPE_IDX_V].shape;
3712 	    shape_table[SHAPE_IDX_VE].percentage =
3713 					 shape_table[SHAPE_IDX_V].percentage;
3714 	    shape_table[SHAPE_IDX_VE].blinkwait =
3715 					  shape_table[SHAPE_IDX_V].blinkwait;
3716 	    shape_table[SHAPE_IDX_VE].blinkon =
3717 					    shape_table[SHAPE_IDX_V].blinkon;
3718 	    shape_table[SHAPE_IDX_VE].blinkoff =
3719 					   shape_table[SHAPE_IDX_V].blinkoff;
3720 	    shape_table[SHAPE_IDX_VE].id = shape_table[SHAPE_IDX_V].id;
3721 	    shape_table[SHAPE_IDX_VE].id_lm = shape_table[SHAPE_IDX_V].id_lm;
3722 	}
3723     }
3724 
3725     return NULL;
3726 }
3727 
3728 # if defined(MCH_CURSOR_SHAPE) || defined(FEAT_GUI) \
3729 	|| defined(FEAT_MOUSESHAPE) || defined(PROTO)
3730 /*
3731  * Return the index into shape_table[] for the current mode.
3732  * When "mouse" is TRUE, consider indexes valid for the mouse pointer.
3733  */
3734     int
3735 get_shape_idx(int mouse)
3736 {
3737 #ifdef FEAT_MOUSESHAPE
3738     if (mouse && (State == HITRETURN || State == ASKMORE))
3739     {
3740 # ifdef FEAT_GUI
3741 	int x, y;
3742 	gui_mch_getmouse(&x, &y);
3743 	if (Y_2_ROW(y) == Rows - 1)
3744 	    return SHAPE_IDX_MOREL;
3745 # endif
3746 	return SHAPE_IDX_MORE;
3747     }
3748     if (mouse && drag_status_line)
3749 	return SHAPE_IDX_SDRAG;
3750     if (mouse && drag_sep_line)
3751 	return SHAPE_IDX_VDRAG;
3752 #endif
3753     if (!mouse && State == SHOWMATCH)
3754 	return SHAPE_IDX_SM;
3755     if (State & VREPLACE_FLAG)
3756 	return SHAPE_IDX_R;
3757     if (State & REPLACE_FLAG)
3758 	return SHAPE_IDX_R;
3759     if (State & INSERT)
3760 	return SHAPE_IDX_I;
3761     if (State & CMDLINE)
3762     {
3763 	if (cmdline_at_end())
3764 	    return SHAPE_IDX_C;
3765 	if (cmdline_overstrike())
3766 	    return SHAPE_IDX_CR;
3767 	return SHAPE_IDX_CI;
3768     }
3769     if (finish_op)
3770 	return SHAPE_IDX_O;
3771     if (VIsual_active)
3772     {
3773 	if (*p_sel == 'e')
3774 	    return SHAPE_IDX_VE;
3775 	else
3776 	    return SHAPE_IDX_V;
3777     }
3778     return SHAPE_IDX_N;
3779 }
3780 #endif
3781 
3782 # if defined(FEAT_MOUSESHAPE) || defined(PROTO)
3783 static int old_mouse_shape = 0;
3784 
3785 /*
3786  * Set the mouse shape:
3787  * If "shape" is -1, use shape depending on the current mode,
3788  * depending on the current state.
3789  * If "shape" is -2, only update the shape when it's CLINE or STATUS (used
3790  * when the mouse moves off the status or command line).
3791  */
3792     void
3793 update_mouseshape(int shape_idx)
3794 {
3795     int new_mouse_shape;
3796 
3797     /* Only works in GUI mode. */
3798     if (!gui.in_use || gui.starting)
3799 	return;
3800 
3801     /* Postpone the updating when more is to come.  Speeds up executing of
3802      * mappings. */
3803     if (shape_idx == -1 && char_avail())
3804     {
3805 	postponed_mouseshape = TRUE;
3806 	return;
3807     }
3808 
3809     /* When ignoring the mouse don't change shape on the statusline. */
3810     if (*p_mouse == NUL
3811 	    && (shape_idx == SHAPE_IDX_CLINE
3812 		|| shape_idx == SHAPE_IDX_STATUS
3813 		|| shape_idx == SHAPE_IDX_VSEP))
3814 	shape_idx = -2;
3815 
3816     if (shape_idx == -2
3817 	    && old_mouse_shape != shape_table[SHAPE_IDX_CLINE].mshape
3818 	    && old_mouse_shape != shape_table[SHAPE_IDX_STATUS].mshape
3819 	    && old_mouse_shape != shape_table[SHAPE_IDX_VSEP].mshape)
3820 	return;
3821     if (shape_idx < 0)
3822 	new_mouse_shape = shape_table[get_shape_idx(TRUE)].mshape;
3823     else
3824 	new_mouse_shape = shape_table[shape_idx].mshape;
3825     if (new_mouse_shape != old_mouse_shape)
3826     {
3827 	mch_set_mouse_shape(new_mouse_shape);
3828 	old_mouse_shape = new_mouse_shape;
3829     }
3830     postponed_mouseshape = FALSE;
3831 }
3832 # endif
3833 
3834 #endif /* CURSOR_SHAPE */
3835 
3836 
3837 /*
3838  * Change directory to "new_dir".  If FEAT_SEARCHPATH is defined, search
3839  * 'cdpath' for relative directory names, otherwise just mch_chdir().
3840  */
3841     int
3842 vim_chdir(char_u *new_dir)
3843 {
3844 #ifndef FEAT_SEARCHPATH
3845     return mch_chdir((char *)new_dir);
3846 #else
3847     char_u	*dir_name;
3848     int		r;
3849 
3850     dir_name = find_directory_in_path(new_dir, (int)STRLEN(new_dir),
3851 						FNAME_MESS, curbuf->b_ffname);
3852     if (dir_name == NULL)
3853 	return -1;
3854     r = mch_chdir((char *)dir_name);
3855     vim_free(dir_name);
3856     return r;
3857 #endif
3858 }
3859 
3860 /*
3861  * Get user name from machine-specific function.
3862  * Returns the user name in "buf[len]".
3863  * Some systems are quite slow in obtaining the user name (Windows NT), thus
3864  * cache the result.
3865  * Returns OK or FAIL.
3866  */
3867     int
3868 get_user_name(char_u *buf, int len)
3869 {
3870     if (username == NULL)
3871     {
3872 	if (mch_get_user_name(buf, len) == FAIL)
3873 	    return FAIL;
3874 	username = vim_strsave(buf);
3875     }
3876     else
3877 	vim_strncpy(buf, username, len - 1);
3878     return OK;
3879 }
3880 
3881 #ifndef HAVE_QSORT
3882 /*
3883  * Our own qsort(), for systems that don't have it.
3884  * It's simple and slow.  From the K&R C book.
3885  */
3886     void
3887 qsort(
3888     void	*base,
3889     size_t	elm_count,
3890     size_t	elm_size,
3891     int (*cmp)(const void *, const void *))
3892 {
3893     char_u	*buf;
3894     char_u	*p1;
3895     char_u	*p2;
3896     int		i, j;
3897     int		gap;
3898 
3899     buf = alloc(elm_size);
3900     if (buf == NULL)
3901 	return;
3902 
3903     for (gap = elm_count / 2; gap > 0; gap /= 2)
3904 	for (i = gap; i < elm_count; ++i)
3905 	    for (j = i - gap; j >= 0; j -= gap)
3906 	    {
3907 		/* Compare the elements. */
3908 		p1 = (char_u *)base + j * elm_size;
3909 		p2 = (char_u *)base + (j + gap) * elm_size;
3910 		if ((*cmp)((void *)p1, (void *)p2) <= 0)
3911 		    break;
3912 		/* Exchange the elements. */
3913 		mch_memmove(buf, p1, elm_size);
3914 		mch_memmove(p1, p2, elm_size);
3915 		mch_memmove(p2, buf, elm_size);
3916 	    }
3917 
3918     vim_free(buf);
3919 }
3920 #endif
3921 
3922 /*
3923  * Sort an array of strings.
3924  */
3925 static int sort_compare(const void *s1, const void *s2);
3926 
3927     static int
3928 sort_compare(const void *s1, const void *s2)
3929 {
3930     return STRCMP(*(char **)s1, *(char **)s2);
3931 }
3932 
3933     void
3934 sort_strings(
3935     char_u	**files,
3936     int		count)
3937 {
3938     qsort((void *)files, (size_t)count, sizeof(char_u *), sort_compare);
3939 }
3940 
3941 #if !defined(NO_EXPANDPATH) || defined(PROTO)
3942 /*
3943  * Compare path "p[]" to "q[]".
3944  * If "maxlen" >= 0 compare "p[maxlen]" to "q[maxlen]"
3945  * Return value like strcmp(p, q), but consider path separators.
3946  */
3947     int
3948 pathcmp(const char *p, const char *q, int maxlen)
3949 {
3950     int		i, j;
3951     int		c1, c2;
3952     const char	*s = NULL;
3953 
3954     for (i = 0, j = 0; maxlen < 0 || (i < maxlen && j < maxlen);)
3955     {
3956 	c1 = PTR2CHAR((char_u *)p + i);
3957 	c2 = PTR2CHAR((char_u *)q + j);
3958 
3959 	/* End of "p": check if "q" also ends or just has a slash. */
3960 	if (c1 == NUL)
3961 	{
3962 	    if (c2 == NUL)  /* full match */
3963 		return 0;
3964 	    s = q;
3965 	    i = j;
3966 	    break;
3967 	}
3968 
3969 	/* End of "q": check if "p" just has a slash. */
3970 	if (c2 == NUL)
3971 	{
3972 	    s = p;
3973 	    break;
3974 	}
3975 
3976 	if ((p_fic ? MB_TOUPPER(c1) != MB_TOUPPER(c2) : c1 != c2)
3977 #ifdef BACKSLASH_IN_FILENAME
3978 		/* consider '/' and '\\' to be equal */
3979 		&& !((c1 == '/' && c2 == '\\')
3980 		    || (c1 == '\\' && c2 == '/'))
3981 #endif
3982 		)
3983 	{
3984 	    if (vim_ispathsep(c1))
3985 		return -1;
3986 	    if (vim_ispathsep(c2))
3987 		return 1;
3988 	    return p_fic ? MB_TOUPPER(c1) - MB_TOUPPER(c2)
3989 		    : c1 - c2;  /* no match */
3990 	}
3991 
3992 	i += MB_PTR2LEN((char_u *)p + i);
3993 	j += MB_PTR2LEN((char_u *)q + j);
3994     }
3995     if (s == NULL)	/* "i" or "j" ran into "maxlen" */
3996 	return 0;
3997 
3998     c1 = PTR2CHAR((char_u *)s + i);
3999     c2 = PTR2CHAR((char_u *)s + i + MB_PTR2LEN((char_u *)s + i));
4000     /* ignore a trailing slash, but not "//" or ":/" */
4001     if (c2 == NUL
4002 	    && i > 0
4003 	    && !after_pathsep((char_u *)s, (char_u *)s + i)
4004 #ifdef BACKSLASH_IN_FILENAME
4005 	    && (c1 == '/' || c1 == '\\')
4006 #else
4007 	    && c1 == '/'
4008 #endif
4009        )
4010 	return 0;   /* match with trailing slash */
4011     if (s == q)
4012 	return -1;	    /* no match */
4013     return 1;
4014 }
4015 #endif
4016 
4017 /*
4018  * The putenv() implementation below comes from the "screen" program.
4019  * Included with permission from Juergen Weigert.
4020  * See pty.c for the copyright notice.
4021  */
4022 
4023 /*
4024  *  putenv  --	put value into environment
4025  *
4026  *  Usage:  i = putenv (string)
4027  *    int i;
4028  *    char  *string;
4029  *
4030  *  where string is of the form <name>=<value>.
4031  *  Putenv returns 0 normally, -1 on error (not enough core for malloc).
4032  *
4033  *  Putenv may need to add a new name into the environment, or to
4034  *  associate a value longer than the current value with a particular
4035  *  name.  So, to make life simpler, putenv() copies your entire
4036  *  environment into the heap (i.e. malloc()) from the stack
4037  *  (i.e. where it resides when your process is initiated) the first
4038  *  time you call it.
4039  *
4040  *  (history removed, not very interesting.  See the "screen" sources.)
4041  */
4042 
4043 #if !defined(HAVE_SETENV) && !defined(HAVE_PUTENV)
4044 
4045 #define EXTRASIZE 5		/* increment to add to env. size */
4046 
4047 static int  envsize = -1;	/* current size of environment */
4048 extern char **environ;		/* the global which is your env. */
4049 
4050 static int  findenv(char *name); /* look for a name in the env. */
4051 static int  newenv(void);	/* copy env. from stack to heap */
4052 static int  moreenv(void);	/* incr. size of env. */
4053 
4054     int
4055 putenv(const char *string)
4056 {
4057     int	    i;
4058     char    *p;
4059 
4060     if (envsize < 0)
4061     {				/* first time putenv called */
4062 	if (newenv() < 0)	/* copy env. to heap */
4063 	    return -1;
4064     }
4065 
4066     i = findenv((char *)string); /* look for name in environment */
4067 
4068     if (i < 0)
4069     {				/* name must be added */
4070 	for (i = 0; environ[i]; i++);
4071 	if (i >= (envsize - 1))
4072 	{			/* need new slot */
4073 	    if (moreenv() < 0)
4074 		return -1;
4075 	}
4076 	p = alloc(strlen(string) + 1);
4077 	if (p == NULL)		/* not enough core */
4078 	    return -1;
4079 	environ[i + 1] = 0;	/* new end of env. */
4080     }
4081     else
4082     {				/* name already in env. */
4083 	p = vim_realloc(environ[i], strlen(string) + 1);
4084 	if (p == NULL)
4085 	    return -1;
4086     }
4087     sprintf(p, "%s", string);	/* copy into env. */
4088     environ[i] = p;
4089 
4090     return 0;
4091 }
4092 
4093     static int
4094 findenv(char *name)
4095 {
4096     char    *namechar, *envchar;
4097     int	    i, found;
4098 
4099     found = 0;
4100     for (i = 0; environ[i] && !found; i++)
4101     {
4102 	envchar = environ[i];
4103 	namechar = name;
4104 	while (*namechar && *namechar != '=' && (*namechar == *envchar))
4105 	{
4106 	    namechar++;
4107 	    envchar++;
4108 	}
4109 	found = ((*namechar == '\0' || *namechar == '=') && *envchar == '=');
4110     }
4111     return found ? i - 1 : -1;
4112 }
4113 
4114     static int
4115 newenv(void)
4116 {
4117     char    **env, *elem;
4118     int	    i, esize;
4119 
4120     for (i = 0; environ[i]; i++)
4121 	;
4122 
4123     esize = i + EXTRASIZE + 1;
4124     env = ALLOC_MULT(char *, esize);
4125     if (env == NULL)
4126 	return -1;
4127 
4128     for (i = 0; environ[i]; i++)
4129     {
4130 	elem = alloc(strlen(environ[i]) + 1);
4131 	if (elem == NULL)
4132 	    return -1;
4133 	env[i] = elem;
4134 	strcpy(elem, environ[i]);
4135     }
4136 
4137     env[i] = 0;
4138     environ = env;
4139     envsize = esize;
4140     return 0;
4141 }
4142 
4143     static int
4144 moreenv(void)
4145 {
4146     int	    esize;
4147     char    **env;
4148 
4149     esize = envsize + EXTRASIZE;
4150     env = vim_realloc((char *)environ, esize * sizeof (*env));
4151     if (env == 0)
4152 	return -1;
4153     environ = env;
4154     envsize = esize;
4155     return 0;
4156 }
4157 
4158 # ifdef USE_VIMPTY_GETENV
4159 /*
4160  * Used for mch_getenv() for Mac.
4161  */
4162     char_u *
4163 vimpty_getenv(const char_u *string)
4164 {
4165     int i;
4166     char_u *p;
4167 
4168     if (envsize < 0)
4169 	return NULL;
4170 
4171     i = findenv((char *)string);
4172 
4173     if (i < 0)
4174 	return NULL;
4175 
4176     p = vim_strchr((char_u *)environ[i], '=');
4177     return (p + 1);
4178 }
4179 # endif
4180 
4181 #endif /* !defined(HAVE_SETENV) && !defined(HAVE_PUTENV) */
4182 
4183 #if defined(FEAT_EVAL) || defined(FEAT_SPELL) || defined(PROTO)
4184 /*
4185  * Return 0 for not writable, 1 for writable file, 2 for a dir which we have
4186  * rights to write into.
4187  */
4188     int
4189 filewritable(char_u *fname)
4190 {
4191     int		retval = 0;
4192 #if defined(UNIX) || defined(VMS)
4193     int		perm = 0;
4194 #endif
4195 
4196 #if defined(UNIX) || defined(VMS)
4197     perm = mch_getperm(fname);
4198 #endif
4199     if (
4200 # ifdef MSWIN
4201 	    mch_writable(fname) &&
4202 # else
4203 # if defined(UNIX) || defined(VMS)
4204 	    (perm & 0222) &&
4205 #  endif
4206 # endif
4207 	    mch_access((char *)fname, W_OK) == 0
4208        )
4209     {
4210 	++retval;
4211 	if (mch_isdir(fname))
4212 	    ++retval;
4213     }
4214     return retval;
4215 }
4216 #endif
4217 
4218 #if defined(FEAT_SPELL) || defined(FEAT_PERSISTENT_UNDO) || defined(PROTO)
4219 /*
4220  * Read 2 bytes from "fd" and turn them into an int, MSB first.
4221  * Returns -1 when encountering EOF.
4222  */
4223     int
4224 get2c(FILE *fd)
4225 {
4226     int		c, n;
4227 
4228     n = getc(fd);
4229     if (n == EOF) return -1;
4230     c = getc(fd);
4231     if (c == EOF) return -1;
4232     return (n << 8) + c;
4233 }
4234 
4235 /*
4236  * Read 3 bytes from "fd" and turn them into an int, MSB first.
4237  * Returns -1 when encountering EOF.
4238  */
4239     int
4240 get3c(FILE *fd)
4241 {
4242     int		c, n;
4243 
4244     n = getc(fd);
4245     if (n == EOF) return -1;
4246     c = getc(fd);
4247     if (c == EOF) return -1;
4248     n = (n << 8) + c;
4249     c = getc(fd);
4250     if (c == EOF) return -1;
4251     return (n << 8) + c;
4252 }
4253 
4254 /*
4255  * Read 4 bytes from "fd" and turn them into an int, MSB first.
4256  * Returns -1 when encountering EOF.
4257  */
4258     int
4259 get4c(FILE *fd)
4260 {
4261     int		c;
4262     /* Use unsigned rather than int otherwise result is undefined
4263      * when left-shift sets the MSB. */
4264     unsigned	n;
4265 
4266     c = getc(fd);
4267     if (c == EOF) return -1;
4268     n = (unsigned)c;
4269     c = getc(fd);
4270     if (c == EOF) return -1;
4271     n = (n << 8) + (unsigned)c;
4272     c = getc(fd);
4273     if (c == EOF) return -1;
4274     n = (n << 8) + (unsigned)c;
4275     c = getc(fd);
4276     if (c == EOF) return -1;
4277     n = (n << 8) + (unsigned)c;
4278     return (int)n;
4279 }
4280 
4281 /*
4282  * Read 8 bytes from "fd" and turn them into a time_T, MSB first.
4283  * Returns -1 when encountering EOF.
4284  */
4285     time_T
4286 get8ctime(FILE *fd)
4287 {
4288     int		c;
4289     time_T	n = 0;
4290     int		i;
4291 
4292     for (i = 0; i < 8; ++i)
4293     {
4294 	c = getc(fd);
4295 	if (c == EOF) return -1;
4296 	n = (n << 8) + c;
4297     }
4298     return n;
4299 }
4300 
4301 /*
4302  * Read a string of length "cnt" from "fd" into allocated memory.
4303  * Returns NULL when out of memory or unable to read that many bytes.
4304  */
4305     char_u *
4306 read_string(FILE *fd, int cnt)
4307 {
4308     char_u	*str;
4309     int		i;
4310     int		c;
4311 
4312     /* allocate memory */
4313     str = alloc(cnt + 1);
4314     if (str != NULL)
4315     {
4316 	/* Read the string.  Quit when running into the EOF. */
4317 	for (i = 0; i < cnt; ++i)
4318 	{
4319 	    c = getc(fd);
4320 	    if (c == EOF)
4321 	    {
4322 		vim_free(str);
4323 		return NULL;
4324 	    }
4325 	    str[i] = c;
4326 	}
4327 	str[i] = NUL;
4328     }
4329     return str;
4330 }
4331 
4332 /*
4333  * Write a number to file "fd", MSB first, in "len" bytes.
4334  */
4335     int
4336 put_bytes(FILE *fd, long_u nr, int len)
4337 {
4338     int	    i;
4339 
4340     for (i = len - 1; i >= 0; --i)
4341 	if (putc((int)(nr >> (i * 8)), fd) == EOF)
4342 	    return FAIL;
4343     return OK;
4344 }
4345 
4346 #ifdef _MSC_VER
4347 # if (_MSC_VER <= 1200)
4348 /* This line is required for VC6 without the service pack.  Also see the
4349  * matching #pragma below. */
4350  #  pragma optimize("", off)
4351 # endif
4352 #endif
4353 
4354 /*
4355  * Write time_T to file "fd" in 8 bytes.
4356  * Returns FAIL when the write failed.
4357  */
4358     int
4359 put_time(FILE *fd, time_T the_time)
4360 {
4361     char_u	buf[8];
4362 
4363     time_to_bytes(the_time, buf);
4364     return fwrite(buf, (size_t)8, (size_t)1, fd) == 1 ? OK : FAIL;
4365 }
4366 
4367 /*
4368  * Write time_T to "buf[8]".
4369  */
4370     void
4371 time_to_bytes(time_T the_time, char_u *buf)
4372 {
4373     int		c;
4374     int		i;
4375     int		bi = 0;
4376     time_T	wtime = the_time;
4377 
4378     /* time_T can be up to 8 bytes in size, more than long_u, thus we
4379      * can't use put_bytes() here.
4380      * Another problem is that ">>" may do an arithmetic shift that keeps the
4381      * sign.  This happens for large values of wtime.  A cast to long_u may
4382      * truncate if time_T is 8 bytes.  So only use a cast when it is 4 bytes,
4383      * it's safe to assume that long_u is 4 bytes or more and when using 8
4384      * bytes the top bit won't be set. */
4385     for (i = 7; i >= 0; --i)
4386     {
4387 	if (i + 1 > (int)sizeof(time_T))
4388 	    /* ">>" doesn't work well when shifting more bits than avail */
4389 	    buf[bi++] = 0;
4390 	else
4391 	{
4392 #if defined(SIZEOF_TIME_T) && SIZEOF_TIME_T > 4
4393 	    c = (int)(wtime >> (i * 8));
4394 #else
4395 	    c = (int)((long_u)wtime >> (i * 8));
4396 #endif
4397 	    buf[bi++] = c;
4398 	}
4399     }
4400 }
4401 
4402 #ifdef _MSC_VER
4403 # if (_MSC_VER <= 1200)
4404  #  pragma optimize("", on)
4405 # endif
4406 #endif
4407 
4408 #endif
4409 
4410 #if defined(FEAT_QUICKFIX) || defined(FEAT_SPELL) || defined(PROTO)
4411 /*
4412  * Return TRUE if string "s" contains a non-ASCII character (128 or higher).
4413  * When "s" is NULL FALSE is returned.
4414  */
4415     int
4416 has_non_ascii(char_u *s)
4417 {
4418     char_u	*p;
4419 
4420     if (s != NULL)
4421 	for (p = s; *p != NUL; ++p)
4422 	    if (*p >= 128)
4423 		return TRUE;
4424     return FALSE;
4425 }
4426 #endif
4427 
4428 #if defined(MESSAGE_QUEUE) || defined(PROTO)
4429 # define MAX_REPEAT_PARSE 8
4430 
4431 /*
4432  * Process messages that have been queued for netbeans or clientserver.
4433  * Also check if any jobs have ended.
4434  * These functions can call arbitrary vimscript and should only be called when
4435  * it is safe to do so.
4436  */
4437     void
4438 parse_queued_messages(void)
4439 {
4440     int	    old_curwin_id = curwin->w_id;
4441     int	    old_curbuf_fnum = curbuf->b_fnum;
4442     int	    i;
4443     int	    save_may_garbage_collect = may_garbage_collect;
4444 
4445     // Do not handle messages while redrawing, because it may cause buffers to
4446     // change or be wiped while they are being redrawn.
4447     if (updating_screen)
4448 	return;
4449 
4450     // may_garbage_collect is set in main_loop() to do garbage collection when
4451     // blocking to wait on a character.  We don't want that while parsing
4452     // messages, a callback may invoke vgetc() while lists and dicts are in use
4453     // in the call stack.
4454     may_garbage_collect = FALSE;
4455 
4456     // Loop when a job ended, but don't keep looping forever.
4457     for (i = 0; i < MAX_REPEAT_PARSE; ++i)
4458     {
4459 	// For Win32 mch_breakcheck() does not check for input, do it here.
4460 # if defined(MSWIN) && defined(FEAT_JOB_CHANNEL)
4461 	channel_handle_events(FALSE);
4462 # endif
4463 
4464 # ifdef FEAT_NETBEANS_INTG
4465 	// Process the queued netbeans messages.
4466 	netbeans_parse_messages();
4467 # endif
4468 # ifdef FEAT_JOB_CHANNEL
4469 	// Write any buffer lines still to be written.
4470 	channel_write_any_lines();
4471 
4472 	// Process the messages queued on channels.
4473 	channel_parse_messages();
4474 # endif
4475 # if defined(FEAT_CLIENTSERVER) && defined(FEAT_X11)
4476 	// Process the queued clientserver messages.
4477 	server_parse_messages();
4478 # endif
4479 # ifdef FEAT_JOB_CHANNEL
4480 	// Check if any jobs have ended.  If so, repeat the above to handle
4481 	// changes, e.g. stdin may have been closed.
4482 	if (job_check_ended())
4483 	    continue;
4484 # endif
4485 # ifdef FEAT_TERMINAL
4486 	free_unused_terminals();
4487 # endif
4488 # ifdef FEAT_SOUND_CANBERRA
4489 	if (has_sound_callback_in_queue())
4490 	    invoke_sound_callback();
4491 # endif
4492 	break;
4493     }
4494 
4495     may_garbage_collect = save_may_garbage_collect;
4496 
4497     // If the current window or buffer changed we need to bail out of the
4498     // waiting loop.  E.g. when a job exit callback closes the terminal window.
4499     if (curwin->w_id != old_curwin_id || curbuf->b_fnum != old_curbuf_fnum)
4500 	ins_char_typebuf(K_IGNORE);
4501 }
4502 #endif
4503 
4504 #ifndef PROTO  /* proto is defined in vim.h */
4505 # ifdef ELAPSED_TIMEVAL
4506 /*
4507  * Return time in msec since "start_tv".
4508  */
4509     long
4510 elapsed(struct timeval *start_tv)
4511 {
4512     struct timeval  now_tv;
4513 
4514     gettimeofday(&now_tv, NULL);
4515     return (now_tv.tv_sec - start_tv->tv_sec) * 1000L
4516 	 + (now_tv.tv_usec - start_tv->tv_usec) / 1000L;
4517 }
4518 # endif
4519 
4520 # ifdef ELAPSED_TICKCOUNT
4521 /*
4522  * Return time in msec since "start_tick".
4523  */
4524     long
4525 elapsed(DWORD start_tick)
4526 {
4527     DWORD	now = GetTickCount();
4528 
4529     return (long)now - (long)start_tick;
4530 }
4531 # endif
4532 #endif
4533 
4534 #if defined(FEAT_JOB_CHANNEL) \
4535 	|| (defined(UNIX) && (!defined(USE_SYSTEM) \
4536 	|| (defined(FEAT_GUI) && defined(FEAT_TERMINAL)))) \
4537 	|| defined(PROTO)
4538 /*
4539  * Parse "cmd" and put the white-separated parts in "argv".
4540  * "argv" is an allocated array with "argc" entries and room for 4 more.
4541  * Returns FAIL when out of memory.
4542  */
4543     int
4544 mch_parse_cmd(char_u *cmd, int use_shcf, char ***argv, int *argc)
4545 {
4546     int		i;
4547     char_u	*p, *d;
4548     int		inquote;
4549 
4550     /*
4551      * Do this loop twice:
4552      * 1: find number of arguments
4553      * 2: separate them and build argv[]
4554      */
4555     for (i = 0; i < 2; ++i)
4556     {
4557 	p = skipwhite(cmd);
4558 	inquote = FALSE;
4559 	*argc = 0;
4560 	for (;;)
4561 	{
4562 	    if (i == 1)
4563 		(*argv)[*argc] = (char *)p;
4564 	    ++*argc;
4565 	    d = p;
4566 	    while (*p != NUL && (inquote || (*p != ' ' && *p != TAB)))
4567 	    {
4568 		if (p[0] == '"')
4569 		    // quotes surrounding an argument and are dropped
4570 		    inquote = !inquote;
4571 		else
4572 		{
4573 		    if (rem_backslash(p))
4574 		    {
4575 			// First pass: skip over "\ " and "\"".
4576 			// Second pass: Remove the backslash.
4577 			++p;
4578 		    }
4579 		    if (i == 1)
4580 			*d++ = *p;
4581 		}
4582 		++p;
4583 	    }
4584 	    if (*p == NUL)
4585 	    {
4586 		if (i == 1)
4587 		    *d++ = NUL;
4588 		break;
4589 	    }
4590 	    if (i == 1)
4591 		*d++ = NUL;
4592 	    p = skipwhite(p + 1);
4593 	}
4594 	if (*argv == NULL)
4595 	{
4596 	    if (use_shcf)
4597 	    {
4598 		/* Account for possible multiple args in p_shcf. */
4599 		p = p_shcf;
4600 		for (;;)
4601 		{
4602 		    p = skiptowhite(p);
4603 		    if (*p == NUL)
4604 			break;
4605 		    ++*argc;
4606 		    p = skipwhite(p);
4607 		}
4608 	    }
4609 
4610 	    *argv = ALLOC_MULT(char *, *argc + 4);
4611 	    if (*argv == NULL)	    /* out of memory */
4612 		return FAIL;
4613 	}
4614     }
4615     return OK;
4616 }
4617 
4618 # if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
4619 /*
4620  * Build "argv[argc]" from the string "cmd".
4621  * "argv[argc]" is set to NULL;
4622  * Return FAIL when out of memory.
4623  */
4624     int
4625 build_argv_from_string(char_u *cmd, char ***argv, int *argc)
4626 {
4627     char_u	*cmd_copy;
4628     int		i;
4629 
4630     /* Make a copy, parsing will modify "cmd". */
4631     cmd_copy = vim_strsave(cmd);
4632     if (cmd_copy == NULL
4633 	    || mch_parse_cmd(cmd_copy, FALSE, argv, argc) == FAIL)
4634     {
4635 	vim_free(cmd_copy);
4636 	return FAIL;
4637     }
4638     for (i = 0; i < *argc; i++)
4639 	(*argv)[i] = (char *)vim_strsave((char_u *)(*argv)[i]);
4640     (*argv)[*argc] = NULL;
4641     vim_free(cmd_copy);
4642     return OK;
4643 }
4644 
4645 /*
4646  * Build "argv[argc]" from the list "l".
4647  * "argv[argc]" is set to NULL;
4648  * Return FAIL when out of memory.
4649  */
4650     int
4651 build_argv_from_list(list_T *l, char ***argv, int *argc)
4652 {
4653     listitem_T  *li;
4654     char_u	*s;
4655 
4656     /* Pass argv[] to mch_call_shell(). */
4657     *argv = ALLOC_MULT(char *, l->lv_len + 1);
4658     if (*argv == NULL)
4659 	return FAIL;
4660     *argc = 0;
4661     for (li = l->lv_first; li != NULL; li = li->li_next)
4662     {
4663 	s = tv_get_string_chk(&li->li_tv);
4664 	if (s == NULL)
4665 	{
4666 	    int i;
4667 
4668 	    for (i = 0; i < *argc; ++i)
4669 		vim_free((*argv)[i]);
4670 	    return FAIL;
4671 	}
4672 	(*argv)[*argc] = (char *)vim_strsave(s);
4673 	*argc += 1;
4674     }
4675     (*argv)[*argc] = NULL;
4676     return OK;
4677 }
4678 # endif
4679 #endif
4680