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