xref: /vim-8.2.3635/src/misc1.c (revision 723d165c)
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(FEAT_CMDL_COMPL) && defined(MSWIN)
18 # include <lm.h>
19 #endif
20 
21 static char_u *vim_version_dir(char_u *vimdir);
22 static char_u *remove_tail(char_u *p, char_u *pend, char_u *name);
23 
24 #define URL_SLASH	1		/* path_is_url() has found "://" */
25 #define URL_BACKSLASH	2		/* path_is_url() has found ":\\" */
26 
27 /* All user names (for ~user completion as done by shell). */
28 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
29 static garray_T	ga_users;
30 #endif
31 
32 /*
33  * Count the size (in window cells) of the indent in the current line.
34  */
35     int
36 get_indent(void)
37 {
38 #ifdef FEAT_VARTABS
39     return get_indent_str_vtab(ml_get_curline(), (int)curbuf->b_p_ts,
40 						 curbuf->b_p_vts_array, FALSE);
41 #else
42     return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts, FALSE);
43 #endif
44 }
45 
46 /*
47  * Count the size (in window cells) of the indent in line "lnum".
48  */
49     int
50 get_indent_lnum(linenr_T lnum)
51 {
52 #ifdef FEAT_VARTABS
53     return get_indent_str_vtab(ml_get(lnum), (int)curbuf->b_p_ts,
54 						 curbuf->b_p_vts_array, FALSE);
55 #else
56     return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts, FALSE);
57 #endif
58 }
59 
60 #if defined(FEAT_FOLDING) || defined(PROTO)
61 /*
62  * Count the size (in window cells) of the indent in line "lnum" of buffer
63  * "buf".
64  */
65     int
66 get_indent_buf(buf_T *buf, linenr_T lnum)
67 {
68 #ifdef FEAT_VARTABS
69     return get_indent_str_vtab(ml_get_buf(buf, lnum, FALSE),
70 			       (int)curbuf->b_p_ts, buf->b_p_vts_array, FALSE);
71 #else
72     return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts, FALSE);
73 #endif
74 }
75 #endif
76 
77 /*
78  * count the size (in window cells) of the indent in line "ptr", with
79  * 'tabstop' at "ts"
80  */
81     int
82 get_indent_str(
83     char_u	*ptr,
84     int		ts,
85     int		list) /* if TRUE, count only screen size for tabs */
86 {
87     int		count = 0;
88 
89     for ( ; *ptr; ++ptr)
90     {
91 	if (*ptr == TAB)
92 	{
93 	    if (!list || lcs_tab1)    /* count a tab for what it is worth */
94 		count += ts - (count % ts);
95 	    else
96 		/* In list mode, when tab is not set, count screen char width
97 		 * for Tab, displays: ^I */
98 		count += ptr2cells(ptr);
99 	}
100 	else if (*ptr == ' ')
101 	    ++count;		/* count a space for one */
102 	else
103 	    break;
104     }
105     return count;
106 }
107 
108 #ifdef FEAT_VARTABS
109 /*
110  * Count the size (in window cells) of the indent in line "ptr", using
111  * variable tabstops.
112  * if "list" is TRUE, count only screen size for tabs.
113  */
114     int
115 get_indent_str_vtab(char_u *ptr, int ts, int *vts, int list)
116 {
117     int		count = 0;
118 
119     for ( ; *ptr; ++ptr)
120     {
121 	if (*ptr == TAB)    /* count a tab for what it is worth */
122 	{
123 	    if (!list || lcs_tab1)
124 		count += tabstop_padding(count, ts, vts);
125 	    else
126 		/* In list mode, when tab is not set, count screen char width
127 		 * for Tab, displays: ^I */
128 		count += ptr2cells(ptr);
129 	}
130 	else if (*ptr == ' ')
131 	    ++count;		/* count a space for one */
132 	else
133 	    break;
134     }
135     return count;
136 }
137 #endif
138 
139 /*
140  * Set the indent of the current line.
141  * Leaves the cursor on the first non-blank in the line.
142  * Caller must take care of undo.
143  * "flags":
144  *	SIN_CHANGED:	call changed_bytes() if the line was changed.
145  *	SIN_INSERT:	insert the indent in front of the line.
146  *	SIN_UNDO:	save line for undo before changing it.
147  * Returns TRUE if the line was changed.
148  */
149     int
150 set_indent(
151     int		size,		    /* measured in spaces */
152     int		flags)
153 {
154     char_u	*p;
155     char_u	*newline;
156     char_u	*oldline;
157     char_u	*s;
158     int		todo;
159     int		ind_len;	    /* measured in characters */
160     int		line_len;
161     int		doit = FALSE;
162     int		ind_done = 0;	    /* measured in spaces */
163 #ifdef FEAT_VARTABS
164     int		ind_col = 0;
165 #endif
166     int		tab_pad;
167     int		retval = FALSE;
168     int		orig_char_len = -1; /* number of initial whitespace chars when
169 				       'et' and 'pi' are both set */
170 
171     /*
172      * First check if there is anything to do and compute the number of
173      * characters needed for the indent.
174      */
175     todo = size;
176     ind_len = 0;
177     p = oldline = ml_get_curline();
178 
179     /* Calculate the buffer size for the new indent, and check to see if it
180      * isn't already set */
181 
182     /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
183      * 'preserveindent' are set count the number of characters at the
184      * beginning of the line to be copied */
185     if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
186     {
187 	/* If 'preserveindent' is set then reuse as much as possible of
188 	 * the existing indent structure for the new indent */
189 	if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
190 	{
191 	    ind_done = 0;
192 
193 	    /* count as many characters as we can use */
194 	    while (todo > 0 && VIM_ISWHITE(*p))
195 	    {
196 		if (*p == TAB)
197 		{
198 #ifdef FEAT_VARTABS
199 		    tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
200 							curbuf->b_p_vts_array);
201 #else
202 		    tab_pad = (int)curbuf->b_p_ts
203 					   - (ind_done % (int)curbuf->b_p_ts);
204 #endif
205 		    /* stop if this tab will overshoot the target */
206 		    if (todo < tab_pad)
207 			break;
208 		    todo -= tab_pad;
209 		    ++ind_len;
210 		    ind_done += tab_pad;
211 		}
212 		else
213 		{
214 		    --todo;
215 		    ++ind_len;
216 		    ++ind_done;
217 		}
218 		++p;
219 	    }
220 
221 #ifdef FEAT_VARTABS
222 	    /* These diverge from this point. */
223 	    ind_col = ind_done;
224 #endif
225 	    /* Set initial number of whitespace chars to copy if we are
226 	     * preserving indent but expandtab is set */
227 	    if (curbuf->b_p_et)
228 		orig_char_len = ind_len;
229 
230 	    /* Fill to next tabstop with a tab, if possible */
231 #ifdef FEAT_VARTABS
232 	    tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
233 						curbuf->b_p_vts_array);
234 #else
235 	    tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
236 #endif
237 	    if (todo >= tab_pad && orig_char_len == -1)
238 	    {
239 		doit = TRUE;
240 		todo -= tab_pad;
241 		++ind_len;
242 		/* ind_done += tab_pad; */
243 #ifdef FEAT_VARTABS
244 		ind_col += tab_pad;
245 #endif
246 	    }
247 	}
248 
249 	/* count tabs required for indent */
250 #ifdef FEAT_VARTABS
251 	for (;;)
252 	{
253 	    tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,
254 							curbuf->b_p_vts_array);
255 	    if (todo < tab_pad)
256 		break;
257 	    if (*p != TAB)
258 		doit = TRUE;
259 	    else
260 		++p;
261 	    todo -= tab_pad;
262 	    ++ind_len;
263 	    ind_col += tab_pad;
264 	}
265 #else
266 	while (todo >= (int)curbuf->b_p_ts)
267 	{
268 	    if (*p != TAB)
269 		doit = TRUE;
270 	    else
271 		++p;
272 	    todo -= (int)curbuf->b_p_ts;
273 	    ++ind_len;
274 	    /* ind_done += (int)curbuf->b_p_ts; */
275 	}
276 #endif
277     }
278     /* count spaces required for indent */
279     while (todo > 0)
280     {
281 	if (*p != ' ')
282 	    doit = TRUE;
283 	else
284 	    ++p;
285 	--todo;
286 	++ind_len;
287 	/* ++ind_done; */
288     }
289 
290     /* Return if the indent is OK already. */
291     if (!doit && !VIM_ISWHITE(*p) && !(flags & SIN_INSERT))
292 	return FALSE;
293 
294     /* Allocate memory for the new line. */
295     if (flags & SIN_INSERT)
296 	p = oldline;
297     else
298 	p = skipwhite(p);
299     line_len = (int)STRLEN(p) + 1;
300 
301     /* If 'preserveindent' and 'expandtab' are both set keep the original
302      * characters and allocate accordingly.  We will fill the rest with spaces
303      * after the if (!curbuf->b_p_et) below. */
304     if (orig_char_len != -1)
305     {
306 	newline = alloc(orig_char_len + size - ind_done + line_len);
307 	if (newline == NULL)
308 	    return FALSE;
309 	todo = size - ind_done;
310 	ind_len = orig_char_len + todo;    /* Set total length of indent in
311 					    * characters, which may have been
312 					    * undercounted until now  */
313 	p = oldline;
314 	s = newline;
315 	while (orig_char_len > 0)
316 	{
317 	    *s++ = *p++;
318 	    orig_char_len--;
319 	}
320 
321 	/* Skip over any additional white space (useful when newindent is less
322 	 * than old) */
323 	while (VIM_ISWHITE(*p))
324 	    ++p;
325 
326     }
327     else
328     {
329 	todo = size;
330 	newline = alloc(ind_len + line_len);
331 	if (newline == NULL)
332 	    return FALSE;
333 	s = newline;
334     }
335 
336     /* Put the characters in the new line. */
337     /* if 'expandtab' isn't set: use TABs */
338     if (!curbuf->b_p_et)
339     {
340 	/* If 'preserveindent' is set then reuse as much as possible of
341 	 * the existing indent structure for the new indent */
342 	if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
343 	{
344 	    p = oldline;
345 	    ind_done = 0;
346 
347 	    while (todo > 0 && VIM_ISWHITE(*p))
348 	    {
349 		if (*p == TAB)
350 		{
351 #ifdef FEAT_VARTABS
352 		    tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
353 							curbuf->b_p_vts_array);
354 #else
355 		    tab_pad = (int)curbuf->b_p_ts
356 					   - (ind_done % (int)curbuf->b_p_ts);
357 #endif
358 		    /* stop if this tab will overshoot the target */
359 		    if (todo < tab_pad)
360 			break;
361 		    todo -= tab_pad;
362 		    ind_done += tab_pad;
363 		}
364 		else
365 		{
366 		    --todo;
367 		    ++ind_done;
368 		}
369 		*s++ = *p++;
370 	    }
371 
372 	    /* Fill to next tabstop with a tab, if possible */
373 #ifdef FEAT_VARTABS
374 	    tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
375 						curbuf->b_p_vts_array);
376 #else
377 	    tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
378 #endif
379 	    if (todo >= tab_pad)
380 	    {
381 		*s++ = TAB;
382 		todo -= tab_pad;
383 #ifdef FEAT_VARTABS
384 		ind_done += tab_pad;
385 #endif
386 	    }
387 
388 	    p = skipwhite(p);
389 	}
390 
391 #ifdef FEAT_VARTABS
392 	for (;;)
393 	{
394 	    tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
395 							curbuf->b_p_vts_array);
396 	    if (todo < tab_pad)
397 		break;
398 	    *s++ = TAB;
399 	    todo -= tab_pad;
400 	    ind_done += tab_pad;
401 	}
402 #else
403 	while (todo >= (int)curbuf->b_p_ts)
404 	{
405 	    *s++ = TAB;
406 	    todo -= (int)curbuf->b_p_ts;
407 	}
408 #endif
409     }
410     while (todo > 0)
411     {
412 	*s++ = ' ';
413 	--todo;
414     }
415     mch_memmove(s, p, (size_t)line_len);
416 
417     // Replace the line (unless undo fails).
418     if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
419     {
420 	ml_replace(curwin->w_cursor.lnum, newline, FALSE);
421 	if (flags & SIN_CHANGED)
422 	    changed_bytes(curwin->w_cursor.lnum, 0);
423 
424 	// Correct saved cursor position if it is in this line.
425 	if (saved_cursor.lnum == curwin->w_cursor.lnum)
426 	{
427 	    if (saved_cursor.col >= (colnr_T)(p - oldline))
428 		// cursor was after the indent, adjust for the number of
429 		// bytes added/removed
430 		saved_cursor.col += ind_len - (colnr_T)(p - oldline);
431 	    else if (saved_cursor.col >= (colnr_T)(s - newline))
432 		// cursor was in the indent, and is now after it, put it back
433 		// at the start of the indent (replacing spaces with TAB)
434 		saved_cursor.col = (colnr_T)(s - newline);
435 	}
436 #ifdef FEAT_TEXT_PROP
437 	adjust_prop_columns(curwin->w_cursor.lnum, (colnr_T)(p - oldline),
438 					     ind_len - (colnr_T)(p - oldline));
439 #endif
440 	retval = TRUE;
441     }
442     else
443 	vim_free(newline);
444 
445     curwin->w_cursor.col = ind_len;
446     return retval;
447 }
448 
449 /*
450  * Copy the indent from ptr to the current line (and fill to size)
451  * Leaves the cursor on the first non-blank in the line.
452  * Returns TRUE if the line was changed.
453  */
454     static int
455 copy_indent(int size, char_u *src)
456 {
457     char_u	*p = NULL;
458     char_u	*line = NULL;
459     char_u	*s;
460     int		todo;
461     int		ind_len;
462     int		line_len = 0;
463     int		tab_pad;
464     int		ind_done;
465     int		round;
466 #ifdef FEAT_VARTABS
467     int		ind_col;
468 #endif
469 
470     /* Round 1: compute the number of characters needed for the indent
471      * Round 2: copy the characters. */
472     for (round = 1; round <= 2; ++round)
473     {
474 	todo = size;
475 	ind_len = 0;
476 	ind_done = 0;
477 #ifdef FEAT_VARTABS
478 	ind_col = 0;
479 #endif
480 	s = src;
481 
482 	/* Count/copy the usable portion of the source line */
483 	while (todo > 0 && VIM_ISWHITE(*s))
484 	{
485 	    if (*s == TAB)
486 	    {
487 #ifdef FEAT_VARTABS
488 		tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
489 							curbuf->b_p_vts_array);
490 #else
491 		tab_pad = (int)curbuf->b_p_ts
492 					   - (ind_done % (int)curbuf->b_p_ts);
493 #endif
494 		/* Stop if this tab will overshoot the target */
495 		if (todo < tab_pad)
496 		    break;
497 		todo -= tab_pad;
498 		ind_done += tab_pad;
499 #ifdef FEAT_VARTABS
500 		ind_col += tab_pad;
501 #endif
502 	    }
503 	    else
504 	    {
505 		--todo;
506 		++ind_done;
507 #ifdef FEAT_VARTABS
508 		++ind_col;
509 #endif
510 	    }
511 	    ++ind_len;
512 	    if (p != NULL)
513 		*p++ = *s;
514 	    ++s;
515 	}
516 
517 	/* Fill to next tabstop with a tab, if possible */
518 #ifdef FEAT_VARTABS
519 	tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
520 							curbuf->b_p_vts_array);
521 #else
522 	tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
523 #endif
524 	if (todo >= tab_pad && !curbuf->b_p_et)
525 	{
526 	    todo -= tab_pad;
527 	    ++ind_len;
528 #ifdef FEAT_VARTABS
529 	    ind_col += tab_pad;
530 #endif
531 	    if (p != NULL)
532 		*p++ = TAB;
533 	}
534 
535 	/* Add tabs required for indent */
536 	if (!curbuf->b_p_et)
537 	{
538 #ifdef FEAT_VARTABS
539 	    for (;;)
540 	    {
541 		tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,
542 							curbuf->b_p_vts_array);
543 		if (todo < tab_pad)
544 		    break;
545 		todo -= tab_pad;
546 		++ind_len;
547 		ind_col += tab_pad;
548 		if (p != NULL)
549 		    *p++ = TAB;
550 	    }
551 #else
552 	    while (todo >= (int)curbuf->b_p_ts)
553 	    {
554 		todo -= (int)curbuf->b_p_ts;
555 		++ind_len;
556 		if (p != NULL)
557 		    *p++ = TAB;
558 	    }
559 #endif
560 	}
561 
562 	/* Count/add spaces required for indent */
563 	while (todo > 0)
564 	{
565 	    --todo;
566 	    ++ind_len;
567 	    if (p != NULL)
568 		*p++ = ' ';
569 	}
570 
571 	if (p == NULL)
572 	{
573 	    /* Allocate memory for the result: the copied indent, new indent
574 	     * and the rest of the line. */
575 	    line_len = (int)STRLEN(ml_get_curline()) + 1;
576 	    line = alloc(ind_len + line_len);
577 	    if (line == NULL)
578 		return FALSE;
579 	    p = line;
580 	}
581     }
582 
583     /* Append the original line */
584     mch_memmove(p, ml_get_curline(), (size_t)line_len);
585 
586     /* Replace the line */
587     ml_replace(curwin->w_cursor.lnum, line, FALSE);
588 
589     /* Put the cursor after the indent. */
590     curwin->w_cursor.col = ind_len;
591     return TRUE;
592 }
593 
594 /*
595  * Return the indent of the current line after a number.  Return -1 if no
596  * number was found.  Used for 'n' in 'formatoptions': numbered list.
597  * Since a pattern is used it can actually handle more than numbers.
598  */
599     int
600 get_number_indent(linenr_T lnum)
601 {
602     colnr_T	col;
603     pos_T	pos;
604 
605     regmatch_T	regmatch;
606     int		lead_len = 0;	/* length of comment leader */
607 
608     if (lnum > curbuf->b_ml.ml_line_count)
609 	return -1;
610     pos.lnum = 0;
611 
612 #ifdef FEAT_COMMENTS
613     /* In format_lines() (i.e. not insert mode), fo+=q is needed too...  */
614     if ((State & INSERT) || has_format_option(FO_Q_COMS))
615 	lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
616 #endif
617     regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
618     if (regmatch.regprog != NULL)
619     {
620 	regmatch.rm_ic = FALSE;
621 
622 	/* vim_regexec() expects a pointer to a line.  This lets us
623 	 * start matching for the flp beyond any comment leader...  */
624 	if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0))
625 	{
626 	    pos.lnum = lnum;
627 	    pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
628 	    pos.coladd = 0;
629 	}
630 	vim_regfree(regmatch.regprog);
631     }
632 
633     if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
634 	return -1;
635     getvcol(curwin, &pos, &col, NULL, NULL);
636     return (int)col;
637 }
638 
639 #if defined(FEAT_LINEBREAK) || defined(PROTO)
640 /*
641  * Return appropriate space number for breakindent, taking influencing
642  * parameters into account. Window must be specified, since it is not
643  * necessarily always the current one.
644  */
645     int
646 get_breakindent_win(
647     win_T	*wp,
648     char_u	*line) /* start of the line */
649 {
650     static int	    prev_indent = 0;  /* cached indent value */
651     static long	    prev_ts     = 0L; /* cached tabstop value */
652     static char_u   *prev_line = NULL; /* cached pointer to line */
653     static varnumber_T prev_tick = 0;   /* changedtick of cached value */
654 #ifdef FEAT_VARTABS
655     static int      *prev_vts = NULL;    /* cached vartabs values */
656 #endif
657     int		    bri = 0;
658     /* window width minus window margin space, i.e. what rests for text */
659     const int	    eff_wwidth = wp->w_width
660 			    - ((wp->w_p_nu || wp->w_p_rnu)
661 				&& (vim_strchr(p_cpo, CPO_NUMCOL) == NULL)
662 						? number_width(wp) + 1 : 0);
663 
664     /* used cached indent, unless pointer or 'tabstop' changed */
665     if (prev_line != line || prev_ts != wp->w_buffer->b_p_ts
666 	    || prev_tick != CHANGEDTICK(wp->w_buffer)
667 #ifdef FEAT_VARTABS
668 	    || prev_vts != wp->w_buffer->b_p_vts_array
669 #endif
670 	)
671     {
672 	prev_line = line;
673 	prev_ts = wp->w_buffer->b_p_ts;
674 	prev_tick = CHANGEDTICK(wp->w_buffer);
675 #ifdef FEAT_VARTABS
676 	prev_vts = wp->w_buffer->b_p_vts_array;
677 	prev_indent = get_indent_str_vtab(line,
678 				     (int)wp->w_buffer->b_p_ts,
679 				    wp->w_buffer->b_p_vts_array, wp->w_p_list);
680 #else
681 	prev_indent = get_indent_str(line,
682 				     (int)wp->w_buffer->b_p_ts, wp->w_p_list);
683 #endif
684     }
685     bri = prev_indent + wp->w_p_brishift;
686 
687     /* indent minus the length of the showbreak string */
688     if (wp->w_p_brisbr)
689 	bri -= vim_strsize(p_sbr);
690 
691     /* Add offset for number column, if 'n' is in 'cpoptions' */
692     bri += win_col_off2(wp);
693 
694     /* never indent past left window margin */
695     if (bri < 0)
696 	bri = 0;
697     /* always leave at least bri_min characters on the left,
698      * if text width is sufficient */
699     else if (bri > eff_wwidth - wp->w_p_brimin)
700 	bri = (eff_wwidth - wp->w_p_brimin < 0)
701 			    ? 0 : eff_wwidth - wp->w_p_brimin;
702 
703     return bri;
704 }
705 #endif
706 
707 
708 /*
709  * open_line: Add a new line below or above the current line.
710  *
711  * For VREPLACE mode, we only add a new line when we get to the end of the
712  * file, otherwise we just start replacing the next line.
713  *
714  * Caller must take care of undo.  Since VREPLACE may affect any number of
715  * lines however, it may call u_save_cursor() again when starting to change a
716  * new line.
717  * "flags": OPENLINE_DELSPACES	delete spaces after cursor
718  *	    OPENLINE_DO_COM	format comments
719  *	    OPENLINE_KEEPTRAIL	keep trailing spaces
720  *	    OPENLINE_MARKFIX	adjust mark positions after the line break
721  *	    OPENLINE_COM_LIST	format comments with list or 2nd line indent
722  *
723  * "second_line_indent": indent for after ^^D in Insert mode or if flag
724  *			  OPENLINE_COM_LIST
725  *
726  * Return OK for success, FAIL for failure
727  */
728     int
729 open_line(
730     int		dir,		/* FORWARD or BACKWARD */
731     int		flags,
732     int		second_line_indent)
733 {
734     char_u	*saved_line;		/* copy of the original line */
735     char_u	*next_line = NULL;	/* copy of the next line */
736     char_u	*p_extra = NULL;	/* what goes to next line */
737     int		less_cols = 0;		/* less columns for mark in new line */
738     int		less_cols_off = 0;	/* columns to skip for mark adjust */
739     pos_T	old_cursor;		/* old cursor position */
740     int		newcol = 0;		/* new cursor column */
741     int		newindent = 0;		/* auto-indent of the new line */
742     int		n;
743     int		trunc_line = FALSE;	/* truncate current line afterwards */
744     int		retval = FAIL;		/* return value */
745 #ifdef FEAT_COMMENTS
746     int		extra_len = 0;		/* length of p_extra string */
747     int		lead_len;		/* length of comment leader */
748     char_u	*lead_flags;	/* position in 'comments' for comment leader */
749     char_u	*leader = NULL;		/* copy of comment leader */
750 #endif
751     char_u	*allocated = NULL;	/* allocated memory */
752     char_u	*p;
753     int		saved_char = NUL;	/* init for GCC */
754 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
755     pos_T	*pos;
756 #endif
757 #ifdef FEAT_SMARTINDENT
758     int		do_si = (!p_paste && curbuf->b_p_si
759 # ifdef FEAT_CINDENT
760 					&& !curbuf->b_p_cin
761 # endif
762 # ifdef FEAT_EVAL
763 					&& *curbuf->b_p_inde == NUL
764 # endif
765 			);
766     int		no_si = FALSE;		/* reset did_si afterwards */
767     int		first_char = NUL;	/* init for GCC */
768 #endif
769 #if defined(FEAT_LISP) || defined(FEAT_CINDENT)
770     int		vreplace_mode;
771 #endif
772     int		did_append;		/* appended a new line */
773     int		saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
774 
775     /*
776      * make a copy of the current line so we can mess with it
777      */
778     saved_line = vim_strsave(ml_get_curline());
779     if (saved_line == NULL)	    /* out of memory! */
780 	return FALSE;
781 
782     if (State & VREPLACE_FLAG)
783     {
784 	/*
785 	 * With VREPLACE we make a copy of the next line, which we will be
786 	 * starting to replace.  First make the new line empty and let vim play
787 	 * with the indenting and comment leader to its heart's content.  Then
788 	 * we grab what it ended up putting on the new line, put back the
789 	 * original line, and call ins_char() to put each new character onto
790 	 * the line, replacing what was there before and pushing the right
791 	 * stuff onto the replace stack.  -- webb.
792 	 */
793 	if (curwin->w_cursor.lnum < orig_line_count)
794 	    next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
795 	else
796 	    next_line = vim_strsave((char_u *)"");
797 	if (next_line == NULL)	    /* out of memory! */
798 	    goto theend;
799 
800 	/*
801 	 * In VREPLACE mode, a NL replaces the rest of the line, and starts
802 	 * replacing the next line, so push all of the characters left on the
803 	 * line onto the replace stack.  We'll push any other characters that
804 	 * might be replaced at the start of the next line (due to autoindent
805 	 * etc) a bit later.
806 	 */
807 	replace_push(NUL);  /* Call twice because BS over NL expects it */
808 	replace_push(NUL);
809 	p = saved_line + curwin->w_cursor.col;
810 	while (*p != NUL)
811 	{
812 	    if (has_mbyte)
813 		p += replace_push_mb(p);
814 	    else
815 		replace_push(*p++);
816 	}
817 	saved_line[curwin->w_cursor.col] = NUL;
818     }
819 
820     if ((State & INSERT) && !(State & VREPLACE_FLAG))
821     {
822 	p_extra = saved_line + curwin->w_cursor.col;
823 #ifdef FEAT_SMARTINDENT
824 	if (do_si)		/* need first char after new line break */
825 	{
826 	    p = skipwhite(p_extra);
827 	    first_char = *p;
828 	}
829 #endif
830 #ifdef FEAT_COMMENTS
831 	extra_len = (int)STRLEN(p_extra);
832 #endif
833 	saved_char = *p_extra;
834 	*p_extra = NUL;
835     }
836 
837     u_clearline();		/* cannot do "U" command when adding lines */
838 #ifdef FEAT_SMARTINDENT
839     did_si = FALSE;
840 #endif
841     ai_col = 0;
842 
843     /*
844      * If we just did an auto-indent, then we didn't type anything on
845      * the prior line, and it should be truncated.  Do this even if 'ai' is not
846      * set because automatically inserting a comment leader also sets did_ai.
847      */
848     if (dir == FORWARD && did_ai)
849 	trunc_line = TRUE;
850 
851     /*
852      * If 'autoindent' and/or 'smartindent' is set, try to figure out what
853      * indent to use for the new line.
854      */
855     if (curbuf->b_p_ai
856 #ifdef FEAT_SMARTINDENT
857 			|| do_si
858 #endif
859 					    )
860     {
861 	/*
862 	 * count white space on current line
863 	 */
864 #ifdef FEAT_VARTABS
865 	newindent = get_indent_str_vtab(saved_line, curbuf->b_p_ts,
866 						 curbuf->b_p_vts_array, FALSE);
867 #else
868 	newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts, FALSE);
869 #endif
870 	if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
871 	    newindent = second_line_indent; /* for ^^D command in insert mode */
872 
873 #ifdef FEAT_SMARTINDENT
874 	/*
875 	 * Do smart indenting.
876 	 * In insert/replace mode (only when dir == FORWARD)
877 	 * we may move some text to the next line. If it starts with '{'
878 	 * don't add an indent. Fixes inserting a NL before '{' in line
879 	 *	"if (condition) {"
880 	 */
881 	if (!trunc_line && do_si && *saved_line != NUL
882 				    && (p_extra == NULL || first_char != '{'))
883 	{
884 	    char_u  *ptr;
885 	    char_u  last_char;
886 
887 	    old_cursor = curwin->w_cursor;
888 	    ptr = saved_line;
889 # ifdef FEAT_COMMENTS
890 	    if (flags & OPENLINE_DO_COM)
891 		lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
892 	    else
893 		lead_len = 0;
894 # endif
895 	    if (dir == FORWARD)
896 	    {
897 		/*
898 		 * Skip preprocessor directives, unless they are
899 		 * recognised as comments.
900 		 */
901 		if (
902 # ifdef FEAT_COMMENTS
903 			lead_len == 0 &&
904 # endif
905 			ptr[0] == '#')
906 		{
907 		    while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
908 			ptr = ml_get(--curwin->w_cursor.lnum);
909 		    newindent = get_indent();
910 		}
911 # ifdef FEAT_COMMENTS
912 		if (flags & OPENLINE_DO_COM)
913 		    lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
914 		else
915 		    lead_len = 0;
916 		if (lead_len > 0)
917 		{
918 		    /*
919 		     * This case gets the following right:
920 		     *	    \*
921 		     *	     * A comment (read '\' as '/').
922 		     *	     *\
923 		     * #define IN_THE_WAY
924 		     *	    This should line up here;
925 		     */
926 		    p = skipwhite(ptr);
927 		    if (p[0] == '/' && p[1] == '*')
928 			p++;
929 		    if (p[0] == '*')
930 		    {
931 			for (p++; *p; p++)
932 			{
933 			    if (p[0] == '/' && p[-1] == '*')
934 			    {
935 				/*
936 				 * End of C comment, indent should line up
937 				 * with the line containing the start of
938 				 * the comment
939 				 */
940 				curwin->w_cursor.col = (colnr_T)(p - ptr);
941 				if ((pos = findmatch(NULL, NUL)) != NULL)
942 				{
943 				    curwin->w_cursor.lnum = pos->lnum;
944 				    newindent = get_indent();
945 				}
946 			    }
947 			}
948 		    }
949 		}
950 		else	/* Not a comment line */
951 # endif
952 		{
953 		    /* Find last non-blank in line */
954 		    p = ptr + STRLEN(ptr) - 1;
955 		    while (p > ptr && VIM_ISWHITE(*p))
956 			--p;
957 		    last_char = *p;
958 
959 		    /*
960 		     * find the character just before the '{' or ';'
961 		     */
962 		    if (last_char == '{' || last_char == ';')
963 		    {
964 			if (p > ptr)
965 			    --p;
966 			while (p > ptr && VIM_ISWHITE(*p))
967 			    --p;
968 		    }
969 		    /*
970 		     * Try to catch lines that are split over multiple
971 		     * lines.  eg:
972 		     *	    if (condition &&
973 		     *			condition) {
974 		     *		Should line up here!
975 		     *	    }
976 		     */
977 		    if (*p == ')')
978 		    {
979 			curwin->w_cursor.col = (colnr_T)(p - ptr);
980 			if ((pos = findmatch(NULL, '(')) != NULL)
981 			{
982 			    curwin->w_cursor.lnum = pos->lnum;
983 			    newindent = get_indent();
984 			    ptr = ml_get_curline();
985 			}
986 		    }
987 		    /*
988 		     * If last character is '{' do indent, without
989 		     * checking for "if" and the like.
990 		     */
991 		    if (last_char == '{')
992 		    {
993 			did_si = TRUE;	/* do indent */
994 			no_si = TRUE;	/* don't delete it when '{' typed */
995 		    }
996 		    /*
997 		     * Look for "if" and the like, use 'cinwords'.
998 		     * Don't do this if the previous line ended in ';' or
999 		     * '}'.
1000 		     */
1001 		    else if (last_char != ';' && last_char != '}'
1002 						       && cin_is_cinword(ptr))
1003 			did_si = TRUE;
1004 		}
1005 	    }
1006 	    else /* dir == BACKWARD */
1007 	    {
1008 		/*
1009 		 * Skip preprocessor directives, unless they are
1010 		 * recognised as comments.
1011 		 */
1012 		if (
1013 # ifdef FEAT_COMMENTS
1014 			lead_len == 0 &&
1015 # endif
1016 			ptr[0] == '#')
1017 		{
1018 		    int was_backslashed = FALSE;
1019 
1020 		    while ((ptr[0] == '#' || was_backslashed) &&
1021 			 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
1022 		    {
1023 			if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
1024 			    was_backslashed = TRUE;
1025 			else
1026 			    was_backslashed = FALSE;
1027 			ptr = ml_get(++curwin->w_cursor.lnum);
1028 		    }
1029 		    if (was_backslashed)
1030 			newindent = 0;	    /* Got to end of file */
1031 		    else
1032 			newindent = get_indent();
1033 		}
1034 		p = skipwhite(ptr);
1035 		if (*p == '}')	    /* if line starts with '}': do indent */
1036 		    did_si = TRUE;
1037 		else		    /* can delete indent when '{' typed */
1038 		    can_si_back = TRUE;
1039 	    }
1040 	    curwin->w_cursor = old_cursor;
1041 	}
1042 	if (do_si)
1043 	    can_si = TRUE;
1044 #endif /* FEAT_SMARTINDENT */
1045 
1046 	did_ai = TRUE;
1047     }
1048 
1049 #ifdef FEAT_COMMENTS
1050     /*
1051      * Find out if the current line starts with a comment leader.
1052      * This may then be inserted in front of the new line.
1053      */
1054     end_comment_pending = NUL;
1055     if (flags & OPENLINE_DO_COM)
1056 	lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
1057     else
1058 	lead_len = 0;
1059     if (lead_len > 0)
1060     {
1061 	char_u	*lead_repl = NULL;	    /* replaces comment leader */
1062 	int	lead_repl_len = 0;	    /* length of *lead_repl */
1063 	char_u	lead_middle[COM_MAX_LEN];   /* middle-comment string */
1064 	char_u	lead_end[COM_MAX_LEN];	    /* end-comment string */
1065 	char_u	*comment_end = NULL;	    /* where lead_end has been found */
1066 	int	extra_space = FALSE;	    /* append extra space */
1067 	int	current_flag;
1068 	int	require_blank = FALSE;	    /* requires blank after middle */
1069 	char_u	*p2;
1070 
1071 	/*
1072 	 * If the comment leader has the start, middle or end flag, it may not
1073 	 * be used or may be replaced with the middle leader.
1074 	 */
1075 	for (p = lead_flags; *p && *p != ':'; ++p)
1076 	{
1077 	    if (*p == COM_BLANK)
1078 	    {
1079 		require_blank = TRUE;
1080 		continue;
1081 	    }
1082 	    if (*p == COM_START || *p == COM_MIDDLE)
1083 	    {
1084 		current_flag = *p;
1085 		if (*p == COM_START)
1086 		{
1087 		    /*
1088 		     * Doing "O" on a start of comment does not insert leader.
1089 		     */
1090 		    if (dir == BACKWARD)
1091 		    {
1092 			lead_len = 0;
1093 			break;
1094 		    }
1095 
1096 		    /* find start of middle part */
1097 		    (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
1098 		    require_blank = FALSE;
1099 		}
1100 
1101 		/*
1102 		 * Isolate the strings of the middle and end leader.
1103 		 */
1104 		while (*p && p[-1] != ':')	/* find end of middle flags */
1105 		{
1106 		    if (*p == COM_BLANK)
1107 			require_blank = TRUE;
1108 		    ++p;
1109 		}
1110 		(void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
1111 
1112 		while (*p && p[-1] != ':')	/* find end of end flags */
1113 		{
1114 		    /* Check whether we allow automatic ending of comments */
1115 		    if (*p == COM_AUTO_END)
1116 			end_comment_pending = -1; /* means we want to set it */
1117 		    ++p;
1118 		}
1119 		n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
1120 
1121 		if (end_comment_pending == -1)	/* we can set it now */
1122 		    end_comment_pending = lead_end[n - 1];
1123 
1124 		/*
1125 		 * If the end of the comment is in the same line, don't use
1126 		 * the comment leader.
1127 		 */
1128 		if (dir == FORWARD)
1129 		{
1130 		    for (p = saved_line + lead_len; *p; ++p)
1131 			if (STRNCMP(p, lead_end, n) == 0)
1132 			{
1133 			    comment_end = p;
1134 			    lead_len = 0;
1135 			    break;
1136 			}
1137 		}
1138 
1139 		/*
1140 		 * Doing "o" on a start of comment inserts the middle leader.
1141 		 */
1142 		if (lead_len > 0)
1143 		{
1144 		    if (current_flag == COM_START)
1145 		    {
1146 			lead_repl = lead_middle;
1147 			lead_repl_len = (int)STRLEN(lead_middle);
1148 		    }
1149 
1150 		    /*
1151 		     * If we have hit RETURN immediately after the start
1152 		     * comment leader, then put a space after the middle
1153 		     * comment leader on the next line.
1154 		     */
1155 		    if (!VIM_ISWHITE(saved_line[lead_len - 1])
1156 			    && ((p_extra != NULL
1157 				    && (int)curwin->w_cursor.col == lead_len)
1158 				|| (p_extra == NULL
1159 				    && saved_line[lead_len] == NUL)
1160 				|| require_blank))
1161 			extra_space = TRUE;
1162 		}
1163 		break;
1164 	    }
1165 	    if (*p == COM_END)
1166 	    {
1167 		/*
1168 		 * Doing "o" on the end of a comment does not insert leader.
1169 		 * Remember where the end is, might want to use it to find the
1170 		 * start (for C-comments).
1171 		 */
1172 		if (dir == FORWARD)
1173 		{
1174 		    comment_end = skipwhite(saved_line);
1175 		    lead_len = 0;
1176 		    break;
1177 		}
1178 
1179 		/*
1180 		 * Doing "O" on the end of a comment inserts the middle leader.
1181 		 * Find the string for the middle leader, searching backwards.
1182 		 */
1183 		while (p > curbuf->b_p_com && *p != ',')
1184 		    --p;
1185 		for (lead_repl = p; lead_repl > curbuf->b_p_com
1186 					 && lead_repl[-1] != ':'; --lead_repl)
1187 		    ;
1188 		lead_repl_len = (int)(p - lead_repl);
1189 
1190 		/* We can probably always add an extra space when doing "O" on
1191 		 * the comment-end */
1192 		extra_space = TRUE;
1193 
1194 		/* Check whether we allow automatic ending of comments */
1195 		for (p2 = p; *p2 && *p2 != ':'; p2++)
1196 		{
1197 		    if (*p2 == COM_AUTO_END)
1198 			end_comment_pending = -1; /* means we want to set it */
1199 		}
1200 		if (end_comment_pending == -1)
1201 		{
1202 		    /* Find last character in end-comment string */
1203 		    while (*p2 && *p2 != ',')
1204 			p2++;
1205 		    end_comment_pending = p2[-1];
1206 		}
1207 		break;
1208 	    }
1209 	    if (*p == COM_FIRST)
1210 	    {
1211 		/*
1212 		 * Comment leader for first line only:	Don't repeat leader
1213 		 * when using "O", blank out leader when using "o".
1214 		 */
1215 		if (dir == BACKWARD)
1216 		    lead_len = 0;
1217 		else
1218 		{
1219 		    lead_repl = (char_u *)"";
1220 		    lead_repl_len = 0;
1221 		}
1222 		break;
1223 	    }
1224 	}
1225 	if (lead_len)
1226 	{
1227 	    /* allocate buffer (may concatenate p_extra later) */
1228 	    leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
1229 		     + (second_line_indent > 0 ? second_line_indent : 0) + 1);
1230 	    allocated = leader;		    /* remember to free it later */
1231 
1232 	    if (leader == NULL)
1233 		lead_len = 0;
1234 	    else
1235 	    {
1236 		vim_strncpy(leader, saved_line, lead_len);
1237 
1238 		/*
1239 		 * Replace leader with lead_repl, right or left adjusted
1240 		 */
1241 		if (lead_repl != NULL)
1242 		{
1243 		    int		c = 0;
1244 		    int		off = 0;
1245 
1246 		    for (p = lead_flags; *p != NUL && *p != ':'; )
1247 		    {
1248 			if (*p == COM_RIGHT || *p == COM_LEFT)
1249 			    c = *p++;
1250 			else if (VIM_ISDIGIT(*p) || *p == '-')
1251 			    off = getdigits(&p);
1252 			else
1253 			    ++p;
1254 		    }
1255 		    if (c == COM_RIGHT)    /* right adjusted leader */
1256 		    {
1257 			/* find last non-white in the leader to line up with */
1258 			for (p = leader + lead_len - 1; p > leader
1259 						      && VIM_ISWHITE(*p); --p)
1260 			    ;
1261 			++p;
1262 
1263 			/* Compute the length of the replaced characters in
1264 			 * screen characters, not bytes. */
1265 			{
1266 			    int	    repl_size = vim_strnsize(lead_repl,
1267 							       lead_repl_len);
1268 			    int	    old_size = 0;
1269 			    char_u  *endp = p;
1270 			    int	    l;
1271 
1272 			    while (old_size < repl_size && p > leader)
1273 			    {
1274 				MB_PTR_BACK(leader, p);
1275 				old_size += ptr2cells(p);
1276 			    }
1277 			    l = lead_repl_len - (int)(endp - p);
1278 			    if (l != 0)
1279 				mch_memmove(endp + l, endp,
1280 					(size_t)((leader + lead_len) - endp));
1281 			    lead_len += l;
1282 			}
1283 			mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1284 			if (p + lead_repl_len > leader + lead_len)
1285 			    p[lead_repl_len] = NUL;
1286 
1287 			/* blank-out any other chars from the old leader. */
1288 			while (--p >= leader)
1289 			{
1290 			    int l = mb_head_off(leader, p);
1291 
1292 			    if (l > 1)
1293 			    {
1294 				p -= l;
1295 				if (ptr2cells(p) > 1)
1296 				{
1297 				    p[1] = ' ';
1298 				    --l;
1299 				}
1300 				mch_memmove(p + 1, p + l + 1,
1301 				   (size_t)((leader + lead_len) - (p + l + 1)));
1302 				lead_len -= l;
1303 				*p = ' ';
1304 			    }
1305 			    else if (!VIM_ISWHITE(*p))
1306 				*p = ' ';
1307 			}
1308 		    }
1309 		    else		    /* left adjusted leader */
1310 		    {
1311 			p = skipwhite(leader);
1312 
1313 			/* Compute the length of the replaced characters in
1314 			 * screen characters, not bytes. Move the part that is
1315 			 * not to be overwritten. */
1316 			{
1317 			    int	    repl_size = vim_strnsize(lead_repl,
1318 							       lead_repl_len);
1319 			    int	    i;
1320 			    int	    l;
1321 
1322 			    for (i = 0; i < lead_len && p[i] != NUL; i += l)
1323 			    {
1324 				l = (*mb_ptr2len)(p + i);
1325 				if (vim_strnsize(p, i + l) > repl_size)
1326 				    break;
1327 			    }
1328 			    if (i != lead_repl_len)
1329 			    {
1330 				mch_memmove(p + lead_repl_len, p + i,
1331 				       (size_t)(lead_len - i - (p - leader)));
1332 				lead_len += lead_repl_len - i;
1333 			    }
1334 			}
1335 			mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1336 
1337 			/* Replace any remaining non-white chars in the old
1338 			 * leader by spaces.  Keep Tabs, the indent must
1339 			 * remain the same. */
1340 			for (p += lead_repl_len; p < leader + lead_len; ++p)
1341 			    if (!VIM_ISWHITE(*p))
1342 			    {
1343 				/* Don't put a space before a TAB. */
1344 				if (p + 1 < leader + lead_len && p[1] == TAB)
1345 				{
1346 				    --lead_len;
1347 				    mch_memmove(p, p + 1,
1348 						     (leader + lead_len) - p);
1349 				}
1350 				else
1351 				{
1352 				    int	    l = (*mb_ptr2len)(p);
1353 
1354 				    if (l > 1)
1355 				    {
1356 					if (ptr2cells(p) > 1)
1357 					{
1358 					    /* Replace a double-wide char with
1359 					     * two spaces */
1360 					    --l;
1361 					    *p++ = ' ';
1362 					}
1363 					mch_memmove(p + 1, p + l,
1364 						     (leader + lead_len) - p);
1365 					lead_len -= l - 1;
1366 				    }
1367 				    *p = ' ';
1368 				}
1369 			    }
1370 			*p = NUL;
1371 		    }
1372 
1373 		    /* Recompute the indent, it may have changed. */
1374 		    if (curbuf->b_p_ai
1375 #ifdef FEAT_SMARTINDENT
1376 					|| do_si
1377 #endif
1378 							   )
1379 #ifdef FEAT_VARTABS
1380 			newindent = get_indent_str_vtab(leader, curbuf->b_p_ts,
1381 						 curbuf->b_p_vts_array, FALSE);
1382 #else
1383 			newindent = get_indent_str(leader,
1384 						   (int)curbuf->b_p_ts, FALSE);
1385 #endif
1386 
1387 		    /* Add the indent offset */
1388 		    if (newindent + off < 0)
1389 		    {
1390 			off = -newindent;
1391 			newindent = 0;
1392 		    }
1393 		    else
1394 			newindent += off;
1395 
1396 		    /* Correct trailing spaces for the shift, so that
1397 		     * alignment remains equal. */
1398 		    while (off > 0 && lead_len > 0
1399 					       && leader[lead_len - 1] == ' ')
1400 		    {
1401 			/* Don't do it when there is a tab before the space */
1402 			if (vim_strchr(skipwhite(leader), '\t') != NULL)
1403 			    break;
1404 			--lead_len;
1405 			--off;
1406 		    }
1407 
1408 		    /* If the leader ends in white space, don't add an
1409 		     * extra space */
1410 		    if (lead_len > 0 && VIM_ISWHITE(leader[lead_len - 1]))
1411 			extra_space = FALSE;
1412 		    leader[lead_len] = NUL;
1413 		}
1414 
1415 		if (extra_space)
1416 		{
1417 		    leader[lead_len++] = ' ';
1418 		    leader[lead_len] = NUL;
1419 		}
1420 
1421 		newcol = lead_len;
1422 
1423 		/*
1424 		 * if a new indent will be set below, remove the indent that
1425 		 * is in the comment leader
1426 		 */
1427 		if (newindent
1428 #ifdef FEAT_SMARTINDENT
1429 				|| did_si
1430 #endif
1431 					   )
1432 		{
1433 		    while (lead_len && VIM_ISWHITE(*leader))
1434 		    {
1435 			--lead_len;
1436 			--newcol;
1437 			++leader;
1438 		    }
1439 		}
1440 
1441 	    }
1442 #ifdef FEAT_SMARTINDENT
1443 	    did_si = can_si = FALSE;
1444 #endif
1445 	}
1446 	else if (comment_end != NULL)
1447 	{
1448 	    /*
1449 	     * We have finished a comment, so we don't use the leader.
1450 	     * If this was a C-comment and 'ai' or 'si' is set do a normal
1451 	     * indent to align with the line containing the start of the
1452 	     * comment.
1453 	     */
1454 	    if (comment_end[0] == '*' && comment_end[1] == '/' &&
1455 			(curbuf->b_p_ai
1456 #ifdef FEAT_SMARTINDENT
1457 					|| do_si
1458 #endif
1459 							   ))
1460 	    {
1461 		old_cursor = curwin->w_cursor;
1462 		curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1463 		if ((pos = findmatch(NULL, NUL)) != NULL)
1464 		{
1465 		    curwin->w_cursor.lnum = pos->lnum;
1466 		    newindent = get_indent();
1467 		}
1468 		curwin->w_cursor = old_cursor;
1469 	    }
1470 	}
1471     }
1472 #endif
1473 
1474     /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1475     if (p_extra != NULL)
1476     {
1477 	*p_extra = saved_char;		/* restore char that NUL replaced */
1478 
1479 	/*
1480 	 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1481 	 * non-blank.
1482 	 *
1483 	 * When in REPLACE mode, put the deleted blanks on the replace stack,
1484 	 * preceded by a NUL, so they can be put back when a BS is entered.
1485 	 */
1486 	if (REPLACE_NORMAL(State))
1487 	    replace_push(NUL);	    /* end of extra blanks */
1488 	if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1489 	{
1490 	    while ((*p_extra == ' ' || *p_extra == '\t')
1491 		    && (!enc_utf8
1492 			       || !utf_iscomposing(utf_ptr2char(p_extra + 1))))
1493 	    {
1494 		if (REPLACE_NORMAL(State))
1495 		    replace_push(*p_extra);
1496 		++p_extra;
1497 		++less_cols_off;
1498 	    }
1499 	}
1500 
1501 	/* columns for marks adjusted for removed columns */
1502 	less_cols = (int)(p_extra - saved_line);
1503     }
1504 
1505     if (p_extra == NULL)
1506 	p_extra = (char_u *)"";		    /* append empty line */
1507 
1508 #ifdef FEAT_COMMENTS
1509     /* concatenate leader and p_extra, if there is a leader */
1510     if (lead_len)
1511     {
1512 	if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
1513 	{
1514 	    int i;
1515 	    int padding = second_line_indent
1516 					  - (newindent + (int)STRLEN(leader));
1517 
1518 	    /* Here whitespace is inserted after the comment char.
1519 	     * Below, set_indent(newindent, SIN_INSERT) will insert the
1520 	     * whitespace needed before the comment char. */
1521 	    for (i = 0; i < padding; i++)
1522 	    {
1523 		STRCAT(leader, " ");
1524 		less_cols--;
1525 		newcol++;
1526 	    }
1527 	}
1528 	STRCAT(leader, p_extra);
1529 	p_extra = leader;
1530 	did_ai = TRUE;	    /* So truncating blanks works with comments */
1531 	less_cols -= lead_len;
1532     }
1533     else
1534 	end_comment_pending = NUL;  /* turns out there was no leader */
1535 #endif
1536 
1537     old_cursor = curwin->w_cursor;
1538     if (dir == BACKWARD)
1539 	--curwin->w_cursor.lnum;
1540     if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1541     {
1542 	if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1543 								      == FAIL)
1544 	    goto theend;
1545 	/* Postpone calling changed_lines(), because it would mess up folding
1546 	 * with markers.
1547 	 * Skip mark_adjust when adding a line after the last one, there can't
1548 	 * be marks there. But still needed in diff mode. */
1549 	if (curwin->w_cursor.lnum + 1 < curbuf->b_ml.ml_line_count
1550 #ifdef FEAT_DIFF
1551 		|| curwin->w_p_diff
1552 #endif
1553 	    )
1554 	    mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1555 	did_append = TRUE;
1556     }
1557     else
1558     {
1559 	/*
1560 	 * In VREPLACE mode we are starting to replace the next line.
1561 	 */
1562 	curwin->w_cursor.lnum++;
1563 	if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1564 	{
1565 	    /* In case we NL to a new line, BS to the previous one, and NL
1566 	     * again, we don't want to save the new line for undo twice.
1567 	     */
1568 	    (void)u_save_cursor();		    /* errors are ignored! */
1569 	    vr_lines_changed++;
1570 	}
1571 	ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1572 	changed_bytes(curwin->w_cursor.lnum, 0);
1573 	curwin->w_cursor.lnum--;
1574 	did_append = FALSE;
1575     }
1576 
1577     if (newindent
1578 #ifdef FEAT_SMARTINDENT
1579 		    || did_si
1580 #endif
1581 				)
1582     {
1583 	++curwin->w_cursor.lnum;
1584 #ifdef FEAT_SMARTINDENT
1585 	if (did_si)
1586 	{
1587 	    int sw = (int)get_sw_value(curbuf);
1588 
1589 	    if (p_sr)
1590 		newindent -= newindent % sw;
1591 	    newindent += sw;
1592 	}
1593 #endif
1594 	/* Copy the indent */
1595 	if (curbuf->b_p_ci)
1596 	{
1597 	    (void)copy_indent(newindent, saved_line);
1598 
1599 	    /*
1600 	     * Set the 'preserveindent' option so that any further screwing
1601 	     * with the line doesn't entirely destroy our efforts to preserve
1602 	     * it.  It gets restored at the function end.
1603 	     */
1604 	    curbuf->b_p_pi = TRUE;
1605 	}
1606 	else
1607 	    (void)set_indent(newindent, SIN_INSERT);
1608 	less_cols -= curwin->w_cursor.col;
1609 
1610 	ai_col = curwin->w_cursor.col;
1611 
1612 	/*
1613 	 * In REPLACE mode, for each character in the new indent, there must
1614 	 * be a NUL on the replace stack, for when it is deleted with BS
1615 	 */
1616 	if (REPLACE_NORMAL(State))
1617 	    for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1618 		replace_push(NUL);
1619 	newcol += curwin->w_cursor.col;
1620 #ifdef FEAT_SMARTINDENT
1621 	if (no_si)
1622 	    did_si = FALSE;
1623 #endif
1624     }
1625 
1626 #ifdef FEAT_COMMENTS
1627     /*
1628      * In REPLACE mode, for each character in the extra leader, there must be
1629      * a NUL on the replace stack, for when it is deleted with BS.
1630      */
1631     if (REPLACE_NORMAL(State))
1632 	while (lead_len-- > 0)
1633 	    replace_push(NUL);
1634 #endif
1635 
1636     curwin->w_cursor = old_cursor;
1637 
1638     if (dir == FORWARD)
1639     {
1640 	if (trunc_line || (State & INSERT))
1641 	{
1642 	    /* truncate current line at cursor */
1643 	    saved_line[curwin->w_cursor.col] = NUL;
1644 	    /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1645 	    if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1646 		truncate_spaces(saved_line);
1647 	    ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1648 	    saved_line = NULL;
1649 	    if (did_append)
1650 	    {
1651 		changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1652 					       curwin->w_cursor.lnum + 1, 1L);
1653 		did_append = FALSE;
1654 
1655 		/* Move marks after the line break to the new line. */
1656 		if (flags & OPENLINE_MARKFIX)
1657 		    mark_col_adjust(curwin->w_cursor.lnum,
1658 					 curwin->w_cursor.col + less_cols_off,
1659 						      1L, (long)-less_cols, 0);
1660 	    }
1661 	    else
1662 		changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1663 	}
1664 
1665 	/*
1666 	 * Put the cursor on the new line.  Careful: the scrollup() above may
1667 	 * have moved w_cursor, we must use old_cursor.
1668 	 */
1669 	curwin->w_cursor.lnum = old_cursor.lnum + 1;
1670     }
1671     if (did_append)
1672 	changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1673 
1674     curwin->w_cursor.col = newcol;
1675     curwin->w_cursor.coladd = 0;
1676 
1677 #if defined(FEAT_LISP) || defined(FEAT_CINDENT)
1678     /*
1679      * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1680      * fixthisline() from doing it (via change_indent()) by telling it we're in
1681      * normal INSERT mode.
1682      */
1683     if (State & VREPLACE_FLAG)
1684     {
1685 	vreplace_mode = State;	/* So we know to put things right later */
1686 	State = INSERT;
1687     }
1688     else
1689 	vreplace_mode = 0;
1690 #endif
1691 #ifdef FEAT_LISP
1692     /*
1693      * May do lisp indenting.
1694      */
1695     if (!p_paste
1696 # ifdef FEAT_COMMENTS
1697 	    && leader == NULL
1698 # endif
1699 	    && curbuf->b_p_lisp
1700 	    && curbuf->b_p_ai)
1701     {
1702 	fixthisline(get_lisp_indent);
1703 	ai_col = (colnr_T)getwhitecols_curline();
1704     }
1705 #endif
1706 #ifdef FEAT_CINDENT
1707     /*
1708      * May do indenting after opening a new line.
1709      */
1710     if (!p_paste
1711 	    && (curbuf->b_p_cin
1712 #  ifdef FEAT_EVAL
1713 		    || *curbuf->b_p_inde != NUL
1714 #  endif
1715 		)
1716 	    && in_cinkeys(dir == FORWARD
1717 		? KEY_OPEN_FORW
1718 		: KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1719     {
1720 	do_c_expr_indent();
1721 	ai_col = (colnr_T)getwhitecols_curline();
1722     }
1723 #endif
1724 #if defined(FEAT_LISP) || defined(FEAT_CINDENT)
1725     if (vreplace_mode != 0)
1726 	State = vreplace_mode;
1727 #endif
1728 
1729     /*
1730      * Finally, VREPLACE gets the stuff on the new line, then puts back the
1731      * original line, and inserts the new stuff char by char, pushing old stuff
1732      * onto the replace stack (via ins_char()).
1733      */
1734     if (State & VREPLACE_FLAG)
1735     {
1736 	/* Put new line in p_extra */
1737 	p_extra = vim_strsave(ml_get_curline());
1738 	if (p_extra == NULL)
1739 	    goto theend;
1740 
1741 	/* Put back original line */
1742 	ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1743 
1744 	/* Insert new stuff into line again */
1745 	curwin->w_cursor.col = 0;
1746 	curwin->w_cursor.coladd = 0;
1747 	ins_bytes(p_extra);	/* will call changed_bytes() */
1748 	vim_free(p_extra);
1749 	next_line = NULL;
1750     }
1751 
1752     retval = OK;		/* success! */
1753 theend:
1754     curbuf->b_p_pi = saved_pi;
1755     vim_free(saved_line);
1756     vim_free(next_line);
1757     vim_free(allocated);
1758     return retval;
1759 }
1760 
1761 #if defined(FEAT_COMMENTS) || defined(PROTO)
1762 /*
1763  * get_leader_len() returns the length in bytes of the prefix of the given
1764  * string which introduces a comment.  If this string is not a comment then
1765  * 0 is returned.
1766  * When "flags" is not NULL, it is set to point to the flags of the recognized
1767  * comment leader.
1768  * "backward" must be true for the "O" command.
1769  * If "include_space" is set, include trailing whitespace while calculating the
1770  * length.
1771  */
1772     int
1773 get_leader_len(
1774     char_u	*line,
1775     char_u	**flags,
1776     int		backward,
1777     int		include_space)
1778 {
1779     int		i, j;
1780     int		result;
1781     int		got_com = FALSE;
1782     int		found_one;
1783     char_u	part_buf[COM_MAX_LEN];	/* buffer for one option part */
1784     char_u	*string;		/* pointer to comment string */
1785     char_u	*list;
1786     int		middle_match_len = 0;
1787     char_u	*prev_list;
1788     char_u	*saved_flags = NULL;
1789 
1790     result = i = 0;
1791     while (VIM_ISWHITE(line[i]))    /* leading white space is ignored */
1792 	++i;
1793 
1794     /*
1795      * Repeat to match several nested comment strings.
1796      */
1797     while (line[i] != NUL)
1798     {
1799 	/*
1800 	 * scan through the 'comments' option for a match
1801 	 */
1802 	found_one = FALSE;
1803 	for (list = curbuf->b_p_com; *list; )
1804 	{
1805 	    /* Get one option part into part_buf[].  Advance "list" to next
1806 	     * one.  Put "string" at start of string.  */
1807 	    if (!got_com && flags != NULL)
1808 		*flags = list;	    /* remember where flags started */
1809 	    prev_list = list;
1810 	    (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1811 	    string = vim_strchr(part_buf, ':');
1812 	    if (string == NULL)	    /* missing ':', ignore this part */
1813 		continue;
1814 	    *string++ = NUL;	    /* isolate flags from string */
1815 
1816 	    /* If we found a middle match previously, use that match when this
1817 	     * is not a middle or end. */
1818 	    if (middle_match_len != 0
1819 		    && vim_strchr(part_buf, COM_MIDDLE) == NULL
1820 		    && vim_strchr(part_buf, COM_END) == NULL)
1821 		break;
1822 
1823 	    /* When we already found a nested comment, only accept further
1824 	     * nested comments. */
1825 	    if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1826 		continue;
1827 
1828 	    /* When 'O' flag present and using "O" command skip this one. */
1829 	    if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1830 		continue;
1831 
1832 	    /* Line contents and string must match.
1833 	     * When string starts with white space, must have some white space
1834 	     * (but the amount does not need to match, there might be a mix of
1835 	     * TABs and spaces). */
1836 	    if (VIM_ISWHITE(string[0]))
1837 	    {
1838 		if (i == 0 || !VIM_ISWHITE(line[i - 1]))
1839 		    continue;  /* missing white space */
1840 		while (VIM_ISWHITE(string[0]))
1841 		    ++string;
1842 	    }
1843 	    for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1844 		;
1845 	    if (string[j] != NUL)
1846 		continue;  /* string doesn't match */
1847 
1848 	    /* When 'b' flag used, there must be white space or an
1849 	     * end-of-line after the string in the line. */
1850 	    if (vim_strchr(part_buf, COM_BLANK) != NULL
1851 			   && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
1852 		continue;
1853 
1854 	    /* We have found a match, stop searching unless this is a middle
1855 	     * comment. The middle comment can be a substring of the end
1856 	     * comment in which case it's better to return the length of the
1857 	     * end comment and its flags.  Thus we keep searching with middle
1858 	     * and end matches and use an end match if it matches better. */
1859 	    if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1860 	    {
1861 		if (middle_match_len == 0)
1862 		{
1863 		    middle_match_len = j;
1864 		    saved_flags = prev_list;
1865 		}
1866 		continue;
1867 	    }
1868 	    if (middle_match_len != 0 && j > middle_match_len)
1869 		/* Use this match instead of the middle match, since it's a
1870 		 * longer thus better match. */
1871 		middle_match_len = 0;
1872 
1873 	    if (middle_match_len == 0)
1874 		i += j;
1875 	    found_one = TRUE;
1876 	    break;
1877 	}
1878 
1879 	if (middle_match_len != 0)
1880 	{
1881 	    /* Use the previously found middle match after failing to find a
1882 	     * match with an end. */
1883 	    if (!got_com && flags != NULL)
1884 		*flags = saved_flags;
1885 	    i += middle_match_len;
1886 	    found_one = TRUE;
1887 	}
1888 
1889 	/* No match found, stop scanning. */
1890 	if (!found_one)
1891 	    break;
1892 
1893 	result = i;
1894 
1895 	/* Include any trailing white space. */
1896 	while (VIM_ISWHITE(line[i]))
1897 	    ++i;
1898 
1899 	if (include_space)
1900 	    result = i;
1901 
1902 	/* If this comment doesn't nest, stop here. */
1903 	got_com = TRUE;
1904 	if (vim_strchr(part_buf, COM_NEST) == NULL)
1905 	    break;
1906     }
1907     return result;
1908 }
1909 
1910 /*
1911  * Return the offset at which the last comment in line starts. If there is no
1912  * comment in the whole line, -1 is returned.
1913  *
1914  * When "flags" is not null, it is set to point to the flags describing the
1915  * recognized comment leader.
1916  */
1917     int
1918 get_last_leader_offset(char_u *line, char_u **flags)
1919 {
1920     int		result = -1;
1921     int		i, j;
1922     int		lower_check_bound = 0;
1923     char_u	*string;
1924     char_u	*com_leader;
1925     char_u	*com_flags;
1926     char_u	*list;
1927     int		found_one;
1928     char_u	part_buf[COM_MAX_LEN];	/* buffer for one option part */
1929 
1930     /*
1931      * Repeat to match several nested comment strings.
1932      */
1933     i = (int)STRLEN(line);
1934     while (--i >= lower_check_bound)
1935     {
1936 	/*
1937 	 * scan through the 'comments' option for a match
1938 	 */
1939 	found_one = FALSE;
1940 	for (list = curbuf->b_p_com; *list; )
1941 	{
1942 	    char_u *flags_save = list;
1943 
1944 	    /*
1945 	     * Get one option part into part_buf[].  Advance list to next one.
1946 	     * put string at start of string.
1947 	     */
1948 	    (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1949 	    string = vim_strchr(part_buf, ':');
1950 	    if (string == NULL)	/* If everything is fine, this cannot actually
1951 				 * happen. */
1952 	    {
1953 		continue;
1954 	    }
1955 	    *string++ = NUL;	/* Isolate flags from string. */
1956 	    com_leader = string;
1957 
1958 	    /*
1959 	     * Line contents and string must match.
1960 	     * When string starts with white space, must have some white space
1961 	     * (but the amount does not need to match, there might be a mix of
1962 	     * TABs and spaces).
1963 	     */
1964 	    if (VIM_ISWHITE(string[0]))
1965 	    {
1966 		if (i == 0 || !VIM_ISWHITE(line[i - 1]))
1967 		    continue;
1968 		while (VIM_ISWHITE(*string))
1969 		    ++string;
1970 	    }
1971 	    for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1972 		/* do nothing */;
1973 	    if (string[j] != NUL)
1974 		continue;
1975 
1976 	    /*
1977 	     * When 'b' flag used, there must be white space or an
1978 	     * end-of-line after the string in the line.
1979 	     */
1980 	    if (vim_strchr(part_buf, COM_BLANK) != NULL
1981 		    && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
1982 		continue;
1983 
1984 	    if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1985 	    {
1986 		// For a middlepart comment, only consider it to match if
1987 		// everything before the current position in the line is
1988 		// whitespace.  Otherwise we would think we are inside a
1989 		// comment if the middle part appears somewhere in the middle
1990 		// of the line.  E.g. for C the "*" appears often.
1991 		for (j = 0; VIM_ISWHITE(line[j]) && j <= i; j++)
1992 		    ;
1993 		if (j < i)
1994 		    continue;
1995 	    }
1996 
1997 	    /*
1998 	     * We have found a match, stop searching.
1999 	     */
2000 	    found_one = TRUE;
2001 
2002 	    if (flags)
2003 		*flags = flags_save;
2004 	    com_flags = flags_save;
2005 
2006 	    break;
2007 	}
2008 
2009 	if (found_one)
2010 	{
2011 	    char_u  part_buf2[COM_MAX_LEN];	/* buffer for one option part */
2012 	    int     len1, len2, off;
2013 
2014 	    result = i;
2015 	    /*
2016 	     * If this comment nests, continue searching.
2017 	     */
2018 	    if (vim_strchr(part_buf, COM_NEST) != NULL)
2019 		continue;
2020 
2021 	    lower_check_bound = i;
2022 
2023 	    /* Let's verify whether the comment leader found is a substring
2024 	     * of other comment leaders. If it is, let's adjust the
2025 	     * lower_check_bound so that we make sure that we have determined
2026 	     * the comment leader correctly.
2027 	     */
2028 
2029 	    while (VIM_ISWHITE(*com_leader))
2030 		++com_leader;
2031 	    len1 = (int)STRLEN(com_leader);
2032 
2033 	    for (list = curbuf->b_p_com; *list; )
2034 	    {
2035 		char_u *flags_save = list;
2036 
2037 		(void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
2038 		if (flags_save == com_flags)
2039 		    continue;
2040 		string = vim_strchr(part_buf2, ':');
2041 		++string;
2042 		while (VIM_ISWHITE(*string))
2043 		    ++string;
2044 		len2 = (int)STRLEN(string);
2045 		if (len2 == 0)
2046 		    continue;
2047 
2048 		/* Now we have to verify whether string ends with a substring
2049 		 * beginning the com_leader. */
2050 		for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
2051 		{
2052 		    --off;
2053 		    if (!STRNCMP(string + off, com_leader, len2 - off))
2054 		    {
2055 			if (i - off < lower_check_bound)
2056 			    lower_check_bound = i - off;
2057 		    }
2058 		}
2059 	    }
2060 	}
2061     }
2062     return result;
2063 }
2064 #endif
2065 
2066 /*
2067  * Return the number of window lines occupied by buffer line "lnum".
2068  */
2069     int
2070 plines(linenr_T lnum)
2071 {
2072     return plines_win(curwin, lnum, TRUE);
2073 }
2074 
2075     int
2076 plines_win(
2077     win_T	*wp,
2078     linenr_T	lnum,
2079     int		winheight)	/* when TRUE limit to window height */
2080 {
2081 #if defined(FEAT_DIFF) || defined(PROTO)
2082     /* Check for filler lines above this buffer line.  When folded the result
2083      * is one line anyway. */
2084     return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
2085 }
2086 
2087     int
2088 plines_nofill(linenr_T lnum)
2089 {
2090     return plines_win_nofill(curwin, lnum, TRUE);
2091 }
2092 
2093     int
2094 plines_win_nofill(
2095     win_T	*wp,
2096     linenr_T	lnum,
2097     int		winheight)	/* when TRUE limit to window height */
2098 {
2099 #endif
2100     int		lines;
2101 
2102     if (!wp->w_p_wrap)
2103 	return 1;
2104 
2105     if (wp->w_width == 0)
2106 	return 1;
2107 
2108 #ifdef FEAT_FOLDING
2109     /* A folded lines is handled just like an empty line. */
2110     /* NOTE: Caller must handle lines that are MAYBE folded. */
2111     if (lineFolded(wp, lnum) == TRUE)
2112 	return 1;
2113 #endif
2114 
2115     lines = plines_win_nofold(wp, lnum);
2116     if (winheight > 0 && lines > wp->w_height)
2117 	return (int)wp->w_height;
2118     return lines;
2119 }
2120 
2121 /*
2122  * Return number of window lines physical line "lnum" will occupy in window
2123  * "wp".  Does not care about folding, 'wrap' or 'diff'.
2124  */
2125     int
2126 plines_win_nofold(win_T *wp, linenr_T lnum)
2127 {
2128     char_u	*s;
2129     long	col;
2130     int		width;
2131 
2132     s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2133     if (*s == NUL)		/* empty line */
2134 	return 1;
2135     col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
2136 
2137     /*
2138      * If list mode is on, then the '$' at the end of the line may take up one
2139      * extra column.
2140      */
2141     if (wp->w_p_list && lcs_eol != NUL)
2142 	col += 1;
2143 
2144     /*
2145      * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
2146      */
2147     width = wp->w_width - win_col_off(wp);
2148     if (width <= 0)
2149 	return 32000;
2150     if (col <= width)
2151 	return 1;
2152     col -= width;
2153     width += win_col_off2(wp);
2154     return (col + (width - 1)) / width + 1;
2155 }
2156 
2157 /*
2158  * Like plines_win(), but only reports the number of physical screen lines
2159  * used from the start of the line to the given column number.
2160  */
2161     int
2162 plines_win_col(win_T *wp, linenr_T lnum, long column)
2163 {
2164     long	col;
2165     char_u	*s;
2166     int		lines = 0;
2167     int		width;
2168     char_u	*line;
2169 
2170 #ifdef FEAT_DIFF
2171     /* Check for filler lines above this buffer line.  When folded the result
2172      * is one line anyway. */
2173     lines = diff_check_fill(wp, lnum);
2174 #endif
2175 
2176     if (!wp->w_p_wrap)
2177 	return lines + 1;
2178 
2179     if (wp->w_width == 0)
2180 	return lines + 1;
2181 
2182     line = s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2183 
2184     col = 0;
2185     while (*s != NUL && --column >= 0)
2186     {
2187 	col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL);
2188 	MB_PTR_ADV(s);
2189     }
2190 
2191     /*
2192      * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2193      * INSERT mode, then col must be adjusted so that it represents the last
2194      * screen position of the TAB.  This only fixes an error when the TAB wraps
2195      * from one screen line to the next (when 'columns' is not a multiple of
2196      * 'ts') -- webb.
2197      */
2198     if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2199 	col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL) - 1;
2200 
2201     /*
2202      * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
2203      */
2204     width = wp->w_width - win_col_off(wp);
2205     if (width <= 0)
2206 	return 9999;
2207 
2208     lines += 1;
2209     if (col > width)
2210 	lines += (col - width) / (width + win_col_off2(wp)) + 1;
2211     return lines;
2212 }
2213 
2214     int
2215 plines_m_win(win_T *wp, linenr_T first, linenr_T last)
2216 {
2217     int		count = 0;
2218 
2219     while (first <= last)
2220     {
2221 #ifdef FEAT_FOLDING
2222 	int	x;
2223 
2224 	/* Check if there are any really folded lines, but also included lines
2225 	 * that are maybe folded. */
2226 	x = foldedCount(wp, first, NULL);
2227 	if (x > 0)
2228 	{
2229 	    ++count;	    /* count 1 for "+-- folded" line */
2230 	    first += x;
2231 	}
2232 	else
2233 #endif
2234 	{
2235 #ifdef FEAT_DIFF
2236 	    if (first == wp->w_topline)
2237 		count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2238 	    else
2239 #endif
2240 		count += plines_win(wp, first, TRUE);
2241 	    ++first;
2242 	}
2243     }
2244     return (count);
2245 }
2246 
2247 /*
2248  * Insert string "p" at the cursor position.  Stops at a NUL byte.
2249  * Handles Replace mode and multi-byte characters.
2250  */
2251     void
2252 ins_bytes(char_u *p)
2253 {
2254     ins_bytes_len(p, (int)STRLEN(p));
2255 }
2256 
2257 /*
2258  * Insert string "p" with length "len" at the cursor position.
2259  * Handles Replace mode and multi-byte characters.
2260  */
2261     void
2262 ins_bytes_len(char_u *p, int len)
2263 {
2264     int		i;
2265     int		n;
2266 
2267     if (has_mbyte)
2268 	for (i = 0; i < len; i += n)
2269 	{
2270 	    if (enc_utf8)
2271 		// avoid reading past p[len]
2272 		n = utfc_ptr2len_len(p + i, len - i);
2273 	    else
2274 		n = (*mb_ptr2len)(p + i);
2275 	    ins_char_bytes(p + i, n);
2276 	}
2277     else
2278 	for (i = 0; i < len; ++i)
2279 	    ins_char(p[i]);
2280 }
2281 
2282 /*
2283  * Insert or replace a single character at the cursor position.
2284  * When in REPLACE or VREPLACE mode, replace any existing character.
2285  * Caller must have prepared for undo.
2286  * For multi-byte characters we get the whole character, the caller must
2287  * convert bytes to a character.
2288  */
2289     void
2290 ins_char(int c)
2291 {
2292     char_u	buf[MB_MAXBYTES + 1];
2293     int		n = (*mb_char2bytes)(c, buf);
2294 
2295     /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2296      * Happens for CTRL-Vu9900. */
2297     if (buf[0] == 0)
2298 	buf[0] = '\n';
2299 
2300     ins_char_bytes(buf, n);
2301 }
2302 
2303     void
2304 ins_char_bytes(char_u *buf, int charlen)
2305 {
2306     int		c = buf[0];
2307     int		newlen;		// nr of bytes inserted
2308     int		oldlen;		// nr of bytes deleted (0 when not replacing)
2309     char_u	*p;
2310     char_u	*newp;
2311     char_u	*oldp;
2312     int		linelen;	// length of old line including NUL
2313     colnr_T	col;
2314     linenr_T	lnum = curwin->w_cursor.lnum;
2315     int		i;
2316 
2317     /* Break tabs if needed. */
2318     if (virtual_active() && curwin->w_cursor.coladd > 0)
2319 	coladvance_force(getviscol());
2320 
2321     col = curwin->w_cursor.col;
2322     oldp = ml_get(lnum);
2323     linelen = (int)STRLEN(oldp) + 1;
2324 
2325     /* The lengths default to the values for when not replacing. */
2326     oldlen = 0;
2327     newlen = charlen;
2328 
2329     if (State & REPLACE_FLAG)
2330     {
2331 	if (State & VREPLACE_FLAG)
2332 	{
2333 	    colnr_T	new_vcol = 0;   /* init for GCC */
2334 	    colnr_T	vcol;
2335 	    int		old_list;
2336 
2337 	    /*
2338 	     * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2339 	     * Returns the old value of list, so when finished,
2340 	     * curwin->w_p_list should be set back to this.
2341 	     */
2342 	    old_list = curwin->w_p_list;
2343 	    if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2344 		curwin->w_p_list = FALSE;
2345 
2346 	    /*
2347 	     * In virtual replace mode each character may replace one or more
2348 	     * characters (zero if it's a TAB).  Count the number of bytes to
2349 	     * be deleted to make room for the new character, counting screen
2350 	     * cells.  May result in adding spaces to fill a gap.
2351 	     */
2352 	    getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2353 	    new_vcol = vcol + chartabsize(buf, vcol);
2354 	    while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2355 	    {
2356 		vcol += chartabsize(oldp + col + oldlen, vcol);
2357 		/* Don't need to remove a TAB that takes us to the right
2358 		 * position. */
2359 		if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2360 		    break;
2361 		oldlen += (*mb_ptr2len)(oldp + col + oldlen);
2362 		/* Deleted a bit too much, insert spaces. */
2363 		if (vcol > new_vcol)
2364 		    newlen += vcol - new_vcol;
2365 	    }
2366 	    curwin->w_p_list = old_list;
2367 	}
2368 	else if (oldp[col] != NUL)
2369 	{
2370 	    /* normal replace */
2371 	    oldlen = (*mb_ptr2len)(oldp + col);
2372 	}
2373 
2374 
2375 	/* Push the replaced bytes onto the replace stack, so that they can be
2376 	 * put back when BS is used.  The bytes of a multi-byte character are
2377 	 * done the other way around, so that the first byte is popped off
2378 	 * first (it tells the byte length of the character). */
2379 	replace_push(NUL);
2380 	for (i = 0; i < oldlen; ++i)
2381 	{
2382 	    if (has_mbyte)
2383 		i += replace_push_mb(oldp + col + i) - 1;
2384 	    else
2385 		replace_push(oldp[col + i]);
2386 	}
2387     }
2388 
2389     newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2390     if (newp == NULL)
2391 	return;
2392 
2393     /* Copy bytes before the cursor. */
2394     if (col > 0)
2395 	mch_memmove(newp, oldp, (size_t)col);
2396 
2397     /* Copy bytes after the changed character(s). */
2398     p = newp + col;
2399     if (linelen > col + oldlen)
2400 	mch_memmove(p + newlen, oldp + col + oldlen,
2401 					    (size_t)(linelen - col - oldlen));
2402 
2403     /* Insert or overwrite the new character. */
2404     mch_memmove(p, buf, charlen);
2405     i = charlen;
2406 
2407     /* Fill with spaces when necessary. */
2408     while (i < newlen)
2409 	p[i++] = ' ';
2410 
2411     // Replace the line in the buffer.
2412     ml_replace(lnum, newp, FALSE);
2413 
2414     // mark the buffer as changed and prepare for displaying
2415     inserted_bytes(lnum, col, newlen - oldlen);
2416 
2417     /*
2418      * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2419      * show the match for right parens and braces.
2420      */
2421     if (p_sm && (State & INSERT)
2422 	    && msg_silent == 0
2423 #ifdef FEAT_INS_EXPAND
2424 	    && !ins_compl_active()
2425 #endif
2426        )
2427     {
2428 	if (has_mbyte)
2429 	    showmatch(mb_ptr2char(buf));
2430 	else
2431 	    showmatch(c);
2432     }
2433 
2434 #ifdef FEAT_RIGHTLEFT
2435     if (!p_ri || (State & REPLACE_FLAG))
2436 #endif
2437     {
2438 	/* Normal insert: move cursor right */
2439 	curwin->w_cursor.col += charlen;
2440     }
2441     /*
2442      * TODO: should try to update w_row here, to avoid recomputing it later.
2443      */
2444 }
2445 
2446 /*
2447  * Insert a string at the cursor position.
2448  * Note: Does NOT handle Replace mode.
2449  * Caller must have prepared for undo.
2450  */
2451     void
2452 ins_str(char_u *s)
2453 {
2454     char_u	*oldp, *newp;
2455     int		newlen = (int)STRLEN(s);
2456     int		oldlen;
2457     colnr_T	col;
2458     linenr_T	lnum = curwin->w_cursor.lnum;
2459 
2460     if (virtual_active() && curwin->w_cursor.coladd > 0)
2461 	coladvance_force(getviscol());
2462 
2463     col = curwin->w_cursor.col;
2464     oldp = ml_get(lnum);
2465     oldlen = (int)STRLEN(oldp);
2466 
2467     newp = alloc_check((unsigned)(oldlen + newlen + 1));
2468     if (newp == NULL)
2469 	return;
2470     if (col > 0)
2471 	mch_memmove(newp, oldp, (size_t)col);
2472     mch_memmove(newp + col, s, (size_t)newlen);
2473     mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2474     ml_replace(lnum, newp, FALSE);
2475     inserted_bytes(lnum, col, newlen);
2476     curwin->w_cursor.col += newlen;
2477 }
2478 
2479 /*
2480  * Delete one character under the cursor.
2481  * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2482  * Caller must have prepared for undo.
2483  *
2484  * return FAIL for failure, OK otherwise
2485  */
2486     int
2487 del_char(int fixpos)
2488 {
2489     if (has_mbyte)
2490     {
2491 	/* Make sure the cursor is at the start of a character. */
2492 	mb_adjust_cursor();
2493 	if (*ml_get_cursor() == NUL)
2494 	    return FAIL;
2495 	return del_chars(1L, fixpos);
2496     }
2497     return del_bytes(1L, fixpos, TRUE);
2498 }
2499 
2500 /*
2501  * Like del_bytes(), but delete characters instead of bytes.
2502  */
2503     int
2504 del_chars(long count, int fixpos)
2505 {
2506     long	bytes = 0;
2507     long	i;
2508     char_u	*p;
2509     int		l;
2510 
2511     p = ml_get_cursor();
2512     for (i = 0; i < count && *p != NUL; ++i)
2513     {
2514 	l = (*mb_ptr2len)(p);
2515 	bytes += l;
2516 	p += l;
2517     }
2518     return del_bytes(bytes, fixpos, TRUE);
2519 }
2520 
2521 /*
2522  * Delete "count" bytes under the cursor.
2523  * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2524  * Caller must have prepared for undo.
2525  *
2526  * Return FAIL for failure, OK otherwise.
2527  */
2528     int
2529 del_bytes(
2530     long	count,
2531     int		fixpos_arg,
2532     int		use_delcombine UNUSED)	    /* 'delcombine' option applies */
2533 {
2534     char_u	*oldp, *newp;
2535     colnr_T	oldlen;
2536     colnr_T	newlen;
2537     linenr_T	lnum = curwin->w_cursor.lnum;
2538     colnr_T	col = curwin->w_cursor.col;
2539     int		alloc_newp;
2540     long	movelen;
2541     int		fixpos = fixpos_arg;
2542 
2543     oldp = ml_get(lnum);
2544     oldlen = (int)STRLEN(oldp);
2545 
2546     /* Can't do anything when the cursor is on the NUL after the line. */
2547     if (col >= oldlen)
2548 	return FAIL;
2549 
2550     /* If "count" is zero there is nothing to do. */
2551     if (count == 0)
2552 	return OK;
2553 
2554     /* If "count" is negative the caller must be doing something wrong. */
2555     if (count < 1)
2556     {
2557 	siemsg("E950: Invalid count for del_bytes(): %ld", count);
2558 	return FAIL;
2559     }
2560 
2561     /* If 'delcombine' is set and deleting (less than) one character, only
2562      * delete the last combining character. */
2563     if (p_deco && use_delcombine && enc_utf8
2564 					 && utfc_ptr2len(oldp + col) >= count)
2565     {
2566 	int	cc[MAX_MCO];
2567 	int	n;
2568 
2569 	(void)utfc_ptr2char(oldp + col, cc);
2570 	if (cc[0] != NUL)
2571 	{
2572 	    /* Find the last composing char, there can be several. */
2573 	    n = col;
2574 	    do
2575 	    {
2576 		col = n;
2577 		count = utf_ptr2len(oldp + n);
2578 		n += count;
2579 	    } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2580 	    fixpos = 0;
2581 	}
2582     }
2583 
2584     /*
2585      * When count is too big, reduce it.
2586      */
2587     movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2588     if (movelen <= 1)
2589     {
2590 	/*
2591 	 * If we just took off the last character of a non-blank line, and
2592 	 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2593 	 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2594 	 */
2595 	if (col > 0 && fixpos && restart_edit == 0
2596 					      && (ve_flags & VE_ONEMORE) == 0)
2597 	{
2598 	    --curwin->w_cursor.col;
2599 	    curwin->w_cursor.coladd = 0;
2600 	    if (has_mbyte)
2601 		curwin->w_cursor.col -=
2602 			    (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2603 	}
2604 	count = oldlen - col;
2605 	movelen = 1;
2606     }
2607     newlen = oldlen - count;
2608 
2609     /*
2610      * If the old line has been allocated the deletion can be done in the
2611      * existing line. Otherwise a new line has to be allocated
2612      * Can't do this when using Netbeans, because we would need to invoke
2613      * netbeans_removed(), which deallocates the line.  Let ml_replace() take
2614      * care of notifying Netbeans.
2615      */
2616 #ifdef FEAT_NETBEANS_INTG
2617     if (netbeans_active())
2618 	alloc_newp = TRUE;
2619     else
2620 #endif
2621 	alloc_newp = !ml_line_alloced();    // check if oldp was allocated
2622     if (!alloc_newp)
2623 	newp = oldp;			    // use same allocated memory
2624     else
2625     {					    // need to allocate a new line
2626 	newp = alloc((unsigned)(newlen + 1));
2627 	if (newp == NULL)
2628 	    return FAIL;
2629 	mch_memmove(newp, oldp, (size_t)col);
2630     }
2631     mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2632     if (alloc_newp)
2633 	ml_replace(lnum, newp, FALSE);
2634 #ifdef FEAT_TEXT_PROP
2635     else
2636     {
2637 	// Also move any following text properties.
2638 	if (oldlen + 1 < curbuf->b_ml.ml_line_len)
2639 	    mch_memmove(newp + newlen + 1, oldp + oldlen + 1,
2640 			       (size_t)curbuf->b_ml.ml_line_len - oldlen - 1);
2641 	curbuf->b_ml.ml_line_len -= count;
2642     }
2643 #endif
2644 
2645     // mark the buffer as changed and prepare for displaying
2646     inserted_bytes(lnum, curwin->w_cursor.col, -count);
2647 
2648     return OK;
2649 }
2650 
2651 /*
2652  * Delete from cursor to end of line.
2653  * Caller must have prepared for undo.
2654  *
2655  * return FAIL for failure, OK otherwise
2656  */
2657     int
2658 truncate_line(
2659     int		fixpos)	    /* if TRUE fix the cursor position when done */
2660 {
2661     char_u	*newp;
2662     linenr_T	lnum = curwin->w_cursor.lnum;
2663     colnr_T	col = curwin->w_cursor.col;
2664 
2665     if (col == 0)
2666 	newp = vim_strsave((char_u *)"");
2667     else
2668 	newp = vim_strnsave(ml_get(lnum), col);
2669 
2670     if (newp == NULL)
2671 	return FAIL;
2672 
2673     ml_replace(lnum, newp, FALSE);
2674 
2675     /* mark the buffer as changed and prepare for displaying */
2676     changed_bytes(lnum, curwin->w_cursor.col);
2677 
2678     /*
2679      * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2680      */
2681     if (fixpos && curwin->w_cursor.col > 0)
2682 	--curwin->w_cursor.col;
2683 
2684     return OK;
2685 }
2686 
2687 /*
2688  * Delete "nlines" lines at the cursor.
2689  * Saves the lines for undo first if "undo" is TRUE.
2690  */
2691     void
2692 del_lines(
2693     long	nlines,		/* number of lines to delete */
2694     int		undo)		/* if TRUE, prepare for undo */
2695 {
2696     long	n;
2697     linenr_T	first = curwin->w_cursor.lnum;
2698 
2699     if (nlines <= 0)
2700 	return;
2701 
2702     /* save the deleted lines for undo */
2703     if (undo && u_savedel(first, nlines) == FAIL)
2704 	return;
2705 
2706     for (n = 0; n < nlines; )
2707     {
2708 	if (curbuf->b_ml.ml_flags & ML_EMPTY)	    /* nothing to delete */
2709 	    break;
2710 
2711 	ml_delete(first, TRUE);
2712 	++n;
2713 
2714 	/* If we delete the last line in the file, stop */
2715 	if (first > curbuf->b_ml.ml_line_count)
2716 	    break;
2717     }
2718 
2719     /* Correct the cursor position before calling deleted_lines_mark(), it may
2720      * trigger a callback to display the cursor. */
2721     curwin->w_cursor.col = 0;
2722     check_cursor_lnum();
2723 
2724     /* adjust marks, mark the buffer as changed and prepare for displaying */
2725     deleted_lines_mark(first, n);
2726 }
2727 
2728     int
2729 gchar_pos(pos_T *pos)
2730 {
2731     char_u	*ptr;
2732 
2733     /* When searching columns is sometimes put at the end of a line. */
2734     if (pos->col == MAXCOL)
2735 	return NUL;
2736     ptr = ml_get_pos(pos);
2737     if (has_mbyte)
2738 	return (*mb_ptr2char)(ptr);
2739     return (int)*ptr;
2740 }
2741 
2742     int
2743 gchar_cursor(void)
2744 {
2745     if (has_mbyte)
2746 	return (*mb_ptr2char)(ml_get_cursor());
2747     return (int)*ml_get_cursor();
2748 }
2749 
2750 /*
2751  * Write a character at the current cursor position.
2752  * It is directly written into the block.
2753  */
2754     void
2755 pchar_cursor(int c)
2756 {
2757     *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2758 						  + curwin->w_cursor.col) = c;
2759 }
2760 
2761 /*
2762  * When extra == 0: Return TRUE if the cursor is before or on the first
2763  *		    non-blank in the line.
2764  * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2765  *		    the line.
2766  */
2767     int
2768 inindent(int extra)
2769 {
2770     char_u	*ptr;
2771     colnr_T	col;
2772 
2773     for (col = 0, ptr = ml_get_curline(); VIM_ISWHITE(*ptr); ++col)
2774 	++ptr;
2775     if (col >= curwin->w_cursor.col + extra)
2776 	return TRUE;
2777     else
2778 	return FALSE;
2779 }
2780 
2781 /*
2782  * Skip to next part of an option argument: Skip space and comma.
2783  */
2784     char_u *
2785 skip_to_option_part(char_u *p)
2786 {
2787     if (*p == ',')
2788 	++p;
2789     while (*p == ' ')
2790 	++p;
2791     return p;
2792 }
2793 
2794 /*
2795  * Call this function when something in the current buffer is changed.
2796  *
2797  * Most often called through changed_bytes() and changed_lines(), which also
2798  * mark the area of the display to be redrawn.
2799  *
2800  * Careful: may trigger autocommands that reload the buffer.
2801  */
2802     void
2803 changed(void)
2804 {
2805 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2806     if (p_imst == IM_ON_THE_SPOT)
2807     {
2808 	/* The text of the preediting area is inserted, but this doesn't
2809 	 * mean a change of the buffer yet.  That is delayed until the
2810 	 * text is committed. (this means preedit becomes empty) */
2811 	if (im_is_preediting() && !xim_changed_while_preediting)
2812 	    return;
2813 	xim_changed_while_preediting = FALSE;
2814     }
2815 #endif
2816 
2817     if (!curbuf->b_changed)
2818     {
2819 	int	save_msg_scroll = msg_scroll;
2820 
2821 	/* Give a warning about changing a read-only file.  This may also
2822 	 * check-out the file, thus change "curbuf"! */
2823 	change_warning(0);
2824 
2825 	/* Create a swap file if that is wanted.
2826 	 * Don't do this for "nofile" and "nowrite" buffer types. */
2827 	if (curbuf->b_may_swap
2828 #ifdef FEAT_QUICKFIX
2829 		&& !bt_dontwrite(curbuf)
2830 #endif
2831 		)
2832 	{
2833 	    int save_need_wait_return = need_wait_return;
2834 
2835 	    need_wait_return = FALSE;
2836 	    ml_open_file(curbuf);
2837 
2838 	    /* The ml_open_file() can cause an ATTENTION message.
2839 	     * Wait two seconds, to make sure the user reads this unexpected
2840 	     * message.  Since we could be anywhere, call wait_return() now,
2841 	     * and don't let the emsg() set msg_scroll. */
2842 	    if (need_wait_return && emsg_silent == 0)
2843 	    {
2844 		out_flush();
2845 		ui_delay(2000L, TRUE);
2846 		wait_return(TRUE);
2847 		msg_scroll = save_msg_scroll;
2848 	    }
2849 	    else
2850 		need_wait_return = save_need_wait_return;
2851 	}
2852 	changed_int();
2853     }
2854     ++CHANGEDTICK(curbuf);
2855 
2856 #ifdef FEAT_SEARCH_EXTRA
2857     // If a pattern is highlighted, the position may now be invalid.
2858     highlight_match = FALSE;
2859 #endif
2860 }
2861 
2862 /*
2863  * Internal part of changed(), no user interaction.
2864  */
2865     void
2866 changed_int(void)
2867 {
2868     curbuf->b_changed = TRUE;
2869     ml_setflags(curbuf);
2870     check_status(curbuf);
2871     redraw_tabline = TRUE;
2872 #ifdef FEAT_TITLE
2873     need_maketitle = TRUE;	    /* set window title later */
2874 #endif
2875 }
2876 
2877 static void changedOneline(buf_T *buf, linenr_T lnum);
2878 static void changed_lines_buf(buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra);
2879 static void changed_common(linenr_T lnum, colnr_T col, linenr_T lnume, long xtra);
2880 
2881 /*
2882  * Changed bytes within a single line for the current buffer.
2883  * - marks the windows on this buffer to be redisplayed
2884  * - marks the buffer changed by calling changed()
2885  * - invalidates cached values
2886  * Careful: may trigger autocommands that reload the buffer.
2887  */
2888     void
2889 changed_bytes(linenr_T lnum, colnr_T col)
2890 {
2891     changedOneline(curbuf, lnum);
2892     changed_common(lnum, col, lnum + 1, 0L);
2893 
2894 #ifdef FEAT_DIFF
2895     /* Diff highlighting in other diff windows may need to be updated too. */
2896     if (curwin->w_p_diff)
2897     {
2898 	win_T	    *wp;
2899 	linenr_T    wlnum;
2900 
2901 	FOR_ALL_WINDOWS(wp)
2902 	    if (wp->w_p_diff && wp != curwin)
2903 	    {
2904 		redraw_win_later(wp, VALID);
2905 		wlnum = diff_lnum_win(lnum, wp);
2906 		if (wlnum > 0)
2907 		    changedOneline(wp->w_buffer, wlnum);
2908 	    }
2909     }
2910 #endif
2911 }
2912 
2913 /*
2914  * Like changed_bytes() but also adjust text properties for "added" bytes.
2915  * When "added" is negative text was deleted.
2916  */
2917     void
2918 inserted_bytes(linenr_T lnum, colnr_T col, int added UNUSED)
2919 {
2920     changed_bytes(lnum, col);
2921 
2922 #ifdef FEAT_TEXT_PROP
2923     if (curbuf->b_has_textprop && added != 0)
2924 	adjust_prop_columns(lnum, col, added);
2925 #endif
2926 }
2927 
2928     static void
2929 changedOneline(buf_T *buf, linenr_T lnum)
2930 {
2931     if (buf->b_mod_set)
2932     {
2933 	/* find the maximum area that must be redisplayed */
2934 	if (lnum < buf->b_mod_top)
2935 	    buf->b_mod_top = lnum;
2936 	else if (lnum >= buf->b_mod_bot)
2937 	    buf->b_mod_bot = lnum + 1;
2938     }
2939     else
2940     {
2941 	/* set the area that must be redisplayed to one line */
2942 	buf->b_mod_set = TRUE;
2943 	buf->b_mod_top = lnum;
2944 	buf->b_mod_bot = lnum + 1;
2945 	buf->b_mod_xlines = 0;
2946     }
2947 }
2948 
2949 /*
2950  * Appended "count" lines below line "lnum" in the current buffer.
2951  * Must be called AFTER the change and after mark_adjust().
2952  * Takes care of marking the buffer to be redrawn and sets the changed flag.
2953  */
2954     void
2955 appended_lines(linenr_T lnum, long count)
2956 {
2957     changed_lines(lnum + 1, 0, lnum + 1, count);
2958 }
2959 
2960 /*
2961  * Like appended_lines(), but adjust marks first.
2962  */
2963     void
2964 appended_lines_mark(linenr_T lnum, long count)
2965 {
2966     /* Skip mark_adjust when adding a line after the last one, there can't
2967      * be marks there. But it's still needed in diff mode. */
2968     if (lnum + count < curbuf->b_ml.ml_line_count
2969 #ifdef FEAT_DIFF
2970 	    || curwin->w_p_diff
2971 #endif
2972 	)
2973 	mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2974     changed_lines(lnum + 1, 0, lnum + 1, count);
2975 }
2976 
2977 /*
2978  * Deleted "count" lines at line "lnum" in the current buffer.
2979  * Must be called AFTER the change and after mark_adjust().
2980  * Takes care of marking the buffer to be redrawn and sets the changed flag.
2981  */
2982     void
2983 deleted_lines(linenr_T lnum, long count)
2984 {
2985     changed_lines(lnum, 0, lnum + count, -count);
2986 }
2987 
2988 /*
2989  * Like deleted_lines(), but adjust marks first.
2990  * Make sure the cursor is on a valid line before calling, a GUI callback may
2991  * be triggered to display the cursor.
2992  */
2993     void
2994 deleted_lines_mark(linenr_T lnum, long count)
2995 {
2996     mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2997     changed_lines(lnum, 0, lnum + count, -count);
2998 }
2999 
3000 /*
3001  * Changed lines for the current buffer.
3002  * Must be called AFTER the change and after mark_adjust().
3003  * - mark the buffer changed by calling changed()
3004  * - mark the windows on this buffer to be redisplayed
3005  * - invalidate cached values
3006  * "lnum" is the first line that needs displaying, "lnume" the first line
3007  * below the changed lines (BEFORE the change).
3008  * When only inserting lines, "lnum" and "lnume" are equal.
3009  * Takes care of calling changed() and updating b_mod_*.
3010  * Careful: may trigger autocommands that reload the buffer.
3011  */
3012     void
3013 changed_lines(
3014     linenr_T	lnum,	    /* first line with change */
3015     colnr_T	col,	    /* column in first line with change */
3016     linenr_T	lnume,	    /* line below last changed line */
3017     long	xtra)	    /* number of extra lines (negative when deleting) */
3018 {
3019     changed_lines_buf(curbuf, lnum, lnume, xtra);
3020 
3021 #ifdef FEAT_DIFF
3022     if (xtra == 0 && curwin->w_p_diff && !diff_internal())
3023     {
3024 	/* When the number of lines doesn't change then mark_adjust() isn't
3025 	 * called and other diff buffers still need to be marked for
3026 	 * displaying. */
3027 	win_T	    *wp;
3028 	linenr_T    wlnum;
3029 
3030 	FOR_ALL_WINDOWS(wp)
3031 	    if (wp->w_p_diff && wp != curwin)
3032 	    {
3033 		redraw_win_later(wp, VALID);
3034 		wlnum = diff_lnum_win(lnum, wp);
3035 		if (wlnum > 0)
3036 		    changed_lines_buf(wp->w_buffer, wlnum,
3037 						    lnume - lnum + wlnum, 0L);
3038 	    }
3039     }
3040 #endif
3041 
3042     changed_common(lnum, col, lnume, xtra);
3043 }
3044 
3045     static void
3046 changed_lines_buf(
3047     buf_T	*buf,
3048     linenr_T	lnum,	    /* first line with change */
3049     linenr_T	lnume,	    /* line below last changed line */
3050     long	xtra)	    /* number of extra lines (negative when deleting) */
3051 {
3052     if (buf->b_mod_set)
3053     {
3054 	/* find the maximum area that must be redisplayed */
3055 	if (lnum < buf->b_mod_top)
3056 	    buf->b_mod_top = lnum;
3057 	if (lnum < buf->b_mod_bot)
3058 	{
3059 	    /* adjust old bot position for xtra lines */
3060 	    buf->b_mod_bot += xtra;
3061 	    if (buf->b_mod_bot < lnum)
3062 		buf->b_mod_bot = lnum;
3063 	}
3064 	if (lnume + xtra > buf->b_mod_bot)
3065 	    buf->b_mod_bot = lnume + xtra;
3066 	buf->b_mod_xlines += xtra;
3067     }
3068     else
3069     {
3070 	/* set the area that must be redisplayed */
3071 	buf->b_mod_set = TRUE;
3072 	buf->b_mod_top = lnum;
3073 	buf->b_mod_bot = lnume + xtra;
3074 	buf->b_mod_xlines = xtra;
3075     }
3076 }
3077 
3078 /*
3079  * Common code for when a change is was made.
3080  * See changed_lines() for the arguments.
3081  * Careful: may trigger autocommands that reload the buffer.
3082  */
3083     static void
3084 changed_common(
3085     linenr_T	lnum,
3086     colnr_T	col,
3087     linenr_T	lnume,
3088     long	xtra)
3089 {
3090     win_T	*wp;
3091     tabpage_T	*tp;
3092     int		i;
3093 #ifdef FEAT_JUMPLIST
3094     int		cols;
3095     pos_T	*p;
3096     int		add;
3097 #endif
3098 
3099     /* mark the buffer as modified */
3100     changed();
3101 
3102 #ifdef FEAT_DIFF
3103     if (curwin->w_p_diff && diff_internal())
3104 	curtab->tp_diff_update = TRUE;
3105 #endif
3106 
3107     /* set the '. mark */
3108     if (!cmdmod.keepjumps)
3109     {
3110 	curbuf->b_last_change.lnum = lnum;
3111 	curbuf->b_last_change.col = col;
3112 
3113 #ifdef FEAT_JUMPLIST
3114 	/* Create a new entry if a new undo-able change was started or we
3115 	 * don't have an entry yet. */
3116 	if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
3117 	{
3118 	    if (curbuf->b_changelistlen == 0)
3119 		add = TRUE;
3120 	    else
3121 	    {
3122 		/* Don't create a new entry when the line number is the same
3123 		 * as the last one and the column is not too far away.  Avoids
3124 		 * creating many entries for typing "xxxxx". */
3125 		p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
3126 		if (p->lnum != lnum)
3127 		    add = TRUE;
3128 		else
3129 		{
3130 		    cols = comp_textwidth(FALSE);
3131 		    if (cols == 0)
3132 			cols = 79;
3133 		    add = (p->col + cols < col || col + cols < p->col);
3134 		}
3135 	    }
3136 	    if (add)
3137 	    {
3138 		/* This is the first of a new sequence of undo-able changes
3139 		 * and it's at some distance of the last change.  Use a new
3140 		 * position in the changelist. */
3141 		curbuf->b_new_change = FALSE;
3142 
3143 		if (curbuf->b_changelistlen == JUMPLISTSIZE)
3144 		{
3145 		    /* changelist is full: remove oldest entry */
3146 		    curbuf->b_changelistlen = JUMPLISTSIZE - 1;
3147 		    mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
3148 					  sizeof(pos_T) * (JUMPLISTSIZE - 1));
3149 		    FOR_ALL_TAB_WINDOWS(tp, wp)
3150 		    {
3151 			/* Correct position in changelist for other windows on
3152 			 * this buffer. */
3153 			if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
3154 			    --wp->w_changelistidx;
3155 		    }
3156 		}
3157 		FOR_ALL_TAB_WINDOWS(tp, wp)
3158 		{
3159 		    /* For other windows, if the position in the changelist is
3160 		     * at the end it stays at the end. */
3161 		    if (wp->w_buffer == curbuf
3162 			    && wp->w_changelistidx == curbuf->b_changelistlen)
3163 			++wp->w_changelistidx;
3164 		}
3165 		++curbuf->b_changelistlen;
3166 	    }
3167 	}
3168 	curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3169 							curbuf->b_last_change;
3170 	/* The current window is always after the last change, so that "g,"
3171 	 * takes you back to it. */
3172 	curwin->w_changelistidx = curbuf->b_changelistlen;
3173 #endif
3174     }
3175 
3176     FOR_ALL_TAB_WINDOWS(tp, wp)
3177     {
3178 	if (wp->w_buffer == curbuf)
3179 	{
3180 	    /* Mark this window to be redrawn later. */
3181 	    if (wp->w_redr_type < VALID)
3182 		wp->w_redr_type = VALID;
3183 
3184 	    /* Check if a change in the buffer has invalidated the cached
3185 	     * values for the cursor. */
3186 #ifdef FEAT_FOLDING
3187 	    /*
3188 	     * Update the folds for this window.  Can't postpone this, because
3189 	     * a following operator might work on the whole fold: ">>dd".
3190 	     */
3191 	    foldUpdate(wp, lnum, lnume + xtra - 1);
3192 
3193 	    /* The change may cause lines above or below the change to become
3194 	     * included in a fold.  Set lnum/lnume to the first/last line that
3195 	     * might be displayed differently.
3196 	     * Set w_cline_folded here as an efficient way to update it when
3197 	     * inserting lines just above a closed fold. */
3198 	    i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3199 	    if (wp->w_cursor.lnum == lnum)
3200 		wp->w_cline_folded = i;
3201 	    i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3202 	    if (wp->w_cursor.lnum == lnume)
3203 		wp->w_cline_folded = i;
3204 
3205 	    /* If the changed line is in a range of previously folded lines,
3206 	     * compare with the first line in that range. */
3207 	    if (wp->w_cursor.lnum <= lnum)
3208 	    {
3209 		i = find_wl_entry(wp, lnum);
3210 		if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3211 		    changed_line_abv_curs_win(wp);
3212 	    }
3213 #endif
3214 
3215 	    if (wp->w_cursor.lnum > lnum)
3216 		changed_line_abv_curs_win(wp);
3217 	    else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3218 		changed_cline_bef_curs_win(wp);
3219 	    if (wp->w_botline >= lnum)
3220 	    {
3221 		/* Assume that botline doesn't change (inserted lines make
3222 		 * other lines scroll down below botline). */
3223 		approximate_botline_win(wp);
3224 	    }
3225 
3226 	    /* Check if any w_lines[] entries have become invalid.
3227 	     * For entries below the change: Correct the lnums for
3228 	     * inserted/deleted lines.  Makes it possible to stop displaying
3229 	     * after the change. */
3230 	    for (i = 0; i < wp->w_lines_valid; ++i)
3231 		if (wp->w_lines[i].wl_valid)
3232 		{
3233 		    if (wp->w_lines[i].wl_lnum >= lnum)
3234 		    {
3235 			if (wp->w_lines[i].wl_lnum < lnume)
3236 			{
3237 			    /* line included in change */
3238 			    wp->w_lines[i].wl_valid = FALSE;
3239 			}
3240 			else if (xtra != 0)
3241 			{
3242 			    /* line below change */
3243 			    wp->w_lines[i].wl_lnum += xtra;
3244 #ifdef FEAT_FOLDING
3245 			    wp->w_lines[i].wl_lastlnum += xtra;
3246 #endif
3247 			}
3248 		    }
3249 #ifdef FEAT_FOLDING
3250 		    else if (wp->w_lines[i].wl_lastlnum >= lnum)
3251 		    {
3252 			/* change somewhere inside this range of folded lines,
3253 			 * may need to be redrawn */
3254 			wp->w_lines[i].wl_valid = FALSE;
3255 		    }
3256 #endif
3257 		}
3258 
3259 #ifdef FEAT_FOLDING
3260 	    /* Take care of side effects for setting w_topline when folds have
3261 	     * changed.  Esp. when the buffer was changed in another window. */
3262 	    if (hasAnyFolding(wp))
3263 		set_topline(wp, wp->w_topline);
3264 #endif
3265 	    /* relative numbering may require updating more */
3266 	    if (wp->w_p_rnu)
3267 		redraw_win_later(wp, SOME_VALID);
3268 	}
3269     }
3270 
3271     /* Call update_screen() later, which checks out what needs to be redrawn,
3272      * since it notices b_mod_set and then uses b_mod_*. */
3273     if (must_redraw < VALID)
3274 	must_redraw = VALID;
3275 
3276     /* when the cursor line is changed always trigger CursorMoved */
3277     if (lnum <= curwin->w_cursor.lnum
3278 		 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
3279 	last_cursormoved.lnum = 0;
3280 }
3281 
3282 /*
3283  * unchanged() is called when the changed flag must be reset for buffer 'buf'
3284  */
3285     void
3286 unchanged(
3287     buf_T	*buf,
3288     int		ff)	/* also reset 'fileformat' */
3289 {
3290     if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
3291     {
3292 	buf->b_changed = 0;
3293 	ml_setflags(buf);
3294 	if (ff)
3295 	    save_file_ff(buf);
3296 	check_status(buf);
3297 	redraw_tabline = TRUE;
3298 #ifdef FEAT_TITLE
3299 	need_maketitle = TRUE;	    /* set window title later */
3300 #endif
3301     }
3302     ++CHANGEDTICK(buf);
3303 #ifdef FEAT_NETBEANS_INTG
3304     netbeans_unmodified(buf);
3305 #endif
3306 }
3307 
3308 /*
3309  * check_status: called when the status bars for the buffer 'buf'
3310  *		 need to be updated
3311  */
3312     void
3313 check_status(buf_T *buf)
3314 {
3315     win_T	*wp;
3316 
3317     FOR_ALL_WINDOWS(wp)
3318 	if (wp->w_buffer == buf && wp->w_status_height)
3319 	{
3320 	    wp->w_redr_status = TRUE;
3321 	    if (must_redraw < VALID)
3322 		must_redraw = VALID;
3323 	}
3324 }
3325 
3326 /*
3327  * If the file is readonly, give a warning message with the first change.
3328  * Don't do this for autocommands.
3329  * Don't use emsg(), because it flushes the macro buffer.
3330  * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
3331  * will be TRUE.
3332  * Careful: may trigger autocommands that reload the buffer.
3333  */
3334     void
3335 change_warning(
3336     int	    col)		/* column for message; non-zero when in insert
3337 				   mode and 'showmode' is on */
3338 {
3339     static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3340 
3341     if (curbuf->b_did_warn == FALSE
3342 	    && curbufIsChanged() == 0
3343 	    && !autocmd_busy
3344 	    && curbuf->b_p_ro)
3345     {
3346 	++curbuf_lock;
3347 	apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
3348 	--curbuf_lock;
3349 	if (!curbuf->b_p_ro)
3350 	    return;
3351 	/*
3352 	 * Do what msg() does, but with a column offset if the warning should
3353 	 * be after the mode message.
3354 	 */
3355 	msg_start();
3356 	if (msg_row == Rows - 1)
3357 	    msg_col = col;
3358 	msg_source(HL_ATTR(HLF_W));
3359 	msg_puts_attr(_(w_readonly), HL_ATTR(HLF_W) | MSG_HIST);
3360 #ifdef FEAT_EVAL
3361 	set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3362 #endif
3363 	msg_clr_eos();
3364 	(void)msg_end();
3365 	if (msg_silent == 0 && !silent_mode
3366 #ifdef FEAT_EVAL
3367 		&& time_for_testing != 1
3368 #endif
3369 		)
3370 	{
3371 	    out_flush();
3372 	    ui_delay(1000L, TRUE); /* give the user time to think about it */
3373 	}
3374 	curbuf->b_did_warn = TRUE;
3375 	redraw_cmdline = FALSE;	/* don't redraw and erase the message */
3376 	if (msg_row < Rows - 1)
3377 	    showmode();
3378     }
3379 }
3380 
3381 /*
3382  * Ask for a reply from the user, a 'y' or a 'n'.
3383  * No other characters are accepted, the message is repeated until a valid
3384  * reply is entered or CTRL-C is hit.
3385  * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3386  * from any buffers but directly from the user.
3387  *
3388  * return the 'y' or 'n'
3389  */
3390     int
3391 ask_yesno(char_u *str, int direct)
3392 {
3393     int	    r = ' ';
3394     int	    save_State = State;
3395 
3396     if (exiting)		/* put terminal in raw mode for this question */
3397 	settmode(TMODE_RAW);
3398     ++no_wait_return;
3399 #ifdef USE_ON_FLY_SCROLL
3400     dont_scroll = TRUE;		/* disallow scrolling here */
3401 #endif
3402     State = CONFIRM;		/* mouse behaves like with :confirm */
3403 #ifdef FEAT_MOUSE
3404     setmouse();			/* disables mouse for xterm */
3405 #endif
3406     ++no_mapping;
3407     ++allow_keys;		/* no mapping here, but recognize keys */
3408 
3409     while (r != 'y' && r != 'n')
3410     {
3411 	/* same highlighting as for wait_return */
3412 	smsg_attr(HL_ATTR(HLF_R), "%s (y/n)?", str);
3413 	if (direct)
3414 	    r = get_keystroke();
3415 	else
3416 	    r = plain_vgetc();
3417 	if (r == Ctrl_C || r == ESC)
3418 	    r = 'n';
3419 	msg_putchar(r);	    /* show what you typed */
3420 	out_flush();
3421     }
3422     --no_wait_return;
3423     State = save_State;
3424 #ifdef FEAT_MOUSE
3425     setmouse();
3426 #endif
3427     --no_mapping;
3428     --allow_keys;
3429 
3430     return r;
3431 }
3432 
3433 #if defined(FEAT_MOUSE) || defined(PROTO)
3434 /*
3435  * Return TRUE if "c" is a mouse key.
3436  */
3437     int
3438 is_mouse_key(int c)
3439 {
3440     return c == K_LEFTMOUSE
3441 	|| c == K_LEFTMOUSE_NM
3442 	|| c == K_LEFTDRAG
3443 	|| c == K_LEFTRELEASE
3444 	|| c == K_LEFTRELEASE_NM
3445 	|| c == K_MOUSEMOVE
3446 	|| c == K_MIDDLEMOUSE
3447 	|| c == K_MIDDLEDRAG
3448 	|| c == K_MIDDLERELEASE
3449 	|| c == K_RIGHTMOUSE
3450 	|| c == K_RIGHTDRAG
3451 	|| c == K_RIGHTRELEASE
3452 	|| c == K_MOUSEDOWN
3453 	|| c == K_MOUSEUP
3454 	|| c == K_MOUSELEFT
3455 	|| c == K_MOUSERIGHT
3456 	|| c == K_X1MOUSE
3457 	|| c == K_X1DRAG
3458 	|| c == K_X1RELEASE
3459 	|| c == K_X2MOUSE
3460 	|| c == K_X2DRAG
3461 	|| c == K_X2RELEASE;
3462 }
3463 #endif
3464 
3465 /*
3466  * Get a key stroke directly from the user.
3467  * Ignores mouse clicks and scrollbar events, except a click for the left
3468  * button (used at the more prompt).
3469  * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3470  * Disadvantage: typeahead is ignored.
3471  * Translates the interrupt character for unix to ESC.
3472  */
3473     int
3474 get_keystroke(void)
3475 {
3476     char_u	*buf = NULL;
3477     int		buflen = 150;
3478     int		maxlen;
3479     int		len = 0;
3480     int		n;
3481     int		save_mapped_ctrl_c = mapped_ctrl_c;
3482     int		waited = 0;
3483 
3484     mapped_ctrl_c = FALSE;	/* mappings are not used here */
3485     for (;;)
3486     {
3487 	cursor_on();
3488 	out_flush();
3489 
3490 	/* Leave some room for check_termcode() to insert a key code into (max
3491 	 * 5 chars plus NUL).  And fix_input_buffer() can triple the number of
3492 	 * bytes. */
3493 	maxlen = (buflen - 6 - len) / 3;
3494 	if (buf == NULL)
3495 	    buf = alloc(buflen);
3496 	else if (maxlen < 10)
3497 	{
3498 	    char_u  *t_buf = buf;
3499 
3500 	    /* Need some more space. This might happen when receiving a long
3501 	     * escape sequence. */
3502 	    buflen += 100;
3503 	    buf = vim_realloc(buf, buflen);
3504 	    if (buf == NULL)
3505 		vim_free(t_buf);
3506 	    maxlen = (buflen - 6 - len) / 3;
3507 	}
3508 	if (buf == NULL)
3509 	{
3510 	    do_outofmem_msg((long_u)buflen);
3511 	    return ESC;  /* panic! */
3512 	}
3513 
3514 	/* First time: blocking wait.  Second time: wait up to 100ms for a
3515 	 * terminal code to complete. */
3516 	n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
3517 	if (n > 0)
3518 	{
3519 	    /* Replace zero and CSI by a special key code. */
3520 	    n = fix_input_buffer(buf + len, n);
3521 	    len += n;
3522 	    waited = 0;
3523 	}
3524 	else if (len > 0)
3525 	    ++waited;	    /* keep track of the waiting time */
3526 
3527 	/* Incomplete termcode and not timed out yet: get more characters */
3528 	if ((n = check_termcode(1, buf, buflen, &len)) < 0
3529 	       && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
3530 	    continue;
3531 
3532 	if (n == KEYLEN_REMOVED)  /* key code removed */
3533 	{
3534 	    if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
3535 	    {
3536 		/* Redrawing was postponed, do it now. */
3537 		update_screen(0);
3538 		setcursor(); /* put cursor back where it belongs */
3539 	    }
3540 	    continue;
3541 	}
3542 	if (n > 0)		/* found a termcode: adjust length */
3543 	    len = n;
3544 	if (len == 0)		/* nothing typed yet */
3545 	    continue;
3546 
3547 	/* Handle modifier and/or special key code. */
3548 	n = buf[0];
3549 	if (n == K_SPECIAL)
3550 	{
3551 	    n = TO_SPECIAL(buf[1], buf[2]);
3552 	    if (buf[1] == KS_MODIFIER
3553 		    || n == K_IGNORE
3554 #ifdef FEAT_MOUSE
3555 		    || (is_mouse_key(n) && n != K_LEFTMOUSE)
3556 #endif
3557 #ifdef FEAT_GUI
3558 		    || n == K_VER_SCROLLBAR
3559 		    || n == K_HOR_SCROLLBAR
3560 #endif
3561 	       )
3562 	    {
3563 		if (buf[1] == KS_MODIFIER)
3564 		    mod_mask = buf[2];
3565 		len -= 3;
3566 		if (len > 0)
3567 		    mch_memmove(buf, buf + 3, (size_t)len);
3568 		continue;
3569 	    }
3570 	    break;
3571 	}
3572 	if (has_mbyte)
3573 	{
3574 	    if (MB_BYTE2LEN(n) > len)
3575 		continue;	/* more bytes to get */
3576 	    buf[len >= buflen ? buflen - 1 : len] = NUL;
3577 	    n = (*mb_ptr2char)(buf);
3578 	}
3579 #ifdef UNIX
3580 	if (n == intr_char)
3581 	    n = ESC;
3582 #endif
3583 	break;
3584     }
3585     vim_free(buf);
3586 
3587     mapped_ctrl_c = save_mapped_ctrl_c;
3588     return n;
3589 }
3590 
3591 /*
3592  * Get a number from the user.
3593  * When "mouse_used" is not NULL allow using the mouse.
3594  */
3595     int
3596 get_number(
3597     int	    colon,			/* allow colon to abort */
3598     int	    *mouse_used)
3599 {
3600     int	n = 0;
3601     int	c;
3602     int typed = 0;
3603 
3604     if (mouse_used != NULL)
3605 	*mouse_used = FALSE;
3606 
3607     /* When not printing messages, the user won't know what to type, return a
3608      * zero (as if CR was hit). */
3609     if (msg_silent != 0)
3610 	return 0;
3611 
3612 #ifdef USE_ON_FLY_SCROLL
3613     dont_scroll = TRUE;		/* disallow scrolling here */
3614 #endif
3615     ++no_mapping;
3616     ++allow_keys;		/* no mapping here, but recognize keys */
3617     for (;;)
3618     {
3619 	windgoto(msg_row, msg_col);
3620 	c = safe_vgetc();
3621 	if (VIM_ISDIGIT(c))
3622 	{
3623 	    n = n * 10 + c - '0';
3624 	    msg_putchar(c);
3625 	    ++typed;
3626 	}
3627 	else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3628 	{
3629 	    if (typed > 0)
3630 	    {
3631 		msg_puts("\b \b");
3632 		--typed;
3633 	    }
3634 	    n /= 10;
3635 	}
3636 #ifdef FEAT_MOUSE
3637 	else if (mouse_used != NULL && c == K_LEFTMOUSE)
3638 	{
3639 	    *mouse_used = TRUE;
3640 	    n = mouse_row + 1;
3641 	    break;
3642 	}
3643 #endif
3644 	else if (n == 0 && c == ':' && colon)
3645 	{
3646 	    stuffcharReadbuff(':');
3647 	    if (!exmode_active)
3648 		cmdline_row = msg_row;
3649 	    skip_redraw = TRUE;	    /* skip redraw once */
3650 	    do_redraw = FALSE;
3651 	    break;
3652 	}
3653 	else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3654 	    break;
3655     }
3656     --no_mapping;
3657     --allow_keys;
3658     return n;
3659 }
3660 
3661 /*
3662  * Ask the user to enter a number.
3663  * When "mouse_used" is not NULL allow using the mouse and in that case return
3664  * the line number.
3665  */
3666     int
3667 prompt_for_number(int *mouse_used)
3668 {
3669     int		i;
3670     int		save_cmdline_row;
3671     int		save_State;
3672 
3673     /* When using ":silent" assume that <CR> was entered. */
3674     if (mouse_used != NULL)
3675 	msg_puts(_("Type number and <Enter> or click with mouse (empty cancels): "));
3676     else
3677 	msg_puts(_("Type number and <Enter> (empty cancels): "));
3678 
3679     // Set the state such that text can be selected/copied/pasted and we still
3680     // get mouse events. redraw_after_callback() will not redraw if cmdline_row
3681     // is zero.
3682     save_cmdline_row = cmdline_row;
3683     cmdline_row = 0;
3684     save_State = State;
3685     State = CMDLINE;
3686 #ifdef FEAT_MOUSE
3687     // May show different mouse shape.
3688     setmouse();
3689 #endif
3690 
3691     i = get_number(TRUE, mouse_used);
3692     if (KeyTyped)
3693     {
3694 	/* don't call wait_return() now */
3695 	/* msg_putchar('\n'); */
3696 	cmdline_row = msg_row - 1;
3697 	need_wait_return = FALSE;
3698 	msg_didany = FALSE;
3699 	msg_didout = FALSE;
3700     }
3701     else
3702 	cmdline_row = save_cmdline_row;
3703     State = save_State;
3704 #ifdef FEAT_MOUSE
3705     // May need to restore mouse shape.
3706     setmouse();
3707 #endif
3708 
3709     return i;
3710 }
3711 
3712     void
3713 msgmore(long n)
3714 {
3715     long pn;
3716 
3717     if (global_busy	    /* no messages now, wait until global is finished */
3718 	    || !messaging())  /* 'lazyredraw' set, don't do messages now */
3719 	return;
3720 
3721     /* We don't want to overwrite another important message, but do overwrite
3722      * a previous "more lines" or "fewer lines" message, so that "5dd" and
3723      * then "put" reports the last action. */
3724     if (keep_msg != NULL && !keep_msg_more)
3725 	return;
3726 
3727     if (n > 0)
3728 	pn = n;
3729     else
3730 	pn = -n;
3731 
3732     if (pn > p_report)
3733     {
3734 	if (n > 0)
3735 	    vim_snprintf(msg_buf, MSG_BUF_LEN,
3736 		    NGETTEXT("%ld more line", "%ld more lines", pn), pn);
3737 	else
3738 	    vim_snprintf(msg_buf, MSG_BUF_LEN,
3739 		    NGETTEXT("%ld line less", "%ld fewer lines", pn), pn);
3740 	if (got_int)
3741 	    vim_strcat((char_u *)msg_buf, (char_u *)_(" (Interrupted)"),
3742 								  MSG_BUF_LEN);
3743 	if (msg(msg_buf))
3744 	{
3745 	    set_keep_msg((char_u *)msg_buf, 0);
3746 	    keep_msg_more = TRUE;
3747 	}
3748     }
3749 }
3750 
3751 /*
3752  * flush map and typeahead buffers and give a warning for an error
3753  */
3754     void
3755 beep_flush(void)
3756 {
3757     if (emsg_silent == 0)
3758     {
3759 	flush_buffers(FLUSH_MINIMAL);
3760 	vim_beep(BO_ERROR);
3761     }
3762 }
3763 
3764 /*
3765  * Give a warning for an error.
3766  */
3767     void
3768 vim_beep(
3769     unsigned val) /* one of the BO_ values, e.g., BO_OPER */
3770 {
3771 #ifdef FEAT_EVAL
3772     called_vim_beep = TRUE;
3773 #endif
3774 
3775     if (emsg_silent == 0)
3776     {
3777 	if (!((bo_flags & val) || (bo_flags & BO_ALL)))
3778 	{
3779 #ifdef ELAPSED_FUNC
3780 	    static int		did_init = FALSE;
3781 	    static elapsed_T	start_tv;
3782 
3783 	    /* Only beep once per half a second, otherwise a sequence of beeps
3784 	     * would freeze Vim. */
3785 	    if (!did_init || ELAPSED_FUNC(start_tv) > 500)
3786 	    {
3787 		did_init = TRUE;
3788 		ELAPSED_INIT(start_tv);
3789 #endif
3790 		if (p_vb
3791 #ifdef FEAT_GUI
3792 			/* While the GUI is starting up the termcap is set for
3793 			 * the GUI but the output still goes to a terminal. */
3794 			&& !(gui.in_use && gui.starting)
3795 #endif
3796 			)
3797 		{
3798 		    out_str_cf(T_VB);
3799 #ifdef FEAT_VTP
3800 		    /* No restore color information, refresh the screen. */
3801 		    if (has_vtp_working() != 0
3802 # ifdef FEAT_TERMGUICOLORS
3803 			    && (p_tgc || (!p_tgc && t_colors >= 256))
3804 # endif
3805 			)
3806 		    {
3807 			redraw_later(CLEAR);
3808 			update_screen(0);
3809 			redrawcmd();
3810 		    }
3811 #endif
3812 		}
3813 		else
3814 		    out_char(BELL);
3815 #ifdef ELAPSED_FUNC
3816 	    }
3817 #endif
3818 	}
3819 
3820 	/* When 'debug' contains "beep" produce a message.  If we are sourcing
3821 	 * a script or executing a function give the user a hint where the beep
3822 	 * comes from. */
3823 	if (vim_strchr(p_debug, 'e') != NULL)
3824 	{
3825 	    msg_source(HL_ATTR(HLF_W));
3826 	    msg_attr(_("Beep!"), HL_ATTR(HLF_W));
3827 	}
3828     }
3829 }
3830 
3831 /*
3832  * To get the "real" home directory:
3833  * - get value of $HOME
3834  * For Unix:
3835  *  - go to that directory
3836  *  - do mch_dirname() to get the real name of that directory.
3837  *  This also works with mounts and links.
3838  *  Don't do this for MS-DOS, it will change the "current dir" for a drive.
3839  * For Windows:
3840  *  This code is duplicated in init_homedir() in dosinst.c.  Keep in sync!
3841  */
3842 static char_u	*homedir = NULL;
3843 
3844     void
3845 init_homedir(void)
3846 {
3847     char_u  *var;
3848 
3849     /* In case we are called a second time (when 'encoding' changes). */
3850     VIM_CLEAR(homedir);
3851 
3852 #ifdef VMS
3853     var = mch_getenv((char_u *)"SYS$LOGIN");
3854 #else
3855     var = mch_getenv((char_u *)"HOME");
3856 #endif
3857 
3858 #ifdef MSWIN
3859     /*
3860      * Typically, $HOME is not defined on Windows, unless the user has
3861      * specifically defined it for Vim's sake.  However, on Windows NT
3862      * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3863      * each user.  Try constructing $HOME from these.
3864      */
3865     if (var == NULL || *var == NUL)
3866     {
3867 	char_u *homedrive, *homepath;
3868 
3869 	homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3870 	homepath = mch_getenv((char_u *)"HOMEPATH");
3871 	if (homepath == NULL || *homepath == NUL)
3872 	    homepath = (char_u *)"\\";
3873 	if (homedrive != NULL
3874 			   && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3875 	{
3876 	    sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3877 	    if (NameBuff[0] != NUL)
3878 		var = NameBuff;
3879 	}
3880     }
3881 
3882     if (var == NULL)
3883 	var = mch_getenv((char_u *)"USERPROFILE");
3884 
3885     /*
3886      * Weird but true: $HOME may contain an indirect reference to another
3887      * variable, esp. "%USERPROFILE%".  Happens when $USERPROFILE isn't set
3888      * when $HOME is being set.
3889      */
3890     if (var != NULL && *var == '%')
3891     {
3892 	char_u	*p;
3893 	char_u	*exp;
3894 
3895 	p = vim_strchr(var + 1, '%');
3896 	if (p != NULL)
3897 	{
3898 	    vim_strncpy(NameBuff, var + 1, p - (var + 1));
3899 	    exp = mch_getenv(NameBuff);
3900 	    if (exp != NULL && *exp != NUL
3901 					&& STRLEN(exp) + STRLEN(p) < MAXPATHL)
3902 	    {
3903 		vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
3904 		var = NameBuff;
3905 	    }
3906 	}
3907     }
3908 
3909     if (var != NULL && *var == NUL)	/* empty is same as not set */
3910 	var = NULL;
3911 
3912     if (enc_utf8 && var != NULL)
3913     {
3914 	int	len;
3915 	char_u  *pp = NULL;
3916 
3917 	/* Convert from active codepage to UTF-8.  Other conversions are
3918 	 * not done, because they would fail for non-ASCII characters. */
3919 	acp_to_enc(var, (int)STRLEN(var), &pp, &len);
3920 	if (pp != NULL)
3921 	{
3922 	    homedir = pp;
3923 	    return;
3924 	}
3925     }
3926 
3927     /*
3928      * Default home dir is C:/
3929      * Best assumption we can make in such a situation.
3930      */
3931     if (var == NULL)
3932 	var = (char_u *)"C:/";
3933 #endif
3934 
3935     if (var != NULL)
3936     {
3937 #ifdef UNIX
3938 	/*
3939 	 * Change to the directory and get the actual path.  This resolves
3940 	 * links.  Don't do it when we can't return.
3941 	 */
3942 	if (mch_dirname(NameBuff, MAXPATHL) == OK
3943 					  && mch_chdir((char *)NameBuff) == 0)
3944 	{
3945 	    if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3946 		var = IObuff;
3947 	    if (mch_chdir((char *)NameBuff) != 0)
3948 		emsg(_(e_prev_dir));
3949 	}
3950 #endif
3951 	homedir = vim_strsave(var);
3952     }
3953 }
3954 
3955 #if defined(EXITFREE) || defined(PROTO)
3956     void
3957 free_homedir(void)
3958 {
3959     vim_free(homedir);
3960 }
3961 
3962 # ifdef FEAT_CMDL_COMPL
3963     void
3964 free_users(void)
3965 {
3966     ga_clear_strings(&ga_users);
3967 }
3968 # endif
3969 #endif
3970 
3971 /*
3972  * Call expand_env() and store the result in an allocated string.
3973  * This is not very memory efficient, this expects the result to be freed
3974  * again soon.
3975  */
3976     char_u *
3977 expand_env_save(char_u *src)
3978 {
3979     return expand_env_save_opt(src, FALSE);
3980 }
3981 
3982 /*
3983  * Idem, but when "one" is TRUE handle the string as one file name, only
3984  * expand "~" at the start.
3985  */
3986     char_u *
3987 expand_env_save_opt(char_u *src, int one)
3988 {
3989     char_u	*p;
3990 
3991     p = alloc(MAXPATHL);
3992     if (p != NULL)
3993 	expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3994     return p;
3995 }
3996 
3997 /*
3998  * Expand environment variable with path name.
3999  * "~/" is also expanded, using $HOME.	For Unix "~user/" is expanded.
4000  * Skips over "\ ", "\~" and "\$" (not for Win32 though).
4001  * If anything fails no expansion is done and dst equals src.
4002  */
4003     void
4004 expand_env(
4005     char_u	*src,		/* input string e.g. "$HOME/vim.hlp" */
4006     char_u	*dst,		/* where to put the result */
4007     int		dstlen)		/* maximum length of the result */
4008 {
4009     expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
4010 }
4011 
4012     void
4013 expand_env_esc(
4014     char_u	*srcp,		/* input string e.g. "$HOME/vim.hlp" */
4015     char_u	*dst,		/* where to put the result */
4016     int		dstlen,		/* maximum length of the result */
4017     int		esc,		/* escape spaces in expanded variables */
4018     int		one,		/* "srcp" is one file name */
4019     char_u	*startstr)	/* start again after this (can be NULL) */
4020 {
4021     char_u	*src;
4022     char_u	*tail;
4023     int		c;
4024     char_u	*var;
4025     int		copy_char;
4026     int		mustfree;	/* var was allocated, need to free it later */
4027     int		at_start = TRUE; /* at start of a name */
4028     int		startstr_len = 0;
4029 
4030     if (startstr != NULL)
4031 	startstr_len = (int)STRLEN(startstr);
4032 
4033     src = skipwhite(srcp);
4034     --dstlen;		    /* leave one char space for "\," */
4035     while (*src && dstlen > 0)
4036     {
4037 #ifdef FEAT_EVAL
4038 	/* Skip over `=expr`. */
4039 	if (src[0] == '`' && src[1] == '=')
4040 	{
4041 	    size_t len;
4042 
4043 	    var = src;
4044 	    src += 2;
4045 	    (void)skip_expr(&src);
4046 	    if (*src == '`')
4047 		++src;
4048 	    len = src - var;
4049 	    if (len > (size_t)dstlen)
4050 		len = dstlen;
4051 	    vim_strncpy(dst, var, len);
4052 	    dst += len;
4053 	    dstlen -= (int)len;
4054 	    continue;
4055 	}
4056 #endif
4057 	copy_char = TRUE;
4058 	if ((*src == '$'
4059 #ifdef VMS
4060 		    && at_start
4061 #endif
4062 	   )
4063 #if defined(MSWIN)
4064 		|| *src == '%'
4065 #endif
4066 		|| (*src == '~' && at_start))
4067 	{
4068 	    mustfree = FALSE;
4069 
4070 	    /*
4071 	     * The variable name is copied into dst temporarily, because it may
4072 	     * be a string in read-only memory and a NUL needs to be appended.
4073 	     */
4074 	    if (*src != '~')				/* environment var */
4075 	    {
4076 		tail = src + 1;
4077 		var = dst;
4078 		c = dstlen - 1;
4079 
4080 #ifdef UNIX
4081 		/* Unix has ${var-name} type environment vars */
4082 		if (*tail == '{' && !vim_isIDc('{'))
4083 		{
4084 		    tail++;	/* ignore '{' */
4085 		    while (c-- > 0 && *tail && *tail != '}')
4086 			*var++ = *tail++;
4087 		}
4088 		else
4089 #endif
4090 		{
4091 		    while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
4092 #if defined(MSWIN)
4093 			    || (*src == '%' && *tail != '%')
4094 #endif
4095 			    ))
4096 		    {
4097 			*var++ = *tail++;
4098 		    }
4099 		}
4100 
4101 #if defined(MSWIN) || defined(UNIX)
4102 # ifdef UNIX
4103 		if (src[1] == '{' && *tail != '}')
4104 # else
4105 		if (*src == '%' && *tail != '%')
4106 # endif
4107 		    var = NULL;
4108 		else
4109 		{
4110 # ifdef UNIX
4111 		    if (src[1] == '{')
4112 # else
4113 		    if (*src == '%')
4114 #endif
4115 			++tail;
4116 #endif
4117 		    *var = NUL;
4118 		    var = vim_getenv(dst, &mustfree);
4119 #if defined(MSWIN) || defined(UNIX)
4120 		}
4121 #endif
4122 	    }
4123 							/* home directory */
4124 	    else if (  src[1] == NUL
4125 		    || vim_ispathsep(src[1])
4126 		    || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
4127 	    {
4128 		var = homedir;
4129 		tail = src + 1;
4130 	    }
4131 	    else					/* user directory */
4132 	    {
4133 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
4134 		/*
4135 		 * Copy ~user to dst[], so we can put a NUL after it.
4136 		 */
4137 		tail = src;
4138 		var = dst;
4139 		c = dstlen - 1;
4140 		while (	   c-- > 0
4141 			&& *tail
4142 			&& vim_isfilec(*tail)
4143 			&& !vim_ispathsep(*tail))
4144 		    *var++ = *tail++;
4145 		*var = NUL;
4146 # ifdef UNIX
4147 		/*
4148 		 * If the system supports getpwnam(), use it.
4149 		 * Otherwise, or if getpwnam() fails, the shell is used to
4150 		 * expand ~user.  This is slower and may fail if the shell
4151 		 * does not support ~user (old versions of /bin/sh).
4152 		 */
4153 #  if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
4154 		{
4155 		    /* Note: memory allocated by getpwnam() is never freed.
4156 		     * Calling endpwent() apparently doesn't help. */
4157 		    struct passwd *pw = (*dst == NUL)
4158 					? NULL : getpwnam((char *)dst + 1);
4159 
4160 		    var = (pw == NULL) ? NULL : (char_u *)pw->pw_dir;
4161 		}
4162 		if (var == NULL)
4163 #  endif
4164 		{
4165 		    expand_T	xpc;
4166 
4167 		    ExpandInit(&xpc);
4168 		    xpc.xp_context = EXPAND_FILES;
4169 		    var = ExpandOne(&xpc, dst, NULL,
4170 				WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
4171 		    mustfree = TRUE;
4172 		}
4173 
4174 # else	/* !UNIX, thus VMS */
4175 		/*
4176 		 * USER_HOME is a comma-separated list of
4177 		 * directories to search for the user account in.
4178 		 */
4179 		{
4180 		    char_u	test[MAXPATHL], paths[MAXPATHL];
4181 		    char_u	*path, *next_path, *ptr;
4182 		    stat_T	st;
4183 
4184 		    STRCPY(paths, USER_HOME);
4185 		    next_path = paths;
4186 		    while (*next_path)
4187 		    {
4188 			for (path = next_path; *next_path && *next_path != ',';
4189 				next_path++);
4190 			if (*next_path)
4191 			    *next_path++ = NUL;
4192 			STRCPY(test, path);
4193 			STRCAT(test, "/");
4194 			STRCAT(test, dst + 1);
4195 			if (mch_stat(test, &st) == 0)
4196 			{
4197 			    var = alloc(STRLEN(test) + 1);
4198 			    STRCPY(var, test);
4199 			    mustfree = TRUE;
4200 			    break;
4201 			}
4202 		    }
4203 		}
4204 # endif /* UNIX */
4205 #else
4206 		/* cannot expand user's home directory, so don't try */
4207 		var = NULL;
4208 		tail = (char_u *)"";	/* for gcc */
4209 #endif /* UNIX || VMS */
4210 	    }
4211 
4212 #ifdef BACKSLASH_IN_FILENAME
4213 	    /* If 'shellslash' is set change backslashes to forward slashes.
4214 	     * Can't use slash_adjust(), p_ssl may be set temporarily. */
4215 	    if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4216 	    {
4217 		char_u	*p = vim_strsave(var);
4218 
4219 		if (p != NULL)
4220 		{
4221 		    if (mustfree)
4222 			vim_free(var);
4223 		    var = p;
4224 		    mustfree = TRUE;
4225 		    forward_slash(var);
4226 		}
4227 	    }
4228 #endif
4229 
4230 	    /* If "var" contains white space, escape it with a backslash.
4231 	     * Required for ":e ~/tt" when $HOME includes a space. */
4232 	    if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4233 	    {
4234 		char_u	*p = vim_strsave_escaped(var, (char_u *)" \t");
4235 
4236 		if (p != NULL)
4237 		{
4238 		    if (mustfree)
4239 			vim_free(var);
4240 		    var = p;
4241 		    mustfree = TRUE;
4242 		}
4243 	    }
4244 
4245 	    if (var != NULL && *var != NUL
4246 		    && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4247 	    {
4248 		STRCPY(dst, var);
4249 		dstlen -= (int)STRLEN(var);
4250 		c = (int)STRLEN(var);
4251 		/* if var[] ends in a path separator and tail[] starts
4252 		 * with it, skip a character */
4253 		if (*var != NUL && after_pathsep(dst, dst + c)
4254 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4255 			&& dst[-1] != ':'
4256 #endif
4257 			&& vim_ispathsep(*tail))
4258 		    ++tail;
4259 		dst += c;
4260 		src = tail;
4261 		copy_char = FALSE;
4262 	    }
4263 	    if (mustfree)
4264 		vim_free(var);
4265 	}
4266 
4267 	if (copy_char)	    /* copy at least one char */
4268 	{
4269 	    /*
4270 	     * Recognize the start of a new name, for '~'.
4271 	     * Don't do this when "one" is TRUE, to avoid expanding "~" in
4272 	     * ":edit foo ~ foo".
4273 	     */
4274 	    at_start = FALSE;
4275 	    if (src[0] == '\\' && src[1] != NUL)
4276 	    {
4277 		*dst++ = *src++;
4278 		--dstlen;
4279 	    }
4280 	    else if ((src[0] == ' ' || src[0] == ',') && !one)
4281 		at_start = TRUE;
4282 	    if (dstlen > 0)
4283 	    {
4284 		*dst++ = *src++;
4285 		--dstlen;
4286 
4287 		if (startstr != NULL && src - startstr_len >= srcp
4288 			&& STRNCMP(src - startstr_len, startstr,
4289 							    startstr_len) == 0)
4290 		    at_start = TRUE;
4291 	    }
4292 	}
4293 
4294     }
4295     *dst = NUL;
4296 }
4297 
4298 /*
4299  * Vim's version of getenv().
4300  * Special handling of $HOME, $VIM and $VIMRUNTIME.
4301  * Also does ACP to 'enc' conversion for Win32.
4302  * "mustfree" is set to TRUE when returned is allocated, it must be
4303  * initialized to FALSE by the caller.
4304  */
4305     char_u *
4306 vim_getenv(char_u *name, int *mustfree)
4307 {
4308     char_u	*p;
4309     char_u	*pend;
4310     int		vimruntime;
4311 
4312 #if defined(MSWIN)
4313     /* use "C:/" when $HOME is not set */
4314     if (STRCMP(name, "HOME") == 0)
4315 	return homedir;
4316 #endif
4317 
4318     p = mch_getenv(name);
4319     if (p != NULL && *p == NUL)	    /* empty is the same as not set */
4320 	p = NULL;
4321 
4322     if (p != NULL)
4323     {
4324 #if defined(MSWIN)
4325 	if (enc_utf8)
4326 	{
4327 	    int	    len;
4328 	    char_u  *pp = NULL;
4329 
4330 	    /* Convert from active codepage to UTF-8.  Other conversions are
4331 	     * not done, because they would fail for non-ASCII characters. */
4332 	    acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4333 	    if (pp != NULL)
4334 	    {
4335 		p = pp;
4336 		*mustfree = TRUE;
4337 	    }
4338 	}
4339 #endif
4340 	return p;
4341     }
4342 
4343     vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4344     if (!vimruntime && STRCMP(name, "VIM") != 0)
4345 	return NULL;
4346 
4347     /*
4348      * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4349      * Don't do this when default_vimruntime_dir is non-empty.
4350      */
4351     if (vimruntime
4352 #ifdef HAVE_PATHDEF
4353 	    && *default_vimruntime_dir == NUL
4354 #endif
4355        )
4356     {
4357 	p = mch_getenv((char_u *)"VIM");
4358 	if (p != NULL && *p == NUL)	    /* empty is the same as not set */
4359 	    p = NULL;
4360 	if (p != NULL)
4361 	{
4362 	    p = vim_version_dir(p);
4363 	    if (p != NULL)
4364 		*mustfree = TRUE;
4365 	    else
4366 		p = mch_getenv((char_u *)"VIM");
4367 
4368 #if defined(MSWIN)
4369 	    if (enc_utf8)
4370 	    {
4371 		int	len;
4372 		char_u  *pp = NULL;
4373 
4374 		/* Convert from active codepage to UTF-8.  Other conversions
4375 		 * are not done, because they would fail for non-ASCII
4376 		 * characters. */
4377 		acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4378 		if (pp != NULL)
4379 		{
4380 		    if (*mustfree)
4381 			vim_free(p);
4382 		    p = pp;
4383 		    *mustfree = TRUE;
4384 		}
4385 	    }
4386 #endif
4387 	}
4388     }
4389 
4390     /*
4391      * When expanding $VIM or $VIMRUNTIME fails, try using:
4392      * - the directory name from 'helpfile' (unless it contains '$')
4393      * - the executable name from argv[0]
4394      */
4395     if (p == NULL)
4396     {
4397 	if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4398 	    p = p_hf;
4399 #ifdef USE_EXE_NAME
4400 	/*
4401 	 * Use the name of the executable, obtained from argv[0].
4402 	 */
4403 	else
4404 	    p = exe_name;
4405 #endif
4406 	if (p != NULL)
4407 	{
4408 	    /* remove the file name */
4409 	    pend = gettail(p);
4410 
4411 	    /* remove "doc/" from 'helpfile', if present */
4412 	    if (p == p_hf)
4413 		pend = remove_tail(p, pend, (char_u *)"doc");
4414 
4415 #ifdef USE_EXE_NAME
4416 # ifdef MACOS_X
4417 	    /* remove "MacOS" from exe_name and add "Resources/vim" */
4418 	    if (p == exe_name)
4419 	    {
4420 		char_u	*pend1;
4421 		char_u	*pnew;
4422 
4423 		pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4424 		if (pend1 != pend)
4425 		{
4426 		    pnew = alloc((unsigned)(pend1 - p) + 15);
4427 		    if (pnew != NULL)
4428 		    {
4429 			STRNCPY(pnew, p, (pend1 - p));
4430 			STRCPY(pnew + (pend1 - p), "Resources/vim");
4431 			p = pnew;
4432 			pend = p + STRLEN(p);
4433 		    }
4434 		}
4435 	    }
4436 # endif
4437 	    /* remove "src/" from exe_name, if present */
4438 	    if (p == exe_name)
4439 		pend = remove_tail(p, pend, (char_u *)"src");
4440 #endif
4441 
4442 	    /* for $VIM, remove "runtime/" or "vim54/", if present */
4443 	    if (!vimruntime)
4444 	    {
4445 		pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4446 		pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4447 	    }
4448 
4449 	    /* remove trailing path separator */
4450 	    if (pend > p && after_pathsep(p, pend))
4451 		--pend;
4452 
4453 #ifdef MACOS_X
4454 	    if (p == exe_name || p == p_hf)
4455 #endif
4456 		/* check that the result is a directory name */
4457 		p = vim_strnsave(p, (int)(pend - p));
4458 
4459 	    if (p != NULL && !mch_isdir(p))
4460 		VIM_CLEAR(p);
4461 	    else
4462 	    {
4463 #ifdef USE_EXE_NAME
4464 		/* may add "/vim54" or "/runtime" if it exists */
4465 		if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4466 		{
4467 		    vim_free(p);
4468 		    p = pend;
4469 		}
4470 #endif
4471 		*mustfree = TRUE;
4472 	    }
4473 	}
4474     }
4475 
4476 #ifdef HAVE_PATHDEF
4477     /* When there is a pathdef.c file we can use default_vim_dir and
4478      * default_vimruntime_dir */
4479     if (p == NULL)
4480     {
4481 	/* Only use default_vimruntime_dir when it is not empty */
4482 	if (vimruntime && *default_vimruntime_dir != NUL)
4483 	{
4484 	    p = default_vimruntime_dir;
4485 	    *mustfree = FALSE;
4486 	}
4487 	else if (*default_vim_dir != NUL)
4488 	{
4489 	    if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4490 		*mustfree = TRUE;
4491 	    else
4492 	    {
4493 		p = default_vim_dir;
4494 		*mustfree = FALSE;
4495 	    }
4496 	}
4497     }
4498 #endif
4499 
4500     /*
4501      * Set the environment variable, so that the new value can be found fast
4502      * next time, and others can also use it (e.g. Perl).
4503      */
4504     if (p != NULL)
4505     {
4506 	if (vimruntime)
4507 	{
4508 	    vim_setenv((char_u *)"VIMRUNTIME", p);
4509 	    didset_vimruntime = TRUE;
4510 	}
4511 	else
4512 	{
4513 	    vim_setenv((char_u *)"VIM", p);
4514 	    didset_vim = TRUE;
4515 	}
4516     }
4517     return p;
4518 }
4519 
4520 /*
4521  * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4522  * Return NULL if not, return its name in allocated memory otherwise.
4523  */
4524     static char_u *
4525 vim_version_dir(char_u *vimdir)
4526 {
4527     char_u	*p;
4528 
4529     if (vimdir == NULL || *vimdir == NUL)
4530 	return NULL;
4531     p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4532     if (p != NULL && mch_isdir(p))
4533 	return p;
4534     vim_free(p);
4535     p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4536     if (p != NULL && mch_isdir(p))
4537 	return p;
4538     vim_free(p);
4539     return NULL;
4540 }
4541 
4542 /*
4543  * If the string between "p" and "pend" ends in "name/", return "pend" minus
4544  * the length of "name/".  Otherwise return "pend".
4545  */
4546     static char_u *
4547 remove_tail(char_u *p, char_u *pend, char_u *name)
4548 {
4549     int		len = (int)STRLEN(name) + 1;
4550     char_u	*newend = pend - len;
4551 
4552     if (newend >= p
4553 	    && fnamencmp(newend, name, len - 1) == 0
4554 	    && (newend == p || after_pathsep(p, newend)))
4555 	return newend;
4556     return pend;
4557 }
4558 
4559 #if defined(FEAT_EVAL) || defined(PROTO)
4560     void
4561 vim_unsetenv(char_u *var)
4562 {
4563 #ifdef HAVE_UNSETENV
4564     unsetenv((char *)var);
4565 #else
4566     vim_setenv(var, (char_u *)"");
4567 #endif
4568 }
4569 #endif
4570 
4571 
4572 /*
4573  * Our portable version of setenv.
4574  */
4575     void
4576 vim_setenv(char_u *name, char_u *val)
4577 {
4578 #ifdef HAVE_SETENV
4579     mch_setenv((char *)name, (char *)val, 1);
4580 #else
4581     char_u	*envbuf;
4582 
4583     /*
4584      * Putenv does not copy the string, it has to remain
4585      * valid.  The allocated memory will never be freed.
4586      */
4587     envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4588     if (envbuf != NULL)
4589     {
4590 	sprintf((char *)envbuf, "%s=%s", name, val);
4591 	putenv((char *)envbuf);
4592     }
4593 #endif
4594 #ifdef FEAT_GETTEXT
4595     /*
4596      * When setting $VIMRUNTIME adjust the directory to find message
4597      * translations to $VIMRUNTIME/lang.
4598      */
4599     if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4600     {
4601 	char_u	*buf = concat_str(val, (char_u *)"/lang");
4602 
4603 	if (buf != NULL)
4604 	{
4605 	    bindtextdomain(VIMPACKAGE, (char *)buf);
4606 	    vim_free(buf);
4607 	}
4608     }
4609 #endif
4610 }
4611 
4612 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4613 /*
4614  * Function given to ExpandGeneric() to obtain an environment variable name.
4615  */
4616     char_u *
4617 get_env_name(
4618     expand_T	*xp UNUSED,
4619     int		idx)
4620 {
4621 # if defined(AMIGA)
4622     /*
4623      * No environ[] on the Amiga.
4624      */
4625     return NULL;
4626 # else
4627 # ifndef __WIN32__
4628     /* Borland C++ 5.2 has this in a header file. */
4629     extern char		**environ;
4630 # endif
4631 # define ENVNAMELEN 100
4632     static char_u	name[ENVNAMELEN];
4633     char_u		*str;
4634     int			n;
4635 
4636     str = (char_u *)environ[idx];
4637     if (str == NULL)
4638 	return NULL;
4639 
4640     for (n = 0; n < ENVNAMELEN - 1; ++n)
4641     {
4642 	if (str[n] == '=' || str[n] == NUL)
4643 	    break;
4644 	name[n] = str[n];
4645     }
4646     name[n] = NUL;
4647     return name;
4648 # endif
4649 }
4650 
4651 /*
4652  * Add a user name to the list of users in ga_users.
4653  * Do nothing if user name is NULL or empty.
4654  */
4655     static void
4656 add_user(char_u *user, int need_copy)
4657 {
4658     char_u	*user_copy = (user != NULL && need_copy)
4659 						    ? vim_strsave(user) : user;
4660 
4661     if (user_copy == NULL || *user_copy == NUL || ga_grow(&ga_users, 1) == FAIL)
4662     {
4663 	if (need_copy)
4664 	    vim_free(user);
4665 	return;
4666     }
4667     ((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user_copy;
4668 }
4669 
4670 /*
4671  * Find all user names for user completion.
4672  * Done only once and then cached.
4673  */
4674     static void
4675 init_users(void)
4676 {
4677     static int	lazy_init_done = FALSE;
4678 
4679     if (lazy_init_done)
4680 	return;
4681 
4682     lazy_init_done = TRUE;
4683     ga_init2(&ga_users, sizeof(char_u *), 20);
4684 
4685 # if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
4686     {
4687 	struct passwd*	pw;
4688 
4689 	setpwent();
4690 	while ((pw = getpwent()) != NULL)
4691 	    add_user((char_u *)pw->pw_name, TRUE);
4692 	endpwent();
4693     }
4694 # elif defined(MSWIN)
4695     {
4696 	DWORD		nusers = 0, ntotal = 0, i;
4697 	PUSER_INFO_0	uinfo;
4698 
4699 	if (NetUserEnum(NULL, 0, 0, (LPBYTE *) &uinfo, MAX_PREFERRED_LENGTH,
4700 				       &nusers, &ntotal, NULL) == NERR_Success)
4701 	{
4702 	    for (i = 0; i < nusers; i++)
4703 		add_user(utf16_to_enc(uinfo[i].usri0_name, NULL), FALSE);
4704 
4705 	    NetApiBufferFree(uinfo);
4706 	}
4707     }
4708 # endif
4709 # if defined(HAVE_GETPWNAM)
4710     {
4711 	char_u	*user_env = mch_getenv((char_u *)"USER");
4712 
4713 	// The $USER environment variable may be a valid remote user name (NIS,
4714 	// LDAP) not already listed by getpwent(), as getpwent() only lists
4715 	// local user names.  If $USER is not already listed, check whether it
4716 	// is a valid remote user name using getpwnam() and if it is, add it to
4717 	// the list of user names.
4718 
4719 	if (user_env != NULL && *user_env != NUL)
4720 	{
4721 	    int	i;
4722 
4723 	    for (i = 0; i < ga_users.ga_len; i++)
4724 	    {
4725 		char_u	*local_user = ((char_u **)ga_users.ga_data)[i];
4726 
4727 		if (STRCMP(local_user, user_env) == 0)
4728 		    break;
4729 	    }
4730 
4731 	    if (i == ga_users.ga_len)
4732 	    {
4733 		struct passwd	*pw = getpwnam((char *)user_env);
4734 
4735 		if (pw != NULL)
4736 		    add_user((char_u *)pw->pw_name, TRUE);
4737 	    }
4738 	}
4739     }
4740 # endif
4741 }
4742 
4743 /*
4744  * Function given to ExpandGeneric() to obtain an user names.
4745  */
4746     char_u*
4747 get_users(expand_T *xp UNUSED, int idx)
4748 {
4749     init_users();
4750     if (idx < ga_users.ga_len)
4751 	return ((char_u **)ga_users.ga_data)[idx];
4752     return NULL;
4753 }
4754 
4755 /*
4756  * Check whether name matches a user name. Return:
4757  * 0 if name does not match any user name.
4758  * 1 if name partially matches the beginning of a user name.
4759  * 2 is name fully matches a user name.
4760  */
4761     int
4762 match_user(char_u *name)
4763 {
4764     int i;
4765     int n = (int)STRLEN(name);
4766     int result = 0;
4767 
4768     init_users();
4769     for (i = 0; i < ga_users.ga_len; i++)
4770     {
4771 	if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
4772 	    return 2; /* full match */
4773 	if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
4774 	    result = 1; /* partial match */
4775     }
4776     return result;
4777 }
4778 #endif
4779 
4780 /*
4781  * Replace home directory by "~" in each space or comma separated file name in
4782  * 'src'.
4783  * If anything fails (except when out of space) dst equals src.
4784  */
4785     void
4786 home_replace(
4787     buf_T	*buf,	/* when not NULL, check for help files */
4788     char_u	*src,	/* input file name */
4789     char_u	*dst,	/* where to put the result */
4790     int		dstlen,	/* maximum length of the result */
4791     int		one)	/* if TRUE, only replace one file name, include
4792 			   spaces and commas in the file name. */
4793 {
4794     size_t	dirlen = 0, envlen = 0;
4795     size_t	len;
4796     char_u	*homedir_env, *homedir_env_orig;
4797     char_u	*p;
4798 
4799     if (src == NULL)
4800     {
4801 	*dst = NUL;
4802 	return;
4803     }
4804 
4805     /*
4806      * If the file is a help file, remove the path completely.
4807      */
4808     if (buf != NULL && buf->b_help)
4809     {
4810 	vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
4811 	return;
4812     }
4813 
4814     /*
4815      * We check both the value of the $HOME environment variable and the
4816      * "real" home directory.
4817      */
4818     if (homedir != NULL)
4819 	dirlen = STRLEN(homedir);
4820 
4821 #ifdef VMS
4822     homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4823 #else
4824     homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4825 #endif
4826 #ifdef MSWIN
4827     if (homedir_env == NULL)
4828 	homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
4829 #endif
4830     /* Empty is the same as not set. */
4831     if (homedir_env != NULL && *homedir_env == NUL)
4832 	homedir_env = NULL;
4833 
4834 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL)
4835     if (homedir_env != NULL && *homedir_env == '~')
4836     {
4837 	int	usedlen = 0;
4838 	int	flen;
4839 	char_u	*fbuf = NULL;
4840 
4841 	flen = (int)STRLEN(homedir_env);
4842 	(void)modify_fname((char_u *)":p", FALSE, &usedlen,
4843 						  &homedir_env, &fbuf, &flen);
4844 	flen = (int)STRLEN(homedir_env);
4845 	if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4846 	    /* Remove the trailing / that is added to a directory. */
4847 	    homedir_env[flen - 1] = NUL;
4848     }
4849 #endif
4850 
4851     if (homedir_env != NULL)
4852 	envlen = STRLEN(homedir_env);
4853 
4854     if (!one)
4855 	src = skipwhite(src);
4856     while (*src && dstlen > 0)
4857     {
4858 	/*
4859 	 * Here we are at the beginning of a file name.
4860 	 * First, check to see if the beginning of the file name matches
4861 	 * $HOME or the "real" home directory. Check that there is a '/'
4862 	 * after the match (so that if e.g. the file is "/home/pieter/bla",
4863 	 * and the home directory is "/home/piet", the file does not end up
4864 	 * as "~er/bla" (which would seem to indicate the file "bla" in user
4865 	 * er's home directory)).
4866 	 */
4867 	p = homedir;
4868 	len = dirlen;
4869 	for (;;)
4870 	{
4871 	    if (   len
4872 		&& fnamencmp(src, p, len) == 0
4873 		&& (vim_ispathsep(src[len])
4874 		    || (!one && (src[len] == ',' || src[len] == ' '))
4875 		    || src[len] == NUL))
4876 	    {
4877 		src += len;
4878 		if (--dstlen > 0)
4879 		    *dst++ = '~';
4880 
4881 		/*
4882 		 * If it's just the home directory, add  "/".
4883 		 */
4884 		if (!vim_ispathsep(src[0]) && --dstlen > 0)
4885 		    *dst++ = '/';
4886 		break;
4887 	    }
4888 	    if (p == homedir_env)
4889 		break;
4890 	    p = homedir_env;
4891 	    len = envlen;
4892 	}
4893 
4894 	/* if (!one) skip to separator: space or comma */
4895 	while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4896 	    *dst++ = *src++;
4897 	/* skip separator */
4898 	while ((*src == ' ' || *src == ',') && --dstlen > 0)
4899 	    *dst++ = *src++;
4900     }
4901     /* if (dstlen == 0) out of space, what to do??? */
4902 
4903     *dst = NUL;
4904 
4905     if (homedir_env != homedir_env_orig)
4906 	vim_free(homedir_env);
4907 }
4908 
4909 /*
4910  * Like home_replace, store the replaced string in allocated memory.
4911  * When something fails, NULL is returned.
4912  */
4913     char_u  *
4914 home_replace_save(
4915     buf_T	*buf,	/* when not NULL, check for help files */
4916     char_u	*src)	/* input file name */
4917 {
4918     char_u	*dst;
4919     unsigned	len;
4920 
4921     len = 3;			/* space for "~/" and trailing NUL */
4922     if (src != NULL)		/* just in case */
4923 	len += (unsigned)STRLEN(src);
4924     dst = alloc(len);
4925     if (dst != NULL)
4926 	home_replace(buf, src, dst, len, TRUE);
4927     return dst;
4928 }
4929 
4930 /*
4931  * Compare two file names and return:
4932  * FPC_SAME   if they both exist and are the same file.
4933  * FPC_SAMEX  if they both don't exist and have the same file name.
4934  * FPC_DIFF   if they both exist and are different files.
4935  * FPC_NOTX   if they both don't exist.
4936  * FPC_DIFFX  if one of them doesn't exist.
4937  * For the first name environment variables are expanded
4938  */
4939     int
4940 fullpathcmp(
4941     char_u *s1,
4942     char_u *s2,
4943     int	    checkname)		/* when both don't exist, check file names */
4944 {
4945 #ifdef UNIX
4946     char_u	    exp1[MAXPATHL];
4947     char_u	    full1[MAXPATHL];
4948     char_u	    full2[MAXPATHL];
4949     stat_T	    st1, st2;
4950     int		    r1, r2;
4951 
4952     expand_env(s1, exp1, MAXPATHL);
4953     r1 = mch_stat((char *)exp1, &st1);
4954     r2 = mch_stat((char *)s2, &st2);
4955     if (r1 != 0 && r2 != 0)
4956     {
4957 	/* if mch_stat() doesn't work, may compare the names */
4958 	if (checkname)
4959 	{
4960 	    if (fnamecmp(exp1, s2) == 0)
4961 		return FPC_SAMEX;
4962 	    r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4963 	    r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4964 	    if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4965 		return FPC_SAMEX;
4966 	}
4967 	return FPC_NOTX;
4968     }
4969     if (r1 != 0 || r2 != 0)
4970 	return FPC_DIFFX;
4971     if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4972 	return FPC_SAME;
4973     return FPC_DIFF;
4974 #else
4975     char_u  *exp1;		/* expanded s1 */
4976     char_u  *full1;		/* full path of s1 */
4977     char_u  *full2;		/* full path of s2 */
4978     int	    retval = FPC_DIFF;
4979     int	    r1, r2;
4980 
4981     /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4982     if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4983     {
4984 	full1 = exp1 + MAXPATHL;
4985 	full2 = full1 + MAXPATHL;
4986 
4987 	expand_env(s1, exp1, MAXPATHL);
4988 	r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4989 	r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4990 
4991 	/* If vim_FullName() fails, the file probably doesn't exist. */
4992 	if (r1 != OK && r2 != OK)
4993 	{
4994 	    if (checkname && fnamecmp(exp1, s2) == 0)
4995 		retval = FPC_SAMEX;
4996 	    else
4997 		retval = FPC_NOTX;
4998 	}
4999 	else if (r1 != OK || r2 != OK)
5000 	    retval = FPC_DIFFX;
5001 	else if (fnamecmp(full1, full2))
5002 	    retval = FPC_DIFF;
5003 	else
5004 	    retval = FPC_SAME;
5005 	vim_free(exp1);
5006     }
5007     return retval;
5008 #endif
5009 }
5010 
5011 /*
5012  * Get the tail of a path: the file name.
5013  * When the path ends in a path separator the tail is the NUL after it.
5014  * Fail safe: never returns NULL.
5015  */
5016     char_u *
5017 gettail(char_u *fname)
5018 {
5019     char_u  *p1, *p2;
5020 
5021     if (fname == NULL)
5022 	return (char_u *)"";
5023     for (p1 = p2 = get_past_head(fname); *p2; )	/* find last part of path */
5024     {
5025 	if (vim_ispathsep_nocolon(*p2))
5026 	    p1 = p2 + 1;
5027 	MB_PTR_ADV(p2);
5028     }
5029     return p1;
5030 }
5031 
5032 /*
5033  * Get pointer to tail of "fname", including path separators.  Putting a NUL
5034  * here leaves the directory name.  Takes care of "c:/" and "//".
5035  * Always returns a valid pointer.
5036  */
5037     char_u *
5038 gettail_sep(char_u *fname)
5039 {
5040     char_u	*p;
5041     char_u	*t;
5042 
5043     p = get_past_head(fname);	/* don't remove the '/' from "c:/file" */
5044     t = gettail(fname);
5045     while (t > p && after_pathsep(fname, t))
5046 	--t;
5047 #ifdef VMS
5048     /* path separator is part of the path */
5049     ++t;
5050 #endif
5051     return t;
5052 }
5053 
5054 /*
5055  * get the next path component (just after the next path separator).
5056  */
5057     char_u *
5058 getnextcomp(char_u *fname)
5059 {
5060     while (*fname && !vim_ispathsep(*fname))
5061 	MB_PTR_ADV(fname);
5062     if (*fname)
5063 	++fname;
5064     return fname;
5065 }
5066 
5067 /*
5068  * Get a pointer to one character past the head of a path name.
5069  * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
5070  * If there is no head, path is returned.
5071  */
5072     char_u *
5073 get_past_head(char_u *path)
5074 {
5075     char_u  *retval;
5076 
5077 #if defined(MSWIN)
5078     /* may skip "c:" */
5079     if (isalpha(path[0]) && path[1] == ':')
5080 	retval = path + 2;
5081     else
5082 	retval = path;
5083 #else
5084 # if defined(AMIGA)
5085     /* may skip "label:" */
5086     retval = vim_strchr(path, ':');
5087     if (retval == NULL)
5088 	retval = path;
5089 # else	/* Unix */
5090     retval = path;
5091 # endif
5092 #endif
5093 
5094     while (vim_ispathsep(*retval))
5095 	++retval;
5096 
5097     return retval;
5098 }
5099 
5100 /*
5101  * Return TRUE if 'c' is a path separator.
5102  * Note that for MS-Windows this includes the colon.
5103  */
5104     int
5105 vim_ispathsep(int c)
5106 {
5107 #ifdef UNIX
5108     return (c == '/');	    /* UNIX has ':' inside file names */
5109 #else
5110 # ifdef BACKSLASH_IN_FILENAME
5111     return (c == ':' || c == '/' || c == '\\');
5112 # else
5113 #  ifdef VMS
5114     /* server"user passwd"::device:[full.path.name]fname.extension;version" */
5115     return (c == ':' || c == '[' || c == ']' || c == '/'
5116 	    || c == '<' || c == '>' || c == '"' );
5117 #  else
5118     return (c == ':' || c == '/');
5119 #  endif /* VMS */
5120 # endif
5121 #endif
5122 }
5123 
5124 /*
5125  * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
5126  */
5127     int
5128 vim_ispathsep_nocolon(int c)
5129 {
5130     return vim_ispathsep(c)
5131 #ifdef BACKSLASH_IN_FILENAME
5132 	&& c != ':'
5133 #endif
5134 	;
5135 }
5136 
5137 /*
5138  * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
5139  * It's done in-place.
5140  */
5141     void
5142 shorten_dir(char_u *str)
5143 {
5144     char_u	*tail, *s, *d;
5145     int		skip = FALSE;
5146 
5147     tail = gettail(str);
5148     d = str;
5149     for (s = str; ; ++s)
5150     {
5151 	if (s >= tail)		    /* copy the whole tail */
5152 	{
5153 	    *d++ = *s;
5154 	    if (*s == NUL)
5155 		break;
5156 	}
5157 	else if (vim_ispathsep(*s))	    /* copy '/' and next char */
5158 	{
5159 	    *d++ = *s;
5160 	    skip = FALSE;
5161 	}
5162 	else if (!skip)
5163 	{
5164 	    *d++ = *s;		    /* copy next char */
5165 	    if (*s != '~' && *s != '.') /* and leading "~" and "." */
5166 		skip = TRUE;
5167 	    if (has_mbyte)
5168 	    {
5169 		int l = mb_ptr2len(s);
5170 
5171 		while (--l > 0)
5172 		    *d++ = *++s;
5173 	    }
5174 	}
5175     }
5176 }
5177 
5178 /*
5179  * Return TRUE if the directory of "fname" exists, FALSE otherwise.
5180  * Also returns TRUE if there is no directory name.
5181  * "fname" must be writable!.
5182  */
5183     int
5184 dir_of_file_exists(char_u *fname)
5185 {
5186     char_u	*p;
5187     int		c;
5188     int		retval;
5189 
5190     p = gettail_sep(fname);
5191     if (p == fname)
5192 	return TRUE;
5193     c = *p;
5194     *p = NUL;
5195     retval = mch_isdir(fname);
5196     *p = c;
5197     return retval;
5198 }
5199 
5200 /*
5201  * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
5202  * and deal with 'fileignorecase'.
5203  */
5204     int
5205 vim_fnamecmp(char_u *x, char_u *y)
5206 {
5207 #ifdef BACKSLASH_IN_FILENAME
5208     return vim_fnamencmp(x, y, MAXPATHL);
5209 #else
5210     if (p_fic)
5211 	return MB_STRICMP(x, y);
5212     return STRCMP(x, y);
5213 #endif
5214 }
5215 
5216     int
5217 vim_fnamencmp(char_u *x, char_u *y, size_t len)
5218 {
5219 #ifdef BACKSLASH_IN_FILENAME
5220     char_u	*px = x;
5221     char_u	*py = y;
5222     int		cx = NUL;
5223     int		cy = NUL;
5224 
5225     while (len > 0)
5226     {
5227 	cx = PTR2CHAR(px);
5228 	cy = PTR2CHAR(py);
5229 	if (cx == NUL || cy == NUL
5230 	    || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
5231 		&& !(cx == '/' && cy == '\\')
5232 		&& !(cx == '\\' && cy == '/')))
5233 	    break;
5234 	len -= MB_PTR2LEN(px);
5235 	px += MB_PTR2LEN(px);
5236 	py += MB_PTR2LEN(py);
5237     }
5238     if (len == 0)
5239 	return 0;
5240     return (cx - cy);
5241 #else
5242     if (p_fic)
5243 	return MB_STRNICMP(x, y, len);
5244     return STRNCMP(x, y, len);
5245 #endif
5246 }
5247 
5248 /*
5249  * Concatenate file names fname1 and fname2 into allocated memory.
5250  * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
5251  */
5252     char_u  *
5253 concat_fnames(char_u *fname1, char_u *fname2, int sep)
5254 {
5255     char_u  *dest;
5256 
5257     dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
5258     if (dest != NULL)
5259     {
5260 	STRCPY(dest, fname1);
5261 	if (sep)
5262 	    add_pathsep(dest);
5263 	STRCAT(dest, fname2);
5264     }
5265     return dest;
5266 }
5267 
5268 /*
5269  * Concatenate two strings and return the result in allocated memory.
5270  * Returns NULL when out of memory.
5271  */
5272     char_u  *
5273 concat_str(char_u *str1, char_u *str2)
5274 {
5275     char_u  *dest;
5276     size_t  l = STRLEN(str1);
5277 
5278     dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5279     if (dest != NULL)
5280     {
5281 	STRCPY(dest, str1);
5282 	STRCPY(dest + l, str2);
5283     }
5284     return dest;
5285 }
5286 
5287 /*
5288  * Add a path separator to a file name, unless it already ends in a path
5289  * separator.
5290  */
5291     void
5292 add_pathsep(char_u *p)
5293 {
5294     if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
5295 	STRCAT(p, PATHSEPSTR);
5296 }
5297 
5298 /*
5299  * FullName_save - Make an allocated copy of a full file name.
5300  * Returns NULL when out of memory.
5301  */
5302     char_u  *
5303 FullName_save(
5304     char_u	*fname,
5305     int		force)		/* force expansion, even when it already looks
5306 				 * like a full path name */
5307 {
5308     char_u	*buf;
5309     char_u	*new_fname = NULL;
5310 
5311     if (fname == NULL)
5312 	return NULL;
5313 
5314     buf = alloc((unsigned)MAXPATHL);
5315     if (buf != NULL)
5316     {
5317 	if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5318 	    new_fname = vim_strsave(buf);
5319 	else
5320 	    new_fname = vim_strsave(fname);
5321 	vim_free(buf);
5322     }
5323     return new_fname;
5324 }
5325 
5326     void
5327 prepare_to_exit(void)
5328 {
5329 #if defined(SIGHUP) && defined(SIG_IGN)
5330     /* Ignore SIGHUP, because a dropped connection causes a read error, which
5331      * makes Vim exit and then handling SIGHUP causes various reentrance
5332      * problems. */
5333     signal(SIGHUP, SIG_IGN);
5334 #endif
5335 
5336 #ifdef FEAT_GUI
5337     if (gui.in_use)
5338     {
5339 	gui.dying = TRUE;
5340 	out_trash();	/* trash any pending output */
5341     }
5342     else
5343 #endif
5344     {
5345 	windgoto((int)Rows - 1, 0);
5346 
5347 	/*
5348 	 * Switch terminal mode back now, so messages end up on the "normal"
5349 	 * screen (if there are two screens).
5350 	 */
5351 	settmode(TMODE_COOK);
5352 	stoptermcap();
5353 	out_flush();
5354     }
5355 }
5356 
5357 /*
5358  * Preserve files and exit.
5359  * When called IObuff must contain a message.
5360  * NOTE: This may be called from deathtrap() in a signal handler, avoid unsafe
5361  * functions, such as allocating memory.
5362  */
5363     void
5364 preserve_exit(void)
5365 {
5366     buf_T	*buf;
5367 
5368     prepare_to_exit();
5369 
5370     /* Setting this will prevent free() calls.  That avoids calling free()
5371      * recursively when free() was invoked with a bad pointer. */
5372     really_exiting = TRUE;
5373 
5374     out_str(IObuff);
5375     screen_start();		    /* don't know where cursor is now */
5376     out_flush();
5377 
5378     ml_close_notmod();		    /* close all not-modified buffers */
5379 
5380     FOR_ALL_BUFFERS(buf)
5381     {
5382 	if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
5383 	{
5384 	    OUT_STR("Vim: preserving files...\n");
5385 	    screen_start();	    /* don't know where cursor is now */
5386 	    out_flush();
5387 	    ml_sync_all(FALSE, FALSE);	/* preserve all swap files */
5388 	    break;
5389 	}
5390     }
5391 
5392     ml_close_all(FALSE);	    /* close all memfiles, without deleting */
5393 
5394     OUT_STR("Vim: Finished.\n");
5395 
5396     getout(1);
5397 }
5398 
5399 /*
5400  * return TRUE if "fname" exists.
5401  */
5402     int
5403 vim_fexists(char_u *fname)
5404 {
5405     stat_T st;
5406 
5407     if (mch_stat((char *)fname, &st))
5408 	return FALSE;
5409     return TRUE;
5410 }
5411 
5412 /*
5413  * Check for CTRL-C pressed, but only once in a while.
5414  * Should be used instead of ui_breakcheck() for functions that check for
5415  * each line in the file.  Calling ui_breakcheck() each time takes too much
5416  * time, because it can be a system call.
5417  */
5418 
5419 #ifndef BREAKCHECK_SKIP
5420 # ifdef FEAT_GUI		    /* assume the GUI only runs on fast computers */
5421 #  define BREAKCHECK_SKIP 200
5422 # else
5423 #  define BREAKCHECK_SKIP 32
5424 # endif
5425 #endif
5426 
5427 static int	breakcheck_count = 0;
5428 
5429     void
5430 line_breakcheck(void)
5431 {
5432     if (++breakcheck_count >= BREAKCHECK_SKIP)
5433     {
5434 	breakcheck_count = 0;
5435 	ui_breakcheck();
5436     }
5437 }
5438 
5439 /*
5440  * Like line_breakcheck() but check 10 times less often.
5441  */
5442     void
5443 fast_breakcheck(void)
5444 {
5445     if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
5446     {
5447 	breakcheck_count = 0;
5448 	ui_breakcheck();
5449     }
5450 }
5451 
5452 /*
5453  * Invoke expand_wildcards() for one pattern.
5454  * Expand items like "%:h" before the expansion.
5455  * Returns OK or FAIL.
5456  */
5457     int
5458 expand_wildcards_eval(
5459     char_u	 **pat,		/* pointer to input pattern */
5460     int		  *num_file,	/* resulting number of files */
5461     char_u	***file,	/* array of resulting files */
5462     int		   flags)	/* EW_DIR, etc. */
5463 {
5464     int		ret = FAIL;
5465     char_u	*eval_pat = NULL;
5466     char_u	*exp_pat = *pat;
5467     char      *ignored_msg;
5468     int		usedlen;
5469 
5470     if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
5471     {
5472 	++emsg_off;
5473 	eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
5474 						    NULL, &ignored_msg, NULL);
5475 	--emsg_off;
5476 	if (eval_pat != NULL)
5477 	    exp_pat = concat_str(eval_pat, exp_pat + usedlen);
5478     }
5479 
5480     if (exp_pat != NULL)
5481 	ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
5482 
5483     if (eval_pat != NULL)
5484     {
5485 	vim_free(exp_pat);
5486 	vim_free(eval_pat);
5487     }
5488 
5489     return ret;
5490 }
5491 
5492 /*
5493  * Expand wildcards.  Calls gen_expand_wildcards() and removes files matching
5494  * 'wildignore'.
5495  * Returns OK or FAIL.  When FAIL then "num_files" won't be set.
5496  */
5497     int
5498 expand_wildcards(
5499     int		   num_pat,	/* number of input patterns */
5500     char_u	 **pat,		/* array of input patterns */
5501     int		  *num_files,	/* resulting number of files */
5502     char_u	***files,	/* array of resulting files */
5503     int		   flags)	/* EW_DIR, etc. */
5504 {
5505     int		retval;
5506     int		i, j;
5507     char_u	*p;
5508     int		non_suf_match;	/* number without matching suffix */
5509 
5510     retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
5511 
5512     /* When keeping all matches, return here */
5513     if ((flags & EW_KEEPALL) || retval == FAIL)
5514 	return retval;
5515 
5516 #ifdef FEAT_WILDIGN
5517     /*
5518      * Remove names that match 'wildignore'.
5519      */
5520     if (*p_wig)
5521     {
5522 	char_u	*ffname;
5523 
5524 	/* check all files in (*files)[] */
5525 	for (i = 0; i < *num_files; ++i)
5526 	{
5527 	    ffname = FullName_save((*files)[i], FALSE);
5528 	    if (ffname == NULL)		/* out of memory */
5529 		break;
5530 # ifdef VMS
5531 	    vms_remove_version(ffname);
5532 # endif
5533 	    if (match_file_list(p_wig, (*files)[i], ffname))
5534 	    {
5535 		/* remove this matching file from the list */
5536 		vim_free((*files)[i]);
5537 		for (j = i; j + 1 < *num_files; ++j)
5538 		    (*files)[j] = (*files)[j + 1];
5539 		--*num_files;
5540 		--i;
5541 	    }
5542 	    vim_free(ffname);
5543 	}
5544 
5545 	/* If the number of matches is now zero, we fail. */
5546 	if (*num_files == 0)
5547 	{
5548 	    VIM_CLEAR(*files);
5549 	    return FAIL;
5550 	}
5551     }
5552 #endif
5553 
5554     /*
5555      * Move the names where 'suffixes' match to the end.
5556      */
5557     if (*num_files > 1)
5558     {
5559 	non_suf_match = 0;
5560 	for (i = 0; i < *num_files; ++i)
5561 	{
5562 	    if (!match_suffix((*files)[i]))
5563 	    {
5564 		/*
5565 		 * Move the name without matching suffix to the front
5566 		 * of the list.
5567 		 */
5568 		p = (*files)[i];
5569 		for (j = i; j > non_suf_match; --j)
5570 		    (*files)[j] = (*files)[j - 1];
5571 		(*files)[non_suf_match++] = p;
5572 	    }
5573 	}
5574     }
5575 
5576     return retval;
5577 }
5578 
5579 /*
5580  * Return TRUE if "fname" matches with an entry in 'suffixes'.
5581  */
5582     int
5583 match_suffix(char_u *fname)
5584 {
5585     int		fnamelen, setsuflen;
5586     char_u	*setsuf;
5587 #define MAXSUFLEN 30	    /* maximum length of a file suffix */
5588     char_u	suf_buf[MAXSUFLEN];
5589 
5590     fnamelen = (int)STRLEN(fname);
5591     setsuflen = 0;
5592     for (setsuf = p_su; *setsuf; )
5593     {
5594 	setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
5595 	if (setsuflen == 0)
5596 	{
5597 	    char_u *tail = gettail(fname);
5598 
5599 	    /* empty entry: match name without a '.' */
5600 	    if (vim_strchr(tail, '.') == NULL)
5601 	    {
5602 		setsuflen = 1;
5603 		break;
5604 	    }
5605 	}
5606 	else
5607 	{
5608 	    if (fnamelen >= setsuflen
5609 		    && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
5610 						  (size_t)setsuflen) == 0)
5611 		break;
5612 	    setsuflen = 0;
5613 	}
5614     }
5615     return (setsuflen != 0);
5616 }
5617 
5618 #if !defined(NO_EXPANDPATH) || defined(PROTO)
5619 
5620 # ifdef VIM_BACKTICK
5621 static int vim_backtick(char_u *p);
5622 static int expand_backtick(garray_T *gap, char_u *pat, int flags);
5623 # endif
5624 
5625 # if defined(MSWIN)
5626 /*
5627  * File name expansion code for MS-DOS, Win16 and Win32.  It's here because
5628  * it's shared between these systems.
5629  */
5630 # if defined(PROTO)
5631 #  define _cdecl
5632 # else
5633 #  ifdef __BORLANDC__
5634 #   define _cdecl _RTLENTRYF
5635 #  endif
5636 # endif
5637 
5638 /*
5639  * comparison function for qsort in dos_expandpath()
5640  */
5641     static int _cdecl
5642 pstrcmp(const void *a, const void *b)
5643 {
5644     return (pathcmp(*(char **)a, *(char **)b, -1));
5645 }
5646 
5647 /*
5648  * Recursively expand one path component into all matching files and/or
5649  * directories.  Adds matches to "gap".  Handles "*", "?", "[a-z]", "**", etc.
5650  * Return the number of matches found.
5651  * "path" has backslashes before chars that are not to be expanded, starting
5652  * at "path[wildoff]".
5653  * Return the number of matches found.
5654  * NOTE: much of this is identical to unix_expandpath(), keep in sync!
5655  */
5656     static int
5657 dos_expandpath(
5658     garray_T	*gap,
5659     char_u	*path,
5660     int		wildoff,
5661     int		flags,		/* EW_* flags */
5662     int		didstar)	/* expanded "**" once already */
5663 {
5664     char_u	*buf;
5665     char_u	*path_end;
5666     char_u	*p, *s, *e;
5667     int		start_len = gap->ga_len;
5668     char_u	*pat;
5669     regmatch_T	regmatch;
5670     int		starts_with_dot;
5671     int		matches;
5672     int		len;
5673     int		starstar = FALSE;
5674     static int	stardepth = 0;	    /* depth for "**" expansion */
5675     WIN32_FIND_DATA	fb;
5676     HANDLE		hFind = (HANDLE)0;
5677     WIN32_FIND_DATAW    wfb;
5678     WCHAR		*wn = NULL;	/* UCS-2 name, NULL when not used. */
5679     char_u		*matchname;
5680     int			ok;
5681 
5682     /* Expanding "**" may take a long time, check for CTRL-C. */
5683     if (stardepth > 0)
5684     {
5685 	ui_breakcheck();
5686 	if (got_int)
5687 	    return 0;
5688     }
5689 
5690     // Make room for file name.  When doing encoding conversion the actual
5691     // length may be quite a bit longer, thus use the maximum possible length.
5692     buf = alloc((int)MAXPATHL);
5693     if (buf == NULL)
5694 	return 0;
5695 
5696     /*
5697      * Find the first part in the path name that contains a wildcard or a ~1.
5698      * Copy it into buf, including the preceding characters.
5699      */
5700     p = buf;
5701     s = buf;
5702     e = NULL;
5703     path_end = path;
5704     while (*path_end != NUL)
5705     {
5706 	/* May ignore a wildcard that has a backslash before it; it will
5707 	 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
5708 	if (path_end >= path + wildoff && rem_backslash(path_end))
5709 	    *p++ = *path_end++;
5710 	else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
5711 	{
5712 	    if (e != NULL)
5713 		break;
5714 	    s = p + 1;
5715 	}
5716 	else if (path_end >= path + wildoff
5717 			 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
5718 	    e = p;
5719 	if (has_mbyte)
5720 	{
5721 	    len = (*mb_ptr2len)(path_end);
5722 	    STRNCPY(p, path_end, len);
5723 	    p += len;
5724 	    path_end += len;
5725 	}
5726 	else
5727 	    *p++ = *path_end++;
5728     }
5729     e = p;
5730     *e = NUL;
5731 
5732     /* now we have one wildcard component between s and e */
5733     /* Remove backslashes between "wildoff" and the start of the wildcard
5734      * component. */
5735     for (p = buf + wildoff; p < s; ++p)
5736 	if (rem_backslash(p))
5737 	{
5738 	    STRMOVE(p, p + 1);
5739 	    --e;
5740 	    --s;
5741 	}
5742 
5743     /* Check for "**" between "s" and "e". */
5744     for (p = s; p < e; ++p)
5745 	if (p[0] == '*' && p[1] == '*')
5746 	    starstar = TRUE;
5747 
5748     starts_with_dot = *s == '.';
5749     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
5750     if (pat == NULL)
5751     {
5752 	vim_free(buf);
5753 	return 0;
5754     }
5755 
5756     /* compile the regexp into a program */
5757     if (flags & (EW_NOERROR | EW_NOTWILD))
5758 	++emsg_silent;
5759     regmatch.rm_ic = TRUE;		/* Always ignore case */
5760     regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
5761     if (flags & (EW_NOERROR | EW_NOTWILD))
5762 	--emsg_silent;
5763     vim_free(pat);
5764 
5765     if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
5766     {
5767 	vim_free(buf);
5768 	return 0;
5769     }
5770 
5771     /* remember the pattern or file name being looked for */
5772     matchname = vim_strsave(s);
5773 
5774     /* If "**" is by itself, this is the first time we encounter it and more
5775      * is following then find matches without any directory. */
5776     if (!didstar && stardepth < 100 && starstar && e - s == 2
5777 							  && *path_end == '/')
5778     {
5779 	STRCPY(s, path_end + 1);
5780 	++stardepth;
5781 	(void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
5782 	--stardepth;
5783     }
5784 
5785     /* Scan all files in the directory with "dir/ *.*" */
5786     STRCPY(s, "*.*");
5787     if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5788     {
5789 	/* The active codepage differs from 'encoding'.  Attempt using the
5790 	 * wide function.  If it fails because it is not implemented fall back
5791 	 * to the non-wide version (for Windows 98) */
5792 	wn = enc_to_utf16(buf, NULL);
5793 	if (wn != NULL)
5794 	{
5795 	    hFind = FindFirstFileW(wn, &wfb);
5796 	    if (hFind == INVALID_HANDLE_VALUE
5797 			      && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5798 		VIM_CLEAR(wn);
5799 	}
5800     }
5801 
5802     if (wn == NULL)
5803 	hFind = FindFirstFile((LPCSTR)buf, &fb);
5804     ok = (hFind != INVALID_HANDLE_VALUE);
5805 
5806     while (ok)
5807     {
5808 	if (wn != NULL)
5809 	    p = utf16_to_enc(wfb.cFileName, NULL);   /* p is allocated here */
5810 	else
5811 	    p = (char_u *)fb.cFileName;
5812 	/* Ignore entries starting with a dot, unless when asked for.  Accept
5813 	 * all entries found with "matchname". */
5814 	if ((p[0] != '.' || starts_with_dot
5815 			 || ((flags & EW_DODOT)
5816 			     && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
5817 		&& (matchname == NULL
5818 		  || (regmatch.regprog != NULL
5819 				     && vim_regexec(&regmatch, p, (colnr_T)0))
5820 		  || ((flags & EW_NOTWILD)
5821 		     && fnamencmp(path + (s - buf), p, e - s) == 0)))
5822 	{
5823 	    STRCPY(s, p);
5824 	    len = (int)STRLEN(buf);
5825 
5826 	    if (starstar && stardepth < 100)
5827 	    {
5828 		/* For "**" in the pattern first go deeper in the tree to
5829 		 * find matches. */
5830 		STRCPY(buf + len, "/**");
5831 		STRCPY(buf + len + 3, path_end);
5832 		++stardepth;
5833 		(void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
5834 		--stardepth;
5835 	    }
5836 
5837 	    STRCPY(buf + len, path_end);
5838 	    if (mch_has_exp_wildcard(path_end))
5839 	    {
5840 		/* need to expand another component of the path */
5841 		/* remove backslashes for the remaining components only */
5842 		(void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
5843 	    }
5844 	    else
5845 	    {
5846 		/* no more wildcards, check if there is a match */
5847 		/* remove backslashes for the remaining components only */
5848 		if (*path_end != 0)
5849 		    backslash_halve(buf + len + 1);
5850 		if (mch_getperm(buf) >= 0)	/* add existing file */
5851 		    addfile(gap, buf, flags);
5852 	    }
5853 	}
5854 
5855 	if (wn != NULL)
5856 	{
5857 	    vim_free(p);
5858 	    ok = FindNextFileW(hFind, &wfb);
5859 	}
5860 	else
5861 	    ok = FindNextFile(hFind, &fb);
5862 
5863 	/* If no more matches and no match was used, try expanding the name
5864 	 * itself.  Finds the long name of a short filename. */
5865 	if (!ok && matchname != NULL && gap->ga_len == start_len)
5866 	{
5867 	    STRCPY(s, matchname);
5868 	    FindClose(hFind);
5869 	    if (wn != NULL)
5870 	    {
5871 		vim_free(wn);
5872 		wn = enc_to_utf16(buf, NULL);
5873 		if (wn != NULL)
5874 		    hFind = FindFirstFileW(wn, &wfb);
5875 	    }
5876 	    if (wn == NULL)
5877 		hFind = FindFirstFile((LPCSTR)buf, &fb);
5878 	    ok = (hFind != INVALID_HANDLE_VALUE);
5879 	    VIM_CLEAR(matchname);
5880 	}
5881     }
5882 
5883     FindClose(hFind);
5884     vim_free(wn);
5885     vim_free(buf);
5886     vim_regfree(regmatch.regprog);
5887     vim_free(matchname);
5888 
5889     matches = gap->ga_len - start_len;
5890     if (matches > 0)
5891 	qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
5892 						   sizeof(char_u *), pstrcmp);
5893     return matches;
5894 }
5895 
5896     int
5897 mch_expandpath(
5898     garray_T	*gap,
5899     char_u	*path,
5900     int		flags)		/* EW_* flags */
5901 {
5902     return dos_expandpath(gap, path, 0, flags, FALSE);
5903 }
5904 # endif // MSWIN
5905 
5906 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
5907 	|| defined(PROTO)
5908 /*
5909  * Unix style wildcard expansion code.
5910  * It's here because it's used both for Unix and Mac.
5911  */
5912     static int
5913 pstrcmp(const void *a, const void *b)
5914 {
5915     return (pathcmp(*(char **)a, *(char **)b, -1));
5916 }
5917 
5918 /*
5919  * Recursively expand one path component into all matching files and/or
5920  * directories.  Adds matches to "gap".  Handles "*", "?", "[a-z]", "**", etc.
5921  * "path" has backslashes before chars that are not to be expanded, starting
5922  * at "path + wildoff".
5923  * Return the number of matches found.
5924  * NOTE: much of this is identical to dos_expandpath(), keep in sync!
5925  */
5926     int
5927 unix_expandpath(
5928     garray_T	*gap,
5929     char_u	*path,
5930     int		wildoff,
5931     int		flags,		/* EW_* flags */
5932     int		didstar)	/* expanded "**" once already */
5933 {
5934     char_u	*buf;
5935     char_u	*path_end;
5936     char_u	*p, *s, *e;
5937     int		start_len = gap->ga_len;
5938     char_u	*pat;
5939     regmatch_T	regmatch;
5940     int		starts_with_dot;
5941     int		matches;
5942     int		len;
5943     int		starstar = FALSE;
5944     static int	stardepth = 0;	    /* depth for "**" expansion */
5945 
5946     DIR		*dirp;
5947     struct dirent *dp;
5948 
5949     /* Expanding "**" may take a long time, check for CTRL-C. */
5950     if (stardepth > 0)
5951     {
5952 	ui_breakcheck();
5953 	if (got_int)
5954 	    return 0;
5955     }
5956 
5957     /* make room for file name */
5958     buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
5959     if (buf == NULL)
5960 	return 0;
5961 
5962     /*
5963      * Find the first part in the path name that contains a wildcard.
5964      * When EW_ICASE is set every letter is considered to be a wildcard.
5965      * Copy it into "buf", including the preceding characters.
5966      */
5967     p = buf;
5968     s = buf;
5969     e = NULL;
5970     path_end = path;
5971     while (*path_end != NUL)
5972     {
5973 	/* May ignore a wildcard that has a backslash before it; it will
5974 	 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
5975 	if (path_end >= path + wildoff && rem_backslash(path_end))
5976 	    *p++ = *path_end++;
5977 	else if (*path_end == '/')
5978 	{
5979 	    if (e != NULL)
5980 		break;
5981 	    s = p + 1;
5982 	}
5983 	else if (path_end >= path + wildoff
5984 			 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
5985 			     || (!p_fic && (flags & EW_ICASE)
5986 					     && isalpha(PTR2CHAR(path_end)))))
5987 	    e = p;
5988 	if (has_mbyte)
5989 	{
5990 	    len = (*mb_ptr2len)(path_end);
5991 	    STRNCPY(p, path_end, len);
5992 	    p += len;
5993 	    path_end += len;
5994 	}
5995 	else
5996 	    *p++ = *path_end++;
5997     }
5998     e = p;
5999     *e = NUL;
6000 
6001     /* Now we have one wildcard component between "s" and "e". */
6002     /* Remove backslashes between "wildoff" and the start of the wildcard
6003      * component. */
6004     for (p = buf + wildoff; p < s; ++p)
6005 	if (rem_backslash(p))
6006 	{
6007 	    STRMOVE(p, p + 1);
6008 	    --e;
6009 	    --s;
6010 	}
6011 
6012     /* Check for "**" between "s" and "e". */
6013     for (p = s; p < e; ++p)
6014 	if (p[0] == '*' && p[1] == '*')
6015 	    starstar = TRUE;
6016 
6017     /* convert the file pattern to a regexp pattern */
6018     starts_with_dot = *s == '.';
6019     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
6020     if (pat == NULL)
6021     {
6022 	vim_free(buf);
6023 	return 0;
6024     }
6025 
6026     /* compile the regexp into a program */
6027     if (flags & EW_ICASE)
6028 	regmatch.rm_ic = TRUE;		/* 'wildignorecase' set */
6029     else
6030 	regmatch.rm_ic = p_fic;	/* ignore case when 'fileignorecase' is set */
6031     if (flags & (EW_NOERROR | EW_NOTWILD))
6032 	++emsg_silent;
6033     regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
6034     if (flags & (EW_NOERROR | EW_NOTWILD))
6035 	--emsg_silent;
6036     vim_free(pat);
6037 
6038     if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
6039     {
6040 	vim_free(buf);
6041 	return 0;
6042     }
6043 
6044     /* If "**" is by itself, this is the first time we encounter it and more
6045      * is following then find matches without any directory. */
6046     if (!didstar && stardepth < 100 && starstar && e - s == 2
6047 							  && *path_end == '/')
6048     {
6049 	STRCPY(s, path_end + 1);
6050 	++stardepth;
6051 	(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
6052 	--stardepth;
6053     }
6054 
6055     /* open the directory for scanning */
6056     *s = NUL;
6057     dirp = opendir(*buf == NUL ? "." : (char *)buf);
6058 
6059     /* Find all matching entries */
6060     if (dirp != NULL)
6061     {
6062 	for (;;)
6063 	{
6064 	    dp = readdir(dirp);
6065 	    if (dp == NULL)
6066 		break;
6067 	    if ((dp->d_name[0] != '.' || starts_with_dot
6068 			|| ((flags & EW_DODOT)
6069 			    && dp->d_name[1] != NUL
6070 			    && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
6071 		 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
6072 					     (char_u *)dp->d_name, (colnr_T)0))
6073 		   || ((flags & EW_NOTWILD)
6074 		     && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
6075 	    {
6076 		STRCPY(s, dp->d_name);
6077 		len = STRLEN(buf);
6078 
6079 		if (starstar && stardepth < 100)
6080 		{
6081 		    /* For "**" in the pattern first go deeper in the tree to
6082 		     * find matches. */
6083 		    STRCPY(buf + len, "/**");
6084 		    STRCPY(buf + len + 3, path_end);
6085 		    ++stardepth;
6086 		    (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
6087 		    --stardepth;
6088 		}
6089 
6090 		STRCPY(buf + len, path_end);
6091 		if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
6092 		{
6093 		    /* need to expand another component of the path */
6094 		    /* remove backslashes for the remaining components only */
6095 		    (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
6096 		}
6097 		else
6098 		{
6099 		    stat_T  sb;
6100 
6101 		    /* no more wildcards, check if there is a match */
6102 		    /* remove backslashes for the remaining components only */
6103 		    if (*path_end != NUL)
6104 			backslash_halve(buf + len + 1);
6105 		    /* add existing file or symbolic link */
6106 		    if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
6107 						      : mch_getperm(buf) >= 0)
6108 		    {
6109 #ifdef MACOS_CONVERT
6110 			size_t precomp_len = STRLEN(buf)+1;
6111 			char_u *precomp_buf =
6112 			    mac_precompose_path(buf, precomp_len, &precomp_len);
6113 
6114 			if (precomp_buf)
6115 			{
6116 			    mch_memmove(buf, precomp_buf, precomp_len);
6117 			    vim_free(precomp_buf);
6118 			}
6119 #endif
6120 			addfile(gap, buf, flags);
6121 		    }
6122 		}
6123 	    }
6124 	}
6125 
6126 	closedir(dirp);
6127     }
6128 
6129     vim_free(buf);
6130     vim_regfree(regmatch.regprog);
6131 
6132     matches = gap->ga_len - start_len;
6133     if (matches > 0)
6134 	qsort(((char_u **)gap->ga_data) + start_len, matches,
6135 						   sizeof(char_u *), pstrcmp);
6136     return matches;
6137 }
6138 #endif
6139 
6140 #if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
6141 /*
6142  * Sort "gap" and remove duplicate entries.  "gap" is expected to contain a
6143  * list of file names in allocated memory.
6144  */
6145     void
6146 remove_duplicates(garray_T *gap)
6147 {
6148     int	    i;
6149     int	    j;
6150     char_u  **fnames = (char_u **)gap->ga_data;
6151 
6152     sort_strings(fnames, gap->ga_len);
6153     for (i = gap->ga_len - 1; i > 0; --i)
6154 	if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
6155 	{
6156 	    vim_free(fnames[i]);
6157 	    for (j = i + 1; j < gap->ga_len; ++j)
6158 		fnames[j - 1] = fnames[j];
6159 	    --gap->ga_len;
6160 	}
6161 }
6162 #endif
6163 
6164 /*
6165  * Return TRUE if "p" contains what looks like an environment variable.
6166  * Allowing for escaping.
6167  */
6168     static int
6169 has_env_var(char_u *p)
6170 {
6171     for ( ; *p; MB_PTR_ADV(p))
6172     {
6173 	if (*p == '\\' && p[1] != NUL)
6174 	    ++p;
6175 	else if (vim_strchr((char_u *)
6176 #if defined(MSWIN)
6177 				    "$%"
6178 #else
6179 				    "$"
6180 #endif
6181 					, *p) != NULL)
6182 	    return TRUE;
6183     }
6184     return FALSE;
6185 }
6186 
6187 #ifdef SPECIAL_WILDCHAR
6188 /*
6189  * Return TRUE if "p" contains a special wildcard character, one that Vim
6190  * cannot expand, requires using a shell.
6191  */
6192     static int
6193 has_special_wildchar(char_u *p)
6194 {
6195     for ( ; *p; MB_PTR_ADV(p))
6196     {
6197 	/* Allow for escaping. */
6198 	if (*p == '\\' && p[1] != NUL)
6199 	    ++p;
6200 	else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
6201 	    return TRUE;
6202     }
6203     return FALSE;
6204 }
6205 #endif
6206 
6207 /*
6208  * Generic wildcard expansion code.
6209  *
6210  * Characters in "pat" that should not be expanded must be preceded with a
6211  * backslash. E.g., "/path\ with\ spaces/my\*star*"
6212  *
6213  * Return FAIL when no single file was found.  In this case "num_file" is not
6214  * set, and "file" may contain an error message.
6215  * Return OK when some files found.  "num_file" is set to the number of
6216  * matches, "file" to the array of matches.  Call FreeWild() later.
6217  */
6218     int
6219 gen_expand_wildcards(
6220     int		num_pat,	/* number of input patterns */
6221     char_u	**pat,		/* array of input patterns */
6222     int		*num_file,	/* resulting number of files */
6223     char_u	***file,	/* array of resulting files */
6224     int		flags)		/* EW_* flags */
6225 {
6226     int			i;
6227     garray_T		ga;
6228     char_u		*p;
6229     static int		recursive = FALSE;
6230     int			add_pat;
6231     int			retval = OK;
6232 #if defined(FEAT_SEARCHPATH)
6233     int			did_expand_in_path = FALSE;
6234 #endif
6235 
6236     /*
6237      * expand_env() is called to expand things like "~user".  If this fails,
6238      * it calls ExpandOne(), which brings us back here.  In this case, always
6239      * call the machine specific expansion function, if possible.  Otherwise,
6240      * return FAIL.
6241      */
6242     if (recursive)
6243 #ifdef SPECIAL_WILDCHAR
6244 	return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
6245 #else
6246 	return FAIL;
6247 #endif
6248 
6249 #ifdef SPECIAL_WILDCHAR
6250     /*
6251      * If there are any special wildcard characters which we cannot handle
6252      * here, call machine specific function for all the expansion.  This
6253      * avoids starting the shell for each argument separately.
6254      * For `=expr` do use the internal function.
6255      */
6256     for (i = 0; i < num_pat; i++)
6257     {
6258 	if (has_special_wildchar(pat[i])
6259 # ifdef VIM_BACKTICK
6260 		&& !(vim_backtick(pat[i]) && pat[i][1] == '=')
6261 # endif
6262 	   )
6263 	    return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
6264     }
6265 #endif
6266 
6267     recursive = TRUE;
6268 
6269     /*
6270      * The matching file names are stored in a growarray.  Init it empty.
6271      */
6272     ga_init2(&ga, (int)sizeof(char_u *), 30);
6273 
6274     for (i = 0; i < num_pat; ++i)
6275     {
6276 	add_pat = -1;
6277 	p = pat[i];
6278 
6279 #ifdef VIM_BACKTICK
6280 	if (vim_backtick(p))
6281 	{
6282 	    add_pat = expand_backtick(&ga, p, flags);
6283 	    if (add_pat == -1)
6284 		retval = FAIL;
6285 	}
6286 	else
6287 #endif
6288 	{
6289 	    /*
6290 	     * First expand environment variables, "~/" and "~user/".
6291 	     */
6292 	    if (has_env_var(p) || *p == '~')
6293 	    {
6294 		p = expand_env_save_opt(p, TRUE);
6295 		if (p == NULL)
6296 		    p = pat[i];
6297 #ifdef UNIX
6298 		/*
6299 		 * On Unix, if expand_env() can't expand an environment
6300 		 * variable, use the shell to do that.  Discard previously
6301 		 * found file names and start all over again.
6302 		 */
6303 		else if (has_env_var(p) || *p == '~')
6304 		{
6305 		    vim_free(p);
6306 		    ga_clear_strings(&ga);
6307 		    i = mch_expand_wildcards(num_pat, pat, num_file, file,
6308 							 flags|EW_KEEPDOLLAR);
6309 		    recursive = FALSE;
6310 		    return i;
6311 		}
6312 #endif
6313 	    }
6314 
6315 	    /*
6316 	     * If there are wildcards: Expand file names and add each match to
6317 	     * the list.  If there is no match, and EW_NOTFOUND is given, add
6318 	     * the pattern.
6319 	     * If there are no wildcards: Add the file name if it exists or
6320 	     * when EW_NOTFOUND is given.
6321 	     */
6322 	    if (mch_has_exp_wildcard(p))
6323 	    {
6324 #if defined(FEAT_SEARCHPATH)
6325 		if ((flags & EW_PATH)
6326 			&& !mch_isFullName(p)
6327 			&& !(p[0] == '.'
6328 			    && (vim_ispathsep(p[1])
6329 				|| (p[1] == '.' && vim_ispathsep(p[2]))))
6330 		   )
6331 		{
6332 		    /* :find completion where 'path' is used.
6333 		     * Recursiveness is OK here. */
6334 		    recursive = FALSE;
6335 		    add_pat = expand_in_path(&ga, p, flags);
6336 		    recursive = TRUE;
6337 		    did_expand_in_path = TRUE;
6338 		}
6339 		else
6340 #endif
6341 		    add_pat = mch_expandpath(&ga, p, flags);
6342 	    }
6343 	}
6344 
6345 	if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
6346 	{
6347 	    char_u	*t = backslash_halve_save(p);
6348 
6349 	    /* When EW_NOTFOUND is used, always add files and dirs.  Makes
6350 	     * "vim c:/" work. */
6351 	    if (flags & EW_NOTFOUND)
6352 		addfile(&ga, t, flags | EW_DIR | EW_FILE);
6353 	    else
6354 		addfile(&ga, t, flags);
6355 	    vim_free(t);
6356 	}
6357 
6358 #if defined(FEAT_SEARCHPATH)
6359 	if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
6360 	    uniquefy_paths(&ga, p);
6361 #endif
6362 	if (p != pat[i])
6363 	    vim_free(p);
6364     }
6365 
6366     *num_file = ga.ga_len;
6367     *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
6368 
6369     recursive = FALSE;
6370 
6371     return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
6372 }
6373 
6374 # ifdef VIM_BACKTICK
6375 
6376 /*
6377  * Return TRUE if we can expand this backtick thing here.
6378  */
6379     static int
6380 vim_backtick(char_u *p)
6381 {
6382     return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
6383 }
6384 
6385 /*
6386  * Expand an item in `backticks` by executing it as a command.
6387  * Currently only works when pat[] starts and ends with a `.
6388  * Returns number of file names found, -1 if an error is encountered.
6389  */
6390     static int
6391 expand_backtick(
6392     garray_T	*gap,
6393     char_u	*pat,
6394     int		flags)	/* EW_* flags */
6395 {
6396     char_u	*p;
6397     char_u	*cmd;
6398     char_u	*buffer;
6399     int		cnt = 0;
6400     int		i;
6401 
6402     /* Create the command: lop off the backticks. */
6403     cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
6404     if (cmd == NULL)
6405 	return -1;
6406 
6407 #ifdef FEAT_EVAL
6408     if (*cmd == '=')	    /* `={expr}`: Expand expression */
6409 	buffer = eval_to_string(cmd + 1, &p, TRUE);
6410     else
6411 #endif
6412 	buffer = get_cmd_output(cmd, NULL,
6413 				(flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
6414     vim_free(cmd);
6415     if (buffer == NULL)
6416 	return -1;
6417 
6418     cmd = buffer;
6419     while (*cmd != NUL)
6420     {
6421 	cmd = skipwhite(cmd);		/* skip over white space */
6422 	p = cmd;
6423 	while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
6424 	    ++p;
6425 	/* add an entry if it is not empty */
6426 	if (p > cmd)
6427 	{
6428 	    i = *p;
6429 	    *p = NUL;
6430 	    addfile(gap, cmd, flags);
6431 	    *p = i;
6432 	    ++cnt;
6433 	}
6434 	cmd = p;
6435 	while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
6436 	    ++cmd;
6437     }
6438 
6439     vim_free(buffer);
6440     return cnt;
6441 }
6442 # endif /* VIM_BACKTICK */
6443 
6444 /*
6445  * Add a file to a file list.  Accepted flags:
6446  * EW_DIR	add directories
6447  * EW_FILE	add files
6448  * EW_EXEC	add executable files
6449  * EW_NOTFOUND	add even when it doesn't exist
6450  * EW_ADDSLASH	add slash after directory name
6451  * EW_ALLLINKS	add symlink also when the referred file does not exist
6452  */
6453     void
6454 addfile(
6455     garray_T	*gap,
6456     char_u	*f,	/* filename */
6457     int		flags)
6458 {
6459     char_u	*p;
6460     int		isdir;
6461     stat_T	sb;
6462 
6463     /* if the file/dir/link doesn't exist, may not add it */
6464     if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
6465 			? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
6466 	return;
6467 
6468 #ifdef FNAME_ILLEGAL
6469     /* if the file/dir contains illegal characters, don't add it */
6470     if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
6471 	return;
6472 #endif
6473 
6474     isdir = mch_isdir(f);
6475     if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
6476 	return;
6477 
6478     /* If the file isn't executable, may not add it.  Do accept directories.
6479      * When invoked from expand_shellcmd() do not use $PATH. */
6480     if (!isdir && (flags & EW_EXEC)
6481 			     && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
6482 	return;
6483 
6484     /* Make room for another item in the file list. */
6485     if (ga_grow(gap, 1) == FAIL)
6486 	return;
6487 
6488     p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
6489     if (p == NULL)
6490 	return;
6491 
6492     STRCPY(p, f);
6493 #ifdef BACKSLASH_IN_FILENAME
6494     slash_adjust(p);
6495 #endif
6496     /*
6497      * Append a slash or backslash after directory names if none is present.
6498      */
6499 #ifndef DONT_ADD_PATHSEP_TO_DIR
6500     if (isdir && (flags & EW_ADDSLASH))
6501 	add_pathsep(p);
6502 #endif
6503     ((char_u **)gap->ga_data)[gap->ga_len++] = p;
6504 }
6505 #endif /* !NO_EXPANDPATH */
6506 
6507 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
6508 
6509 #ifndef SEEK_SET
6510 # define SEEK_SET 0
6511 #endif
6512 #ifndef SEEK_END
6513 # define SEEK_END 2
6514 #endif
6515 
6516 /*
6517  * Get the stdout of an external command.
6518  * If "ret_len" is NULL replace NUL characters with NL.  When "ret_len" is not
6519  * NULL store the length there.
6520  * Returns an allocated string, or NULL for error.
6521  */
6522     char_u *
6523 get_cmd_output(
6524     char_u	*cmd,
6525     char_u	*infile,	/* optional input file name */
6526     int		flags,		/* can be SHELL_SILENT */
6527     int		*ret_len)
6528 {
6529     char_u	*tempname;
6530     char_u	*command;
6531     char_u	*buffer = NULL;
6532     int		len;
6533     int		i = 0;
6534     FILE	*fd;
6535 
6536     if (check_restricted() || check_secure())
6537 	return NULL;
6538 
6539     /* get a name for the temp file */
6540     if ((tempname = vim_tempname('o', FALSE)) == NULL)
6541     {
6542 	emsg(_(e_notmp));
6543 	return NULL;
6544     }
6545 
6546     /* Add the redirection stuff */
6547     command = make_filter_cmd(cmd, infile, tempname);
6548     if (command == NULL)
6549 	goto done;
6550 
6551     /*
6552      * Call the shell to execute the command (errors are ignored).
6553      * Don't check timestamps here.
6554      */
6555     ++no_check_timestamps;
6556     call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
6557     --no_check_timestamps;
6558 
6559     vim_free(command);
6560 
6561     /*
6562      * read the names from the file into memory
6563      */
6564 # ifdef VMS
6565     /* created temporary file is not always readable as binary */
6566     fd = mch_fopen((char *)tempname, "r");
6567 # else
6568     fd = mch_fopen((char *)tempname, READBIN);
6569 # endif
6570 
6571     if (fd == NULL)
6572     {
6573 	semsg(_(e_notopen), tempname);
6574 	goto done;
6575     }
6576 
6577     fseek(fd, 0L, SEEK_END);
6578     len = ftell(fd);		    /* get size of temp file */
6579     fseek(fd, 0L, SEEK_SET);
6580 
6581     buffer = alloc(len + 1);
6582     if (buffer != NULL)
6583 	i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
6584     fclose(fd);
6585     mch_remove(tempname);
6586     if (buffer == NULL)
6587 	goto done;
6588 #ifdef VMS
6589     len = i;	/* VMS doesn't give us what we asked for... */
6590 #endif
6591     if (i != len)
6592     {
6593 	semsg(_(e_notread), tempname);
6594 	VIM_CLEAR(buffer);
6595     }
6596     else if (ret_len == NULL)
6597     {
6598 	/* Change NUL into SOH, otherwise the string is truncated. */
6599 	for (i = 0; i < len; ++i)
6600 	    if (buffer[i] == NUL)
6601 		buffer[i] = 1;
6602 
6603 	buffer[len] = NUL;	/* make sure the buffer is terminated */
6604     }
6605     else
6606 	*ret_len = len;
6607 
6608 done:
6609     vim_free(tempname);
6610     return buffer;
6611 }
6612 #endif
6613 
6614 /*
6615  * Free the list of files returned by expand_wildcards() or other expansion
6616  * functions.
6617  */
6618     void
6619 FreeWild(int count, char_u **files)
6620 {
6621     if (count <= 0 || files == NULL)
6622 	return;
6623     while (count--)
6624 	vim_free(files[count]);
6625     vim_free(files);
6626 }
6627 
6628 /*
6629  * Return TRUE when need to go to Insert mode because of 'insertmode'.
6630  * Don't do this when still processing a command or a mapping.
6631  * Don't do this when inside a ":normal" command.
6632  */
6633     int
6634 goto_im(void)
6635 {
6636     return (p_im && stuff_empty() && typebuf_typed());
6637 }
6638 
6639 /*
6640  * Returns the isolated name of the shell in allocated memory:
6641  * - Skip beyond any path.  E.g., "/usr/bin/csh -f" -> "csh -f".
6642  * - Remove any argument.  E.g., "csh -f" -> "csh".
6643  * But don't allow a space in the path, so that this works:
6644  *   "/usr/bin/csh --rcfile ~/.cshrc"
6645  * But don't do that for Windows, it's common to have a space in the path.
6646  */
6647     char_u *
6648 get_isolated_shell_name(void)
6649 {
6650     char_u *p;
6651 
6652 #ifdef MSWIN
6653     p = gettail(p_sh);
6654     p = vim_strnsave(p, (int)(skiptowhite(p) - p));
6655 #else
6656     p = skiptowhite(p_sh);
6657     if (*p == NUL)
6658     {
6659 	/* No white space, use the tail. */
6660 	p = vim_strsave(gettail(p_sh));
6661     }
6662     else
6663     {
6664 	char_u  *p1, *p2;
6665 
6666 	/* Find the last path separator before the space. */
6667 	p1 = p_sh;
6668 	for (p2 = p_sh; p2 < p; MB_PTR_ADV(p2))
6669 	    if (vim_ispathsep(*p2))
6670 		p1 = p2 + 1;
6671 	p = vim_strnsave(p1, (int)(p - p1));
6672     }
6673 #endif
6674     return p;
6675 }
6676 
6677 /*
6678  * Check if the "://" of a URL is at the pointer, return URL_SLASH.
6679  * Also check for ":\\", which MS Internet Explorer accepts, return
6680  * URL_BACKSLASH.
6681  */
6682     int
6683 path_is_url(char_u *p)
6684 {
6685     if (STRNCMP(p, "://", (size_t)3) == 0)
6686 	return URL_SLASH;
6687     else if (STRNCMP(p, ":\\\\", (size_t)3) == 0)
6688 	return URL_BACKSLASH;
6689     return 0;
6690 }
6691 
6692 /*
6693  * Check if "fname" starts with "name://".  Return URL_SLASH if it does.
6694  * Return URL_BACKSLASH for "name:\\".
6695  * Return zero otherwise.
6696  */
6697     int
6698 path_with_url(char_u *fname)
6699 {
6700     char_u *p;
6701 
6702     for (p = fname; isalpha(*p); ++p)
6703 	;
6704     return path_is_url(p);
6705 }
6706 
6707 /*
6708  * Return TRUE if "name" is a full (absolute) path name or URL.
6709  */
6710     int
6711 vim_isAbsName(char_u *name)
6712 {
6713     return (path_with_url(name) != 0 || mch_isFullName(name));
6714 }
6715 
6716 /*
6717  * Get absolute file name into buffer "buf[len]".
6718  *
6719  * return FAIL for failure, OK otherwise
6720  */
6721     int
6722 vim_FullName(
6723     char_u	*fname,
6724     char_u	*buf,
6725     int		len,
6726     int		force)	    /* force expansion even when already absolute */
6727 {
6728     int		retval = OK;
6729     int		url;
6730 
6731     *buf = NUL;
6732     if (fname == NULL)
6733 	return FAIL;
6734 
6735     url = path_with_url(fname);
6736     if (!url)
6737 	retval = mch_FullName(fname, buf, len, force);
6738     if (url || retval == FAIL)
6739     {
6740 	/* something failed; use the file name (truncate when too long) */
6741 	vim_strncpy(buf, fname, len - 1);
6742     }
6743 #if defined(MSWIN)
6744     slash_adjust(buf);
6745 #endif
6746     return retval;
6747 }
6748