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