xref: /vim-8.2.3635/src/misc1.c (revision a0122dcd)
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  * misc1.c: functions that didn't seem to fit elsewhere
12  */
13 
14 #include "vim.h"
15 #include "version.h"
16 
17 #if defined(__HAIKU__)
18 # include <storage/FindDirectory.h>
19 #endif
20 
21 #if defined(MSWIN)
22 # include <lm.h>
23 #endif
24 
25 #define URL_SLASH	1		// path_is_url() has found "://"
26 #define URL_BACKSLASH	2		// path_is_url() has found ":\\"
27 
28 // All user names (for ~user completion as done by shell).
29 static garray_T	ga_users;
30 
31 /*
32  * get_leader_len() returns the length in bytes of the prefix of the given
33  * string which introduces a comment.  If this string is not a comment then
34  * 0 is returned.
35  * When "flags" is not NULL, it is set to point to the flags of the recognized
36  * comment leader.
37  * "backward" must be true for the "O" command.
38  * If "include_space" is set, include trailing whitespace while calculating the
39  * length.
40  */
41     int
42 get_leader_len(
43     char_u	*line,
44     char_u	**flags,
45     int		backward,
46     int		include_space)
47 {
48     int		i, j;
49     int		result;
50     int		got_com = FALSE;
51     int		found_one;
52     char_u	part_buf[COM_MAX_LEN];	// buffer for one option part
53     char_u	*string;		// pointer to comment string
54     char_u	*list;
55     int		middle_match_len = 0;
56     char_u	*prev_list;
57     char_u	*saved_flags = NULL;
58 
59     result = i = 0;
60     while (VIM_ISWHITE(line[i]))    // leading white space is ignored
61 	++i;
62 
63     /*
64      * Repeat to match several nested comment strings.
65      */
66     while (line[i] != NUL)
67     {
68 	/*
69 	 * scan through the 'comments' option for a match
70 	 */
71 	found_one = FALSE;
72 	for (list = curbuf->b_p_com; *list; )
73 	{
74 	    // Get one option part into part_buf[].  Advance "list" to next
75 	    // one.  Put "string" at start of string.
76 	    if (!got_com && flags != NULL)
77 		*flags = list;	    // remember where flags started
78 	    prev_list = list;
79 	    (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
80 	    string = vim_strchr(part_buf, ':');
81 	    if (string == NULL)	    // missing ':', ignore this part
82 		continue;
83 	    *string++ = NUL;	    // isolate flags from string
84 
85 	    // If we found a middle match previously, use that match when this
86 	    // is not a middle or end.
87 	    if (middle_match_len != 0
88 		    && vim_strchr(part_buf, COM_MIDDLE) == NULL
89 		    && vim_strchr(part_buf, COM_END) == NULL)
90 		break;
91 
92 	    // When we already found a nested comment, only accept further
93 	    // nested comments.
94 	    if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
95 		continue;
96 
97 	    // When 'O' flag present and using "O" command skip this one.
98 	    if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
99 		continue;
100 
101 	    // Line contents and string must match.
102 	    // When string starts with white space, must have some white space
103 	    // (but the amount does not need to match, there might be a mix of
104 	    // TABs and spaces).
105 	    if (VIM_ISWHITE(string[0]))
106 	    {
107 		if (i == 0 || !VIM_ISWHITE(line[i - 1]))
108 		    continue;  // missing white space
109 		while (VIM_ISWHITE(string[0]))
110 		    ++string;
111 	    }
112 	    for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
113 		;
114 	    if (string[j] != NUL)
115 		continue;  // string doesn't match
116 
117 	    // When 'b' flag used, there must be white space or an
118 	    // end-of-line after the string in the line.
119 	    if (vim_strchr(part_buf, COM_BLANK) != NULL
120 			   && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
121 		continue;
122 
123 	    // We have found a match, stop searching unless this is a middle
124 	    // comment. The middle comment can be a substring of the end
125 	    // comment in which case it's better to return the length of the
126 	    // end comment and its flags.  Thus we keep searching with middle
127 	    // and end matches and use an end match if it matches better.
128 	    if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
129 	    {
130 		if (middle_match_len == 0)
131 		{
132 		    middle_match_len = j;
133 		    saved_flags = prev_list;
134 		}
135 		continue;
136 	    }
137 	    if (middle_match_len != 0 && j > middle_match_len)
138 		// Use this match instead of the middle match, since it's a
139 		// longer thus better match.
140 		middle_match_len = 0;
141 
142 	    if (middle_match_len == 0)
143 		i += j;
144 	    found_one = TRUE;
145 	    break;
146 	}
147 
148 	if (middle_match_len != 0)
149 	{
150 	    // Use the previously found middle match after failing to find a
151 	    // match with an end.
152 	    if (!got_com && flags != NULL)
153 		*flags = saved_flags;
154 	    i += middle_match_len;
155 	    found_one = TRUE;
156 	}
157 
158 	// No match found, stop scanning.
159 	if (!found_one)
160 	    break;
161 
162 	result = i;
163 
164 	// Include any trailing white space.
165 	while (VIM_ISWHITE(line[i]))
166 	    ++i;
167 
168 	if (include_space)
169 	    result = i;
170 
171 	// If this comment doesn't nest, stop here.
172 	got_com = TRUE;
173 	if (vim_strchr(part_buf, COM_NEST) == NULL)
174 	    break;
175     }
176     return result;
177 }
178 
179 /*
180  * Return the offset at which the last comment in line starts. If there is no
181  * comment in the whole line, -1 is returned.
182  *
183  * When "flags" is not null, it is set to point to the flags describing the
184  * recognized comment leader.
185  */
186     int
187 get_last_leader_offset(char_u *line, char_u **flags)
188 {
189     int		result = -1;
190     int		i, j;
191     int		lower_check_bound = 0;
192     char_u	*string;
193     char_u	*com_leader;
194     char_u	*com_flags;
195     char_u	*list;
196     int		found_one;
197     char_u	part_buf[COM_MAX_LEN];	// buffer for one option part
198 
199     /*
200      * Repeat to match several nested comment strings.
201      */
202     i = (int)STRLEN(line);
203     while (--i >= lower_check_bound)
204     {
205 	/*
206 	 * scan through the 'comments' option for a match
207 	 */
208 	found_one = FALSE;
209 	for (list = curbuf->b_p_com; *list; )
210 	{
211 	    char_u *flags_save = list;
212 
213 	    /*
214 	     * Get one option part into part_buf[].  Advance list to next one.
215 	     * put string at start of string.
216 	     */
217 	    (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
218 	    string = vim_strchr(part_buf, ':');
219 	    if (string == NULL)	// If everything is fine, this cannot actually
220 				// happen.
221 		continue;
222 	    *string++ = NUL;	// Isolate flags from string.
223 	    com_leader = string;
224 
225 	    /*
226 	     * Line contents and string must match.
227 	     * When string starts with white space, must have some white space
228 	     * (but the amount does not need to match, there might be a mix of
229 	     * TABs and spaces).
230 	     */
231 	    if (VIM_ISWHITE(string[0]))
232 	    {
233 		if (i == 0 || !VIM_ISWHITE(line[i - 1]))
234 		    continue;
235 		while (VIM_ISWHITE(*string))
236 		    ++string;
237 	    }
238 	    for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
239 		/* do nothing */;
240 	    if (string[j] != NUL)
241 		continue;
242 
243 	    /*
244 	     * When 'b' flag used, there must be white space or an
245 	     * end-of-line after the string in the line.
246 	     */
247 	    if (vim_strchr(part_buf, COM_BLANK) != NULL
248 		    && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
249 		continue;
250 
251 	    if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
252 	    {
253 		// For a middlepart comment, only consider it to match if
254 		// everything before the current position in the line is
255 		// whitespace.  Otherwise we would think we are inside a
256 		// comment if the middle part appears somewhere in the middle
257 		// of the line.  E.g. for C the "*" appears often.
258 		for (j = 0; VIM_ISWHITE(line[j]) && j <= i; j++)
259 		    ;
260 		if (j < i)
261 		    continue;
262 	    }
263 
264 	    /*
265 	     * We have found a match, stop searching.
266 	     */
267 	    found_one = TRUE;
268 
269 	    if (flags)
270 		*flags = flags_save;
271 	    com_flags = flags_save;
272 
273 	    break;
274 	}
275 
276 	if (found_one)
277 	{
278 	    char_u  part_buf2[COM_MAX_LEN];	// buffer for one option part
279 	    int     len1, len2, off;
280 
281 	    result = i;
282 	    /*
283 	     * If this comment nests, continue searching.
284 	     */
285 	    if (vim_strchr(part_buf, COM_NEST) != NULL)
286 		continue;
287 
288 	    lower_check_bound = i;
289 
290 	    // Let's verify whether the comment leader found is a substring
291 	    // of other comment leaders. If it is, let's adjust the
292 	    // lower_check_bound so that we make sure that we have determined
293 	    // the comment leader correctly.
294 
295 	    while (VIM_ISWHITE(*com_leader))
296 		++com_leader;
297 	    len1 = (int)STRLEN(com_leader);
298 
299 	    for (list = curbuf->b_p_com; *list; )
300 	    {
301 		char_u *flags_save = list;
302 
303 		(void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
304 		if (flags_save == com_flags)
305 		    continue;
306 		string = vim_strchr(part_buf2, ':');
307 		++string;
308 		while (VIM_ISWHITE(*string))
309 		    ++string;
310 		len2 = (int)STRLEN(string);
311 		if (len2 == 0)
312 		    continue;
313 
314 		// Now we have to verify whether string ends with a substring
315 		// beginning the com_leader.
316 		for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
317 		{
318 		    --off;
319 		    if (!STRNCMP(string + off, com_leader, len2 - off))
320 		    {
321 			if (i - off < lower_check_bound)
322 			    lower_check_bound = i - off;
323 		    }
324 		}
325 	    }
326 	}
327     }
328     return result;
329 }
330 
331 /*
332  * Return the number of window lines occupied by buffer line "lnum".
333  */
334     int
335 plines(linenr_T lnum)
336 {
337     return plines_win(curwin, lnum, TRUE);
338 }
339 
340     int
341 plines_win(
342     win_T	*wp,
343     linenr_T	lnum,
344     int		winheight)	// when TRUE limit to window height
345 {
346 #if defined(FEAT_DIFF) || defined(PROTO)
347     // Check for filler lines above this buffer line.  When folded the result
348     // is one line anyway.
349     return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
350 }
351 
352     int
353 plines_nofill(linenr_T lnum)
354 {
355     return plines_win_nofill(curwin, lnum, TRUE);
356 }
357 
358     int
359 plines_win_nofill(
360     win_T	*wp,
361     linenr_T	lnum,
362     int		winheight)	// when TRUE limit to window height
363 {
364 #endif
365     int		lines;
366 
367     if (!wp->w_p_wrap)
368 	return 1;
369 
370     if (wp->w_width == 0)
371 	return 1;
372 
373 #ifdef FEAT_FOLDING
374     // A folded lines is handled just like an empty line.
375     // NOTE: Caller must handle lines that are MAYBE folded.
376     if (lineFolded(wp, lnum) == TRUE)
377 	return 1;
378 #endif
379 
380     lines = plines_win_nofold(wp, lnum);
381     if (winheight > 0 && lines > wp->w_height)
382 	return (int)wp->w_height;
383     return lines;
384 }
385 
386 /*
387  * Return number of window lines physical line "lnum" will occupy in window
388  * "wp".  Does not care about folding, 'wrap' or 'diff'.
389  */
390     int
391 plines_win_nofold(win_T *wp, linenr_T lnum)
392 {
393     char_u	*s;
394     long	col;
395     int		width;
396 
397     s = ml_get_buf(wp->w_buffer, lnum, FALSE);
398     if (*s == NUL)		// empty line
399 	return 1;
400     col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
401 
402     /*
403      * If list mode is on, then the '$' at the end of the line may take up one
404      * extra column.
405      */
406     if (wp->w_p_list && lcs_eol != NUL)
407 	col += 1;
408 
409     /*
410      * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
411      */
412     width = wp->w_width - win_col_off(wp);
413     if (width <= 0)
414 	return 32000;
415     if (col <= width)
416 	return 1;
417     col -= width;
418     width += win_col_off2(wp);
419     return (col + (width - 1)) / width + 1;
420 }
421 
422 /*
423  * Like plines_win(), but only reports the number of physical screen lines
424  * used from the start of the line to the given column number.
425  */
426     int
427 plines_win_col(win_T *wp, linenr_T lnum, long column)
428 {
429     long	col;
430     char_u	*s;
431     int		lines = 0;
432     int		width;
433     char_u	*line;
434 
435 #ifdef FEAT_DIFF
436     // Check for filler lines above this buffer line.  When folded the result
437     // is one line anyway.
438     lines = diff_check_fill(wp, lnum);
439 #endif
440 
441     if (!wp->w_p_wrap)
442 	return lines + 1;
443 
444     if (wp->w_width == 0)
445 	return lines + 1;
446 
447     line = s = ml_get_buf(wp->w_buffer, lnum, FALSE);
448 
449     col = 0;
450     while (*s != NUL && --column >= 0)
451     {
452 	col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL);
453 	MB_PTR_ADV(s);
454     }
455 
456     /*
457      * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
458      * INSERT mode, then col must be adjusted so that it represents the last
459      * screen position of the TAB.  This only fixes an error when the TAB wraps
460      * from one screen line to the next (when 'columns' is not a multiple of
461      * 'ts') -- webb.
462      */
463     if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
464 	col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL) - 1;
465 
466     /*
467      * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
468      */
469     width = wp->w_width - win_col_off(wp);
470     if (width <= 0)
471 	return 9999;
472 
473     lines += 1;
474     if (col > width)
475 	lines += (col - width) / (width + win_col_off2(wp)) + 1;
476     return lines;
477 }
478 
479     int
480 plines_m_win(win_T *wp, linenr_T first, linenr_T last)
481 {
482     int		count = 0;
483 
484     while (first <= last)
485     {
486 #ifdef FEAT_FOLDING
487 	int	x;
488 
489 	// Check if there are any really folded lines, but also included lines
490 	// that are maybe folded.
491 	x = foldedCount(wp, first, NULL);
492 	if (x > 0)
493 	{
494 	    ++count;	    // count 1 for "+-- folded" line
495 	    first += x;
496 	}
497 	else
498 #endif
499 	{
500 #ifdef FEAT_DIFF
501 	    if (first == wp->w_topline)
502 		count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
503 	    else
504 #endif
505 		count += plines_win(wp, first, TRUE);
506 	    ++first;
507 	}
508     }
509     return (count);
510 }
511 
512     int
513 gchar_pos(pos_T *pos)
514 {
515     char_u	*ptr;
516 
517     // When searching columns is sometimes put at the end of a line.
518     if (pos->col == MAXCOL)
519 	return NUL;
520     ptr = ml_get_pos(pos);
521     if (has_mbyte)
522 	return (*mb_ptr2char)(ptr);
523     return (int)*ptr;
524 }
525 
526     int
527 gchar_cursor(void)
528 {
529     if (has_mbyte)
530 	return (*mb_ptr2char)(ml_get_cursor());
531     return (int)*ml_get_cursor();
532 }
533 
534 /*
535  * Write a character at the current cursor position.
536  * It is directly written into the block.
537  */
538     void
539 pchar_cursor(int c)
540 {
541     *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
542 						  + curwin->w_cursor.col) = c;
543 }
544 
545 /*
546  * Skip to next part of an option argument: Skip space and comma.
547  */
548     char_u *
549 skip_to_option_part(char_u *p)
550 {
551     if (*p == ',')
552 	++p;
553     while (*p == ' ')
554 	++p;
555     return p;
556 }
557 
558 /*
559  * check_status: called when the status bars for the buffer 'buf'
560  *		 need to be updated
561  */
562     void
563 check_status(buf_T *buf)
564 {
565     win_T	*wp;
566 
567     FOR_ALL_WINDOWS(wp)
568 	if (wp->w_buffer == buf && wp->w_status_height)
569 	{
570 	    wp->w_redr_status = TRUE;
571 	    if (must_redraw < VALID)
572 		must_redraw = VALID;
573 	}
574 }
575 
576 /*
577  * Ask for a reply from the user, a 'y' or a 'n'.
578  * No other characters are accepted, the message is repeated until a valid
579  * reply is entered or CTRL-C is hit.
580  * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
581  * from any buffers but directly from the user.
582  *
583  * return the 'y' or 'n'
584  */
585     int
586 ask_yesno(char_u *str, int direct)
587 {
588     int	    r = ' ';
589     int	    save_State = State;
590 
591     if (exiting)		// put terminal in raw mode for this question
592 	settmode(TMODE_RAW);
593     ++no_wait_return;
594 #ifdef USE_ON_FLY_SCROLL
595     dont_scroll = TRUE;		// disallow scrolling here
596 #endif
597     State = CONFIRM;		// mouse behaves like with :confirm
598     setmouse();			// disables mouse for xterm
599     ++no_mapping;
600     ++allow_keys;		// no mapping here, but recognize keys
601 
602     while (r != 'y' && r != 'n')
603     {
604 	// same highlighting as for wait_return
605 	smsg_attr(HL_ATTR(HLF_R), "%s (y/n)?", str);
606 	if (direct)
607 	    r = get_keystroke();
608 	else
609 	    r = plain_vgetc();
610 	if (r == Ctrl_C || r == ESC)
611 	    r = 'n';
612 	msg_putchar(r);	    // show what you typed
613 	out_flush();
614     }
615     --no_wait_return;
616     State = save_State;
617     setmouse();
618     --no_mapping;
619     --allow_keys;
620 
621     return r;
622 }
623 
624 #if defined(FEAT_EVAL) || defined(PROTO)
625 
626 /*
627  * "mode()" function
628  */
629     void
630 f_mode(typval_T *argvars, typval_T *rettv)
631 {
632     char_u	buf[4];
633 
634     CLEAR_FIELD(buf);
635 
636     if (time_for_testing == 93784)
637     {
638 	// Testing the two-character code.
639 	buf[0] = 'x';
640 	buf[1] = '!';
641     }
642 #ifdef FEAT_TERMINAL
643     else if (term_use_loop())
644 	buf[0] = 't';
645 #endif
646     else if (VIsual_active)
647     {
648 	if (VIsual_select)
649 	    buf[0] = VIsual_mode + 's' - 'v';
650 	else
651 	    buf[0] = VIsual_mode;
652     }
653     else if (State == HITRETURN || State == ASKMORE || State == SETWSIZE
654 		|| State == CONFIRM)
655     {
656 	buf[0] = 'r';
657 	if (State == ASKMORE)
658 	    buf[1] = 'm';
659 	else if (State == CONFIRM)
660 	    buf[1] = '?';
661     }
662     else if (State == EXTERNCMD)
663 	buf[0] = '!';
664     else if (State & INSERT)
665     {
666 	if (State & VREPLACE_FLAG)
667 	{
668 	    buf[0] = 'R';
669 	    buf[1] = 'v';
670 	}
671 	else
672 	{
673 	    if (State & REPLACE_FLAG)
674 		buf[0] = 'R';
675 	    else
676 		buf[0] = 'i';
677 	    if (ins_compl_active())
678 		buf[1] = 'c';
679 	    else if (ctrl_x_mode_not_defined_yet())
680 		buf[1] = 'x';
681 	}
682     }
683     else if ((State & CMDLINE) || exmode_active)
684     {
685 	buf[0] = 'c';
686 	if (exmode_active == EXMODE_VIM)
687 	    buf[1] = 'v';
688 	else if (exmode_active == EXMODE_NORMAL)
689 	    buf[1] = 'e';
690     }
691     else
692     {
693 	buf[0] = 'n';
694 	if (finish_op)
695 	{
696 	    buf[1] = 'o';
697 	    // to be able to detect force-linewise/blockwise/characterwise operations
698 	    buf[2] = motion_force;
699 	}
700 	else if (restart_edit == 'I' || restart_edit == 'R'
701 							|| restart_edit == 'V')
702 	{
703 	    buf[1] = 'i';
704 	    buf[2] = restart_edit;
705 	}
706     }
707 
708     // Clear out the minor mode when the argument is not a non-zero number or
709     // non-empty string.
710     if (!non_zero_arg(&argvars[0]))
711 	buf[1] = NUL;
712 
713     rettv->vval.v_string = vim_strsave(buf);
714     rettv->v_type = VAR_STRING;
715 }
716 
717     static void
718 may_add_state_char(garray_T *gap, char_u *include, int c)
719 {
720     if (include == NULL || vim_strchr(include, c) != NULL)
721 	ga_append(gap, c);
722 }
723 
724 /*
725  * "state()" function
726  */
727     void
728 f_state(typval_T *argvars, typval_T *rettv)
729 {
730     garray_T	ga;
731     char_u	*include = NULL;
732     int		i;
733 
734     ga_init2(&ga, 1, 20);
735     if (argvars[0].v_type != VAR_UNKNOWN)
736 	include = tv_get_string(&argvars[0]);
737 
738     if (!(stuff_empty() && typebuf.tb_len == 0 && scriptin[curscript] == NULL))
739 	may_add_state_char(&ga, include, 'm');
740     if (op_pending())
741 	may_add_state_char(&ga, include, 'o');
742     if (autocmd_busy)
743 	may_add_state_char(&ga, include, 'x');
744     if (ins_compl_active())
745 	may_add_state_char(&ga, include, 'a');
746 
747 # ifdef FEAT_JOB_CHANNEL
748     if (channel_in_blocking_wait())
749 	may_add_state_char(&ga, include, 'w');
750 # endif
751     if (!get_was_safe_state())
752 	may_add_state_char(&ga, include, 'S');
753     for (i = 0; i < get_callback_depth() && i < 3; ++i)
754 	may_add_state_char(&ga, include, 'c');
755     if (msg_scrolled > 0)
756 	may_add_state_char(&ga, include, 's');
757 
758     rettv->v_type = VAR_STRING;
759     rettv->vval.v_string = ga.ga_data;
760 }
761 
762 #endif // FEAT_EVAL
763 
764 /*
765  * Get a key stroke directly from the user.
766  * Ignores mouse clicks and scrollbar events, except a click for the left
767  * button (used at the more prompt).
768  * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
769  * Disadvantage: typeahead is ignored.
770  * Translates the interrupt character for unix to ESC.
771  */
772     int
773 get_keystroke(void)
774 {
775     char_u	*buf = NULL;
776     int		buflen = 150;
777     int		maxlen;
778     int		len = 0;
779     int		n;
780     int		save_mapped_ctrl_c = mapped_ctrl_c;
781     int		waited = 0;
782 
783     mapped_ctrl_c = FALSE;	// mappings are not used here
784     for (;;)
785     {
786 	cursor_on();
787 	out_flush();
788 
789 	// Leave some room for check_termcode() to insert a key code into (max
790 	// 5 chars plus NUL).  And fix_input_buffer() can triple the number of
791 	// bytes.
792 	maxlen = (buflen - 6 - len) / 3;
793 	if (buf == NULL)
794 	    buf = alloc(buflen);
795 	else if (maxlen < 10)
796 	{
797 	    char_u  *t_buf = buf;
798 
799 	    // Need some more space. This might happen when receiving a long
800 	    // escape sequence.
801 	    buflen += 100;
802 	    buf = vim_realloc(buf, buflen);
803 	    if (buf == NULL)
804 		vim_free(t_buf);
805 	    maxlen = (buflen - 6 - len) / 3;
806 	}
807 	if (buf == NULL)
808 	{
809 	    do_outofmem_msg((long_u)buflen);
810 	    return ESC;  // panic!
811 	}
812 
813 	// First time: blocking wait.  Second time: wait up to 100ms for a
814 	// terminal code to complete.
815 	n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
816 	if (n > 0)
817 	{
818 	    // Replace zero and CSI by a special key code.
819 	    n = fix_input_buffer(buf + len, n);
820 	    len += n;
821 	    waited = 0;
822 	}
823 	else if (len > 0)
824 	    ++waited;	    // keep track of the waiting time
825 
826 	// Incomplete termcode and not timed out yet: get more characters
827 	if ((n = check_termcode(1, buf, buflen, &len)) < 0
828 	       && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
829 	    continue;
830 
831 	if (n == KEYLEN_REMOVED)  // key code removed
832 	{
833 	    if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
834 	    {
835 		// Redrawing was postponed, do it now.
836 		update_screen(0);
837 		setcursor(); // put cursor back where it belongs
838 	    }
839 	    continue;
840 	}
841 	if (n > 0)		// found a termcode: adjust length
842 	    len = n;
843 	if (len == 0)		// nothing typed yet
844 	    continue;
845 
846 	// Handle modifier and/or special key code.
847 	n = buf[0];
848 	if (n == K_SPECIAL)
849 	{
850 	    n = TO_SPECIAL(buf[1], buf[2]);
851 	    if (buf[1] == KS_MODIFIER
852 		    || n == K_IGNORE
853 		    || (is_mouse_key(n) && n != K_LEFTMOUSE)
854 #ifdef FEAT_GUI
855 		    || n == K_VER_SCROLLBAR
856 		    || n == K_HOR_SCROLLBAR
857 #endif
858 	       )
859 	    {
860 		if (buf[1] == KS_MODIFIER)
861 		    mod_mask = buf[2];
862 		len -= 3;
863 		if (len > 0)
864 		    mch_memmove(buf, buf + 3, (size_t)len);
865 		continue;
866 	    }
867 	    break;
868 	}
869 	if (has_mbyte)
870 	{
871 	    if (MB_BYTE2LEN(n) > len)
872 		continue;	// more bytes to get
873 	    buf[len >= buflen ? buflen - 1 : len] = NUL;
874 	    n = (*mb_ptr2char)(buf);
875 	}
876 #ifdef UNIX
877 	if (n == intr_char)
878 	    n = ESC;
879 #endif
880 	break;
881     }
882     vim_free(buf);
883 
884     mapped_ctrl_c = save_mapped_ctrl_c;
885     return n;
886 }
887 
888 /*
889  * Get a number from the user.
890  * When "mouse_used" is not NULL allow using the mouse.
891  */
892     int
893 get_number(
894     int	    colon,			// allow colon to abort
895     int	    *mouse_used)
896 {
897     int	n = 0;
898     int	c;
899     int typed = 0;
900 
901     if (mouse_used != NULL)
902 	*mouse_used = FALSE;
903 
904     // When not printing messages, the user won't know what to type, return a
905     // zero (as if CR was hit).
906     if (msg_silent != 0)
907 	return 0;
908 
909 #ifdef USE_ON_FLY_SCROLL
910     dont_scroll = TRUE;		// disallow scrolling here
911 #endif
912     ++no_mapping;
913     ++allow_keys;		// no mapping here, but recognize keys
914     for (;;)
915     {
916 	windgoto(msg_row, msg_col);
917 	c = safe_vgetc();
918 	if (VIM_ISDIGIT(c))
919 	{
920 	    n = n * 10 + c - '0';
921 	    msg_putchar(c);
922 	    ++typed;
923 	}
924 	else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
925 	{
926 	    if (typed > 0)
927 	    {
928 		msg_puts("\b \b");
929 		--typed;
930 	    }
931 	    n /= 10;
932 	}
933 	else if (mouse_used != NULL && c == K_LEFTMOUSE)
934 	{
935 	    *mouse_used = TRUE;
936 	    n = mouse_row + 1;
937 	    break;
938 	}
939 	else if (n == 0 && c == ':' && colon)
940 	{
941 	    stuffcharReadbuff(':');
942 	    if (!exmode_active)
943 		cmdline_row = msg_row;
944 	    skip_redraw = TRUE;	    // skip redraw once
945 	    do_redraw = FALSE;
946 	    break;
947 	}
948 	else if (c == CAR || c == NL || c == Ctrl_C || c == ESC || c == 'q')
949 	    break;
950     }
951     --no_mapping;
952     --allow_keys;
953     return n;
954 }
955 
956 /*
957  * Ask the user to enter a number.
958  * When "mouse_used" is not NULL allow using the mouse and in that case return
959  * the line number.
960  */
961     int
962 prompt_for_number(int *mouse_used)
963 {
964     int		i;
965     int		save_cmdline_row;
966     int		save_State;
967 
968     // When using ":silent" assume that <CR> was entered.
969     if (mouse_used != NULL)
970 	msg_puts(_("Type number and <Enter> or click with the mouse (q or empty cancels): "));
971     else
972 	msg_puts(_("Type number and <Enter> (q or empty cancels): "));
973 
974     // Set the state such that text can be selected/copied/pasted and we still
975     // get mouse events. redraw_after_callback() will not redraw if cmdline_row
976     // is zero.
977     save_cmdline_row = cmdline_row;
978     cmdline_row = 0;
979     save_State = State;
980     State = CMDLINE;
981     // May show different mouse shape.
982     setmouse();
983 
984     i = get_number(TRUE, mouse_used);
985     if (KeyTyped)
986     {
987 	// don't call wait_return() now
988 	if (msg_row > 0)
989 	    cmdline_row = msg_row - 1;
990 	need_wait_return = FALSE;
991 	msg_didany = FALSE;
992 	msg_didout = FALSE;
993     }
994     else
995 	cmdline_row = save_cmdline_row;
996     State = save_State;
997     // May need to restore mouse shape.
998     setmouse();
999 
1000     return i;
1001 }
1002 
1003     void
1004 msgmore(long n)
1005 {
1006     long pn;
1007 
1008     if (global_busy	    // no messages now, wait until global is finished
1009 	    || !messaging())  // 'lazyredraw' set, don't do messages now
1010 	return;
1011 
1012     // We don't want to overwrite another important message, but do overwrite
1013     // a previous "more lines" or "fewer lines" message, so that "5dd" and
1014     // then "put" reports the last action.
1015     if (keep_msg != NULL && !keep_msg_more)
1016 	return;
1017 
1018     if (n > 0)
1019 	pn = n;
1020     else
1021 	pn = -n;
1022 
1023     if (pn > p_report)
1024     {
1025 	if (n > 0)
1026 	    vim_snprintf(msg_buf, MSG_BUF_LEN,
1027 		    NGETTEXT("%ld more line", "%ld more lines", pn), pn);
1028 	else
1029 	    vim_snprintf(msg_buf, MSG_BUF_LEN,
1030 		    NGETTEXT("%ld line less", "%ld fewer lines", pn), pn);
1031 	if (got_int)
1032 	    vim_strcat((char_u *)msg_buf, (char_u *)_(" (Interrupted)"),
1033 								  MSG_BUF_LEN);
1034 	if (msg(msg_buf))
1035 	{
1036 	    set_keep_msg((char_u *)msg_buf, 0);
1037 	    keep_msg_more = TRUE;
1038 	}
1039     }
1040 }
1041 
1042 /*
1043  * flush map and typeahead buffers and give a warning for an error
1044  */
1045     void
1046 beep_flush(void)
1047 {
1048     if (emsg_silent == 0)
1049     {
1050 	flush_buffers(FLUSH_MINIMAL);
1051 	vim_beep(BO_ERROR);
1052     }
1053 }
1054 
1055 /*
1056  * Give a warning for an error.
1057  */
1058     void
1059 vim_beep(
1060     unsigned val) // one of the BO_ values, e.g., BO_OPER
1061 {
1062 #ifdef FEAT_EVAL
1063     called_vim_beep = TRUE;
1064 #endif
1065 
1066     if (emsg_silent == 0 && !in_assert_fails)
1067     {
1068 	if (!((bo_flags & val) || (bo_flags & BO_ALL)))
1069 	{
1070 #ifdef ELAPSED_FUNC
1071 	    static int		did_init = FALSE;
1072 	    static elapsed_T	start_tv;
1073 
1074 	    // Only beep once per half a second, otherwise a sequence of beeps
1075 	    // would freeze Vim.
1076 	    if (!did_init || ELAPSED_FUNC(start_tv) > 500)
1077 	    {
1078 		did_init = TRUE;
1079 		ELAPSED_INIT(start_tv);
1080 #endif
1081 		if (p_vb
1082 #ifdef FEAT_GUI
1083 			// While the GUI is starting up the termcap is set for
1084 			// the GUI but the output still goes to a terminal.
1085 			&& !(gui.in_use && gui.starting)
1086 #endif
1087 			)
1088 		{
1089 		    out_str_cf(T_VB);
1090 #ifdef FEAT_VTP
1091 		    // No restore color information, refresh the screen.
1092 		    if (has_vtp_working() != 0
1093 # ifdef FEAT_TERMGUICOLORS
1094 			    && (p_tgc || (!p_tgc && t_colors >= 256))
1095 # endif
1096 			)
1097 		    {
1098 			redraw_later(CLEAR);
1099 			update_screen(0);
1100 			redrawcmd();
1101 		    }
1102 #endif
1103 		}
1104 		else
1105 		    out_char(BELL);
1106 #ifdef ELAPSED_FUNC
1107 	    }
1108 #endif
1109 	}
1110 
1111 	// When 'debug' contains "beep" produce a message.  If we are sourcing
1112 	// a script or executing a function give the user a hint where the beep
1113 	// comes from.
1114 	if (vim_strchr(p_debug, 'e') != NULL)
1115 	{
1116 	    msg_source(HL_ATTR(HLF_W));
1117 	    msg_attr(_("Beep!"), HL_ATTR(HLF_W));
1118 	}
1119     }
1120 }
1121 
1122 /*
1123  * To get the "real" home directory:
1124  * - get value of $HOME
1125  * For Unix:
1126  *  - go to that directory
1127  *  - do mch_dirname() to get the real name of that directory.
1128  *  This also works with mounts and links.
1129  *  Don't do this for MS-DOS, it will change the "current dir" for a drive.
1130  * For Windows:
1131  *  This code is duplicated in init_homedir() in dosinst.c.  Keep in sync!
1132  */
1133     void
1134 init_homedir(void)
1135 {
1136     char_u  *var;
1137 
1138     // In case we are called a second time (when 'encoding' changes).
1139     VIM_CLEAR(homedir);
1140 
1141 #ifdef VMS
1142     var = mch_getenv((char_u *)"SYS$LOGIN");
1143 #else
1144     var = mch_getenv((char_u *)"HOME");
1145 #endif
1146 
1147 #ifdef MSWIN
1148     /*
1149      * Typically, $HOME is not defined on Windows, unless the user has
1150      * specifically defined it for Vim's sake.  However, on Windows NT
1151      * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
1152      * each user.  Try constructing $HOME from these.
1153      */
1154     if (var == NULL || *var == NUL)
1155     {
1156 	char_u *homedrive, *homepath;
1157 
1158 	homedrive = mch_getenv((char_u *)"HOMEDRIVE");
1159 	homepath = mch_getenv((char_u *)"HOMEPATH");
1160 	if (homepath == NULL || *homepath == NUL)
1161 	    homepath = (char_u *)"\\";
1162 	if (homedrive != NULL
1163 			   && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
1164 	{
1165 	    sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
1166 	    if (NameBuff[0] != NUL)
1167 		var = NameBuff;
1168 	}
1169     }
1170 
1171     if (var == NULL)
1172 	var = mch_getenv((char_u *)"USERPROFILE");
1173 
1174     /*
1175      * Weird but true: $HOME may contain an indirect reference to another
1176      * variable, esp. "%USERPROFILE%".  Happens when $USERPROFILE isn't set
1177      * when $HOME is being set.
1178      */
1179     if (var != NULL && *var == '%')
1180     {
1181 	char_u	*p;
1182 	char_u	*exp;
1183 
1184 	p = vim_strchr(var + 1, '%');
1185 	if (p != NULL)
1186 	{
1187 	    vim_strncpy(NameBuff, var + 1, p - (var + 1));
1188 	    exp = mch_getenv(NameBuff);
1189 	    if (exp != NULL && *exp != NUL
1190 					&& STRLEN(exp) + STRLEN(p) < MAXPATHL)
1191 	    {
1192 		vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
1193 		var = NameBuff;
1194 	    }
1195 	}
1196     }
1197 
1198     if (var != NULL && *var == NUL)	// empty is same as not set
1199 	var = NULL;
1200 
1201     if (enc_utf8 && var != NULL)
1202     {
1203 	int	len;
1204 	char_u  *pp = NULL;
1205 
1206 	// Convert from active codepage to UTF-8.  Other conversions are
1207 	// not done, because they would fail for non-ASCII characters.
1208 	acp_to_enc(var, (int)STRLEN(var), &pp, &len);
1209 	if (pp != NULL)
1210 	{
1211 	    homedir = pp;
1212 	    return;
1213 	}
1214     }
1215 
1216     /*
1217      * Default home dir is C:/
1218      * Best assumption we can make in such a situation.
1219      */
1220     if (var == NULL)
1221 	var = (char_u *)"C:/";
1222 #endif
1223 
1224     if (var != NULL)
1225     {
1226 #ifdef UNIX
1227 	/*
1228 	 * Change to the directory and get the actual path.  This resolves
1229 	 * links.  Don't do it when we can't return.
1230 	 */
1231 	if (mch_dirname(NameBuff, MAXPATHL) == OK
1232 					  && mch_chdir((char *)NameBuff) == 0)
1233 	{
1234 	    if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
1235 		var = IObuff;
1236 	    if (mch_chdir((char *)NameBuff) != 0)
1237 		emsg(_(e_prev_dir));
1238 	}
1239 #endif
1240 	homedir = vim_strsave(var);
1241     }
1242 }
1243 
1244 #if defined(EXITFREE) || defined(PROTO)
1245     void
1246 free_homedir(void)
1247 {
1248     vim_free(homedir);
1249 }
1250 
1251     void
1252 free_users(void)
1253 {
1254     ga_clear_strings(&ga_users);
1255 }
1256 #endif
1257 
1258 /*
1259  * Call expand_env() and store the result in an allocated string.
1260  * This is not very memory efficient, this expects the result to be freed
1261  * again soon.
1262  */
1263     char_u *
1264 expand_env_save(char_u *src)
1265 {
1266     return expand_env_save_opt(src, FALSE);
1267 }
1268 
1269 /*
1270  * Idem, but when "one" is TRUE handle the string as one file name, only
1271  * expand "~" at the start.
1272  */
1273     char_u *
1274 expand_env_save_opt(char_u *src, int one)
1275 {
1276     char_u	*p;
1277 
1278     p = alloc(MAXPATHL);
1279     if (p != NULL)
1280 	expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
1281     return p;
1282 }
1283 
1284 /*
1285  * Expand environment variable with path name.
1286  * "~/" is also expanded, using $HOME.	For Unix "~user/" is expanded.
1287  * Skips over "\ ", "\~" and "\$" (not for Win32 though).
1288  * If anything fails no expansion is done and dst equals src.
1289  */
1290     void
1291 expand_env(
1292     char_u	*src,		// input string e.g. "$HOME/vim.hlp"
1293     char_u	*dst,		// where to put the result
1294     int		dstlen)		// maximum length of the result
1295 {
1296     expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
1297 }
1298 
1299     void
1300 expand_env_esc(
1301     char_u	*srcp,		// input string e.g. "$HOME/vim.hlp"
1302     char_u	*dst,		// where to put the result
1303     int		dstlen,		// maximum length of the result
1304     int		esc,		// escape spaces in expanded variables
1305     int		one,		// "srcp" is one file name
1306     char_u	*startstr)	// start again after this (can be NULL)
1307 {
1308     char_u	*src;
1309     char_u	*tail;
1310     int		c;
1311     char_u	*var;
1312     int		copy_char;
1313     int		mustfree;	// var was allocated, need to free it later
1314     int		at_start = TRUE; // at start of a name
1315     int		startstr_len = 0;
1316 
1317     if (startstr != NULL)
1318 	startstr_len = (int)STRLEN(startstr);
1319 
1320     src = skipwhite(srcp);
1321     --dstlen;		    // leave one char space for "\,"
1322     while (*src && dstlen > 0)
1323     {
1324 #ifdef FEAT_EVAL
1325 	// Skip over `=expr`.
1326 	if (src[0] == '`' && src[1] == '=')
1327 	{
1328 	    size_t len;
1329 
1330 	    var = src;
1331 	    src += 2;
1332 	    (void)skip_expr(&src, NULL);
1333 	    if (*src == '`')
1334 		++src;
1335 	    len = src - var;
1336 	    if (len > (size_t)dstlen)
1337 		len = dstlen;
1338 	    vim_strncpy(dst, var, len);
1339 	    dst += len;
1340 	    dstlen -= (int)len;
1341 	    continue;
1342 	}
1343 #endif
1344 	copy_char = TRUE;
1345 	if ((*src == '$'
1346 #ifdef VMS
1347 		    && at_start
1348 #endif
1349 	   )
1350 #if defined(MSWIN)
1351 		|| *src == '%'
1352 #endif
1353 		|| (*src == '~' && at_start))
1354 	{
1355 	    mustfree = FALSE;
1356 
1357 	    /*
1358 	     * The variable name is copied into dst temporarily, because it may
1359 	     * be a string in read-only memory and a NUL needs to be appended.
1360 	     */
1361 	    if (*src != '~')				// environment var
1362 	    {
1363 		tail = src + 1;
1364 		var = dst;
1365 		c = dstlen - 1;
1366 
1367 #ifdef UNIX
1368 		// Unix has ${var-name} type environment vars
1369 		if (*tail == '{' && !vim_isIDc('{'))
1370 		{
1371 		    tail++;	// ignore '{'
1372 		    while (c-- > 0 && *tail && *tail != '}')
1373 			*var++ = *tail++;
1374 		}
1375 		else
1376 #endif
1377 		{
1378 		    while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
1379 #if defined(MSWIN)
1380 			    || (*src == '%' && *tail != '%')
1381 #endif
1382 			    ))
1383 			*var++ = *tail++;
1384 		}
1385 
1386 #if defined(MSWIN) || defined(UNIX)
1387 # ifdef UNIX
1388 		if (src[1] == '{' && *tail != '}')
1389 # else
1390 		if (*src == '%' && *tail != '%')
1391 # endif
1392 		    var = NULL;
1393 		else
1394 		{
1395 # ifdef UNIX
1396 		    if (src[1] == '{')
1397 # else
1398 		    if (*src == '%')
1399 #endif
1400 			++tail;
1401 #endif
1402 		    *var = NUL;
1403 		    var = vim_getenv(dst, &mustfree);
1404 #if defined(MSWIN) || defined(UNIX)
1405 		}
1406 #endif
1407 	    }
1408 							// home directory
1409 	    else if (  src[1] == NUL
1410 		    || vim_ispathsep(src[1])
1411 		    || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
1412 	    {
1413 		var = homedir;
1414 		tail = src + 1;
1415 	    }
1416 	    else					// user directory
1417 	    {
1418 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
1419 		/*
1420 		 * Copy ~user to dst[], so we can put a NUL after it.
1421 		 */
1422 		tail = src;
1423 		var = dst;
1424 		c = dstlen - 1;
1425 		while (	   c-- > 0
1426 			&& *tail
1427 			&& vim_isfilec(*tail)
1428 			&& !vim_ispathsep(*tail))
1429 		    *var++ = *tail++;
1430 		*var = NUL;
1431 # ifdef UNIX
1432 		/*
1433 		 * If the system supports getpwnam(), use it.
1434 		 * Otherwise, or if getpwnam() fails, the shell is used to
1435 		 * expand ~user.  This is slower and may fail if the shell
1436 		 * does not support ~user (old versions of /bin/sh).
1437 		 */
1438 #  if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
1439 		{
1440 		    // Note: memory allocated by getpwnam() is never freed.
1441 		    // Calling endpwent() apparently doesn't help.
1442 		    struct passwd *pw = (*dst == NUL)
1443 					? NULL : getpwnam((char *)dst + 1);
1444 
1445 		    var = (pw == NULL) ? NULL : (char_u *)pw->pw_dir;
1446 		}
1447 		if (var == NULL)
1448 #  endif
1449 		{
1450 		    expand_T	xpc;
1451 
1452 		    ExpandInit(&xpc);
1453 		    xpc.xp_context = EXPAND_FILES;
1454 		    var = ExpandOne(&xpc, dst, NULL,
1455 				WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
1456 		    mustfree = TRUE;
1457 		}
1458 
1459 # else	// !UNIX, thus VMS
1460 		/*
1461 		 * USER_HOME is a comma-separated list of
1462 		 * directories to search for the user account in.
1463 		 */
1464 		{
1465 		    char_u	test[MAXPATHL], paths[MAXPATHL];
1466 		    char_u	*path, *next_path, *ptr;
1467 		    stat_T	st;
1468 
1469 		    STRCPY(paths, USER_HOME);
1470 		    next_path = paths;
1471 		    while (*next_path)
1472 		    {
1473 			for (path = next_path; *next_path && *next_path != ',';
1474 				next_path++);
1475 			if (*next_path)
1476 			    *next_path++ = NUL;
1477 			STRCPY(test, path);
1478 			STRCAT(test, "/");
1479 			STRCAT(test, dst + 1);
1480 			if (mch_stat(test, &st) == 0)
1481 			{
1482 			    var = alloc(STRLEN(test) + 1);
1483 			    STRCPY(var, test);
1484 			    mustfree = TRUE;
1485 			    break;
1486 			}
1487 		    }
1488 		}
1489 # endif // UNIX
1490 #else
1491 		// cannot expand user's home directory, so don't try
1492 		var = NULL;
1493 		tail = (char_u *)"";	// for gcc
1494 #endif // UNIX || VMS
1495 	    }
1496 
1497 #ifdef BACKSLASH_IN_FILENAME
1498 	    // If 'shellslash' is set change backslashes to forward slashes.
1499 	    // Can't use slash_adjust(), p_ssl may be set temporarily.
1500 	    if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
1501 	    {
1502 		char_u	*p = vim_strsave(var);
1503 
1504 		if (p != NULL)
1505 		{
1506 		    if (mustfree)
1507 			vim_free(var);
1508 		    var = p;
1509 		    mustfree = TRUE;
1510 		    forward_slash(var);
1511 		}
1512 	    }
1513 #endif
1514 
1515 	    // If "var" contains white space, escape it with a backslash.
1516 	    // Required for ":e ~/tt" when $HOME includes a space.
1517 	    if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
1518 	    {
1519 		char_u	*p = vim_strsave_escaped(var, (char_u *)" \t");
1520 
1521 		if (p != NULL)
1522 		{
1523 		    if (mustfree)
1524 			vim_free(var);
1525 		    var = p;
1526 		    mustfree = TRUE;
1527 		}
1528 	    }
1529 
1530 	    if (var != NULL && *var != NUL
1531 		    && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
1532 	    {
1533 		STRCPY(dst, var);
1534 		dstlen -= (int)STRLEN(var);
1535 		c = (int)STRLEN(var);
1536 		// if var[] ends in a path separator and tail[] starts
1537 		// with it, skip a character
1538 		if (*var != NUL && after_pathsep(dst, dst + c)
1539 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
1540 			&& dst[-1] != ':'
1541 #endif
1542 			&& vim_ispathsep(*tail))
1543 		    ++tail;
1544 		dst += c;
1545 		src = tail;
1546 		copy_char = FALSE;
1547 	    }
1548 	    if (mustfree)
1549 		vim_free(var);
1550 	}
1551 
1552 	if (copy_char)	    // copy at least one char
1553 	{
1554 	    /*
1555 	     * Recognize the start of a new name, for '~'.
1556 	     * Don't do this when "one" is TRUE, to avoid expanding "~" in
1557 	     * ":edit foo ~ foo".
1558 	     */
1559 	    at_start = FALSE;
1560 	    if (src[0] == '\\' && src[1] != NUL)
1561 	    {
1562 		*dst++ = *src++;
1563 		--dstlen;
1564 	    }
1565 	    else if ((src[0] == ' ' || src[0] == ',') && !one)
1566 		at_start = TRUE;
1567 	    if (dstlen > 0)
1568 	    {
1569 		*dst++ = *src++;
1570 		--dstlen;
1571 
1572 		if (startstr != NULL && src - startstr_len >= srcp
1573 			&& STRNCMP(src - startstr_len, startstr,
1574 							    startstr_len) == 0)
1575 		    at_start = TRUE;
1576 	    }
1577 	}
1578 
1579     }
1580     *dst = NUL;
1581 }
1582 
1583 /*
1584  * If the string between "p" and "pend" ends in "name/", return "pend" minus
1585  * the length of "name/".  Otherwise return "pend".
1586  */
1587     static char_u *
1588 remove_tail(char_u *p, char_u *pend, char_u *name)
1589 {
1590     int		len = (int)STRLEN(name) + 1;
1591     char_u	*newend = pend - len;
1592 
1593     if (newend >= p
1594 	    && fnamencmp(newend, name, len - 1) == 0
1595 	    && (newend == p || after_pathsep(p, newend)))
1596 	return newend;
1597     return pend;
1598 }
1599 
1600 /*
1601  * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
1602  * Return NULL if not, return its name in allocated memory otherwise.
1603  */
1604     static char_u *
1605 vim_version_dir(char_u *vimdir)
1606 {
1607     char_u	*p;
1608 
1609     if (vimdir == NULL || *vimdir == NUL)
1610 	return NULL;
1611     p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
1612     if (p != NULL && mch_isdir(p))
1613 	return p;
1614     vim_free(p);
1615     p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
1616     if (p != NULL && mch_isdir(p))
1617 	return p;
1618     vim_free(p);
1619     return NULL;
1620 }
1621 
1622 /*
1623  * Vim's version of getenv().
1624  * Special handling of $HOME, $VIM and $VIMRUNTIME.
1625  * Also does ACP to 'enc' conversion for Win32.
1626  * "mustfree" is set to TRUE when returned is allocated, it must be
1627  * initialized to FALSE by the caller.
1628  */
1629     char_u *
1630 vim_getenv(char_u *name, int *mustfree)
1631 {
1632     char_u	*p = NULL;
1633     char_u	*pend;
1634     int		vimruntime;
1635 #ifdef MSWIN
1636     WCHAR	*wn, *wp;
1637 
1638     // use "C:/" when $HOME is not set
1639     if (STRCMP(name, "HOME") == 0)
1640 	return homedir;
1641 
1642     // Use Wide function
1643     wn = enc_to_utf16(name, NULL);
1644     if (wn == NULL)
1645 	return NULL;
1646 
1647     wp = _wgetenv(wn);
1648     vim_free(wn);
1649 
1650     if (wp != NULL && *wp == NUL)   // empty is the same as not set
1651 	wp = NULL;
1652 
1653     if (wp != NULL)
1654     {
1655 	p = utf16_to_enc(wp, NULL);
1656 	if (p == NULL)
1657 	    return NULL;
1658 
1659 	*mustfree = TRUE;
1660 	return p;
1661     }
1662 #else
1663     p = mch_getenv(name);
1664     if (p != NULL && *p == NUL)	    // empty is the same as not set
1665 	p = NULL;
1666 
1667     if (p != NULL)
1668 	return p;
1669 
1670 # ifdef __HAIKU__
1671     // special handling for user settings directory...
1672     if (STRCMP(name, "BE_USER_SETTINGS") == 0)
1673     {
1674 	static char userSettingsPath[MAXPATHL];
1675 
1676 	if (find_directory(B_USER_SETTINGS_DIRECTORY, 0, false,
1677 					   userSettingsPath, MAXPATHL) == B_OK)
1678 	    return (char_u *)userSettingsPath;
1679 	else
1680 	    return NULL;
1681     }
1682 # endif
1683 #endif
1684 
1685     // handling $VIMRUNTIME and $VIM is below, bail out if it's another name.
1686     vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
1687     if (!vimruntime && STRCMP(name, "VIM") != 0)
1688 	return NULL;
1689 
1690     /*
1691      * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
1692      * Don't do this when default_vimruntime_dir is non-empty.
1693      */
1694     if (vimruntime
1695 #ifdef HAVE_PATHDEF
1696 	    && *default_vimruntime_dir == NUL
1697 #endif
1698        )
1699     {
1700 #ifdef MSWIN
1701 	// Use Wide function
1702 	wp = _wgetenv(L"VIM");
1703 	if (wp != NULL && *wp == NUL)	    // empty is the same as not set
1704 	    wp = NULL;
1705 	if (wp != NULL)
1706 	{
1707 	    char_u *q = utf16_to_enc(wp, NULL);
1708 	    if (q != NULL)
1709 	    {
1710 		p = vim_version_dir(q);
1711 		*mustfree = TRUE;
1712 		if (p == NULL)
1713 		    p = q;
1714 	    }
1715 	}
1716 #else
1717 	p = mch_getenv((char_u *)"VIM");
1718 	if (p != NULL && *p == NUL)	    // empty is the same as not set
1719 	    p = NULL;
1720 	if (p != NULL)
1721 	{
1722 	    p = vim_version_dir(p);
1723 	    if (p != NULL)
1724 		*mustfree = TRUE;
1725 	    else
1726 		p = mch_getenv((char_u *)"VIM");
1727 	}
1728 #endif
1729     }
1730 
1731     /*
1732      * When expanding $VIM or $VIMRUNTIME fails, try using:
1733      * - the directory name from 'helpfile' (unless it contains '$')
1734      * - the executable name from argv[0]
1735      */
1736     if (p == NULL)
1737     {
1738 	if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
1739 	    p = p_hf;
1740 #ifdef USE_EXE_NAME
1741 	/*
1742 	 * Use the name of the executable, obtained from argv[0].
1743 	 */
1744 	else
1745 	    p = exe_name;
1746 #endif
1747 	if (p != NULL)
1748 	{
1749 	    // remove the file name
1750 	    pend = gettail(p);
1751 
1752 	    // remove "doc/" from 'helpfile', if present
1753 	    if (p == p_hf)
1754 		pend = remove_tail(p, pend, (char_u *)"doc");
1755 
1756 #ifdef USE_EXE_NAME
1757 # ifdef MACOS_X
1758 	    // remove "MacOS" from exe_name and add "Resources/vim"
1759 	    if (p == exe_name)
1760 	    {
1761 		char_u	*pend1;
1762 		char_u	*pnew;
1763 
1764 		pend1 = remove_tail(p, pend, (char_u *)"MacOS");
1765 		if (pend1 != pend)
1766 		{
1767 		    pnew = alloc(pend1 - p + 15);
1768 		    if (pnew != NULL)
1769 		    {
1770 			STRNCPY(pnew, p, (pend1 - p));
1771 			STRCPY(pnew + (pend1 - p), "Resources/vim");
1772 			p = pnew;
1773 			pend = p + STRLEN(p);
1774 		    }
1775 		}
1776 	    }
1777 # endif
1778 	    // remove "src/" from exe_name, if present
1779 	    if (p == exe_name)
1780 		pend = remove_tail(p, pend, (char_u *)"src");
1781 #endif
1782 
1783 	    // for $VIM, remove "runtime/" or "vim54/", if present
1784 	    if (!vimruntime)
1785 	    {
1786 		pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
1787 		pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
1788 	    }
1789 
1790 	    // remove trailing path separator
1791 	    if (pend > p && after_pathsep(p, pend))
1792 		--pend;
1793 
1794 #ifdef MACOS_X
1795 	    if (p == exe_name || p == p_hf)
1796 #endif
1797 		// check that the result is a directory name
1798 		p = vim_strnsave(p, pend - p);
1799 
1800 	    if (p != NULL && !mch_isdir(p))
1801 		VIM_CLEAR(p);
1802 	    else
1803 	    {
1804 #ifdef USE_EXE_NAME
1805 		// may add "/vim54" or "/runtime" if it exists
1806 		if (vimruntime && (pend = vim_version_dir(p)) != NULL)
1807 		{
1808 		    vim_free(p);
1809 		    p = pend;
1810 		}
1811 #endif
1812 		*mustfree = TRUE;
1813 	    }
1814 	}
1815     }
1816 
1817 #ifdef HAVE_PATHDEF
1818     // When there is a pathdef.c file we can use default_vim_dir and
1819     // default_vimruntime_dir
1820     if (p == NULL)
1821     {
1822 	// Only use default_vimruntime_dir when it is not empty
1823 	if (vimruntime && *default_vimruntime_dir != NUL)
1824 	{
1825 	    p = default_vimruntime_dir;
1826 	    *mustfree = FALSE;
1827 	}
1828 	else if (*default_vim_dir != NUL)
1829 	{
1830 	    if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
1831 		*mustfree = TRUE;
1832 	    else
1833 	    {
1834 		p = default_vim_dir;
1835 		*mustfree = FALSE;
1836 	    }
1837 	}
1838     }
1839 #endif
1840 
1841     /*
1842      * Set the environment variable, so that the new value can be found fast
1843      * next time, and others can also use it (e.g. Perl).
1844      */
1845     if (p != NULL)
1846     {
1847 	if (vimruntime)
1848 	{
1849 	    vim_setenv((char_u *)"VIMRUNTIME", p);
1850 	    didset_vimruntime = TRUE;
1851 	}
1852 	else
1853 	{
1854 	    vim_setenv((char_u *)"VIM", p);
1855 	    didset_vim = TRUE;
1856 	}
1857     }
1858     return p;
1859 }
1860 
1861 #if defined(FEAT_EVAL) || defined(PROTO)
1862     void
1863 vim_unsetenv(char_u *var)
1864 {
1865 #ifdef HAVE_UNSETENV
1866     unsetenv((char *)var);
1867 #else
1868     vim_setenv(var, (char_u *)"");
1869 #endif
1870 }
1871 #endif
1872 
1873 
1874 /*
1875  * Set environment variable "name" and take care of side effects.
1876  */
1877     void
1878 vim_setenv_ext(char_u *name, char_u *val)
1879 {
1880     vim_setenv(name, val);
1881     if (STRICMP(name, "HOME") == 0)
1882 	init_homedir();
1883     else if (didset_vim && STRICMP(name, "VIM") == 0)
1884 	didset_vim = FALSE;
1885     else if (didset_vimruntime
1886 	    && STRICMP(name, "VIMRUNTIME") == 0)
1887 	didset_vimruntime = FALSE;
1888 }
1889 
1890 /*
1891  * Our portable version of setenv.
1892  */
1893     void
1894 vim_setenv(char_u *name, char_u *val)
1895 {
1896 #ifdef HAVE_SETENV
1897     mch_setenv((char *)name, (char *)val, 1);
1898 #else
1899     char_u	*envbuf;
1900 
1901     /*
1902      * Putenv does not copy the string, it has to remain
1903      * valid.  The allocated memory will never be freed.
1904      */
1905     envbuf = alloc(STRLEN(name) + STRLEN(val) + 2);
1906     if (envbuf != NULL)
1907     {
1908 	sprintf((char *)envbuf, "%s=%s", name, val);
1909 	putenv((char *)envbuf);
1910     }
1911 #endif
1912 #ifdef FEAT_GETTEXT
1913     /*
1914      * When setting $VIMRUNTIME adjust the directory to find message
1915      * translations to $VIMRUNTIME/lang.
1916      */
1917     if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
1918     {
1919 	char_u	*buf = concat_str(val, (char_u *)"/lang");
1920 
1921 	if (buf != NULL)
1922 	{
1923 	    bindtextdomain(VIMPACKAGE, (char *)buf);
1924 	    vim_free(buf);
1925 	}
1926     }
1927 #endif
1928 }
1929 
1930 /*
1931  * Function given to ExpandGeneric() to obtain an environment variable name.
1932  */
1933     char_u *
1934 get_env_name(
1935     expand_T	*xp UNUSED,
1936     int		idx)
1937 {
1938 # if defined(AMIGA)
1939     /*
1940      * No environ[] on the Amiga.
1941      */
1942     return NULL;
1943 # else
1944 # ifndef __WIN32__
1945     // Borland C++ 5.2 has this in a header file.
1946     extern char		**environ;
1947 # endif
1948 # define ENVNAMELEN 100
1949     static char_u	name[ENVNAMELEN];
1950     char_u		*str;
1951     int			n;
1952 
1953     str = (char_u *)environ[idx];
1954     if (str == NULL)
1955 	return NULL;
1956 
1957     for (n = 0; n < ENVNAMELEN - 1; ++n)
1958     {
1959 	if (str[n] == '=' || str[n] == NUL)
1960 	    break;
1961 	name[n] = str[n];
1962     }
1963     name[n] = NUL;
1964     return name;
1965 # endif
1966 }
1967 
1968 /*
1969  * Add a user name to the list of users in ga_users.
1970  * Do nothing if user name is NULL or empty.
1971  */
1972     static void
1973 add_user(char_u *user, int need_copy)
1974 {
1975     char_u	*user_copy = (user != NULL && need_copy)
1976 						    ? vim_strsave(user) : user;
1977 
1978     if (user_copy == NULL || *user_copy == NUL || ga_grow(&ga_users, 1) == FAIL)
1979     {
1980 	if (need_copy)
1981 	    vim_free(user);
1982 	return;
1983     }
1984     ((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user_copy;
1985 }
1986 
1987 /*
1988  * Find all user names for user completion.
1989  * Done only once and then cached.
1990  */
1991     static void
1992 init_users(void)
1993 {
1994     static int	lazy_init_done = FALSE;
1995 
1996     if (lazy_init_done)
1997 	return;
1998 
1999     lazy_init_done = TRUE;
2000     ga_init2(&ga_users, sizeof(char_u *), 20);
2001 
2002 # if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
2003     {
2004 	struct passwd*	pw;
2005 
2006 	setpwent();
2007 	while ((pw = getpwent()) != NULL)
2008 	    add_user((char_u *)pw->pw_name, TRUE);
2009 	endpwent();
2010     }
2011 # elif defined(MSWIN)
2012     {
2013 	DWORD		nusers = 0, ntotal = 0, i;
2014 	PUSER_INFO_0	uinfo;
2015 
2016 	if (NetUserEnum(NULL, 0, 0, (LPBYTE *) &uinfo, MAX_PREFERRED_LENGTH,
2017 				       &nusers, &ntotal, NULL) == NERR_Success)
2018 	{
2019 	    for (i = 0; i < nusers; i++)
2020 		add_user(utf16_to_enc(uinfo[i].usri0_name, NULL), FALSE);
2021 
2022 	    NetApiBufferFree(uinfo);
2023 	}
2024     }
2025 # endif
2026 # if defined(HAVE_GETPWNAM)
2027     {
2028 	char_u	*user_env = mch_getenv((char_u *)"USER");
2029 
2030 	// The $USER environment variable may be a valid remote user name (NIS,
2031 	// LDAP) not already listed by getpwent(), as getpwent() only lists
2032 	// local user names.  If $USER is not already listed, check whether it
2033 	// is a valid remote user name using getpwnam() and if it is, add it to
2034 	// the list of user names.
2035 
2036 	if (user_env != NULL && *user_env != NUL)
2037 	{
2038 	    int	i;
2039 
2040 	    for (i = 0; i < ga_users.ga_len; i++)
2041 	    {
2042 		char_u	*local_user = ((char_u **)ga_users.ga_data)[i];
2043 
2044 		if (STRCMP(local_user, user_env) == 0)
2045 		    break;
2046 	    }
2047 
2048 	    if (i == ga_users.ga_len)
2049 	    {
2050 		struct passwd	*pw = getpwnam((char *)user_env);
2051 
2052 		if (pw != NULL)
2053 		    add_user((char_u *)pw->pw_name, TRUE);
2054 	    }
2055 	}
2056     }
2057 # endif
2058 }
2059 
2060 /*
2061  * Function given to ExpandGeneric() to obtain an user names.
2062  */
2063     char_u*
2064 get_users(expand_T *xp UNUSED, int idx)
2065 {
2066     init_users();
2067     if (idx < ga_users.ga_len)
2068 	return ((char_u **)ga_users.ga_data)[idx];
2069     return NULL;
2070 }
2071 
2072 /*
2073  * Check whether name matches a user name. Return:
2074  * 0 if name does not match any user name.
2075  * 1 if name partially matches the beginning of a user name.
2076  * 2 is name fully matches a user name.
2077  */
2078     int
2079 match_user(char_u *name)
2080 {
2081     int i;
2082     int n = (int)STRLEN(name);
2083     int result = 0;
2084 
2085     init_users();
2086     for (i = 0; i < ga_users.ga_len; i++)
2087     {
2088 	if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
2089 	    return 2; // full match
2090 	if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
2091 	    result = 1; // partial match
2092     }
2093     return result;
2094 }
2095 
2096 /*
2097  * Concatenate two strings and return the result in allocated memory.
2098  * Returns NULL when out of memory.
2099  */
2100     char_u  *
2101 concat_str(char_u *str1, char_u *str2)
2102 {
2103     char_u  *dest;
2104     size_t  l = str1 == NULL ? 0 : STRLEN(str1);
2105 
2106     dest = alloc(l + (str2 == NULL ? 0 : STRLEN(str2)) + 1L);
2107     if (dest != NULL)
2108     {
2109 	if (str1 == NULL)
2110 	    *dest = NUL;
2111 	else
2112 	    STRCPY(dest, str1);
2113 	if (str2 != NULL)
2114 	    STRCPY(dest + l, str2);
2115     }
2116     return dest;
2117 }
2118 
2119     static void
2120 prepare_to_exit(void)
2121 {
2122 #if defined(SIGHUP) && defined(SIG_IGN)
2123     // Ignore SIGHUP, because a dropped connection causes a read error, which
2124     // makes Vim exit and then handling SIGHUP causes various reentrance
2125     // problems.
2126     signal(SIGHUP, SIG_IGN);
2127 #endif
2128 
2129 #ifdef FEAT_GUI
2130     if (gui.in_use)
2131     {
2132 	gui.dying = TRUE;
2133 	out_trash();	// trash any pending output
2134     }
2135     else
2136 #endif
2137     {
2138 	windgoto((int)Rows - 1, 0);
2139 
2140 	/*
2141 	 * Switch terminal mode back now, so messages end up on the "normal"
2142 	 * screen (if there are two screens).
2143 	 */
2144 	settmode(TMODE_COOK);
2145 	stoptermcap();
2146 	out_flush();
2147     }
2148 }
2149 
2150 /*
2151  * Preserve files and exit.
2152  * When called IObuff must contain a message.
2153  * NOTE: This may be called from deathtrap() in a signal handler, avoid unsafe
2154  * functions, such as allocating memory.
2155  */
2156     void
2157 preserve_exit(void)
2158 {
2159     buf_T	*buf;
2160 
2161     prepare_to_exit();
2162 
2163     // Setting this will prevent free() calls.  That avoids calling free()
2164     // recursively when free() was invoked with a bad pointer.
2165     really_exiting = TRUE;
2166 
2167     out_str(IObuff);
2168     screen_start();		    // don't know where cursor is now
2169     out_flush();
2170 
2171     ml_close_notmod();		    // close all not-modified buffers
2172 
2173     FOR_ALL_BUFFERS(buf)
2174     {
2175 	if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
2176 	{
2177 	    OUT_STR("Vim: preserving files...\r\n");
2178 	    screen_start();	    // don't know where cursor is now
2179 	    out_flush();
2180 	    ml_sync_all(FALSE, FALSE);	// preserve all swap files
2181 	    break;
2182 	}
2183     }
2184 
2185     ml_close_all(FALSE);	    // close all memfiles, without deleting
2186 
2187     OUT_STR("Vim: Finished.\r\n");
2188 
2189     getout(1);
2190 }
2191 
2192 /*
2193  * Check for CTRL-C pressed, but only once in a while.
2194  * Should be used instead of ui_breakcheck() for functions that check for
2195  * each line in the file.  Calling ui_breakcheck() each time takes too much
2196  * time, because it can be a system call.
2197  */
2198 
2199 #ifndef BREAKCHECK_SKIP
2200 # define BREAKCHECK_SKIP 1000
2201 #endif
2202 
2203 static int	breakcheck_count = 0;
2204 
2205     void
2206 line_breakcheck(void)
2207 {
2208     if (++breakcheck_count >= BREAKCHECK_SKIP)
2209     {
2210 	breakcheck_count = 0;
2211 	ui_breakcheck();
2212     }
2213 }
2214 
2215 /*
2216  * Like line_breakcheck() but check 10 times less often.
2217  */
2218     void
2219 fast_breakcheck(void)
2220 {
2221     if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
2222     {
2223 	breakcheck_count = 0;
2224 	ui_breakcheck();
2225     }
2226 }
2227 
2228 /*
2229  * Like line_breakcheck() but check 100 times less often.
2230  */
2231     void
2232 veryfast_breakcheck(void)
2233 {
2234     if (++breakcheck_count >= BREAKCHECK_SKIP * 100)
2235     {
2236 	breakcheck_count = 0;
2237 	ui_breakcheck();
2238     }
2239 }
2240 
2241 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) \
2242 	|| (defined(HAVE_LOCALE_H) || defined(X_LOCALE)) \
2243 	|| defined(PROTO)
2244 
2245 #ifndef SEEK_SET
2246 # define SEEK_SET 0
2247 #endif
2248 #ifndef SEEK_END
2249 # define SEEK_END 2
2250 #endif
2251 
2252 /*
2253  * Get the stdout of an external command.
2254  * If "ret_len" is NULL replace NUL characters with NL.  When "ret_len" is not
2255  * NULL store the length there.
2256  * Returns an allocated string, or NULL for error.
2257  */
2258     char_u *
2259 get_cmd_output(
2260     char_u	*cmd,
2261     char_u	*infile,	// optional input file name
2262     int		flags,		// can be SHELL_SILENT
2263     int		*ret_len)
2264 {
2265     char_u	*tempname;
2266     char_u	*command;
2267     char_u	*buffer = NULL;
2268     int		len;
2269     int		i = 0;
2270     FILE	*fd;
2271 
2272     if (check_restricted() || check_secure())
2273 	return NULL;
2274 
2275     // get a name for the temp file
2276     if ((tempname = vim_tempname('o', FALSE)) == NULL)
2277     {
2278 	emsg(_(e_notmp));
2279 	return NULL;
2280     }
2281 
2282     // Add the redirection stuff
2283     command = make_filter_cmd(cmd, infile, tempname);
2284     if (command == NULL)
2285 	goto done;
2286 
2287     /*
2288      * Call the shell to execute the command (errors are ignored).
2289      * Don't check timestamps here.
2290      */
2291     ++no_check_timestamps;
2292     call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
2293     --no_check_timestamps;
2294 
2295     vim_free(command);
2296 
2297     /*
2298      * read the names from the file into memory
2299      */
2300 # ifdef VMS
2301     // created temporary file is not always readable as binary
2302     fd = mch_fopen((char *)tempname, "r");
2303 # else
2304     fd = mch_fopen((char *)tempname, READBIN);
2305 # endif
2306 
2307     if (fd == NULL)
2308     {
2309 	semsg(_(e_notopen), tempname);
2310 	goto done;
2311     }
2312 
2313     fseek(fd, 0L, SEEK_END);
2314     len = ftell(fd);		    // get size of temp file
2315     fseek(fd, 0L, SEEK_SET);
2316 
2317     buffer = alloc(len + 1);
2318     if (buffer != NULL)
2319 	i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
2320     fclose(fd);
2321     mch_remove(tempname);
2322     if (buffer == NULL)
2323 	goto done;
2324 #ifdef VMS
2325     len = i;	// VMS doesn't give us what we asked for...
2326 #endif
2327     if (i != len)
2328     {
2329 	semsg(_(e_notread), tempname);
2330 	VIM_CLEAR(buffer);
2331     }
2332     else if (ret_len == NULL)
2333     {
2334 	// Change NUL into SOH, otherwise the string is truncated.
2335 	for (i = 0; i < len; ++i)
2336 	    if (buffer[i] == NUL)
2337 		buffer[i] = 1;
2338 
2339 	buffer[len] = NUL;	// make sure the buffer is terminated
2340     }
2341     else
2342 	*ret_len = len;
2343 
2344 done:
2345     vim_free(tempname);
2346     return buffer;
2347 }
2348 
2349 # if defined(FEAT_EVAL) || defined(PROTO)
2350 
2351     static void
2352 get_cmd_output_as_rettv(
2353     typval_T	*argvars,
2354     typval_T	*rettv,
2355     int		retlist)
2356 {
2357     char_u	*res = NULL;
2358     char_u	*p;
2359     char_u	*infile = NULL;
2360     int		err = FALSE;
2361     FILE	*fd;
2362     list_T	*list = NULL;
2363     int		flags = SHELL_SILENT;
2364 
2365     rettv->v_type = VAR_STRING;
2366     rettv->vval.v_string = NULL;
2367     if (check_restricted() || check_secure())
2368 	goto errret;
2369 
2370     if (argvars[1].v_type != VAR_UNKNOWN)
2371     {
2372 	/*
2373 	 * Write the text to a temp file, to be used for input of the shell
2374 	 * command.
2375 	 */
2376 	if ((infile = vim_tempname('i', TRUE)) == NULL)
2377 	{
2378 	    emsg(_(e_notmp));
2379 	    goto errret;
2380 	}
2381 
2382 	fd = mch_fopen((char *)infile, WRITEBIN);
2383 	if (fd == NULL)
2384 	{
2385 	    semsg(_(e_notopen), infile);
2386 	    goto errret;
2387 	}
2388 	if (argvars[1].v_type == VAR_NUMBER)
2389 	{
2390 	    linenr_T	lnum;
2391 	    buf_T	*buf;
2392 
2393 	    buf = buflist_findnr(argvars[1].vval.v_number);
2394 	    if (buf == NULL)
2395 	    {
2396 		semsg(_(e_nobufnr), argvars[1].vval.v_number);
2397 		fclose(fd);
2398 		goto errret;
2399 	    }
2400 
2401 	    for (lnum = 1; lnum <= buf->b_ml.ml_line_count; lnum++)
2402 	    {
2403 		for (p = ml_get_buf(buf, lnum, FALSE); *p != NUL; ++p)
2404 		    if (putc(*p == '\n' ? NUL : *p, fd) == EOF)
2405 		    {
2406 			err = TRUE;
2407 			break;
2408 		    }
2409 		if (putc(NL, fd) == EOF)
2410 		{
2411 		    err = TRUE;
2412 		    break;
2413 		}
2414 	    }
2415 	}
2416 	else if (argvars[1].v_type == VAR_LIST)
2417 	{
2418 	    if (write_list(fd, argvars[1].vval.v_list, TRUE) == FAIL)
2419 		err = TRUE;
2420 	}
2421 	else
2422 	{
2423 	    size_t	len;
2424 	    char_u	buf[NUMBUFLEN];
2425 
2426 	    p = tv_get_string_buf_chk(&argvars[1], buf);
2427 	    if (p == NULL)
2428 	    {
2429 		fclose(fd);
2430 		goto errret;		// type error; errmsg already given
2431 	    }
2432 	    len = STRLEN(p);
2433 	    if (len > 0 && fwrite(p, len, 1, fd) != 1)
2434 		err = TRUE;
2435 	}
2436 	if (fclose(fd) != 0)
2437 	    err = TRUE;
2438 	if (err)
2439 	{
2440 	    emsg(_("E677: Error writing temp file"));
2441 	    goto errret;
2442 	}
2443     }
2444 
2445     // Omit SHELL_COOKED when invoked with ":silent".  Avoids that the shell
2446     // echoes typeahead, that messes up the display.
2447     if (!msg_silent)
2448 	flags += SHELL_COOKED;
2449 
2450     if (retlist)
2451     {
2452 	int		len;
2453 	listitem_T	*li;
2454 	char_u		*s = NULL;
2455 	char_u		*start;
2456 	char_u		*end;
2457 	int		i;
2458 
2459 	res = get_cmd_output(tv_get_string(&argvars[0]), infile, flags, &len);
2460 	if (res == NULL)
2461 	    goto errret;
2462 
2463 	list = list_alloc();
2464 	if (list == NULL)
2465 	    goto errret;
2466 
2467 	for (i = 0; i < len; ++i)
2468 	{
2469 	    start = res + i;
2470 	    while (i < len && res[i] != NL)
2471 		++i;
2472 	    end = res + i;
2473 
2474 	    s = alloc(end - start + 1);
2475 	    if (s == NULL)
2476 		goto errret;
2477 
2478 	    for (p = s; start < end; ++p, ++start)
2479 		*p = *start == NUL ? NL : *start;
2480 	    *p = NUL;
2481 
2482 	    li = listitem_alloc();
2483 	    if (li == NULL)
2484 	    {
2485 		vim_free(s);
2486 		goto errret;
2487 	    }
2488 	    li->li_tv.v_type = VAR_STRING;
2489 	    li->li_tv.v_lock = 0;
2490 	    li->li_tv.vval.v_string = s;
2491 	    list_append(list, li);
2492 	}
2493 
2494 	rettv_list_set(rettv, list);
2495 	list = NULL;
2496     }
2497     else
2498     {
2499 	res = get_cmd_output(tv_get_string(&argvars[0]), infile, flags, NULL);
2500 #ifdef USE_CRNL
2501 	// translate <CR><NL> into <NL>
2502 	if (res != NULL)
2503 	{
2504 	    char_u	*s, *d;
2505 
2506 	    d = res;
2507 	    for (s = res; *s; ++s)
2508 	    {
2509 		if (s[0] == CAR && s[1] == NL)
2510 		    ++s;
2511 		*d++ = *s;
2512 	    }
2513 	    *d = NUL;
2514 	}
2515 #endif
2516 	rettv->vval.v_string = res;
2517 	res = NULL;
2518     }
2519 
2520 errret:
2521     if (infile != NULL)
2522     {
2523 	mch_remove(infile);
2524 	vim_free(infile);
2525     }
2526     if (res != NULL)
2527 	vim_free(res);
2528     if (list != NULL)
2529 	list_free(list);
2530 }
2531 
2532 /*
2533  * "system()" function
2534  */
2535     void
2536 f_system(typval_T *argvars, typval_T *rettv)
2537 {
2538     get_cmd_output_as_rettv(argvars, rettv, FALSE);
2539 }
2540 
2541 /*
2542  * "systemlist()" function
2543  */
2544     void
2545 f_systemlist(typval_T *argvars, typval_T *rettv)
2546 {
2547     get_cmd_output_as_rettv(argvars, rettv, TRUE);
2548 }
2549 # endif // FEAT_EVAL
2550 
2551 #endif
2552 
2553 /*
2554  * Return TRUE when need to go to Insert mode because of 'insertmode'.
2555  * Don't do this when still processing a command or a mapping.
2556  * Don't do this when inside a ":normal" command.
2557  */
2558     int
2559 goto_im(void)
2560 {
2561     return (p_im && stuff_empty() && typebuf_typed());
2562 }
2563 
2564 /*
2565  * Returns the isolated name of the shell in allocated memory:
2566  * - Skip beyond any path.  E.g., "/usr/bin/csh -f" -> "csh -f".
2567  * - Remove any argument.  E.g., "csh -f" -> "csh".
2568  * But don't allow a space in the path, so that this works:
2569  *   "/usr/bin/csh --rcfile ~/.cshrc"
2570  * But don't do that for Windows, it's common to have a space in the path.
2571  * Returns NULL when out of memory.
2572  */
2573     char_u *
2574 get_isolated_shell_name(void)
2575 {
2576     char_u *p;
2577 
2578 #ifdef MSWIN
2579     p = gettail(p_sh);
2580     p = vim_strnsave(p, skiptowhite(p) - p);
2581 #else
2582     p = skiptowhite(p_sh);
2583     if (*p == NUL)
2584     {
2585 	// No white space, use the tail.
2586 	p = vim_strsave(gettail(p_sh));
2587     }
2588     else
2589     {
2590 	char_u  *p1, *p2;
2591 
2592 	// Find the last path separator before the space.
2593 	p1 = p_sh;
2594 	for (p2 = p_sh; p2 < p; MB_PTR_ADV(p2))
2595 	    if (vim_ispathsep(*p2))
2596 		p1 = p2 + 1;
2597 	p = vim_strnsave(p1, p - p1);
2598     }
2599 #endif
2600     return p;
2601 }
2602 
2603 /*
2604  * Check if the "://" of a URL is at the pointer, return URL_SLASH.
2605  * Also check for ":\\", which MS Internet Explorer accepts, return
2606  * URL_BACKSLASH.
2607  */
2608     int
2609 path_is_url(char_u *p)
2610 {
2611     if (STRNCMP(p, "://", (size_t)3) == 0)
2612 	return URL_SLASH;
2613     else if (STRNCMP(p, ":\\\\", (size_t)3) == 0)
2614 	return URL_BACKSLASH;
2615     return 0;
2616 }
2617 
2618 /*
2619  * Check if "fname" starts with "name://".  Return URL_SLASH if it does.
2620  * Return URL_BACKSLASH for "name:\\".
2621  * Return zero otherwise.
2622  */
2623     int
2624 path_with_url(char_u *fname)
2625 {
2626     char_u *p;
2627 
2628     for (p = fname; isalpha(*p); ++p)
2629 	;
2630     return path_is_url(p);
2631 }
2632