xref: /vim-8.2.3635/src/ex_cmds.c (revision 1d30fde3)
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  * ex_cmds.c: some functions for command line commands
12  */
13 
14 #include "vim.h"
15 #include "version.h"
16 
17 #ifdef FEAT_FLOAT
18 # include <float.h>
19 #endif
20 
21 static int linelen(int *has_tab);
22 static void do_filter(linenr_T line1, linenr_T line2, exarg_T *eap, char_u *cmd, int do_in, int do_out);
23 static int not_writing(void);
24 static int check_readonly(int *forceit, buf_T *buf);
25 static void delbuf_msg(char_u *name);
26 
27 /*
28  * ":ascii" and "ga".
29  */
30     void
do_ascii(exarg_T * eap UNUSED)31 do_ascii(exarg_T *eap UNUSED)
32 {
33     int		c;
34     int		cval;
35     char	buf1[20];
36     char	buf2[20];
37     char_u	buf3[7];
38 #ifdef FEAT_DIGRAPHS
39     char_u      *dig;
40 #endif
41     int		cc[MAX_MCO];
42     int		ci = 0;
43     int		len;
44 
45     if (enc_utf8)
46 	c = utfc_ptr2char(ml_get_cursor(), cc);
47     else
48 	c = gchar_cursor();
49     if (c == NUL)
50     {
51 	msg("NUL");
52 	return;
53     }
54 
55     IObuff[0] = NUL;
56     if (!has_mbyte || (enc_dbcs != 0 && c < 0x100) || c < 0x80)
57     {
58 	if (c == NL)	    // NUL is stored as NL
59 	    c = NUL;
60 	if (c == CAR && get_fileformat(curbuf) == EOL_MAC)
61 	    cval = NL;	    // NL is stored as CR
62 	else
63 	    cval = c;
64 	if (vim_isprintc_strict(c) && (c < ' '
65 #ifndef EBCDIC
66 		    || c > '~'
67 #endif
68 			       ))
69 	{
70 	    transchar_nonprint(curbuf, buf3, c);
71 	    vim_snprintf(buf1, sizeof(buf1), "  <%s>", (char *)buf3);
72 	}
73 	else
74 	    buf1[0] = NUL;
75 #ifndef EBCDIC
76 	if (c >= 0x80)
77 	    vim_snprintf(buf2, sizeof(buf2), "  <M-%s>",
78 						 (char *)transchar(c & 0x7f));
79 	else
80 #endif
81 	    buf2[0] = NUL;
82 #ifdef FEAT_DIGRAPHS
83 	dig = get_digraph_for_char(cval);
84 	if (dig != NULL)
85 	    vim_snprintf((char *)IObuff, IOSIZE,
86 		_("<%s>%s%s  %d,  Hex %02x,  Oct %03o, Digr %s"),
87 			      transchar(c), buf1, buf2, cval, cval, cval, dig);
88 	else
89 #endif
90 	    vim_snprintf((char *)IObuff, IOSIZE,
91 		_("<%s>%s%s  %d,  Hex %02x,  Octal %03o"),
92 				  transchar(c), buf1, buf2, cval, cval, cval);
93 	if (enc_utf8)
94 	    c = cc[ci++];
95 	else
96 	    c = 0;
97     }
98 
99     // Repeat for combining characters.
100     while (has_mbyte && (c >= 0x100 || (enc_utf8 && c >= 0x80)))
101     {
102 	len = (int)STRLEN(IObuff);
103 	// This assumes every multi-byte char is printable...
104 	if (len > 0)
105 	    IObuff[len++] = ' ';
106 	IObuff[len++] = '<';
107 	if (enc_utf8 && utf_iscomposing(c)
108 # ifdef USE_GUI
109 		&& !gui.in_use
110 # endif
111 		)
112 	    IObuff[len++] = ' '; // draw composing char on top of a space
113 	len += (*mb_char2bytes)(c, IObuff + len);
114 #ifdef FEAT_DIGRAPHS
115 	dig = get_digraph_for_char(c);
116 	if (dig != NULL)
117 	    vim_snprintf((char *)IObuff + len, IOSIZE - len,
118 			c < 0x10000 ? _("> %d, Hex %04x, Oct %o, Digr %s")
119 				    : _("> %d, Hex %08x, Oct %o, Digr %s"),
120 					c, c, c, dig);
121 	else
122 #endif
123 	    vim_snprintf((char *)IObuff + len, IOSIZE - len,
124 			 c < 0x10000 ? _("> %d, Hex %04x, Octal %o")
125 				     : _("> %d, Hex %08x, Octal %o"),
126 				     c, c, c);
127 	if (ci == MAX_MCO)
128 	    break;
129 	if (enc_utf8)
130 	    c = cc[ci++];
131 	else
132 	    c = 0;
133     }
134 
135     msg((char *)IObuff);
136 }
137 
138 /*
139  * ":left", ":center" and ":right": align text.
140  */
141     void
ex_align(exarg_T * eap)142 ex_align(exarg_T *eap)
143 {
144     pos_T	save_curpos;
145     int		len;
146     int		indent = 0;
147     int		new_indent;
148     int		has_tab;
149     int		width;
150 
151 #ifdef FEAT_RIGHTLEFT
152     if (curwin->w_p_rl)
153     {
154 	// switch left and right aligning
155 	if (eap->cmdidx == CMD_right)
156 	    eap->cmdidx = CMD_left;
157 	else if (eap->cmdidx == CMD_left)
158 	    eap->cmdidx = CMD_right;
159     }
160 #endif
161 
162     width = atoi((char *)eap->arg);
163     save_curpos = curwin->w_cursor;
164     if (eap->cmdidx == CMD_left)    // width is used for new indent
165     {
166 	if (width >= 0)
167 	    indent = width;
168     }
169     else
170     {
171 	/*
172 	 * if 'textwidth' set, use it
173 	 * else if 'wrapmargin' set, use it
174 	 * if invalid value, use 80
175 	 */
176 	if (width <= 0)
177 	    width = curbuf->b_p_tw;
178 	if (width == 0 && curbuf->b_p_wm > 0)
179 	    width = curwin->w_width - curbuf->b_p_wm;
180 	if (width <= 0)
181 	    width = 80;
182     }
183 
184     if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL)
185 	return;
186 
187     for (curwin->w_cursor.lnum = eap->line1;
188 		 curwin->w_cursor.lnum <= eap->line2; ++curwin->w_cursor.lnum)
189     {
190 	if (eap->cmdidx == CMD_left)		// left align
191 	    new_indent = indent;
192 	else
193 	{
194 	    has_tab = FALSE;	// avoid uninit warnings
195 	    len = linelen(eap->cmdidx == CMD_right ? &has_tab
196 						   : NULL) - get_indent();
197 
198 	    if (len <= 0)			// skip blank lines
199 		continue;
200 
201 	    if (eap->cmdidx == CMD_center)
202 		new_indent = (width - len) / 2;
203 	    else
204 	    {
205 		new_indent = width - len;	// right align
206 
207 		/*
208 		 * Make sure that embedded TABs don't make the text go too far
209 		 * to the right.
210 		 */
211 		if (has_tab)
212 		    while (new_indent > 0)
213 		    {
214 			(void)set_indent(new_indent, 0);
215 			if (linelen(NULL) <= width)
216 			{
217 			    /*
218 			     * Now try to move the line as much as possible to
219 			     * the right.  Stop when it moves too far.
220 			     */
221 			    do
222 				(void)set_indent(++new_indent, 0);
223 			    while (linelen(NULL) <= width);
224 			    --new_indent;
225 			    break;
226 			}
227 			--new_indent;
228 		    }
229 	    }
230 	}
231 	if (new_indent < 0)
232 	    new_indent = 0;
233 	(void)set_indent(new_indent, 0);		// set indent
234     }
235     changed_lines(eap->line1, 0, eap->line2 + 1, 0L);
236     curwin->w_cursor = save_curpos;
237     beginline(BL_WHITE | BL_FIX);
238 }
239 
240 /*
241  * Get the length of the current line, excluding trailing white space.
242  */
243     static int
linelen(int * has_tab)244 linelen(int *has_tab)
245 {
246     char_u  *line;
247     char_u  *first;
248     char_u  *last;
249     int	    save;
250     int	    len;
251 
252     // Get the line.  If it's empty bail out early (could be the empty string
253     // for an unloaded buffer).
254     line = ml_get_curline();
255     if (*line == NUL)
256 	return 0;
257 
258     // find the first non-blank character
259     first = skipwhite(line);
260 
261     // find the character after the last non-blank character
262     for (last = first + STRLEN(first);
263 				last > first && VIM_ISWHITE(last[-1]); --last)
264 	;
265     save = *last;
266     *last = NUL;
267     len = linetabsize(line);		// get line length
268     if (has_tab != NULL)		// check for embedded TAB
269 	*has_tab = (vim_strchr(first, TAB) != NULL);
270     *last = save;
271 
272     return len;
273 }
274 
275 // Buffer for two lines used during sorting.  They are allocated to
276 // contain the longest line being sorted.
277 static char_u	*sortbuf1;
278 static char_u	*sortbuf2;
279 
280 static int	sort_lc;	// sort using locale
281 static int	sort_ic;	// ignore case
282 static int	sort_nr;	// sort on number
283 static int	sort_rx;	// sort on regex instead of skipping it
284 #ifdef FEAT_FLOAT
285 static int	sort_flt;	// sort on floating number
286 #endif
287 
288 static int	sort_abort;	// flag to indicate if sorting has been interrupted
289 
290 // Struct to store info to be sorted.
291 typedef struct
292 {
293     linenr_T	lnum;			// line number
294     union {
295 	struct
296 	{
297 	    varnumber_T	start_col_nr;	// starting column number
298 	    varnumber_T	end_col_nr;	// ending column number
299 	} line;
300 	struct
301 	{
302 	    varnumber_T	value;		// value if sorting by integer
303 	    int is_number;		// TRUE when line contains a number
304 	} num;
305 #ifdef FEAT_FLOAT
306 	float_T value_flt;		// value if sorting by float
307 #endif
308     } st_u;
309 } sorti_T;
310 
311     static int
string_compare(const void * s1,const void * s2)312 string_compare(const void *s1, const void *s2)
313 {
314     if (sort_lc)
315 	return strcoll((char *)s1, (char *)s2);
316     return sort_ic ? STRICMP(s1, s2) : STRCMP(s1, s2);
317 }
318 
319     static int
sort_compare(const void * s1,const void * s2)320 sort_compare(const void *s1, const void *s2)
321 {
322     sorti_T	l1 = *(sorti_T *)s1;
323     sorti_T	l2 = *(sorti_T *)s2;
324     int		result = 0;
325 
326     // If the user interrupts, there's no way to stop qsort() immediately, but
327     // if we return 0 every time, qsort will assume it's done sorting and
328     // exit.
329     if (sort_abort)
330 	return 0;
331     fast_breakcheck();
332     if (got_int)
333 	sort_abort = TRUE;
334 
335     if (sort_nr)
336     {
337 	if (l1.st_u.num.is_number != l2.st_u.num.is_number)
338 	    result = l1.st_u.num.is_number - l2.st_u.num.is_number;
339 	else
340 	    result = l1.st_u.num.value == l2.st_u.num.value ? 0
341 			     : l1.st_u.num.value > l2.st_u.num.value ? 1 : -1;
342     }
343 #ifdef FEAT_FLOAT
344     else if (sort_flt)
345 	result = l1.st_u.value_flt == l2.st_u.value_flt ? 0
346 			     : l1.st_u.value_flt > l2.st_u.value_flt ? 1 : -1;
347 #endif
348     else
349     {
350 	// We need to copy one line into "sortbuf1", because there is no
351 	// guarantee that the first pointer becomes invalid when obtaining the
352 	// second one.
353 	STRNCPY(sortbuf1, ml_get(l1.lnum) + l1.st_u.line.start_col_nr,
354 		     l1.st_u.line.end_col_nr - l1.st_u.line.start_col_nr + 1);
355 	sortbuf1[l1.st_u.line.end_col_nr - l1.st_u.line.start_col_nr] = 0;
356 	STRNCPY(sortbuf2, ml_get(l2.lnum) + l2.st_u.line.start_col_nr,
357 		     l2.st_u.line.end_col_nr - l2.st_u.line.start_col_nr + 1);
358 	sortbuf2[l2.st_u.line.end_col_nr - l2.st_u.line.start_col_nr] = 0;
359 
360 	result = string_compare(sortbuf1, sortbuf2);
361     }
362 
363     // If two lines have the same value, preserve the original line order.
364     if (result == 0)
365 	return (int)(l1.lnum - l2.lnum);
366     return result;
367 }
368 
369 /*
370  * ":sort".
371  */
372     void
ex_sort(exarg_T * eap)373 ex_sort(exarg_T *eap)
374 {
375     regmatch_T	regmatch;
376     int		len;
377     linenr_T	lnum;
378     long	maxlen = 0;
379     sorti_T	*nrs;
380     size_t	count = (size_t)(eap->line2 - eap->line1 + 1);
381     size_t	i;
382     char_u	*p;
383     char_u	*s;
384     char_u	*s2;
385     char_u	c;			// temporary character storage
386     int		unique = FALSE;
387     long	deleted;
388     colnr_T	start_col;
389     colnr_T	end_col;
390     int		sort_what = 0;
391     int		format_found = 0;
392     int		change_occurred = FALSE; // Buffer contents changed.
393 
394     // Sorting one line is really quick!
395     if (count <= 1)
396 	return;
397 
398     if (u_save((linenr_T)(eap->line1 - 1), (linenr_T)(eap->line2 + 1)) == FAIL)
399 	return;
400     sortbuf1 = NULL;
401     sortbuf2 = NULL;
402     regmatch.regprog = NULL;
403     nrs = ALLOC_MULT(sorti_T, count);
404     if (nrs == NULL)
405 	goto sortend;
406 
407     sort_abort = sort_ic = sort_lc = sort_rx = sort_nr = 0;
408 #ifdef FEAT_FLOAT
409     sort_flt = 0;
410 #endif
411 
412     for (p = eap->arg; *p != NUL; ++p)
413     {
414 	if (VIM_ISWHITE(*p))
415 	    ;
416 	else if (*p == 'i')
417 	    sort_ic = TRUE;
418 	else if (*p == 'l')
419 	    sort_lc = TRUE;
420 	else if (*p == 'r')
421 	    sort_rx = TRUE;
422 	else if (*p == 'n')
423 	{
424 	    sort_nr = 1;
425 	    ++format_found;
426 	}
427 #ifdef FEAT_FLOAT
428 	else if (*p == 'f')
429 	{
430 	    sort_flt = 1;
431 	    ++format_found;
432 	}
433 #endif
434 	else if (*p == 'b')
435 	{
436 	    sort_what = STR2NR_BIN + STR2NR_FORCE;
437 	    ++format_found;
438 	}
439 	else if (*p == 'o')
440 	{
441 	    sort_what = STR2NR_OCT + STR2NR_FORCE;
442 	    ++format_found;
443 	}
444 	else if (*p == 'x')
445 	{
446 	    sort_what = STR2NR_HEX + STR2NR_FORCE;
447 	    ++format_found;
448 	}
449 	else if (*p == 'u')
450 	    unique = TRUE;
451 	else if (*p == '"')	// comment start
452 	    break;
453 	else if (eap->nextcmd == NULL && check_nextcmd(p) != NULL)
454 	{
455 	    eap->nextcmd = check_nextcmd(p);
456 	    break;
457 	}
458 	else if (!ASCII_ISALPHA(*p) && regmatch.regprog == NULL)
459 	{
460 	    s = skip_regexp_err(p + 1, *p, TRUE);
461 	    if (s == NULL)
462 		goto sortend;
463 	    *s = NUL;
464 	    // Use last search pattern if sort pattern is empty.
465 	    if (s == p + 1)
466 	    {
467 		if (last_search_pat() == NULL)
468 		{
469 		    emsg(_(e_no_previous_regular_expression));
470 		    goto sortend;
471 		}
472 		regmatch.regprog = vim_regcomp(last_search_pat(), RE_MAGIC);
473 	    }
474 	    else
475 		regmatch.regprog = vim_regcomp(p + 1, RE_MAGIC);
476 	    if (regmatch.regprog == NULL)
477 		goto sortend;
478 	    p = s;		// continue after the regexp
479 	    regmatch.rm_ic = p_ic;
480 	}
481 	else
482 	{
483 	    semsg(_(e_invarg2), p);
484 	    goto sortend;
485 	}
486     }
487 
488     // Can only have one of 'n', 'b', 'o' and 'x'.
489     if (format_found > 1)
490     {
491 	emsg(_(e_invarg));
492 	goto sortend;
493     }
494 
495     // From here on "sort_nr" is used as a flag for any integer number
496     // sorting.
497     sort_nr += sort_what;
498 
499     /*
500      * Make an array with all line numbers.  This avoids having to copy all
501      * the lines into allocated memory.
502      * When sorting on strings "start_col_nr" is the offset in the line, for
503      * numbers sorting it's the number to sort on.  This means the pattern
504      * matching and number conversion only has to be done once per line.
505      * Also get the longest line length for allocating "sortbuf".
506      */
507     for (lnum = eap->line1; lnum <= eap->line2; ++lnum)
508     {
509 	s = ml_get(lnum);
510 	len = (int)STRLEN(s);
511 	if (maxlen < len)
512 	    maxlen = len;
513 
514 	start_col = 0;
515 	end_col = len;
516 	if (regmatch.regprog != NULL && vim_regexec(&regmatch, s, 0))
517 	{
518 	    if (sort_rx)
519 	    {
520 		start_col = (colnr_T)(regmatch.startp[0] - s);
521 		end_col = (colnr_T)(regmatch.endp[0] - s);
522 	    }
523 	    else
524 		start_col = (colnr_T)(regmatch.endp[0] - s);
525 	}
526 	else
527 	    if (regmatch.regprog != NULL)
528 		end_col = 0;
529 
530 	if (sort_nr
531 #ifdef FEAT_FLOAT
532 		|| sort_flt
533 #endif
534 		)
535 	{
536 	    // Make sure vim_str2nr doesn't read any digits past the end
537 	    // of the match, by temporarily terminating the string there
538 	    s2 = s + end_col;
539 	    c = *s2;
540 	    *s2 = NUL;
541 	    // Sorting on number: Store the number itself.
542 	    p = s + start_col;
543 	    if (sort_nr)
544 	    {
545 		if (sort_what & STR2NR_HEX)
546 		    s = skiptohex(p);
547 		else if (sort_what & STR2NR_BIN)
548 		    s = skiptobin(p);
549 		else
550 		    s = skiptodigit(p);
551 		if (s > p && s[-1] == '-')
552 		    --s;  // include preceding negative sign
553 		if (*s == NUL)
554 		{
555 		    // line without number should sort before any number
556 		    nrs[lnum - eap->line1].st_u.num.is_number = FALSE;
557 		    nrs[lnum - eap->line1].st_u.num.value = 0;
558 		}
559 		else
560 		{
561 		    nrs[lnum - eap->line1].st_u.num.is_number = TRUE;
562 		    vim_str2nr(s, NULL, NULL, sort_what,
563 			&nrs[lnum - eap->line1].st_u.num.value,
564 			NULL, 0, FALSE);
565 		}
566 	    }
567 #ifdef FEAT_FLOAT
568 	    else
569 	    {
570 		s = skipwhite(p);
571 		if (*s == '+')
572 		    s = skipwhite(s + 1);
573 
574 		if (*s == NUL)
575 		    // empty line should sort before any number
576 		    nrs[lnum - eap->line1].st_u.value_flt = -DBL_MAX;
577 		else
578 		    nrs[lnum - eap->line1].st_u.value_flt =
579 						      strtod((char *)s, NULL);
580 	    }
581 #endif
582 	    *s2 = c;
583 	}
584 	else
585 	{
586 	    // Store the column to sort at.
587 	    nrs[lnum - eap->line1].st_u.line.start_col_nr = start_col;
588 	    nrs[lnum - eap->line1].st_u.line.end_col_nr = end_col;
589 	}
590 
591 	nrs[lnum - eap->line1].lnum = lnum;
592 
593 	if (regmatch.regprog != NULL)
594 	    fast_breakcheck();
595 	if (got_int)
596 	    goto sortend;
597     }
598 
599     // Allocate a buffer that can hold the longest line.
600     sortbuf1 = alloc(maxlen + 1);
601     if (sortbuf1 == NULL)
602 	goto sortend;
603     sortbuf2 = alloc(maxlen + 1);
604     if (sortbuf2 == NULL)
605 	goto sortend;
606 
607     // Sort the array of line numbers.  Note: can't be interrupted!
608     qsort((void *)nrs, count, sizeof(sorti_T), sort_compare);
609 
610     if (sort_abort)
611 	goto sortend;
612 
613     // Insert the lines in the sorted order below the last one.
614     lnum = eap->line2;
615     for (i = 0; i < count; ++i)
616     {
617 	linenr_T get_lnum = nrs[eap->forceit ? count - i - 1 : i].lnum;
618 
619 	// If the original line number of the line being placed is not the same
620 	// as "lnum" (accounting for offset), we know that the buffer changed.
621 	if (get_lnum + ((linenr_T)count - 1) != lnum)
622 	    change_occurred = TRUE;
623 
624 	s = ml_get(get_lnum);
625 	if (!unique || i == 0 || string_compare(s, sortbuf1) != 0)
626 	{
627 	    // Copy the line into a buffer, it may become invalid in
628 	    // ml_append(). And it's needed for "unique".
629 	    STRCPY(sortbuf1, s);
630 	    if (ml_append(lnum++, sortbuf1, (colnr_T)0, FALSE) == FAIL)
631 		break;
632 	}
633 	fast_breakcheck();
634 	if (got_int)
635 	    goto sortend;
636     }
637 
638     // delete the original lines if appending worked
639     if (i == count)
640 	for (i = 0; i < count; ++i)
641 	    ml_delete(eap->line1);
642     else
643 	count = 0;
644 
645     // Adjust marks for deleted (or added) lines and prepare for displaying.
646     deleted = (long)(count - (lnum - eap->line2));
647     if (deleted > 0)
648     {
649 	mark_adjust(eap->line2 - deleted, eap->line2, (long)MAXLNUM, -deleted);
650 	msgmore(-deleted);
651     }
652     else if (deleted < 0)
653 	mark_adjust(eap->line2, MAXLNUM, -deleted, 0L);
654 
655     if (change_occurred || deleted != 0)
656 	changed_lines(eap->line1, 0, eap->line2 + 1, -deleted);
657 
658     curwin->w_cursor.lnum = eap->line1;
659     beginline(BL_WHITE | BL_FIX);
660 
661 sortend:
662     vim_free(nrs);
663     vim_free(sortbuf1);
664     vim_free(sortbuf2);
665     vim_regfree(regmatch.regprog);
666     if (got_int)
667 	emsg(_(e_interr));
668 }
669 
670 /*
671  * :move command - move lines line1-line2 to line dest
672  *
673  * return FAIL for failure, OK otherwise
674  */
675     int
do_move(linenr_T line1,linenr_T line2,linenr_T dest)676 do_move(linenr_T line1, linenr_T line2, linenr_T dest)
677 {
678     char_u	*str;
679     linenr_T	l;
680     linenr_T	extra;	    // Num lines added before line1
681     linenr_T	num_lines;  // Num lines moved
682     linenr_T	last_line;  // Last line in file after adding new text
683 #ifdef FEAT_FOLDING
684     win_T	*win;
685     tabpage_T	*tp;
686 #endif
687 
688     if (dest >= line1 && dest < line2)
689     {
690 	emsg(_("E134: Cannot move a range of lines into itself"));
691 	return FAIL;
692     }
693 
694     // Do nothing if we are not actually moving any lines.  This will prevent
695     // the 'modified' flag from being set without cause.
696     if (dest == line1 - 1 || dest == line2)
697     {
698 	// Move the cursor as if lines were moved (see below) to be backwards
699 	// compatible.
700 	if (dest >= line1)
701 	    curwin->w_cursor.lnum = dest;
702 	else
703 	    curwin->w_cursor.lnum = dest + (line2 - line1) + 1;
704 
705 	return OK;
706     }
707 
708     num_lines = line2 - line1 + 1;
709 
710     /*
711      * First we copy the old text to its new location -- webb
712      * Also copy the flag that ":global" command uses.
713      */
714     if (u_save(dest, dest + 1) == FAIL)
715 	return FAIL;
716     for (extra = 0, l = line1; l <= line2; l++)
717     {
718 	str = vim_strsave(ml_get(l + extra));
719 	if (str != NULL)
720 	{
721 	    ml_append(dest + l - line1, str, (colnr_T)0, FALSE);
722 	    vim_free(str);
723 	    if (dest < line1)
724 		extra++;
725 	}
726     }
727 
728     /*
729      * Now we must be careful adjusting our marks so that we don't overlap our
730      * mark_adjust() calls.
731      *
732      * We adjust the marks within the old text so that they refer to the
733      * last lines of the file (temporarily), because we know no other marks
734      * will be set there since these line numbers did not exist until we added
735      * our new lines.
736      *
737      * Then we adjust the marks on lines between the old and new text positions
738      * (either forwards or backwards).
739      *
740      * And Finally we adjust the marks we put at the end of the file back to
741      * their final destination at the new text position -- webb
742      */
743     last_line = curbuf->b_ml.ml_line_count;
744     mark_adjust_nofold(line1, line2, last_line - line2, 0L);
745     if (dest >= line2)
746     {
747 	mark_adjust_nofold(line2 + 1, dest, -num_lines, 0L);
748 #ifdef FEAT_FOLDING
749 	FOR_ALL_TAB_WINDOWS(tp, win) {
750 	    if (win->w_buffer == curbuf)
751 		foldMoveRange(&win->w_folds, line1, line2, dest);
752 	}
753 #endif
754 	if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
755 	{
756 	    curbuf->b_op_start.lnum = dest - num_lines + 1;
757 	    curbuf->b_op_end.lnum = dest;
758 	}
759     }
760     else
761     {
762 	mark_adjust_nofold(dest + 1, line1 - 1, num_lines, 0L);
763 #ifdef FEAT_FOLDING
764 	FOR_ALL_TAB_WINDOWS(tp, win) {
765 	    if (win->w_buffer == curbuf)
766 		foldMoveRange(&win->w_folds, dest + 1, line1 - 1, line2);
767 	}
768 #endif
769 	if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
770 	{
771 	    curbuf->b_op_start.lnum = dest + 1;
772 	    curbuf->b_op_end.lnum = dest + num_lines;
773 	}
774     }
775     if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
776 	curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
777     mark_adjust_nofold(last_line - num_lines + 1, last_line,
778 					     -(last_line - dest - extra), 0L);
779 
780     /*
781      * Now we delete the original text -- webb
782      */
783     if (u_save(line1 + extra - 1, line2 + extra + 1) == FAIL)
784 	return FAIL;
785 
786     for (l = line1; l <= line2; l++)
787 	ml_delete_flags(line1 + extra, ML_DEL_MESSAGE);
788 
789     if (!global_busy && num_lines > p_report)
790 	smsg(NGETTEXT("%ld line moved", "%ld lines moved", num_lines),
791 			(long)num_lines);
792 
793     /*
794      * Leave the cursor on the last of the moved lines.
795      */
796     if (dest >= line1)
797 	curwin->w_cursor.lnum = dest;
798     else
799 	curwin->w_cursor.lnum = dest + (line2 - line1) + 1;
800 
801     if (line1 < dest)
802     {
803 	dest += num_lines + 1;
804 	last_line = curbuf->b_ml.ml_line_count;
805 	if (dest > last_line + 1)
806 	    dest = last_line + 1;
807 	changed_lines(line1, 0, dest, 0L);
808     }
809     else
810 	changed_lines(dest + 1, 0, line1 + num_lines, 0L);
811 
812     return OK;
813 }
814 
815 /*
816  * ":copy"
817  */
818     void
ex_copy(linenr_T line1,linenr_T line2,linenr_T n)819 ex_copy(linenr_T line1, linenr_T line2, linenr_T n)
820 {
821     linenr_T	count;
822     char_u	*p;
823 
824     count = line2 - line1 + 1;
825     if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
826     {
827 	curbuf->b_op_start.lnum = n + 1;
828 	curbuf->b_op_end.lnum = n + count;
829 	curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
830     }
831 
832     /*
833      * there are three situations:
834      * 1. destination is above line1
835      * 2. destination is between line1 and line2
836      * 3. destination is below line2
837      *
838      * n = destination (when starting)
839      * curwin->w_cursor.lnum = destination (while copying)
840      * line1 = start of source (while copying)
841      * line2 = end of source (while copying)
842      */
843     if (u_save(n, n + 1) == FAIL)
844 	return;
845 
846     curwin->w_cursor.lnum = n;
847     while (line1 <= line2)
848     {
849 	// need to use vim_strsave() because the line will be unlocked within
850 	// ml_append()
851 	p = vim_strsave(ml_get(line1));
852 	if (p != NULL)
853 	{
854 	    ml_append(curwin->w_cursor.lnum, p, (colnr_T)0, FALSE);
855 	    vim_free(p);
856 	}
857 	// situation 2: skip already copied lines
858 	if (line1 == n)
859 	    line1 = curwin->w_cursor.lnum;
860 	++line1;
861 	if (curwin->w_cursor.lnum < line1)
862 	    ++line1;
863 	if (curwin->w_cursor.lnum < line2)
864 	    ++line2;
865 	++curwin->w_cursor.lnum;
866     }
867 
868     appended_lines_mark(n, count);
869 
870     msgmore((long)count);
871 }
872 
873 static char_u	*prevcmd = NULL;	// the previous command
874 
875 #if defined(EXITFREE) || defined(PROTO)
876     void
free_prev_shellcmd(void)877 free_prev_shellcmd(void)
878 {
879     vim_free(prevcmd);
880 }
881 #endif
882 
883 /*
884  * Handle the ":!cmd" command.	Also for ":r !cmd" and ":w !cmd"
885  * Bangs in the argument are replaced with the previously entered command.
886  * Remember the argument.
887  */
888     void
do_bang(int addr_count,exarg_T * eap,int forceit,int do_in,int do_out)889 do_bang(
890     int		addr_count,
891     exarg_T	*eap,
892     int		forceit,
893     int		do_in,
894     int		do_out)
895 {
896     char_u		*arg = eap->arg;	// command
897     linenr_T		line1 = eap->line1;	// start of range
898     linenr_T		line2 = eap->line2;	// end of range
899     char_u		*newcmd = NULL;		// the new command
900     int			free_newcmd = FALSE;    // need to free() newcmd
901     int			ins_prevcmd;
902     char_u		*t;
903     char_u		*p;
904     char_u		*trailarg;
905     int			len;
906     int			scroll_save = msg_scroll;
907 
908     /*
909      * Disallow shell commands for "rvim".
910      * Disallow shell commands from .exrc and .vimrc in current directory for
911      * security reasons.
912      */
913     if (check_restricted() || check_secure())
914 	return;
915 
916     if (addr_count == 0)		// :!
917     {
918 	msg_scroll = FALSE;	    // don't scroll here
919 	autowrite_all();
920 	msg_scroll = scroll_save;
921     }
922 
923     /*
924      * Try to find an embedded bang, like in :!<cmd> ! [args]
925      * (:!! is indicated by the 'forceit' variable)
926      */
927     ins_prevcmd = forceit;
928     trailarg = arg;
929     do
930     {
931 	len = (int)STRLEN(trailarg) + 1;
932 	if (newcmd != NULL)
933 	    len += (int)STRLEN(newcmd);
934 	if (ins_prevcmd)
935 	{
936 	    if (prevcmd == NULL)
937 	    {
938 		emsg(_(e_no_previous_command));
939 		vim_free(newcmd);
940 		return;
941 	    }
942 	    len += (int)STRLEN(prevcmd);
943 	}
944 	if ((t = alloc(len)) == NULL)
945 	{
946 	    vim_free(newcmd);
947 	    return;
948 	}
949 	*t = NUL;
950 	if (newcmd != NULL)
951 	    STRCAT(t, newcmd);
952 	if (ins_prevcmd)
953 	    STRCAT(t, prevcmd);
954 	p = t + STRLEN(t);
955 	STRCAT(t, trailarg);
956 	vim_free(newcmd);
957 	newcmd = t;
958 
959 	/*
960 	 * Scan the rest of the argument for '!', which is replaced by the
961 	 * previous command.  "\!" is replaced by "!" (this is vi compatible).
962 	 */
963 	trailarg = NULL;
964 	while (*p)
965 	{
966 	    if (*p == '!')
967 	    {
968 		if (p > newcmd && p[-1] == '\\')
969 		    STRMOVE(p - 1, p);
970 		else
971 		{
972 		    trailarg = p;
973 		    *trailarg++ = NUL;
974 		    ins_prevcmd = TRUE;
975 		    break;
976 		}
977 	    }
978 	    ++p;
979 	}
980     } while (trailarg != NULL);
981 
982     vim_free(prevcmd);
983     prevcmd = newcmd;
984 
985     if (bangredo)	    // put cmd in redo buffer for ! command
986     {
987 	// If % or # appears in the command, it must have been escaped.
988 	// Reescape them, so that redoing them does not substitute them by the
989 	// buffername.
990 	char_u *cmd = vim_strsave_escaped(prevcmd, (char_u *)"%#");
991 
992 	if (cmd != NULL)
993 	{
994 	    AppendToRedobuffLit(cmd, -1);
995 	    vim_free(cmd);
996 	}
997 	else
998 	    AppendToRedobuffLit(prevcmd, -1);
999 	AppendToRedobuff((char_u *)"\n");
1000 	bangredo = FALSE;
1001     }
1002     /*
1003      * Add quotes around the command, for shells that need them.
1004      */
1005     if (*p_shq != NUL)
1006     {
1007 	newcmd = alloc(STRLEN(prevcmd) + 2 * STRLEN(p_shq) + 1);
1008 	if (newcmd == NULL)
1009 	    return;
1010 	STRCPY(newcmd, p_shq);
1011 	STRCAT(newcmd, prevcmd);
1012 	STRCAT(newcmd, p_shq);
1013 	free_newcmd = TRUE;
1014     }
1015     if (addr_count == 0)		// :!
1016     {
1017 	// echo the command
1018 	msg_start();
1019 	msg_putchar(':');
1020 	msg_putchar('!');
1021 	msg_outtrans(newcmd);
1022 	msg_clr_eos();
1023 	windgoto(msg_row, msg_col);
1024 
1025 	do_shell(newcmd, 0);
1026     }
1027     else				// :range!
1028     {
1029 	// Careful: This may recursively call do_bang() again! (because of
1030 	// autocommands)
1031 	do_filter(line1, line2, eap, newcmd, do_in, do_out);
1032 	apply_autocmds(EVENT_SHELLFILTERPOST, NULL, NULL, FALSE, curbuf);
1033     }
1034     if (free_newcmd)
1035 	vim_free(newcmd);
1036 }
1037 
1038 /*
1039  * do_filter: filter lines through a command given by the user
1040  *
1041  * We mostly use temp files and the call_shell() routine here. This would
1042  * normally be done using pipes on a UNIX machine, but this is more portable
1043  * to non-unix machines. The call_shell() routine needs to be able
1044  * to deal with redirection somehow, and should handle things like looking
1045  * at the PATH env. variable, and adding reasonable extensions to the
1046  * command name given by the user. All reasonable versions of call_shell()
1047  * do this.
1048  * Alternatively, if on Unix and redirecting input or output, but not both,
1049  * and the 'shelltemp' option isn't set, use pipes.
1050  * We use input redirection if do_in is TRUE.
1051  * We use output redirection if do_out is TRUE.
1052  */
1053     static void
do_filter(linenr_T line1,linenr_T line2,exarg_T * eap,char_u * cmd,int do_in,int do_out)1054 do_filter(
1055     linenr_T	line1,
1056     linenr_T	line2,
1057     exarg_T	*eap,		// for forced 'ff' and 'fenc'
1058     char_u	*cmd,
1059     int		do_in,
1060     int		do_out)
1061 {
1062     char_u	*itmp = NULL;
1063     char_u	*otmp = NULL;
1064     linenr_T	linecount;
1065     linenr_T	read_linecount;
1066     pos_T	cursor_save;
1067     char_u	*cmd_buf;
1068     buf_T	*old_curbuf = curbuf;
1069     int		shell_flags = 0;
1070     pos_T	orig_start = curbuf->b_op_start;
1071     pos_T	orig_end = curbuf->b_op_end;
1072     int		save_cmod_flags = cmdmod.cmod_flags;
1073 #ifdef FEAT_FILTERPIPE
1074     int		stmp = p_stmp;
1075 #endif
1076 
1077     if (*cmd == NUL)	    // no filter command
1078 	return;
1079 
1080     // Temporarily disable lockmarks since that's needed to propagate changed
1081     // regions of the buffer for foldUpdate(), linecount, etc.
1082     cmdmod.cmod_flags &= ~CMOD_LOCKMARKS;
1083 
1084     cursor_save = curwin->w_cursor;
1085     linecount = line2 - line1 + 1;
1086     curwin->w_cursor.lnum = line1;
1087     curwin->w_cursor.col = 0;
1088     changed_line_abv_curs();
1089     invalidate_botline();
1090 
1091     /*
1092      * When using temp files:
1093      * 1. * Form temp file names
1094      * 2. * Write the lines to a temp file
1095      * 3.   Run the filter command on the temp file
1096      * 4. * Read the output of the command into the buffer
1097      * 5. * Delete the original lines to be filtered
1098      * 6. * Remove the temp files
1099      *
1100      * When writing the input with a pipe or when catching the output with a
1101      * pipe only need to do 3.
1102      */
1103 
1104     if (do_out)
1105 	shell_flags |= SHELL_DOOUT;
1106 
1107 #ifdef FEAT_FILTERPIPE
1108 # ifdef VIMDLL
1109     if (!gui.in_use && !gui.starting)
1110 	stmp = 1;   // Console mode doesn't support filterpipe.
1111 # endif
1112 
1113     if (!do_in && do_out && !stmp)
1114     {
1115 	// Use a pipe to fetch stdout of the command, do not use a temp file.
1116 	shell_flags |= SHELL_READ;
1117 	curwin->w_cursor.lnum = line2;
1118     }
1119     else if (do_in && !do_out && !stmp)
1120     {
1121 	// Use a pipe to write stdin of the command, do not use a temp file.
1122 	shell_flags |= SHELL_WRITE;
1123 	curbuf->b_op_start.lnum = line1;
1124 	curbuf->b_op_end.lnum = line2;
1125     }
1126     else if (do_in && do_out && !stmp)
1127     {
1128 	// Use a pipe to write stdin and fetch stdout of the command, do not
1129 	// use a temp file.
1130 	shell_flags |= SHELL_READ|SHELL_WRITE;
1131 	curbuf->b_op_start.lnum = line1;
1132 	curbuf->b_op_end.lnum = line2;
1133 	curwin->w_cursor.lnum = line2;
1134     }
1135     else
1136 #endif
1137 	if ((do_in && (itmp = vim_tempname('i', FALSE)) == NULL)
1138 		|| (do_out && (otmp = vim_tempname('o', FALSE)) == NULL))
1139 	{
1140 	    emsg(_(e_notmp));
1141 	    goto filterend;
1142 	}
1143 
1144 /*
1145  * The writing and reading of temp files will not be shown.
1146  * Vi also doesn't do this and the messages are not very informative.
1147  */
1148     ++no_wait_return;		// don't call wait_return() while busy
1149     if (itmp != NULL && buf_write(curbuf, itmp, NULL, line1, line2, eap,
1150 					   FALSE, FALSE, FALSE, TRUE) == FAIL)
1151     {
1152 	msg_putchar('\n');		// keep message from buf_write()
1153 	--no_wait_return;
1154 #if defined(FEAT_EVAL)
1155 	if (!aborting())
1156 #endif
1157 	    (void)semsg(_(e_notcreate), itmp);	// will call wait_return
1158 	goto filterend;
1159     }
1160     if (curbuf != old_curbuf)
1161 	goto filterend;
1162 
1163     if (!do_out)
1164 	msg_putchar('\n');
1165 
1166     // Create the shell command in allocated memory.
1167     cmd_buf = make_filter_cmd(cmd, itmp, otmp);
1168     if (cmd_buf == NULL)
1169 	goto filterend;
1170 
1171     windgoto((int)Rows - 1, 0);
1172     cursor_on();
1173 
1174     /*
1175      * When not redirecting the output the command can write anything to the
1176      * screen. If 'shellredir' is equal to ">", screen may be messed up by
1177      * stderr output of external command. Clear the screen later.
1178      * If do_in is FALSE, this could be something like ":r !cat", which may
1179      * also mess up the screen, clear it later.
1180      */
1181     if (!do_out || STRCMP(p_srr, ">") == 0 || !do_in)
1182 	redraw_later_clear();
1183 
1184     if (do_out)
1185     {
1186 	if (u_save((linenr_T)(line2), (linenr_T)(line2 + 1)) == FAIL)
1187 	{
1188 	    vim_free(cmd_buf);
1189 	    goto error;
1190 	}
1191 	redraw_curbuf_later(VALID);
1192     }
1193     read_linecount = curbuf->b_ml.ml_line_count;
1194 
1195     /*
1196      * When call_shell() fails wait_return() is called to give the user a
1197      * chance to read the error messages. Otherwise errors are ignored, so you
1198      * can see the error messages from the command that appear on stdout; use
1199      * 'u' to fix the text
1200      * Switch to cooked mode when not redirecting stdin, avoids that something
1201      * like ":r !cat" hangs.
1202      * Pass on the SHELL_DOOUT flag when the output is being redirected.
1203      */
1204     if (call_shell(cmd_buf, SHELL_FILTER | SHELL_COOKED | shell_flags))
1205     {
1206 	redraw_later_clear();
1207 	wait_return(FALSE);
1208     }
1209     vim_free(cmd_buf);
1210 
1211     did_check_timestamps = FALSE;
1212     need_check_timestamps = TRUE;
1213 
1214     // When interrupting the shell command, it may still have produced some
1215     // useful output.  Reset got_int here, so that readfile() won't cancel
1216     // reading.
1217     ui_breakcheck();
1218     got_int = FALSE;
1219 
1220     if (do_out)
1221     {
1222 	if (otmp != NULL)
1223 	{
1224 	    if (readfile(otmp, NULL, line2, (linenr_T)0, (linenr_T)MAXLNUM,
1225 						    eap, READ_FILTER) != OK)
1226 	    {
1227 #if defined(FEAT_EVAL)
1228 		if (!aborting())
1229 #endif
1230 		{
1231 		    msg_putchar('\n');
1232 		    semsg(_(e_notread), otmp);
1233 		}
1234 		goto error;
1235 	    }
1236 	    if (curbuf != old_curbuf)
1237 		goto filterend;
1238 	}
1239 
1240 	read_linecount = curbuf->b_ml.ml_line_count - read_linecount;
1241 
1242 	if (shell_flags & SHELL_READ)
1243 	{
1244 	    curbuf->b_op_start.lnum = line2 + 1;
1245 	    curbuf->b_op_end.lnum = curwin->w_cursor.lnum;
1246 	    appended_lines_mark(line2, read_linecount);
1247 	}
1248 
1249 	if (do_in)
1250 	{
1251 	    if ((cmdmod.cmod_flags & CMOD_KEEPMARKS)
1252 				     || vim_strchr(p_cpo, CPO_REMMARK) == NULL)
1253 	    {
1254 		if (read_linecount >= linecount)
1255 		    // move all marks from old lines to new lines
1256 		    mark_adjust(line1, line2, linecount, 0L);
1257 		else if (save_cmod_flags & CMOD_LOCKMARKS)
1258 		{
1259 		    // Move marks from the lines below the new lines down by
1260 		    // the number of lines lost.
1261 		    // Move marks from the lines that will be deleted to the
1262 		    // new lines and below.
1263 		    mark_adjust(line2 + 1, (linenr_T)MAXLNUM,
1264 					       linecount - read_linecount, 0L);
1265 		    mark_adjust(line1, line2, linecount, 0L);
1266 		}
1267 		else
1268 		{
1269 		    // move marks from old lines to new lines, delete marks
1270 		    // that are in deleted lines
1271 		    mark_adjust(line1, line1 + read_linecount - 1,
1272 								linecount, 0L);
1273 		    mark_adjust(line1 + read_linecount, line2, MAXLNUM, 0L);
1274 		}
1275 	    }
1276 
1277 	    /*
1278 	     * Put cursor on first filtered line for ":range!cmd".
1279 	     * Adjust '[ and '] (set by buf_write()).
1280 	     */
1281 	    curwin->w_cursor.lnum = line1;
1282 	    del_lines(linecount, TRUE);
1283 	    curbuf->b_op_start.lnum -= linecount;	// adjust '[
1284 	    curbuf->b_op_end.lnum -= linecount;		// adjust ']
1285 	    write_lnum_adjust(-linecount);		// adjust last line
1286 							// for next write
1287 #ifdef FEAT_FOLDING
1288 	    foldUpdate(curwin, curbuf->b_op_start.lnum, curbuf->b_op_end.lnum);
1289 #endif
1290 	}
1291 	else
1292 	{
1293 	    /*
1294 	     * Put cursor on last new line for ":r !cmd".
1295 	     */
1296 	    linecount = curbuf->b_op_end.lnum - curbuf->b_op_start.lnum + 1;
1297 	    curwin->w_cursor.lnum = curbuf->b_op_end.lnum;
1298 	}
1299 
1300 	beginline(BL_WHITE | BL_FIX);	    // cursor on first non-blank
1301 	--no_wait_return;
1302 
1303 	if (linecount > p_report)
1304 	{
1305 	    if (do_in)
1306 	    {
1307 		vim_snprintf(msg_buf, sizeof(msg_buf),
1308 				    _("%ld lines filtered"), (long)linecount);
1309 		if (msg(msg_buf) && !msg_scroll)
1310 		    // save message to display it after redraw
1311 		    set_keep_msg((char_u *)msg_buf, 0);
1312 	    }
1313 	    else
1314 		msgmore((long)linecount);
1315 	}
1316     }
1317     else
1318     {
1319 error:
1320 	// put cursor back in same position for ":w !cmd"
1321 	curwin->w_cursor = cursor_save;
1322 	--no_wait_return;
1323 	wait_return(FALSE);
1324     }
1325 
1326 filterend:
1327 
1328     cmdmod.cmod_flags = save_cmod_flags;
1329     if (curbuf != old_curbuf)
1330     {
1331 	--no_wait_return;
1332 	emsg(_("E135: *Filter* Autocommands must not change current buffer"));
1333     }
1334     else if (cmdmod.cmod_flags & CMOD_LOCKMARKS)
1335     {
1336 	curbuf->b_op_start = orig_start;
1337 	curbuf->b_op_end = orig_end;
1338     }
1339 
1340     if (itmp != NULL)
1341 	mch_remove(itmp);
1342     if (otmp != NULL)
1343 	mch_remove(otmp);
1344     vim_free(itmp);
1345     vim_free(otmp);
1346 }
1347 
1348 /*
1349  * Call a shell to execute a command.
1350  * When "cmd" is NULL start an interactive shell.
1351  */
1352     void
do_shell(char_u * cmd,int flags)1353 do_shell(
1354     char_u	*cmd,
1355     int		flags)	// may be SHELL_DOOUT when output is redirected
1356 {
1357     buf_T	*buf;
1358 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
1359     int		save_nwr;
1360 #endif
1361 #ifdef MSWIN
1362     int		winstart = FALSE;
1363 #endif
1364     int		keep_termcap = !termcap_active;
1365 
1366     /*
1367      * Disallow shell commands for "rvim".
1368      * Disallow shell commands from .exrc and .vimrc in current directory for
1369      * security reasons.
1370      */
1371     if (check_restricted() || check_secure())
1372     {
1373 	msg_end();
1374 	return;
1375     }
1376 
1377 #ifdef MSWIN
1378     /*
1379      * Check if ":!start" is used.  This implies not stopping termcap mode.
1380      */
1381     if (cmd != NULL)
1382 	keep_termcap = winstart = (STRNICMP(cmd, "start ", 6) == 0);
1383 
1384 # if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
1385     // Don't stop termcap mode when using a terminal window for the shell.
1386     if (gui.in_use && vim_strchr(p_go, GO_TERMINAL) != NULL)
1387 	keep_termcap = TRUE;
1388 # endif
1389 #endif
1390 
1391     /*
1392      * For autocommands we want to get the output on the current screen, to
1393      * avoid having to type return below.
1394      */
1395     msg_putchar('\r');			// put cursor at start of line
1396     if (!autocmd_busy)
1397     {
1398 	if (!keep_termcap)
1399 	    stoptermcap();
1400     }
1401 #ifdef MSWIN
1402     if (!winstart)
1403 #endif
1404 	msg_putchar('\n');		// may shift screen one line up
1405 
1406     // warning message before calling the shell
1407     if (p_warn && !autocmd_busy && msg_silent == 0)
1408 	FOR_ALL_BUFFERS(buf)
1409 	    if (bufIsChangedNotTerm(buf))
1410 	    {
1411 #ifdef FEAT_GUI_MSWIN
1412 		if (!keep_termcap)
1413 		    starttermcap();	// don't want a message box here
1414 #endif
1415 		msg_puts(_("[No write since last change]\n"));
1416 #ifdef FEAT_GUI_MSWIN
1417 		if (!keep_termcap)
1418 		    stoptermcap();
1419 #endif
1420 		break;
1421 	    }
1422 
1423     // This windgoto is required for when the '\n' resulted in a "delete line
1424     // 1" command to the terminal.
1425     if (!swapping_screen())
1426 	windgoto(msg_row, msg_col);
1427     cursor_on();
1428     (void)call_shell(cmd, SHELL_COOKED | flags);
1429     did_check_timestamps = FALSE;
1430     need_check_timestamps = TRUE;
1431 
1432     /*
1433      * put the message cursor at the end of the screen, avoids wait_return()
1434      * to overwrite the text that the external command showed
1435      */
1436     if (!swapping_screen())
1437     {
1438 	msg_row = Rows - 1;
1439 	msg_col = 0;
1440     }
1441 
1442     if (autocmd_busy)
1443     {
1444 	if (msg_silent == 0)
1445 	    redraw_later_clear();
1446     }
1447     else
1448     {
1449 	/*
1450 	 * For ":sh" there is no need to call wait_return(), just redraw.
1451 	 * Also for the Win32 GUI (the output is in a console window).
1452 	 * Otherwise there is probably text on the screen that the user wants
1453 	 * to read before redrawing, so call wait_return().
1454 	 */
1455 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
1456 # ifdef VIMDLL
1457 	if (!gui.in_use)
1458 # endif
1459 	{
1460 	    if (cmd == NULL
1461 # ifdef MSWIN
1462 		    || (keep_termcap && !need_wait_return)
1463 # endif
1464 	       )
1465 	    {
1466 		if (msg_silent == 0)
1467 		    redraw_later_clear();
1468 		need_wait_return = FALSE;
1469 	    }
1470 	    else
1471 	    {
1472 		/*
1473 		 * If we switch screens when starttermcap() is called, we
1474 		 * really want to wait for "hit return to continue".
1475 		 */
1476 		save_nwr = no_wait_return;
1477 		if (swapping_screen())
1478 		    no_wait_return = FALSE;
1479 # ifdef AMIGA
1480 		wait_return(term_console ? -1 : msg_silent == 0); // see below
1481 # else
1482 		wait_return(msg_silent == 0);
1483 # endif
1484 		no_wait_return = save_nwr;
1485 	    }
1486 	}
1487 #endif // FEAT_GUI_MSWIN
1488 
1489 	if (!keep_termcap)	// if keep_termcap is TRUE didn't stop termcap
1490 	    starttermcap();	// start termcap if not done by wait_return()
1491 
1492 	/*
1493 	 * In an Amiga window redrawing is caused by asking the window size.
1494 	 * If we got an interrupt this will not work. The chance that the
1495 	 * window size is wrong is very small, but we need to redraw the
1496 	 * screen.  Don't do this if ':' hit in wait_return().	THIS IS UGLY
1497 	 * but it saves an extra redraw.
1498 	 */
1499 #ifdef AMIGA
1500 	if (skip_redraw)		// ':' hit in wait_return()
1501 	{
1502 	    if (msg_silent == 0)
1503 		redraw_later_clear();
1504 	}
1505 	else if (term_console)
1506 	{
1507 	    OUT_STR(IF_EB("\033[0 q", ESC_STR "[0 q"));	// get window size
1508 	    if (got_int && msg_silent == 0)
1509 		redraw_later_clear();	// if got_int is TRUE, redraw needed
1510 	    else
1511 		must_redraw = 0;	// no extra redraw needed
1512 	}
1513 #endif
1514     }
1515 
1516     // display any error messages now
1517     display_errors();
1518 
1519     apply_autocmds(EVENT_SHELLCMDPOST, NULL, NULL, FALSE, curbuf);
1520 }
1521 
1522 #if !defined(UNIX)
1523     static char_u *
find_pipe(char_u * cmd)1524 find_pipe(char_u *cmd)
1525 {
1526     char_u  *p;
1527     int	    inquote = FALSE;
1528 
1529     for (p = cmd; *p != NUL; ++p)
1530     {
1531 	if (!inquote && *p == '|')
1532 	    return p;
1533 	if (*p == '"')
1534 	    inquote = !inquote;
1535 	else if (rem_backslash(p))
1536 	    ++p;
1537     }
1538     return NULL;
1539 }
1540 #endif
1541 
1542 /*
1543  * Create a shell command from a command string, input redirection file and
1544  * output redirection file.
1545  * Returns an allocated string with the shell command, or NULL for failure.
1546  */
1547     char_u *
make_filter_cmd(char_u * cmd,char_u * itmp,char_u * otmp)1548 make_filter_cmd(
1549     char_u	*cmd,		// command
1550     char_u	*itmp,		// NULL or name of input file
1551     char_u	*otmp)		// NULL or name of output file
1552 {
1553     char_u	*buf;
1554     long_u	len;
1555 
1556 #if defined(UNIX)
1557     int		is_fish_shell;
1558     char_u	*shell_name = get_isolated_shell_name();
1559 
1560     if (shell_name == NULL)
1561 	return NULL;
1562 
1563     // Account for fish's different syntax for subshells
1564     is_fish_shell = (fnamecmp(shell_name, "fish") == 0);
1565     vim_free(shell_name);
1566     if (is_fish_shell)
1567 	len = (long_u)STRLEN(cmd) + 13;		// "begin; " + "; end" + NUL
1568     else
1569 #endif
1570 	len = (long_u)STRLEN(cmd) + 3;			// "()" + NUL
1571     if (itmp != NULL)
1572 	len += (long_u)STRLEN(itmp) + 9;		// " { < " + " } "
1573     if (otmp != NULL)
1574 	len += (long_u)STRLEN(otmp) + (long_u)STRLEN(p_srr) + 2; // "  "
1575     buf = alloc(len);
1576     if (buf == NULL)
1577 	return NULL;
1578 
1579 #if defined(UNIX)
1580     /*
1581      * Put braces around the command (for concatenated commands) when
1582      * redirecting input and/or output.
1583      */
1584     if (itmp != NULL || otmp != NULL)
1585     {
1586 	if (is_fish_shell)
1587 	    vim_snprintf((char *)buf, len, "begin; %s; end", (char *)cmd);
1588 	else
1589 	    vim_snprintf((char *)buf, len, "(%s)", (char *)cmd);
1590     }
1591     else
1592 	STRCPY(buf, cmd);
1593     if (itmp != NULL)
1594     {
1595 	STRCAT(buf, " < ");
1596 	STRCAT(buf, itmp);
1597     }
1598 #else
1599     // For shells that don't understand braces around commands, at least allow
1600     // the use of commands in a pipe.
1601     if (*p_sxe != NUL && *p_sxq == '(')
1602     {
1603 	if (itmp != NULL || otmp != NULL)
1604 	    vim_snprintf((char *)buf, len, "(%s)", (char *)cmd);
1605 	else
1606 	    STRCPY(buf, cmd);
1607 	if (itmp != NULL)
1608 	{
1609 	    STRCAT(buf, " < ");
1610 	    STRCAT(buf, itmp);
1611 	}
1612     }
1613     else
1614     {
1615 	STRCPY(buf, cmd);
1616 	if (itmp != NULL)
1617 	{
1618 	    char_u	*p;
1619 
1620 	    // If there is a pipe, we have to put the '<' in front of it.
1621 	    // Don't do this when 'shellquote' is not empty, otherwise the
1622 	    // redirection would be inside the quotes.
1623 	    if (*p_shq == NUL)
1624 	    {
1625 		p = find_pipe(buf);
1626 		if (p != NULL)
1627 		    *p = NUL;
1628 	    }
1629 	    STRCAT(buf, " <");	// " < " causes problems on Amiga
1630 	    STRCAT(buf, itmp);
1631 	    if (*p_shq == NUL)
1632 	    {
1633 		p = find_pipe(cmd);
1634 		if (p != NULL)
1635 		{
1636 		    STRCAT(buf, " ");  // insert a space before the '|' for DOS
1637 		    STRCAT(buf, p);
1638 		}
1639 	    }
1640 	}
1641     }
1642 #endif
1643     if (otmp != NULL)
1644 	append_redir(buf, (int)len, p_srr, otmp);
1645 
1646     return buf;
1647 }
1648 
1649 /*
1650  * Append output redirection for file "fname" to the end of string buffer
1651  * "buf[buflen]"
1652  * Works with the 'shellredir' and 'shellpipe' options.
1653  * The caller should make sure that there is enough room:
1654  *	STRLEN(opt) + STRLEN(fname) + 3
1655  */
1656     void
append_redir(char_u * buf,int buflen,char_u * opt,char_u * fname)1657 append_redir(
1658     char_u	*buf,
1659     int		buflen,
1660     char_u	*opt,
1661     char_u	*fname)
1662 {
1663     char_u	*p;
1664     char_u	*end;
1665 
1666     end = buf + STRLEN(buf);
1667     // find "%s"
1668     for (p = opt; (p = vim_strchr(p, '%')) != NULL; ++p)
1669     {
1670 	if (p[1] == 's') // found %s
1671 	    break;
1672 	if (p[1] == '%') // skip %%
1673 	    ++p;
1674     }
1675     if (p != NULL)
1676     {
1677 #ifdef MSWIN
1678 	*end++ = ' '; // not really needed? Not with sh, ksh or bash
1679 #endif
1680 	vim_snprintf((char *)end, (size_t)(buflen - (end - buf)),
1681 						  (char *)opt, (char *)fname);
1682     }
1683     else
1684 	vim_snprintf((char *)end, (size_t)(buflen - (end - buf)),
1685 #ifdef FEAT_QUICKFIX
1686 		" %s %s",
1687 #else
1688 		" %s%s",	// " > %s" causes problems on Amiga
1689 #endif
1690 		(char *)opt, (char *)fname);
1691 }
1692 
1693 /*
1694  * Implementation of ":fixdel", also used by get_stty().
1695  *  <BS>    resulting <Del>
1696  *   ^?		^H
1697  * not ^?	^?
1698  */
1699     void
do_fixdel(exarg_T * eap UNUSED)1700 do_fixdel(exarg_T *eap UNUSED)
1701 {
1702     char_u  *p;
1703 
1704     p = find_termcode((char_u *)"kb");
1705     add_termcode((char_u *)"kD", p != NULL
1706 	    && *p == DEL ? (char_u *)CTRL_H_STR : DEL_STR, FALSE);
1707 }
1708 
1709     void
print_line_no_prefix(linenr_T lnum,int use_number,int list)1710 print_line_no_prefix(
1711     linenr_T	lnum,
1712     int		use_number,
1713     int		list)
1714 {
1715     char	numbuf[30];
1716 
1717     if (curwin->w_p_nu || use_number)
1718     {
1719 	vim_snprintf(numbuf, sizeof(numbuf),
1720 				   "%*ld ", number_width(curwin), (long)lnum);
1721 	msg_puts_attr(numbuf, HL_ATTR(HLF_N));	// Highlight line nrs
1722     }
1723     msg_prt_line(ml_get(lnum), list);
1724 }
1725 
1726 /*
1727  * Print a text line.  Also in silent mode ("ex -s").
1728  */
1729     void
print_line(linenr_T lnum,int use_number,int list)1730 print_line(linenr_T lnum, int use_number, int list)
1731 {
1732     int		save_silent = silent_mode;
1733 
1734     // apply :filter /pat/
1735     if (message_filtered(ml_get(lnum)))
1736 	return;
1737 
1738     msg_start();
1739     silent_mode = FALSE;
1740     info_message = TRUE;	// use mch_msg(), not mch_errmsg()
1741     print_line_no_prefix(lnum, use_number, list);
1742     if (save_silent)
1743     {
1744 	msg_putchar('\n');
1745 	cursor_on();		// msg_start() switches it off
1746 	out_flush();
1747 	silent_mode = save_silent;
1748     }
1749     info_message = FALSE;
1750 }
1751 
1752     int
rename_buffer(char_u * new_fname)1753 rename_buffer(char_u *new_fname)
1754 {
1755     char_u	*fname, *sfname, *xfname;
1756     buf_T	*buf;
1757 
1758     buf = curbuf;
1759     apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
1760     // buffer changed, don't change name now
1761     if (buf != curbuf)
1762 	return FAIL;
1763 #ifdef FEAT_EVAL
1764     if (aborting())	    // autocmds may abort script processing
1765 	return FAIL;
1766 #endif
1767     /*
1768      * The name of the current buffer will be changed.
1769      * A new (unlisted) buffer entry needs to be made to hold the old file
1770      * name, which will become the alternate file name.
1771      * But don't set the alternate file name if the buffer didn't have a
1772      * name.
1773      */
1774     fname = curbuf->b_ffname;
1775     sfname = curbuf->b_sfname;
1776     xfname = curbuf->b_fname;
1777     curbuf->b_ffname = NULL;
1778     curbuf->b_sfname = NULL;
1779     if (setfname(curbuf, new_fname, NULL, TRUE) == FAIL)
1780     {
1781 	curbuf->b_ffname = fname;
1782 	curbuf->b_sfname = sfname;
1783 	return FAIL;
1784     }
1785     curbuf->b_flags |= BF_NOTEDITED;
1786     if (xfname != NULL && *xfname != NUL)
1787     {
1788 	buf = buflist_new(fname, xfname, curwin->w_cursor.lnum, 0);
1789 	if (buf != NULL && (cmdmod.cmod_flags & CMOD_KEEPALT) == 0)
1790 	    curwin->w_alt_fnum = buf->b_fnum;
1791     }
1792     vim_free(fname);
1793     vim_free(sfname);
1794     apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
1795 
1796     // Change directories when the 'acd' option is set.
1797     DO_AUTOCHDIR;
1798     return OK;
1799 }
1800 
1801 /*
1802  * ":file[!] [fname]".
1803  */
1804     void
ex_file(exarg_T * eap)1805 ex_file(exarg_T *eap)
1806 {
1807     // ":0file" removes the file name.  Check for illegal uses ":3file",
1808     // "0file name", etc.
1809     if (eap->addr_count > 0
1810 	    && (*eap->arg != NUL
1811 		|| eap->line2 > 0
1812 		|| eap->addr_count > 1))
1813     {
1814 	emsg(_(e_invarg));
1815 	return;
1816     }
1817 
1818     if (*eap->arg != NUL || eap->addr_count == 1)
1819     {
1820 	if (rename_buffer(eap->arg) == FAIL)
1821 	    return;
1822 	redraw_tabline = TRUE;
1823     }
1824 
1825     // print file name if no argument or 'F' is not in 'shortmess'
1826     if (*eap->arg == NUL || !shortmess(SHM_FILEINFO))
1827 	fileinfo(FALSE, FALSE, eap->forceit);
1828 }
1829 
1830 /*
1831  * ":update".
1832  */
1833     void
ex_update(exarg_T * eap)1834 ex_update(exarg_T *eap)
1835 {
1836     if (curbufIsChanged())
1837 	(void)do_write(eap);
1838 }
1839 
1840 /*
1841  * ":write" and ":saveas".
1842  */
1843     void
ex_write(exarg_T * eap)1844 ex_write(exarg_T *eap)
1845 {
1846     if (eap->cmdidx == CMD_saveas)
1847     {
1848 	// :saveas does not take a range, uses all lines.
1849 	eap->line1 = 1;
1850 	eap->line2 = curbuf->b_ml.ml_line_count;
1851     }
1852 
1853     if (eap->usefilter)		// input lines to shell command
1854 	do_bang(1, eap, FALSE, TRUE, FALSE);
1855     else
1856 	(void)do_write(eap);
1857 }
1858 
1859 #ifdef UNIX
1860     static int
check_writable(char_u * fname)1861 check_writable(char_u *fname)
1862 {
1863     if (mch_nodetype(fname) == NODE_OTHER)
1864     {
1865 	semsg(_("E503: \"%s\" is not a file or writable device"), fname);
1866 	return FAIL;
1867     }
1868     return OK;
1869 }
1870 #endif
1871 
1872 /*
1873  * write current buffer to file 'eap->arg'
1874  * if 'eap->append' is TRUE, append to the file
1875  *
1876  * if *eap->arg == NUL write to current file
1877  *
1878  * return FAIL for failure, OK otherwise
1879  */
1880     int
do_write(exarg_T * eap)1881 do_write(exarg_T *eap)
1882 {
1883     int		other;
1884     char_u	*fname = NULL;		// init to shut up gcc
1885     char_u	*ffname;
1886     int		retval = FAIL;
1887     char_u	*free_fname = NULL;
1888 #ifdef FEAT_BROWSE
1889     char_u	*browse_file = NULL;
1890 #endif
1891     buf_T	*alt_buf = NULL;
1892     int		name_was_missing;
1893 
1894     if (not_writing())		// check 'write' option
1895 	return FAIL;
1896 
1897     ffname = eap->arg;
1898 #ifdef FEAT_BROWSE
1899     if ((cmdmod.cmod_flags & CMOD_BROWSE) && !exiting)
1900     {
1901 	browse_file = do_browse(BROWSE_SAVE, (char_u *)_("Save As"), ffname,
1902 						    NULL, NULL, NULL, curbuf);
1903 	if (browse_file == NULL)
1904 	    goto theend;
1905 	ffname = browse_file;
1906     }
1907 #endif
1908     if (*ffname == NUL)
1909     {
1910 	if (eap->cmdidx == CMD_saveas)
1911 	{
1912 	    emsg(_(e_argreq));
1913 	    goto theend;
1914 	}
1915 	other = FALSE;
1916     }
1917     else
1918     {
1919 	fname = ffname;
1920 	free_fname = fix_fname(ffname);
1921 	/*
1922 	 * When out-of-memory, keep unexpanded file name, because we MUST be
1923 	 * able to write the file in this situation.
1924 	 */
1925 	if (free_fname != NULL)
1926 	    ffname = free_fname;
1927 	other = otherfile(ffname);
1928     }
1929 
1930     /*
1931      * If we have a new file, put its name in the list of alternate file names.
1932      */
1933     if (other)
1934     {
1935 	if (vim_strchr(p_cpo, CPO_ALTWRITE) != NULL
1936 						 || eap->cmdidx == CMD_saveas)
1937 	    alt_buf = setaltfname(ffname, fname, (linenr_T)1);
1938 	else
1939 	    alt_buf = buflist_findname(ffname);
1940 	if (alt_buf != NULL && alt_buf->b_ml.ml_mfp != NULL)
1941 	{
1942 	    // Overwriting a file that is loaded in another buffer is not a
1943 	    // good idea.
1944 	    emsg(_(e_bufloaded));
1945 	    goto theend;
1946 	}
1947     }
1948 
1949     /*
1950      * Writing to the current file is not allowed in readonly mode
1951      * and a file name is required.
1952      * "nofile" and "nowrite" buffers cannot be written implicitly either.
1953      */
1954     if (!other && (
1955 #ifdef FEAT_QUICKFIX
1956 		bt_dontwrite_msg(curbuf) ||
1957 #endif
1958 		check_fname() == FAIL
1959 #ifdef UNIX
1960 		|| check_writable(curbuf->b_ffname) == FAIL
1961 #endif
1962 		|| check_readonly(&eap->forceit, curbuf)))
1963 	goto theend;
1964 
1965     if (!other)
1966     {
1967 	ffname = curbuf->b_ffname;
1968 	fname = curbuf->b_fname;
1969 	/*
1970 	 * Not writing the whole file is only allowed with '!'.
1971 	 */
1972 	if (	   (eap->line1 != 1
1973 		    || eap->line2 != curbuf->b_ml.ml_line_count)
1974 		&& !eap->forceit
1975 		&& !eap->append
1976 		&& !p_wa)
1977 	{
1978 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1979 	    if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM))
1980 	    {
1981 		if (vim_dialog_yesno(VIM_QUESTION, NULL,
1982 			       (char_u *)_("Write partial file?"), 2) != VIM_YES)
1983 		    goto theend;
1984 		eap->forceit = TRUE;
1985 	    }
1986 	    else
1987 #endif
1988 	    {
1989 		emsg(_("E140: Use ! to write partial buffer"));
1990 		goto theend;
1991 	    }
1992 	}
1993     }
1994 
1995     if (check_overwrite(eap, curbuf, fname, ffname, other) == OK)
1996     {
1997 	if (eap->cmdidx == CMD_saveas && alt_buf != NULL)
1998 	{
1999 	    buf_T	*was_curbuf = curbuf;
2000 
2001 	    apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, curbuf);
2002 	    apply_autocmds(EVENT_BUFFILEPRE, NULL, NULL, FALSE, alt_buf);
2003 #ifdef FEAT_EVAL
2004 	    if (curbuf != was_curbuf || aborting())
2005 #else
2006 	    if (curbuf != was_curbuf)
2007 #endif
2008 	    {
2009 		// buffer changed, don't change name now
2010 		retval = FAIL;
2011 		goto theend;
2012 	    }
2013 	    // Exchange the file names for the current and the alternate
2014 	    // buffer.  This makes it look like we are now editing the buffer
2015 	    // under the new name.  Must be done before buf_write(), because
2016 	    // if there is no file name and 'cpo' contains 'F', it will set
2017 	    // the file name.
2018 	    fname = alt_buf->b_fname;
2019 	    alt_buf->b_fname = curbuf->b_fname;
2020 	    curbuf->b_fname = fname;
2021 	    fname = alt_buf->b_ffname;
2022 	    alt_buf->b_ffname = curbuf->b_ffname;
2023 	    curbuf->b_ffname = fname;
2024 	    fname = alt_buf->b_sfname;
2025 	    alt_buf->b_sfname = curbuf->b_sfname;
2026 	    curbuf->b_sfname = fname;
2027 	    buf_name_changed(curbuf);
2028 
2029 	    apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, curbuf);
2030 	    apply_autocmds(EVENT_BUFFILEPOST, NULL, NULL, FALSE, alt_buf);
2031 	    if (!alt_buf->b_p_bl)
2032 	    {
2033 		alt_buf->b_p_bl = TRUE;
2034 		apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, alt_buf);
2035 	    }
2036 #ifdef FEAT_EVAL
2037 	    if (curbuf != was_curbuf || aborting())
2038 #else
2039 	    if (curbuf != was_curbuf)
2040 #endif
2041 	    {
2042 		// buffer changed, don't write the file
2043 		retval = FAIL;
2044 		goto theend;
2045 	    }
2046 
2047 	    // If 'filetype' was empty try detecting it now.
2048 	    if (*curbuf->b_p_ft == NUL)
2049 	    {
2050 		if (au_has_group((char_u *)"filetypedetect"))
2051 		    (void)do_doautocmd((char_u *)"filetypedetect BufRead",
2052 								  TRUE, NULL);
2053 		do_modelines(0);
2054 	    }
2055 
2056 	    // Autocommands may have changed buffer names, esp. when
2057 	    // 'autochdir' is set.
2058 	    fname = curbuf->b_sfname;
2059 	}
2060 
2061 	name_was_missing = curbuf->b_ffname == NULL;
2062 
2063 	retval = buf_write(curbuf, ffname, fname, eap->line1, eap->line2,
2064 				 eap, eap->append, eap->forceit, TRUE, FALSE);
2065 
2066 	// After ":saveas fname" reset 'readonly'.
2067 	if (eap->cmdidx == CMD_saveas)
2068 	{
2069 	    if (retval == OK)
2070 	    {
2071 		curbuf->b_p_ro = FALSE;
2072 		redraw_tabline = TRUE;
2073 	    }
2074 	}
2075 
2076 	// Change directories when the 'acd' option is set and the file name
2077 	// got changed or set.
2078 	if (eap->cmdidx == CMD_saveas || name_was_missing)
2079 	    DO_AUTOCHDIR;
2080     }
2081 
2082 theend:
2083 #ifdef FEAT_BROWSE
2084     vim_free(browse_file);
2085 #endif
2086     vim_free(free_fname);
2087     return retval;
2088 }
2089 
2090 /*
2091  * Check if it is allowed to overwrite a file.  If b_flags has BF_NOTEDITED,
2092  * BF_NEW or BF_READERR, check for overwriting current file.
2093  * May set eap->forceit if a dialog says it's OK to overwrite.
2094  * Return OK if it's OK, FAIL if it is not.
2095  */
2096     int
check_overwrite(exarg_T * eap,buf_T * buf,char_u * fname,char_u * ffname,int other)2097 check_overwrite(
2098     exarg_T	*eap,
2099     buf_T	*buf,
2100     char_u	*fname,	    // file name to be used (can differ from
2101 			    // buf->ffname)
2102     char_u	*ffname,    // full path version of fname
2103     int		other)	    // writing under other name
2104 {
2105     /*
2106      * Write to another file or b_flags set or not writing the whole file:
2107      * overwriting only allowed with '!'.
2108      */
2109     if (       (other
2110 		|| (buf->b_flags & BF_NOTEDITED)
2111 		|| ((buf->b_flags & BF_NEW)
2112 		    && vim_strchr(p_cpo, CPO_OVERNEW) == NULL)
2113 		|| (buf->b_flags & BF_READERR))
2114 	    && !p_wa
2115 	    && vim_fexists(ffname))
2116     {
2117 	if (!eap->forceit && !eap->append)
2118 	{
2119 #ifdef UNIX
2120 	    // with UNIX it is possible to open a directory
2121 	    if (mch_isdir(ffname))
2122 	    {
2123 		semsg(_(e_src_is_directory), ffname);
2124 		return FAIL;
2125 	    }
2126 #endif
2127 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2128 	    if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM))
2129 	    {
2130 		char_u	buff[DIALOG_MSG_SIZE];
2131 
2132 		dialog_msg(buff, _("Overwrite existing file \"%s\"?"), fname);
2133 		if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) != VIM_YES)
2134 		    return FAIL;
2135 		eap->forceit = TRUE;
2136 	    }
2137 	    else
2138 #endif
2139 	    {
2140 		emsg(_(e_file_exists));
2141 		return FAIL;
2142 	    }
2143 	}
2144 
2145 	// For ":w! filename" check that no swap file exists for "filename".
2146 	if (other && !emsg_silent)
2147 	{
2148 	    char_u	*dir;
2149 	    char_u	*p;
2150 	    int		r;
2151 	    char_u	*swapname;
2152 
2153 	    // We only try the first entry in 'directory', without checking if
2154 	    // it's writable.  If the "." directory is not writable the write
2155 	    // will probably fail anyway.
2156 	    // Use 'shortname' of the current buffer, since there is no buffer
2157 	    // for the written file.
2158 	    if (*p_dir == NUL)
2159 	    {
2160 		dir = alloc(5);
2161 		if (dir == NULL)
2162 		    return FAIL;
2163 		STRCPY(dir, ".");
2164 	    }
2165 	    else
2166 	    {
2167 		dir = alloc(MAXPATHL);
2168 		if (dir == NULL)
2169 		    return FAIL;
2170 		p = p_dir;
2171 		copy_option_part(&p, dir, MAXPATHL, ",");
2172 	    }
2173 	    swapname = makeswapname(fname, ffname, curbuf, dir);
2174 	    vim_free(dir);
2175 	    r = vim_fexists(swapname);
2176 	    if (r)
2177 	    {
2178 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2179 		if (p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM))
2180 		{
2181 		    char_u	buff[DIALOG_MSG_SIZE];
2182 
2183 		    dialog_msg(buff,
2184 			    _("Swap file \"%s\" exists, overwrite anyway?"),
2185 								    swapname);
2186 		    if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2)
2187 								   != VIM_YES)
2188 		    {
2189 			vim_free(swapname);
2190 			return FAIL;
2191 		    }
2192 		    eap->forceit = TRUE;
2193 		}
2194 		else
2195 #endif
2196 		{
2197 		    semsg(_("E768: Swap file exists: %s (:silent! overrides)"),
2198 								    swapname);
2199 		    vim_free(swapname);
2200 		    return FAIL;
2201 		}
2202 	    }
2203 	    vim_free(swapname);
2204 	}
2205     }
2206     return OK;
2207 }
2208 
2209 /*
2210  * Handle ":wnext", ":wNext" and ":wprevious" commands.
2211  */
2212     void
ex_wnext(exarg_T * eap)2213 ex_wnext(exarg_T *eap)
2214 {
2215     int		i;
2216 
2217     if (eap->cmd[1] == 'n')
2218 	i = curwin->w_arg_idx + (int)eap->line2;
2219     else
2220 	i = curwin->w_arg_idx - (int)eap->line2;
2221     eap->line1 = 1;
2222     eap->line2 = curbuf->b_ml.ml_line_count;
2223     if (do_write(eap) != FAIL)
2224 	do_argfile(eap, i);
2225 }
2226 
2227 /*
2228  * ":wall", ":wqall" and ":xall": Write all changed files (and exit).
2229  */
2230     void
do_wqall(exarg_T * eap)2231 do_wqall(exarg_T *eap)
2232 {
2233     buf_T	*buf;
2234     int		error = 0;
2235     int		save_forceit = eap->forceit;
2236 
2237     if (eap->cmdidx == CMD_xall || eap->cmdidx == CMD_wqall)
2238 	exiting = TRUE;
2239 
2240     FOR_ALL_BUFFERS(buf)
2241     {
2242 #ifdef FEAT_TERMINAL
2243 	if (exiting && term_job_running(buf->b_term))
2244 	{
2245 	    no_write_message_nobang(buf);
2246 	    ++error;
2247 	}
2248 	else
2249 #endif
2250 	if (bufIsChanged(buf) && !bt_dontwrite(buf))
2251 	{
2252 	    /*
2253 	     * Check if there is a reason the buffer cannot be written:
2254 	     * 1. if the 'write' option is set
2255 	     * 2. if there is no file name (even after browsing)
2256 	     * 3. if the 'readonly' is set (even after a dialog)
2257 	     * 4. if overwriting is allowed (even after a dialog)
2258 	     */
2259 	    if (not_writing())
2260 	    {
2261 		++error;
2262 		break;
2263 	    }
2264 #ifdef FEAT_BROWSE
2265 	    // ":browse wall": ask for file name if there isn't one
2266 	    if (buf->b_ffname == NULL && (cmdmod.cmod_flags & CMOD_BROWSE))
2267 		browse_save_fname(buf);
2268 #endif
2269 	    if (buf->b_ffname == NULL)
2270 	    {
2271 		semsg(_("E141: No file name for buffer %ld"),
2272 							    (long)buf->b_fnum);
2273 		++error;
2274 	    }
2275 	    else if (check_readonly(&eap->forceit, buf)
2276 		    || check_overwrite(eap, buf, buf->b_fname, buf->b_ffname,
2277 							       FALSE) == FAIL)
2278 	    {
2279 		++error;
2280 	    }
2281 	    else
2282 	    {
2283 		bufref_T bufref;
2284 
2285 		set_bufref(&bufref, buf);
2286 		if (buf_write_all(buf, eap->forceit) == FAIL)
2287 		    ++error;
2288 		// an autocommand may have deleted the buffer
2289 		if (!bufref_valid(&bufref))
2290 		    buf = firstbuf;
2291 	    }
2292 	    eap->forceit = save_forceit;    // check_overwrite() may set it
2293 	}
2294     }
2295     if (exiting)
2296     {
2297 	if (!error)
2298 	    getout(0);		// exit Vim
2299 	not_exiting();
2300     }
2301 }
2302 
2303 /*
2304  * Check the 'write' option.
2305  * Return TRUE and give a message when it's not set.
2306  */
2307     static int
not_writing(void)2308 not_writing(void)
2309 {
2310     if (p_write)
2311 	return FALSE;
2312     emsg(_("E142: File not written: Writing is disabled by 'write' option"));
2313     return TRUE;
2314 }
2315 
2316 /*
2317  * Check if a buffer is read-only (either 'readonly' option is set or file is
2318  * read-only). Ask for overruling in a dialog. Return TRUE and give an error
2319  * message when the buffer is readonly.
2320  */
2321     static int
check_readonly(int * forceit,buf_T * buf)2322 check_readonly(int *forceit, buf_T *buf)
2323 {
2324     stat_T	st;
2325 
2326     // Handle a file being readonly when the 'readonly' option is set or when
2327     // the file exists and permissions are read-only.
2328     // We will send 0777 to check_file_readonly(), as the "perm" variable is
2329     // important for device checks but not here.
2330     if (!*forceit && (buf->b_p_ro
2331 		|| (mch_stat((char *)buf->b_ffname, &st) >= 0
2332 		    && check_file_readonly(buf->b_ffname, 0777))))
2333     {
2334 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2335 	if ((p_confirm || (cmdmod.cmod_flags & CMOD_CONFIRM))
2336 						       && buf->b_fname != NULL)
2337 	{
2338 	    char_u	buff[DIALOG_MSG_SIZE];
2339 
2340 	    if (buf->b_p_ro)
2341 		dialog_msg(buff, _("'readonly' option is set for \"%s\".\nDo you wish to write anyway?"),
2342 		    buf->b_fname);
2343 	    else
2344 		dialog_msg(buff, _("File permissions of \"%s\" are read-only.\nIt may still be possible to write it.\nDo you wish to try?"),
2345 		    buf->b_fname);
2346 
2347 	    if (vim_dialog_yesno(VIM_QUESTION, NULL, buff, 2) == VIM_YES)
2348 	    {
2349 		// Set forceit, to force the writing of a readonly file
2350 		*forceit = TRUE;
2351 		return FALSE;
2352 	    }
2353 	    else
2354 		return TRUE;
2355 	}
2356 	else
2357 #endif
2358 	if (buf->b_p_ro)
2359 	    emsg(_(e_readonly_option_is_set_add_bang_to_override));
2360 	else
2361 	    semsg(_("E505: \"%s\" is read-only (add ! to override)"),
2362 		    buf->b_fname);
2363 	return TRUE;
2364     }
2365 
2366     return FALSE;
2367 }
2368 
2369 /*
2370  * Try to abandon the current file and edit a new or existing file.
2371  * "fnum" is the number of the file, if zero use "ffname_arg"/"sfname_arg".
2372  * "lnum" is the line number for the cursor in the new file (if non-zero).
2373  *
2374  * Return:
2375  * GETFILE_ERROR for "normal" error,
2376  * GETFILE_NOT_WRITTEN for "not written" error,
2377  * GETFILE_SAME_FILE for success
2378  * GETFILE_OPEN_OTHER for successfully opening another file.
2379  */
2380     int
getfile(int fnum,char_u * ffname_arg,char_u * sfname_arg,int setpm,linenr_T lnum,int forceit)2381 getfile(
2382     int		fnum,
2383     char_u	*ffname_arg,
2384     char_u	*sfname_arg,
2385     int		setpm,
2386     linenr_T	lnum,
2387     int		forceit)
2388 {
2389     char_u	*ffname = ffname_arg;
2390     char_u	*sfname = sfname_arg;
2391     int		other;
2392     int		retval;
2393     char_u	*free_me = NULL;
2394 
2395     if (text_locked())
2396 	return GETFILE_ERROR;
2397     if (curbuf_locked())
2398 	return GETFILE_ERROR;
2399 
2400     if (fnum == 0)
2401     {
2402 					// make ffname full path, set sfname
2403 	fname_expand(curbuf, &ffname, &sfname);
2404 	other = otherfile(ffname);
2405 	free_me = ffname;		// has been allocated, free() later
2406     }
2407     else
2408 	other = (fnum != curbuf->b_fnum);
2409 
2410     if (other)
2411 	++no_wait_return;	    // don't wait for autowrite message
2412     if (other && !forceit && curbuf->b_nwindows == 1 && !buf_hide(curbuf)
2413 		   && curbufIsChanged() && autowrite(curbuf, forceit) == FAIL)
2414     {
2415 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
2416 	if (p_confirm && p_write)
2417 	    dialog_changed(curbuf, FALSE);
2418 	if (curbufIsChanged())
2419 #endif
2420 	{
2421 	    if (other)
2422 		--no_wait_return;
2423 	    no_write_message();
2424 	    retval = GETFILE_NOT_WRITTEN;	// file has been changed
2425 	    goto theend;
2426 	}
2427     }
2428     if (other)
2429 	--no_wait_return;
2430     if (setpm)
2431 	setpcmark();
2432     if (!other)
2433     {
2434 	if (lnum != 0)
2435 	    curwin->w_cursor.lnum = lnum;
2436 	check_cursor_lnum();
2437 	beginline(BL_SOL | BL_FIX);
2438 	retval = GETFILE_SAME_FILE;	// it's in the same file
2439     }
2440     else if (do_ecmd(fnum, ffname, sfname, NULL, lnum,
2441 	     (buf_hide(curbuf) ? ECMD_HIDE : 0) + (forceit ? ECMD_FORCEIT : 0),
2442 		curwin) == OK)
2443 	retval = GETFILE_OPEN_OTHER;	// opened another file
2444     else
2445 	retval = GETFILE_ERROR;		// error encountered
2446 
2447 theend:
2448     vim_free(free_me);
2449     return retval;
2450 }
2451 
2452 /*
2453  * start editing a new file
2454  *
2455  *     fnum: file number; if zero use ffname/sfname
2456  *   ffname: the file name
2457  *		- full path if sfname used,
2458  *		- any file name if sfname is NULL
2459  *		- empty string to re-edit with the same file name (but may be
2460  *		    in a different directory)
2461  *		- NULL to start an empty buffer
2462  *   sfname: the short file name (or NULL)
2463  *	eap: contains the command to be executed after loading the file and
2464  *	     forced 'ff' and 'fenc'
2465  *  newlnum: if > 0: put cursor on this line number (if possible)
2466  *	     if ECMD_LASTL: use last position in loaded file
2467  *	     if ECMD_LAST: use last position in all files
2468  *	     if ECMD_ONE: use first line
2469  *    flags:
2470  *	   ECMD_HIDE: if TRUE don't free the current buffer
2471  *     ECMD_SET_HELP: set b_help flag of (new) buffer before opening file
2472  *	 ECMD_OLDBUF: use existing buffer if it exists
2473  *	ECMD_FORCEIT: ! used for Ex command
2474  *	 ECMD_ADDBUF: don't edit, just add to buffer list
2475  *	 ECMD_ALTBUF: like ECMD_ADDBUF and also set the alternate file
2476  *   ECMD_NOWINENTER: Do not trigger BufWinEnter
2477  *   oldwin: Should be "curwin" when editing a new buffer in the current
2478  *	     window, NULL when splitting the window first.  When not NULL info
2479  *	     of the previous buffer for "oldwin" is stored.
2480  *
2481  * return FAIL for failure, OK otherwise
2482  */
2483     int
do_ecmd(int fnum,char_u * ffname,char_u * sfname,exarg_T * eap,linenr_T newlnum,int flags,win_T * oldwin)2484 do_ecmd(
2485     int		fnum,
2486     char_u	*ffname,
2487     char_u	*sfname,
2488     exarg_T	*eap,			// can be NULL!
2489     linenr_T	newlnum,
2490     int		flags,
2491     win_T	*oldwin)
2492 {
2493     int		other_file;		// TRUE if editing another file
2494     int		oldbuf;			// TRUE if using existing buffer
2495     int		auto_buf = FALSE;	// TRUE if autocommands brought us
2496 					// into the buffer unexpectedly
2497     char_u	*new_name = NULL;
2498 #if defined(FEAT_EVAL)
2499     int		did_set_swapcommand = FALSE;
2500 #endif
2501     buf_T	*buf;
2502     bufref_T	bufref;
2503     bufref_T	old_curbuf;
2504     char_u	*free_fname = NULL;
2505 #ifdef FEAT_BROWSE
2506     char_u	dot_path[] = ".";
2507     char_u	*browse_file = NULL;
2508 #endif
2509     int		retval = FAIL;
2510     long	n;
2511     pos_T	orig_pos;
2512     linenr_T	topline = 0;
2513     int		newcol = -1;
2514     int		solcol = -1;
2515     pos_T	*pos;
2516     char_u	*command = NULL;
2517 #ifdef FEAT_SPELL
2518     int		did_get_winopts = FALSE;
2519 #endif
2520     int		readfile_flags = 0;
2521     int		did_inc_redrawing_disabled = FALSE;
2522     long        *so_ptr = curwin->w_p_so >= 0 ? &curwin->w_p_so : &p_so;
2523 
2524 #ifdef FEAT_PROP_POPUP
2525     if (ERROR_IF_TERM_POPUP_WINDOW)
2526 	return FAIL;
2527 #endif
2528 
2529     if (eap != NULL)
2530 	command = eap->do_ecmd_cmd;
2531     set_bufref(&old_curbuf, curbuf);
2532 
2533     if (fnum != 0)
2534     {
2535 	if (fnum == curbuf->b_fnum)	// file is already being edited
2536 	    return OK;			// nothing to do
2537 	other_file = TRUE;
2538     }
2539     else
2540     {
2541 #ifdef FEAT_BROWSE
2542 	if ((cmdmod.cmod_flags & CMOD_BROWSE) && !exiting)
2543 	{
2544 	    if (
2545 # ifdef FEAT_GUI
2546 		!gui.in_use &&
2547 # endif
2548 		    au_has_group((char_u *)"FileExplorer"))
2549 	    {
2550 		// No browsing supported but we do have the file explorer:
2551 		// Edit the directory.
2552 		if (ffname == NULL || !mch_isdir(ffname))
2553 		    ffname = dot_path;
2554 	    }
2555 	    else
2556 	    {
2557 		browse_file = do_browse(0, (char_u *)_("Edit File"), ffname,
2558 						    NULL, NULL, NULL, curbuf);
2559 		if (browse_file == NULL)
2560 		    goto theend;
2561 		ffname = browse_file;
2562 	    }
2563 	}
2564 #endif
2565 	// if no short name given, use ffname for short name
2566 	if (sfname == NULL)
2567 	    sfname = ffname;
2568 #ifdef USE_FNAME_CASE
2569 	if (sfname != NULL)
2570 	    fname_case(sfname, 0);   // set correct case for sfname
2571 #endif
2572 
2573 	if ((flags & (ECMD_ADDBUF | ECMD_ALTBUF))
2574 					 && (ffname == NULL || *ffname == NUL))
2575 	    goto theend;
2576 
2577 	if (ffname == NULL)
2578 	    other_file = TRUE;
2579 					    // there is no file name
2580 	else if (*ffname == NUL && curbuf->b_ffname == NULL)
2581 	    other_file = FALSE;
2582 	else
2583 	{
2584 	    if (*ffname == NUL)		    // re-edit with same file name
2585 	    {
2586 		ffname = curbuf->b_ffname;
2587 		sfname = curbuf->b_fname;
2588 	    }
2589 	    free_fname = fix_fname(ffname); // may expand to full path name
2590 	    if (free_fname != NULL)
2591 		ffname = free_fname;
2592 	    other_file = otherfile(ffname);
2593 	}
2594     }
2595 
2596     /*
2597      * If the file was changed we may not be allowed to abandon it:
2598      * - if we are going to re-edit the same file
2599      * - or if we are the only window on this file and if ECMD_HIDE is FALSE
2600      */
2601     if (  ((!other_file && !(flags & ECMD_OLDBUF))
2602 	    || (curbuf->b_nwindows == 1
2603 		&& !(flags & (ECMD_HIDE | ECMD_ADDBUF | ECMD_ALTBUF))))
2604 	&& check_changed(curbuf, (p_awa ? CCGD_AW : 0)
2605 			       | (other_file ? 0 : CCGD_MULTWIN)
2606 			       | ((flags & ECMD_FORCEIT) ? CCGD_FORCEIT : 0)
2607 			       | (eap == NULL ? 0 : CCGD_EXCMD)))
2608     {
2609 	if (fnum == 0 && other_file && ffname != NULL)
2610 	    (void)setaltfname(ffname, sfname, newlnum < 0 ? 0 : newlnum);
2611 	goto theend;
2612     }
2613 
2614     /*
2615      * End Visual mode before switching to another buffer, so the text can be
2616      * copied into the GUI selection buffer.
2617      */
2618     reset_VIsual();
2619 
2620 #if defined(FEAT_EVAL)
2621     if ((command != NULL || newlnum > (linenr_T)0)
2622 	    && *get_vim_var_str(VV_SWAPCOMMAND) == NUL)
2623     {
2624 	int	len;
2625 	char_u	*p;
2626 
2627 	// Set v:swapcommand for the SwapExists autocommands.
2628 	if (command != NULL)
2629 	    len = (int)STRLEN(command) + 3;
2630 	else
2631 	    len = 30;
2632 	p = alloc(len);
2633 	if (p != NULL)
2634 	{
2635 	    if (command != NULL)
2636 		vim_snprintf((char *)p, len, ":%s\r", command);
2637 	    else
2638 		vim_snprintf((char *)p, len, "%ldG", (long)newlnum);
2639 	    set_vim_var_string(VV_SWAPCOMMAND, p, -1);
2640 	    did_set_swapcommand = TRUE;
2641 	    vim_free(p);
2642 	}
2643     }
2644 #endif
2645 
2646     /*
2647      * If we are starting to edit another file, open a (new) buffer.
2648      * Otherwise we re-use the current buffer.
2649      */
2650     if (other_file)
2651     {
2652 	int prev_alt_fnum = curwin->w_alt_fnum;
2653 
2654 	if (!(flags & (ECMD_ADDBUF | ECMD_ALTBUF)))
2655 	{
2656 	    if ((cmdmod.cmod_flags & CMOD_KEEPALT) == 0)
2657 		curwin->w_alt_fnum = curbuf->b_fnum;
2658 	    if (oldwin != NULL)
2659 		buflist_altfpos(oldwin);
2660 	}
2661 
2662 	if (fnum)
2663 	    buf = buflist_findnr(fnum);
2664 	else
2665 	{
2666 	    if (flags & (ECMD_ADDBUF | ECMD_ALTBUF))
2667 	    {
2668 		// Default the line number to zero to avoid that a wininfo item
2669 		// is added for the current window.
2670 		linenr_T	tlnum = 0;
2671 		buf_T		*newbuf;
2672 
2673 		if (command != NULL)
2674 		{
2675 		    tlnum = atol((char *)command);
2676 		    if (tlnum <= 0)
2677 			tlnum = 1L;
2678 		}
2679 		// Add BLN_NOCURWIN to avoid a new wininfo items are associated
2680 		// with the current window.
2681 		newbuf = buflist_new(ffname, sfname, tlnum,
2682 						    BLN_LISTED | BLN_NOCURWIN);
2683 		if (newbuf != NULL && (flags & ECMD_ALTBUF))
2684 		    curwin->w_alt_fnum = newbuf->b_fnum;
2685 		goto theend;
2686 	    }
2687 	    buf = buflist_new(ffname, sfname, 0L,
2688 		    BLN_CURBUF | ((flags & ECMD_SET_HELP) ? 0 : BLN_LISTED));
2689 
2690 	    // autocommands may change curwin and curbuf
2691 	    if (oldwin != NULL)
2692 		oldwin = curwin;
2693 	    set_bufref(&old_curbuf, curbuf);
2694 	}
2695 	if (buf == NULL)
2696 	    goto theend;
2697 	if (curwin->w_alt_fnum == buf->b_fnum && prev_alt_fnum != 0)
2698 	    // reusing the buffer, keep the old alternate file
2699 	    curwin->w_alt_fnum = prev_alt_fnum;
2700 
2701 	if (buf->b_ml.ml_mfp == NULL)		// no memfile yet
2702 	{
2703 	    oldbuf = FALSE;
2704 	}
2705 	else					// existing memfile
2706 	{
2707 	    oldbuf = TRUE;
2708 	    set_bufref(&bufref, buf);
2709 	    (void)buf_check_timestamp(buf, FALSE);
2710 	    // Check if autocommands made the buffer invalid or changed the
2711 	    // current buffer.
2712 	    if (!bufref_valid(&bufref) || curbuf != old_curbuf.br_buf)
2713 		goto theend;
2714 #ifdef FEAT_EVAL
2715 	    if (aborting())	    // autocmds may abort script processing
2716 		goto theend;
2717 #endif
2718 	}
2719 
2720 	// May jump to last used line number for a loaded buffer or when asked
2721 	// for explicitly
2722 	if ((oldbuf && newlnum == ECMD_LASTL) || newlnum == ECMD_LAST)
2723 	{
2724 	    pos = buflist_findfpos(buf);
2725 	    newlnum = pos->lnum;
2726 	    solcol = pos->col;
2727 	}
2728 
2729 	/*
2730 	 * Make the (new) buffer the one used by the current window.
2731 	 * If the old buffer becomes unused, free it if ECMD_HIDE is FALSE.
2732 	 * If the current buffer was empty and has no file name, curbuf
2733 	 * is returned by buflist_new(), nothing to do here.
2734 	 */
2735 	if (buf != curbuf)
2736 	{
2737 	    bufref_T	save_au_new_curbuf;
2738 #ifdef FEAT_CMDWIN
2739 	    int		save_cmdwin_type = cmdwin_type;
2740 
2741 	    // BufLeave applies to the old buffer.
2742 	    cmdwin_type = 0;
2743 #endif
2744 	    /*
2745 	     * Be careful: The autocommands may delete any buffer and change
2746 	     * the current buffer.
2747 	     * - If the buffer we are going to edit is deleted, give up.
2748 	     * - If the current buffer is deleted, prefer to load the new
2749 	     *   buffer when loading a buffer is required.  This avoids
2750 	     *   loading another buffer which then must be closed again.
2751 	     * - If we ended up in the new buffer already, need to skip a few
2752 	     *	 things, set auto_buf.
2753 	     */
2754 	    if (buf->b_fname != NULL)
2755 		new_name = vim_strsave(buf->b_fname);
2756 	    save_au_new_curbuf = au_new_curbuf;
2757 	    set_bufref(&au_new_curbuf, buf);
2758 	    apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
2759 #ifdef FEAT_CMDWIN
2760 	    cmdwin_type = save_cmdwin_type;
2761 #endif
2762 	    if (!bufref_valid(&au_new_curbuf))
2763 	    {
2764 		// new buffer has been deleted
2765 		delbuf_msg(new_name);	// frees new_name
2766 		au_new_curbuf = save_au_new_curbuf;
2767 		goto theend;
2768 	    }
2769 #ifdef FEAT_EVAL
2770 	    if (aborting())	    // autocmds may abort script processing
2771 	    {
2772 		vim_free(new_name);
2773 		au_new_curbuf = save_au_new_curbuf;
2774 		goto theend;
2775 	    }
2776 #endif
2777 	    if (buf == curbuf)		// already in new buffer
2778 		auto_buf = TRUE;
2779 	    else
2780 	    {
2781 		win_T	    *the_curwin = curwin;
2782 		int	    did_decrement;
2783 		buf_T	    *was_curbuf = curbuf;
2784 
2785 		// Set the w_closing flag to avoid that autocommands close the
2786 		// window.  And set b_locked for the same reason.
2787 		the_curwin->w_closing = TRUE;
2788 		++buf->b_locked;
2789 
2790 		if (curbuf == old_curbuf.br_buf)
2791 		    buf_copy_options(buf, BCO_ENTER);
2792 
2793 		// Close the link to the current buffer. This will set
2794 		// oldwin->w_buffer to NULL.
2795 		u_sync(FALSE);
2796 		did_decrement = close_buffer(oldwin, curbuf,
2797 			 (flags & ECMD_HIDE) ? 0 : DOBUF_UNLOAD, FALSE, FALSE);
2798 
2799 		// Autocommands may have closed the window.
2800 		if (win_valid(the_curwin))
2801 		    the_curwin->w_closing = FALSE;
2802 		--buf->b_locked;
2803 
2804 #ifdef FEAT_EVAL
2805 		// autocmds may abort script processing
2806 		if (aborting() && curwin->w_buffer != NULL)
2807 		{
2808 		    vim_free(new_name);
2809 		    au_new_curbuf = save_au_new_curbuf;
2810 		    goto theend;
2811 		}
2812 #endif
2813 		// Be careful again, like above.
2814 		if (!bufref_valid(&au_new_curbuf))
2815 		{
2816 		    // new buffer has been deleted
2817 		    delbuf_msg(new_name);	// frees new_name
2818 		    au_new_curbuf = save_au_new_curbuf;
2819 		    goto theend;
2820 		}
2821 		if (buf == curbuf)		// already in new buffer
2822 		{
2823 		    // close_buffer() has decremented the window count,
2824 		    // increment it again here and restore w_buffer.
2825 		    if (did_decrement && buf_valid(was_curbuf))
2826 			++was_curbuf->b_nwindows;
2827 		    if (win_valid_any_tab(oldwin) && oldwin->w_buffer == NULL)
2828 			oldwin->w_buffer = was_curbuf;
2829 		    auto_buf = TRUE;
2830 		}
2831 		else
2832 		{
2833 #ifdef FEAT_SYN_HL
2834 		    /*
2835 		     * <VN> We could instead free the synblock
2836 		     * and re-attach to buffer, perhaps.
2837 		     */
2838 		    if (curwin->w_buffer == NULL
2839 			    || curwin->w_s == &(curwin->w_buffer->b_s))
2840 			curwin->w_s = &(buf->b_s);
2841 #endif
2842 		    curwin->w_buffer = buf;
2843 		    curbuf = buf;
2844 		    ++curbuf->b_nwindows;
2845 
2846 		    // Set 'fileformat', 'binary' and 'fenc' when forced.
2847 		    if (!oldbuf && eap != NULL)
2848 		    {
2849 			set_file_options(TRUE, eap);
2850 			set_forced_fenc(eap);
2851 		    }
2852 		}
2853 
2854 		// May get the window options from the last time this buffer
2855 		// was in this window (or another window).  If not used
2856 		// before, reset the local window options to the global
2857 		// values.  Also restores old folding stuff.
2858 		get_winopts(curbuf);
2859 #ifdef FEAT_SPELL
2860 		did_get_winopts = TRUE;
2861 #endif
2862 	    }
2863 	    vim_free(new_name);
2864 	    au_new_curbuf = save_au_new_curbuf;
2865 	}
2866 
2867 	curwin->w_pcmark.lnum = 1;
2868 	curwin->w_pcmark.col = 0;
2869     }
2870     else // !other_file
2871     {
2872 	if ((flags & (ECMD_ADDBUF | ECMD_ALTBUF)) || check_fname() == FAIL)
2873 	    goto theend;
2874 
2875 	oldbuf = (flags & ECMD_OLDBUF);
2876     }
2877 
2878     // Don't redraw until the cursor is in the right line, otherwise
2879     // autocommands may cause ml_get errors.
2880     ++RedrawingDisabled;
2881     did_inc_redrawing_disabled = TRUE;
2882 
2883     buf = curbuf;
2884     if ((flags & ECMD_SET_HELP) || keep_help_flag)
2885     {
2886 	prepare_help_buffer();
2887     }
2888     else
2889     {
2890 	// Don't make a buffer listed if it's a help buffer.  Useful when
2891 	// using CTRL-O to go back to a help file.
2892 	if (!curbuf->b_help)
2893 	    set_buflisted(TRUE);
2894     }
2895 
2896     // If autocommands change buffers under our fingers, forget about
2897     // editing the file.
2898     if (buf != curbuf)
2899 	goto theend;
2900 #ifdef FEAT_EVAL
2901     if (aborting())	    // autocmds may abort script processing
2902 	goto theend;
2903 #endif
2904 
2905     // Since we are starting to edit a file, consider the filetype to be
2906     // unset.  Helps for when an autocommand changes files and expects syntax
2907     // highlighting to work in the other file.
2908     did_filetype = FALSE;
2909 
2910 /*
2911  * other_file	oldbuf
2912  *  FALSE	FALSE	    re-edit same file, buffer is re-used
2913  *  FALSE	TRUE	    re-edit same file, nothing changes
2914  *  TRUE	FALSE	    start editing new file, new buffer
2915  *  TRUE	TRUE	    start editing in existing buffer (nothing to do)
2916  */
2917     if (!other_file && !oldbuf)		// re-use the buffer
2918     {
2919 	set_last_cursor(curwin);	// may set b_last_cursor
2920 	if (newlnum == ECMD_LAST || newlnum == ECMD_LASTL)
2921 	{
2922 	    newlnum = curwin->w_cursor.lnum;
2923 	    solcol = curwin->w_cursor.col;
2924 	}
2925 	buf = curbuf;
2926 	if (buf->b_fname != NULL)
2927 	    new_name = vim_strsave(buf->b_fname);
2928 	else
2929 	    new_name = NULL;
2930 	set_bufref(&bufref, buf);
2931 
2932 	// If the buffer was used before, store the current contents so that
2933 	// the reload can be undone.  Do not do this if the (empty) buffer is
2934 	// being re-used for another file.
2935 	if (!(curbuf->b_flags & BF_NEVERLOADED)
2936 		&& (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur))
2937 	{
2938 	    // Sync first so that this is a separate undo-able action.
2939 	    u_sync(FALSE);
2940 	    if (u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE)
2941 								     == FAIL)
2942 	    {
2943 		vim_free(new_name);
2944 		goto theend;
2945 	    }
2946 	    u_unchanged(curbuf);
2947 	    buf_freeall(curbuf, BFA_KEEP_UNDO);
2948 
2949 	    // tell readfile() not to clear or reload undo info
2950 	    readfile_flags = READ_KEEP_UNDO;
2951 	}
2952 	else
2953 	    buf_freeall(curbuf, 0);   // free all things for buffer
2954 
2955 	// If autocommands deleted the buffer we were going to re-edit, give
2956 	// up and jump to the end.
2957 	if (!bufref_valid(&bufref))
2958 	{
2959 	    delbuf_msg(new_name);	// frees new_name
2960 	    goto theend;
2961 	}
2962 	vim_free(new_name);
2963 
2964 	// If autocommands change buffers under our fingers, forget about
2965 	// re-editing the file.  Should do the buf_clear_file(), but perhaps
2966 	// the autocommands changed the buffer...
2967 	if (buf != curbuf)
2968 	    goto theend;
2969 #ifdef FEAT_EVAL
2970 	if (aborting())	    // autocmds may abort script processing
2971 	    goto theend;
2972 #endif
2973 	buf_clear_file(curbuf);
2974 	curbuf->b_op_start.lnum = 0;	// clear '[ and '] marks
2975 	curbuf->b_op_end.lnum = 0;
2976     }
2977 
2978 /*
2979  * If we get here we are sure to start editing
2980  */
2981     // Assume success now
2982     retval = OK;
2983 
2984     /*
2985      * Check if we are editing the w_arg_idx file in the argument list.
2986      */
2987     check_arg_idx(curwin);
2988 
2989     if (!auto_buf)
2990     {
2991 	/*
2992 	 * Set cursor and init window before reading the file and executing
2993 	 * autocommands.  This allows for the autocommands to position the
2994 	 * cursor.
2995 	 */
2996 	curwin_init();
2997 
2998 #ifdef FEAT_FOLDING
2999 	// It's possible that all lines in the buffer changed.  Need to update
3000 	// automatic folding for all windows where it's used.
3001 	{
3002 	    win_T	    *win;
3003 	    tabpage_T	    *tp;
3004 
3005 	    FOR_ALL_TAB_WINDOWS(tp, win)
3006 		if (win->w_buffer == curbuf)
3007 		    foldUpdateAll(win);
3008 	}
3009 #endif
3010 
3011 	// Change directories when the 'acd' option is set.
3012 	DO_AUTOCHDIR;
3013 
3014 	/*
3015 	 * Careful: open_buffer() and apply_autocmds() may change the current
3016 	 * buffer and window.
3017 	 */
3018 	orig_pos = curwin->w_cursor;
3019 	topline = curwin->w_topline;
3020 	if (!oldbuf)			    // need to read the file
3021 	{
3022 #ifdef FEAT_PROP_POPUP
3023 	    // Don't use the swap-exists dialog for a popup window, can't edit
3024 	    // the buffer.
3025 	    if (WIN_IS_POPUP(curwin))
3026 		curbuf->b_flags |= BF_NO_SEA;
3027 #endif
3028 	    swap_exists_action = SEA_DIALOG;
3029 	    curbuf->b_flags |= BF_CHECK_RO; // set/reset 'ro' flag
3030 
3031 	    /*
3032 	     * Open the buffer and read the file.
3033 	     */
3034 	    if (flags & ECMD_NOWINENTER)
3035 		readfile_flags |= READ_NOWINENTER;
3036 #if defined(FEAT_EVAL)
3037 	    if (should_abort(open_buffer(FALSE, eap, readfile_flags)))
3038 		retval = FAIL;
3039 #else
3040 	    (void)open_buffer(FALSE, eap, readfile_flags);
3041 #endif
3042 
3043 #ifdef FEAT_PROP_POPUP
3044 	    curbuf->b_flags &= ~BF_NO_SEA;
3045 #endif
3046 	    if (swap_exists_action == SEA_QUIT)
3047 		retval = FAIL;
3048 	    handle_swap_exists(&old_curbuf);
3049 	}
3050 	else
3051 	{
3052 	    // Read the modelines, but only to set window-local options.  Any
3053 	    // buffer-local options have already been set and may have been
3054 	    // changed by the user.
3055 	    do_modelines(OPT_WINONLY);
3056 
3057 	    apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE,
3058 							      curbuf, &retval);
3059 	    if ((flags & ECMD_NOWINENTER) == 0)
3060 		apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE,
3061 							      curbuf, &retval);
3062 	}
3063 	check_arg_idx(curwin);
3064 
3065 	// If autocommands change the cursor position or topline, we should
3066 	// keep it.  Also when it moves within a line. But not when it moves
3067 	// to the first non-blank.
3068 	if (!EQUAL_POS(curwin->w_cursor, orig_pos))
3069 	{
3070 	    char_u *text = ml_get_curline();
3071 
3072 	    if (curwin->w_cursor.lnum != orig_pos.lnum
3073 		    || curwin->w_cursor.col != (int)(skipwhite(text) - text))
3074 	    {
3075 		newlnum = curwin->w_cursor.lnum;
3076 		newcol = curwin->w_cursor.col;
3077 	    }
3078 	}
3079 	if (curwin->w_topline == topline)
3080 	    topline = 0;
3081 
3082 	// Even when cursor didn't move we need to recompute topline.
3083 	changed_line_abv_curs();
3084 
3085 #ifdef FEAT_TITLE
3086 	maketitle();
3087 #endif
3088 #if defined(FEAT_PROP_POPUP) && defined(FEAT_QUICKFIX)
3089 	if (WIN_IS_POPUP(curwin) && curwin->w_p_pvw && retval != FAIL)
3090 	    popup_set_title(curwin);
3091 #endif
3092     }
3093 
3094 #ifdef FEAT_DIFF
3095     // Tell the diff stuff that this buffer is new and/or needs updating.
3096     // Also needed when re-editing the same buffer, because unloading will
3097     // have removed it as a diff buffer.
3098     if (curwin->w_p_diff)
3099     {
3100 	diff_buf_add(curbuf);
3101 	diff_invalidate(curbuf);
3102     }
3103 #endif
3104 
3105 #ifdef FEAT_SPELL
3106     // If the window options were changed may need to set the spell language.
3107     // Can only do this after the buffer has been properly setup.
3108     if (did_get_winopts && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL)
3109 	(void)did_set_spelllang(curwin);
3110 #endif
3111 
3112     if (command == NULL)
3113     {
3114 	if (newcol >= 0)	// position set by autocommands
3115 	{
3116 	    curwin->w_cursor.lnum = newlnum;
3117 	    curwin->w_cursor.col = newcol;
3118 	    check_cursor();
3119 	}
3120 	else if (newlnum > 0)	// line number from caller or old position
3121 	{
3122 	    curwin->w_cursor.lnum = newlnum;
3123 	    check_cursor_lnum();
3124 	    if (solcol >= 0 && !p_sol)
3125 	    {
3126 		// 'sol' is off: Use last known column.
3127 		curwin->w_cursor.col = solcol;
3128 		check_cursor_col();
3129 		curwin->w_cursor.coladd = 0;
3130 		curwin->w_set_curswant = TRUE;
3131 	    }
3132 	    else
3133 		beginline(BL_SOL | BL_FIX);
3134 	}
3135 	else			// no line number, go to last line in Ex mode
3136 	{
3137 	    if (exmode_active)
3138 		curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
3139 	    beginline(BL_WHITE | BL_FIX);
3140 	}
3141     }
3142 
3143     // Check if cursors in other windows on the same buffer are still valid
3144     check_lnums(FALSE);
3145 
3146     /*
3147      * Did not read the file, need to show some info about the file.
3148      * Do this after setting the cursor.
3149      */
3150     if (oldbuf && !auto_buf)
3151     {
3152 	int	msg_scroll_save = msg_scroll;
3153 
3154 	// Obey the 'O' flag in 'cpoptions': overwrite any previous file
3155 	// message.
3156 	if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
3157 	    msg_scroll = FALSE;
3158 	if (!msg_scroll)	// wait a bit when overwriting an error msg
3159 	    check_for_delay(FALSE);
3160 	msg_start();
3161 	msg_scroll = msg_scroll_save;
3162 	msg_scrolled_ign = TRUE;
3163 
3164 	if (!shortmess(SHM_FILEINFO))
3165 	    fileinfo(FALSE, TRUE, FALSE);
3166 
3167 	msg_scrolled_ign = FALSE;
3168     }
3169 
3170 #ifdef FEAT_VIMINFO
3171     curbuf->b_last_used = vim_time();
3172 #endif
3173 
3174     if (command != NULL)
3175 	do_cmdline(command, NULL, NULL, DOCMD_VERBOSE|DOCMD_RANGEOK);
3176 
3177 #ifdef FEAT_KEYMAP
3178     if (curbuf->b_kmap_state & KEYMAP_INIT)
3179 	(void)keymap_init();
3180 #endif
3181 
3182     --RedrawingDisabled;
3183     did_inc_redrawing_disabled = FALSE;
3184     if (!skip_redraw)
3185     {
3186 	n = *so_ptr;
3187 	if (topline == 0 && command == NULL)
3188 	    *so_ptr = 9999;		// force cursor halfway the window
3189 	update_topline();
3190 	curwin->w_scbind_pos = curwin->w_topline;
3191 	*so_ptr = n;
3192 	redraw_curbuf_later(NOT_VALID);	// redraw this buffer later
3193     }
3194 
3195     if (p_im)
3196 	need_start_insertmode = TRUE;
3197 
3198 #ifdef FEAT_AUTOCHDIR
3199     // Change directories when the 'acd' option is set and we aren't already in
3200     // that directory (should already be done above). Expect getcwd() to be
3201     // faster than calling shorten_fnames() unnecessarily.
3202     if (p_acd && curbuf->b_ffname != NULL)
3203     {
3204 	char_u	curdir[MAXPATHL];
3205 	char_u	filedir[MAXPATHL];
3206 
3207 	vim_strncpy(filedir, curbuf->b_ffname, MAXPATHL - 1);
3208 	*gettail_sep(filedir) = NUL;
3209 	if (mch_dirname(curdir, MAXPATHL) != FAIL
3210 		&& vim_fnamecmp(curdir, filedir) != 0)
3211 	    do_autochdir();
3212     }
3213 #endif
3214 
3215 #if defined(FEAT_NETBEANS_INTG)
3216     if (curbuf->b_ffname != NULL)
3217     {
3218 # ifdef FEAT_NETBEANS_INTG
3219 	if ((flags & ECMD_SET_HELP) != ECMD_SET_HELP)
3220 	    netbeans_file_opened(curbuf);
3221 # endif
3222     }
3223 #endif
3224 
3225 theend:
3226     if (did_inc_redrawing_disabled)
3227 	--RedrawingDisabled;
3228 #if defined(FEAT_EVAL)
3229     if (did_set_swapcommand)
3230 	set_vim_var_string(VV_SWAPCOMMAND, NULL, -1);
3231 #endif
3232 #ifdef FEAT_BROWSE
3233     vim_free(browse_file);
3234 #endif
3235     vim_free(free_fname);
3236     return retval;
3237 }
3238 
3239     static void
delbuf_msg(char_u * name)3240 delbuf_msg(char_u *name)
3241 {
3242     semsg(_("E143: Autocommands unexpectedly deleted new buffer %s"),
3243 	    name == NULL ? (char_u *)"" : name);
3244     vim_free(name);
3245     au_new_curbuf.br_buf = NULL;
3246     au_new_curbuf.br_buf_free_count = 0;
3247 }
3248 
3249 static int append_indent = 0;	    // autoindent for first line
3250 
3251 /*
3252  * ":insert" and ":append", also used by ":change"
3253  */
3254     void
ex_append(exarg_T * eap)3255 ex_append(exarg_T *eap)
3256 {
3257     char_u	*theline;
3258     int		did_undo = FALSE;
3259     linenr_T	lnum = eap->line2;
3260     int		indent = 0;
3261     char_u	*p;
3262     int		vcol;
3263     int		empty = (curbuf->b_ml.ml_flags & ML_EMPTY);
3264 
3265 #ifdef FEAT_EVAL
3266     if (not_in_vim9(eap) == FAIL)
3267 	return;
3268 #endif
3269     // the ! flag toggles autoindent
3270     if (eap->forceit)
3271 	curbuf->b_p_ai = !curbuf->b_p_ai;
3272 
3273     // First autoindent comes from the line we start on
3274     if (eap->cmdidx != CMD_change && curbuf->b_p_ai && lnum > 0)
3275 	append_indent = get_indent_lnum(lnum);
3276 
3277     if (eap->cmdidx != CMD_append)
3278 	--lnum;
3279 
3280     // when the buffer is empty need to delete the dummy line
3281     if (empty && lnum == 1)
3282 	lnum = 0;
3283 
3284     State = INSERT;		    // behave like in Insert mode
3285     if (curbuf->b_p_iminsert == B_IMODE_LMAP)
3286 	State |= LANGMAP;
3287 
3288     for (;;)
3289     {
3290 	msg_scroll = TRUE;
3291 	need_wait_return = FALSE;
3292 	if (curbuf->b_p_ai)
3293 	{
3294 	    if (append_indent >= 0)
3295 	    {
3296 		indent = append_indent;
3297 		append_indent = -1;
3298 	    }
3299 	    else if (lnum > 0)
3300 		indent = get_indent_lnum(lnum);
3301 	}
3302 	ex_keep_indent = FALSE;
3303 	if (eap->getline == NULL)
3304 	{
3305 	    // No getline() function, use the lines that follow. This ends
3306 	    // when there is no more.
3307 	    if (eap->nextcmd == NULL || *eap->nextcmd == NUL)
3308 		break;
3309 	    p = vim_strchr(eap->nextcmd, NL);
3310 	    if (p == NULL)
3311 		p = eap->nextcmd + STRLEN(eap->nextcmd);
3312 	    theline = vim_strnsave(eap->nextcmd, p - eap->nextcmd);
3313 	    if (*p != NUL)
3314 		++p;
3315 	    eap->nextcmd = p;
3316 	}
3317 	else
3318 	{
3319 	    int save_State = State;
3320 
3321 	    // Set State to avoid the cursor shape to be set to INSERT mode
3322 	    // when getline() returns.
3323 	    State = CMDLINE;
3324 	    theline = eap->getline(
3325 #ifdef FEAT_EVAL
3326 		    eap->cstack->cs_looplevel > 0 ? -1 :
3327 #endif
3328 		    NUL, eap->cookie, indent, TRUE);
3329 	    State = save_State;
3330 	}
3331 	lines_left = Rows - 1;
3332 	if (theline == NULL)
3333 	    break;
3334 
3335 	// Using ^ CTRL-D in getexmodeline() makes us repeat the indent.
3336 	if (ex_keep_indent)
3337 	    append_indent = indent;
3338 
3339 	// Look for the "." after automatic indent.
3340 	vcol = 0;
3341 	for (p = theline; indent > vcol; ++p)
3342 	{
3343 	    if (*p == ' ')
3344 		++vcol;
3345 	    else if (*p == TAB)
3346 		vcol += 8 - vcol % 8;
3347 	    else
3348 		break;
3349 	}
3350 	if ((p[0] == '.' && p[1] == NUL)
3351 		|| (!did_undo && u_save(lnum, lnum + 1 + (empty ? 1 : 0))
3352 								     == FAIL))
3353 	{
3354 	    vim_free(theline);
3355 	    break;
3356 	}
3357 
3358 	// don't use autoindent if nothing was typed.
3359 	if (p[0] == NUL)
3360 	    theline[0] = NUL;
3361 
3362 	did_undo = TRUE;
3363 	ml_append(lnum, theline, (colnr_T)0, FALSE);
3364 	appended_lines_mark(lnum + (empty ? 1 : 0), 1L);
3365 
3366 	vim_free(theline);
3367 	++lnum;
3368 
3369 	if (empty)
3370 	{
3371 	    ml_delete(2L);
3372 	    empty = FALSE;
3373 	}
3374     }
3375     State = NORMAL;
3376 
3377     if (eap->forceit)
3378 	curbuf->b_p_ai = !curbuf->b_p_ai;
3379 
3380     // "start" is set to eap->line2+1 unless that position is invalid (when
3381     // eap->line2 pointed to the end of the buffer and nothing was appended)
3382     // "end" is set to lnum when something has been appended, otherwise
3383     // it is the same than "start"  -- Acevedo
3384     if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
3385     {
3386 	curbuf->b_op_start.lnum = (eap->line2 < curbuf->b_ml.ml_line_count) ?
3387 	    eap->line2 + 1 : curbuf->b_ml.ml_line_count;
3388 	if (eap->cmdidx != CMD_append)
3389 	    --curbuf->b_op_start.lnum;
3390 	curbuf->b_op_end.lnum = (eap->line2 < lnum)
3391 					      ? lnum : curbuf->b_op_start.lnum;
3392 	curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
3393     }
3394     curwin->w_cursor.lnum = lnum;
3395     check_cursor_lnum();
3396     beginline(BL_SOL | BL_FIX);
3397 
3398     need_wait_return = FALSE;	// don't use wait_return() now
3399     ex_no_reprint = TRUE;
3400 }
3401 
3402 /*
3403  * ":change"
3404  */
3405     void
ex_change(exarg_T * eap)3406 ex_change(exarg_T *eap)
3407 {
3408     linenr_T	lnum;
3409 
3410 #ifdef FEAT_EVAL
3411     if (not_in_vim9(eap) == FAIL)
3412 	return;
3413 #endif
3414     if (eap->line2 >= eap->line1
3415 	    && u_save(eap->line1 - 1, eap->line2 + 1) == FAIL)
3416 	return;
3417 
3418     // the ! flag toggles autoindent
3419     if (eap->forceit ? !curbuf->b_p_ai : curbuf->b_p_ai)
3420 	append_indent = get_indent_lnum(eap->line1);
3421 
3422     for (lnum = eap->line2; lnum >= eap->line1; --lnum)
3423     {
3424 	if (curbuf->b_ml.ml_flags & ML_EMPTY)	    // nothing to delete
3425 	    break;
3426 	ml_delete(eap->line1);
3427     }
3428 
3429     // make sure the cursor is not beyond the end of the file now
3430     check_cursor_lnum();
3431     deleted_lines_mark(eap->line1, (long)(eap->line2 - lnum));
3432 
3433     // ":append" on the line above the deleted lines.
3434     eap->line2 = eap->line1;
3435     ex_append(eap);
3436 }
3437 
3438     void
ex_z(exarg_T * eap)3439 ex_z(exarg_T *eap)
3440 {
3441     char_u	*x;
3442     long	bigness;
3443     char_u	*kind;
3444     int		minus = 0;
3445     linenr_T	start, end, curs, i;
3446     int		j;
3447     linenr_T	lnum = eap->line2;
3448 
3449     // Vi compatible: ":z!" uses display height, without a count uses
3450     // 'scroll'
3451     if (eap->forceit)
3452 	bigness = Rows - 1;
3453     else if (!ONE_WINDOW)
3454 	bigness = curwin->w_height - 3;
3455     else
3456 	bigness = curwin->w_p_scr * 2;
3457     if (bigness < 1)
3458 	bigness = 1;
3459 
3460     x = eap->arg;
3461     kind = x;
3462     if (*kind == '-' || *kind == '+' || *kind == '='
3463 					      || *kind == '^' || *kind == '.')
3464 	++x;
3465     while (*x == '-' || *x == '+')
3466 	++x;
3467 
3468     if (*x != 0)
3469     {
3470 	if (!VIM_ISDIGIT(*x))
3471 	{
3472 	    emsg(_("E144: non-numeric argument to :z"));
3473 	    return;
3474 	}
3475 	else
3476 	{
3477 	    bigness = atol((char *)x);
3478 
3479 	    // bigness could be < 0 if atol(x) overflows.
3480 	    if (bigness > 2 * curbuf->b_ml.ml_line_count || bigness < 0)
3481 		bigness = 2 * curbuf->b_ml.ml_line_count;
3482 
3483 	    p_window = bigness;
3484 	    if (*kind == '=')
3485 		bigness += 2;
3486 	}
3487     }
3488 
3489     // the number of '-' and '+' multiplies the distance
3490     if (*kind == '-' || *kind == '+')
3491 	for (x = kind + 1; *x == *kind; ++x)
3492 	    ;
3493 
3494     switch (*kind)
3495     {
3496 	case '-':
3497 	    start = lnum - bigness * (linenr_T)(x - kind) + 1;
3498 	    end = start + bigness - 1;
3499 	    curs = end;
3500 	    break;
3501 
3502 	case '=':
3503 	    start = lnum - (bigness + 1) / 2 + 1;
3504 	    end = lnum + (bigness + 1) / 2 - 1;
3505 	    curs = lnum;
3506 	    minus = 1;
3507 	    break;
3508 
3509 	case '^':
3510 	    start = lnum - bigness * 2;
3511 	    end = lnum - bigness;
3512 	    curs = lnum - bigness;
3513 	    break;
3514 
3515 	case '.':
3516 	    start = lnum - (bigness + 1) / 2 + 1;
3517 	    end = lnum + (bigness + 1) / 2 - 1;
3518 	    curs = end;
3519 	    break;
3520 
3521 	default:  // '+'
3522 	    start = lnum;
3523 	    if (*kind == '+')
3524 		start += bigness * (linenr_T)(x - kind - 1) + 1;
3525 	    else if (eap->addr_count == 0)
3526 		++start;
3527 	    end = start + bigness - 1;
3528 	    curs = end;
3529 	    break;
3530     }
3531 
3532     if (start < 1)
3533 	start = 1;
3534 
3535     if (end > curbuf->b_ml.ml_line_count)
3536 	end = curbuf->b_ml.ml_line_count;
3537 
3538     if (curs > curbuf->b_ml.ml_line_count)
3539 	curs = curbuf->b_ml.ml_line_count;
3540     else if (curs < 1)
3541 	curs = 1;
3542 
3543     for (i = start; i <= end; i++)
3544     {
3545 	if (minus && i == lnum)
3546 	{
3547 	    msg_putchar('\n');
3548 
3549 	    for (j = 1; j < Columns; j++)
3550 		msg_putchar('-');
3551 	}
3552 
3553 	print_line(i, eap->flags & EXFLAG_NR, eap->flags & EXFLAG_LIST);
3554 
3555 	if (minus && i == lnum)
3556 	{
3557 	    msg_putchar('\n');
3558 
3559 	    for (j = 1; j < Columns; j++)
3560 		msg_putchar('-');
3561 	}
3562     }
3563 
3564     if (curwin->w_cursor.lnum != curs)
3565     {
3566 	curwin->w_cursor.lnum = curs;
3567 	curwin->w_cursor.col = 0;
3568     }
3569     ex_no_reprint = TRUE;
3570 }
3571 
3572 /*
3573  * Check if the restricted flag is set.
3574  * If so, give an error message and return TRUE.
3575  * Otherwise, return FALSE.
3576  */
3577     int
check_restricted(void)3578 check_restricted(void)
3579 {
3580     if (restricted)
3581     {
3582 	emsg(_("E145: Shell commands and some functionality not allowed in rvim"));
3583 	return TRUE;
3584     }
3585     return FALSE;
3586 }
3587 
3588 /*
3589  * Check if the secure flag is set (.exrc or .vimrc in current directory).
3590  * If so, give an error message and return TRUE.
3591  * Otherwise, return FALSE.
3592  */
3593     int
check_secure(void)3594 check_secure(void)
3595 {
3596     if (secure)
3597     {
3598 	secure = 2;
3599 	emsg(_(e_command_not_allowed_from_vimrc_in_current_dir_or_tag_search));
3600 	return TRUE;
3601     }
3602 #ifdef HAVE_SANDBOX
3603     /*
3604      * In the sandbox more things are not allowed, including the things
3605      * disallowed in secure mode.
3606      */
3607     if (sandbox != 0)
3608     {
3609 	emsg(_(e_not_allowed_in_sandbox));
3610 	return TRUE;
3611     }
3612 #endif
3613     return FALSE;
3614 }
3615 
3616 static char_u	*old_sub = NULL;	// previous substitute pattern
3617 static int	global_need_beginline;	// call beginline() after ":g"
3618 
3619 /*
3620  * Flags that are kept between calls to :substitute.
3621  */
3622 typedef struct {
3623     int	do_all;		// do multiple substitutions per line
3624     int	do_ask;		// ask for confirmation
3625     int	do_count;	// count only
3626     int	do_error;	// if false, ignore errors
3627     int	do_print;	// print last line with subs.
3628     int	do_list;	// list last line with subs.
3629     int	do_number;	// list last line with line nr
3630     int	do_ic;		// ignore case flag
3631 } subflags_T;
3632 
3633 /*
3634  * Skip over the "sub" part in :s/pat/sub/ where "delimiter" is the separating
3635  * character.
3636  */
3637     char_u *
skip_substitute(char_u * start,int delimiter)3638 skip_substitute(char_u *start, int delimiter)
3639 {
3640     char_u *p = start;
3641 
3642     while (p[0])
3643     {
3644 	if (p[0] == delimiter)		// end delimiter found
3645 	{
3646 	    *p++ = NUL;			// replace it with a NUL
3647 	    break;
3648 	}
3649 	if (p[0] == '\\' && p[1] != 0)	// skip escaped characters
3650 	    ++p;
3651 	MB_PTR_ADV(p);
3652     }
3653     return p;
3654 }
3655 
3656     static int
check_regexp_delim(int c)3657 check_regexp_delim(int c)
3658 {
3659     if (isalpha(c))
3660     {
3661 	emsg(_("E146: Regular expressions can't be delimited by letters"));
3662 	return FAIL;
3663     }
3664     return OK;
3665 }
3666 
3667 /*
3668  * Perform a substitution from line eap->line1 to line eap->line2 using the
3669  * command pointed to by eap->arg which should be of the form:
3670  *
3671  * /pattern/substitution/{flags}
3672  *
3673  * The usual escapes are supported as described in the regexp docs.
3674  */
3675     void
ex_substitute(exarg_T * eap)3676 ex_substitute(exarg_T *eap)
3677 {
3678     linenr_T	lnum;
3679     long	i = 0;
3680     regmmatch_T regmatch;
3681     static subflags_T subflags = {FALSE, FALSE, FALSE, TRUE, FALSE,
3682 							      FALSE, FALSE, 0};
3683 #ifdef FEAT_EVAL
3684     subflags_T	subflags_save;
3685 #endif
3686     int		save_do_all;		// remember user specified 'g' flag
3687     int		save_do_ask;		// remember user specified 'c' flag
3688     char_u	*pat = NULL, *sub = NULL;	// init for GCC
3689     int		delimiter;
3690     int		sublen;
3691     int		got_quit = FALSE;
3692     int		got_match = FALSE;
3693     int		temp;
3694     int		which_pat;
3695     char_u	*cmd;
3696     int		save_State;
3697     linenr_T	first_line = 0;		// first changed line
3698     linenr_T	last_line= 0;		// below last changed line AFTER the
3699 					// change
3700     linenr_T	old_line_count = curbuf->b_ml.ml_line_count;
3701     linenr_T	line2;
3702     long	nmatch;			// number of lines in match
3703     char_u	*sub_firstline;		// allocated copy of first sub line
3704     int		endcolumn = FALSE;	// cursor in last column when done
3705     pos_T	old_cursor = curwin->w_cursor;
3706     int		start_nsubs;
3707 #ifdef FEAT_EVAL
3708     int		save_ma = 0;
3709 #endif
3710 
3711     cmd = eap->arg;
3712     if (!global_busy)
3713     {
3714 	sub_nsubs = 0;
3715 	sub_nlines = 0;
3716     }
3717     start_nsubs = sub_nsubs;
3718 
3719     if (eap->cmdidx == CMD_tilde)
3720 	which_pat = RE_LAST;	// use last used regexp
3721     else
3722 	which_pat = RE_SUBST;	// use last substitute regexp
3723 
3724 				// new pattern and substitution
3725     if (eap->cmd[0] == 's' && *cmd != NUL && !VIM_ISWHITE(*cmd)
3726 		&& vim_strchr((char_u *)"0123456789cegriIp|\"", *cmd) == NULL)
3727     {
3728 				// don't accept alphanumeric for separator
3729 	if (check_regexp_delim(*cmd) == FAIL)
3730 	    return;
3731 #ifdef FEAT_EVAL
3732 	if (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg)
3733 								      == FAIL)
3734 	    return;
3735 #endif
3736 
3737 	/*
3738 	 * undocumented vi feature:
3739 	 *  "\/sub/" and "\?sub?" use last used search pattern (almost like
3740 	 *  //sub/r).  "\&sub&" use last substitute pattern (like //sub/).
3741 	 */
3742 	if (*cmd == '\\')
3743 	{
3744 	    ++cmd;
3745 	    if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
3746 	    {
3747 		emsg(_(e_backslash_should_be_followed_by));
3748 		return;
3749 	    }
3750 	    if (*cmd != '&')
3751 		which_pat = RE_SEARCH;	    // use last '/' pattern
3752 	    pat = (char_u *)"";		    // empty search pattern
3753 	    delimiter = *cmd++;		    // remember delimiter character
3754 	}
3755 	else		// find the end of the regexp
3756 	{
3757 	    which_pat = RE_LAST;	    // use last used regexp
3758 	    delimiter = *cmd++;		    // remember delimiter character
3759 	    pat = cmd;			    // remember start of search pat
3760 	    cmd = skip_regexp_ex(cmd, delimiter, magic_isset(),
3761 							&eap->arg, NULL, NULL);
3762 	    if (cmd[0] == delimiter)	    // end delimiter found
3763 		*cmd++ = NUL;		    // replace it with a NUL
3764 	}
3765 
3766 	/*
3767 	 * Small incompatibility: vi sees '\n' as end of the command, but in
3768 	 * Vim we want to use '\n' to find/substitute a NUL.
3769 	 */
3770 	sub = cmd;	    // remember the start of the substitution
3771 	cmd = skip_substitute(cmd, delimiter);
3772 
3773 	if (!eap->skip)
3774 	{
3775 	    // In POSIX vi ":s/pat/%/" uses the previous subst. string.
3776 	    if (STRCMP(sub, "%") == 0
3777 				 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
3778 	    {
3779 		if (old_sub == NULL)	// there is no previous command
3780 		{
3781 		    emsg(_(e_no_previous_substitute_regular_expression));
3782 		    return;
3783 		}
3784 		sub = old_sub;
3785 	    }
3786 	    else
3787 	    {
3788 		vim_free(old_sub);
3789 		old_sub = vim_strsave(sub);
3790 	    }
3791 	}
3792     }
3793     else if (!eap->skip)	// use previous pattern and substitution
3794     {
3795 	if (old_sub == NULL)	// there is no previous command
3796 	{
3797 	    emsg(_(e_no_previous_substitute_regular_expression));
3798 	    return;
3799 	}
3800 	pat = NULL;		// search_regcomp() will use previous pattern
3801 	sub = old_sub;
3802 
3803 	// Vi compatibility quirk: repeating with ":s" keeps the cursor in the
3804 	// last column after using "$".
3805 	endcolumn = (curwin->w_curswant == MAXCOL);
3806     }
3807 
3808     // Recognize ":%s/\n//" and turn it into a join command, which is much
3809     // more efficient.
3810     // TODO: find a generic solution to make line-joining operations more
3811     // efficient, avoid allocating a string that grows in size.
3812     if (pat != NULL && STRCMP(pat, "\\n") == 0
3813 	    && *sub == NUL
3814 	    && (*cmd == NUL || (cmd[1] == NUL && (*cmd == 'g' || *cmd == 'l'
3815 					     || *cmd == 'p' || *cmd == '#'))))
3816     {
3817 	linenr_T    joined_lines_count;
3818 
3819 	if (eap->skip)
3820 	    return;
3821 	curwin->w_cursor.lnum = eap->line1;
3822 	if (*cmd == 'l')
3823 	    eap->flags = EXFLAG_LIST;
3824 	else if (*cmd == '#')
3825 	    eap->flags = EXFLAG_NR;
3826 	else if (*cmd == 'p')
3827 	    eap->flags = EXFLAG_PRINT;
3828 
3829 	// The number of lines joined is the number of lines in the range plus
3830 	// one.  One less when the last line is included.
3831 	joined_lines_count = eap->line2 - eap->line1 + 1;
3832 	if (eap->line2 < curbuf->b_ml.ml_line_count)
3833 	    ++joined_lines_count;
3834 	if (joined_lines_count > 1)
3835 	{
3836 	    (void)do_join(joined_lines_count, FALSE, TRUE, FALSE, TRUE);
3837 	    sub_nsubs = joined_lines_count - 1;
3838 	    sub_nlines = 1;
3839 	    (void)do_sub_msg(FALSE);
3840 	    ex_may_print(eap);
3841 	}
3842 
3843 	if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0)
3844 	    save_re_pat(RE_SUBST, pat, magic_isset());
3845 	// put pattern in history
3846 	add_to_history(HIST_SEARCH, pat, TRUE, NUL);
3847 
3848 	return;
3849     }
3850 
3851     /*
3852      * Find trailing options.  When '&' is used, keep old options.
3853      */
3854     if (*cmd == '&')
3855 	++cmd;
3856     else
3857     {
3858 #ifdef FEAT_EVAL
3859 	if (in_vim9script())
3860 	{
3861 	    // ignore 'gdefault' and 'edcompatible'
3862 	    subflags.do_all = FALSE;
3863 	    subflags.do_ask = FALSE;
3864 	}
3865 	else
3866 #endif
3867 	if (!p_ed)
3868 	{
3869 	    if (p_gd)		// default is global on
3870 		subflags.do_all = TRUE;
3871 	    else
3872 		subflags.do_all = FALSE;
3873 	    subflags.do_ask = FALSE;
3874 	}
3875 	subflags.do_error = TRUE;
3876 	subflags.do_print = FALSE;
3877 	subflags.do_list = FALSE;
3878 	subflags.do_count = FALSE;
3879 	subflags.do_number = FALSE;
3880 	subflags.do_ic = 0;
3881     }
3882     while (*cmd)
3883     {
3884 	/*
3885 	 * Note that 'g' and 'c' are always inverted, also when p_ed is off.
3886 	 * 'r' is never inverted.
3887 	 */
3888 	if (*cmd == 'g')
3889 	    subflags.do_all = !subflags.do_all;
3890 	else if (*cmd == 'c')
3891 	    subflags.do_ask = !subflags.do_ask;
3892 	else if (*cmd == 'n')
3893 	    subflags.do_count = TRUE;
3894 	else if (*cmd == 'e')
3895 	    subflags.do_error = !subflags.do_error;
3896 	else if (*cmd == 'r')	    // use last used regexp
3897 	    which_pat = RE_LAST;
3898 	else if (*cmd == 'p')
3899 	    subflags.do_print = TRUE;
3900 	else if (*cmd == '#')
3901 	{
3902 	    subflags.do_print = TRUE;
3903 	    subflags.do_number = TRUE;
3904 	}
3905 	else if (*cmd == 'l')
3906 	{
3907 	    subflags.do_print = TRUE;
3908 	    subflags.do_list = TRUE;
3909 	}
3910 	else if (*cmd == 'i')	    // ignore case
3911 	    subflags.do_ic = 'i';
3912 	else if (*cmd == 'I')	    // don't ignore case
3913 	    subflags.do_ic = 'I';
3914 	else
3915 	    break;
3916 	++cmd;
3917     }
3918     if (subflags.do_count)
3919 	subflags.do_ask = FALSE;
3920 
3921     save_do_all = subflags.do_all;
3922     save_do_ask = subflags.do_ask;
3923 
3924     /*
3925      * check for a trailing count
3926      */
3927     cmd = skipwhite(cmd);
3928     if (VIM_ISDIGIT(*cmd))
3929     {
3930 	i = getdigits(&cmd);
3931 	if (i <= 0 && !eap->skip && subflags.do_error)
3932 	{
3933 	    emsg(_(e_zerocount));
3934 	    return;
3935 	}
3936 	eap->line1 = eap->line2;
3937 	eap->line2 += i - 1;
3938 	if (eap->line2 > curbuf->b_ml.ml_line_count)
3939 	    eap->line2 = curbuf->b_ml.ml_line_count;
3940     }
3941 
3942     /*
3943      * check for trailing command or garbage
3944      */
3945     cmd = skipwhite(cmd);
3946     if (*cmd && *cmd != '"')	    // if not end-of-line or comment
3947     {
3948 	set_nextcmd(eap, cmd);
3949 	if (eap->nextcmd == NULL)
3950 	{
3951 	    semsg(_(e_trailing_arg), cmd);
3952 	    return;
3953 	}
3954     }
3955 
3956     if (eap->skip)	    // not executing commands, only parsing
3957 	return;
3958 
3959     if (!subflags.do_count && !curbuf->b_p_ma)
3960     {
3961 	// Substitution is not allowed in non-'modifiable' buffer
3962 	emsg(_(e_cannot_make_changes_modifiable_is_off));
3963 	return;
3964     }
3965 
3966     if (search_regcomp(pat, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL)
3967     {
3968 	if (subflags.do_error)
3969 	    emsg(_(e_invalid_command));
3970 	return;
3971     }
3972 
3973     // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'
3974     if (subflags.do_ic == 'i')
3975 	regmatch.rmm_ic = TRUE;
3976     else if (subflags.do_ic == 'I')
3977 	regmatch.rmm_ic = FALSE;
3978 
3979     sub_firstline = NULL;
3980 
3981     /*
3982      * ~ in the substitute pattern is replaced with the old pattern.
3983      * We do it here once to avoid it to be replaced over and over again.
3984      * But don't do it when it starts with "\=", then it's an expression.
3985      */
3986     if (!(sub[0] == '\\' && sub[1] == '='))
3987 	sub = regtilde(sub, magic_isset());
3988 
3989     /*
3990      * Check for a match on each line.
3991      */
3992     line2 = eap->line2;
3993     for (lnum = eap->line1; lnum <= line2 && !(got_quit
3994 #if defined(FEAT_EVAL)
3995 		|| aborting()
3996 #endif
3997 		); ++lnum)
3998     {
3999 	nmatch = vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
4000 						       (colnr_T)0, NULL, NULL);
4001 	if (nmatch)
4002 	{
4003 	    colnr_T	copycol;
4004 	    colnr_T	matchcol;
4005 	    colnr_T	prev_matchcol = MAXCOL;
4006 	    char_u	*new_end, *new_start = NULL;
4007 	    unsigned	new_start_len = 0;
4008 	    char_u	*p1;
4009 	    int		did_sub = FALSE;
4010 	    int		lastone;
4011 	    int		len, copy_len, needed_len;
4012 	    long	nmatch_tl = 0;	// nr of lines matched below lnum
4013 	    int		do_again;	// do it again after joining lines
4014 	    int		skip_match = FALSE;
4015 	    linenr_T	sub_firstlnum;	// nr of first sub line
4016 #ifdef FEAT_PROP_POPUP
4017 	    int		apc_flags = APC_SAVE_FOR_UNDO | APC_SUBSTITUTE;
4018 	    colnr_T	total_added =  0;
4019 #endif
4020 
4021 	    /*
4022 	     * The new text is build up step by step, to avoid too much
4023 	     * copying.  There are these pieces:
4024 	     * sub_firstline	The old text, unmodified.
4025 	     * copycol		Column in the old text where we started
4026 	     *			looking for a match; from here old text still
4027 	     *			needs to be copied to the new text.
4028 	     * matchcol		Column number of the old text where to look
4029 	     *			for the next match.  It's just after the
4030 	     *			previous match or one further.
4031 	     * prev_matchcol	Column just after the previous match (if any).
4032 	     *			Mostly equal to matchcol, except for the first
4033 	     *			match and after skipping an empty match.
4034 	     * regmatch.*pos	Where the pattern matched in the old text.
4035 	     * new_start	The new text, all that has been produced so
4036 	     *			far.
4037 	     * new_end		The new text, where to append new text.
4038 	     *
4039 	     * lnum		The line number where we found the start of
4040 	     *			the match.  Can be below the line we searched
4041 	     *			when there is a \n before a \zs in the
4042 	     *			pattern.
4043 	     * sub_firstlnum	The line number in the buffer where to look
4044 	     *			for a match.  Can be different from "lnum"
4045 	     *			when the pattern or substitute string contains
4046 	     *			line breaks.
4047 	     *
4048 	     * Special situations:
4049 	     * - When the substitute string contains a line break, the part up
4050 	     *   to the line break is inserted in the text, but the copy of
4051 	     *   the original line is kept.  "sub_firstlnum" is adjusted for
4052 	     *   the inserted lines.
4053 	     * - When the matched pattern contains a line break, the old line
4054 	     *   is taken from the line at the end of the pattern.  The lines
4055 	     *   in the match are deleted later, "sub_firstlnum" is adjusted
4056 	     *   accordingly.
4057 	     *
4058 	     * The new text is built up in new_start[].  It has some extra
4059 	     * room to avoid using alloc()/free() too often.  new_start_len is
4060 	     * the length of the allocated memory at new_start.
4061 	     *
4062 	     * Make a copy of the old line, so it won't be taken away when
4063 	     * updating the screen or handling a multi-line match.  The "old_"
4064 	     * pointers point into this copy.
4065 	     */
4066 	    sub_firstlnum = lnum;
4067 	    copycol = 0;
4068 	    matchcol = 0;
4069 
4070 	    // At first match, remember current cursor position.
4071 	    if (!got_match)
4072 	    {
4073 		setpcmark();
4074 		got_match = TRUE;
4075 	    }
4076 
4077 	    /*
4078 	     * Loop until nothing more to replace in this line.
4079 	     * 1. Handle match with empty string.
4080 	     * 2. If do_ask is set, ask for confirmation.
4081 	     * 3. substitute the string.
4082 	     * 4. if do_all is set, find next match
4083 	     * 5. break if there isn't another match in this line
4084 	     */
4085 	    for (;;)
4086 	    {
4087 		// Advance "lnum" to the line where the match starts.  The
4088 		// match does not start in the first line when there is a line
4089 		// break before \zs.
4090 		if (regmatch.startpos[0].lnum > 0)
4091 		{
4092 		    lnum += regmatch.startpos[0].lnum;
4093 		    sub_firstlnum += regmatch.startpos[0].lnum;
4094 		    nmatch -= regmatch.startpos[0].lnum;
4095 		    VIM_CLEAR(sub_firstline);
4096 		}
4097 
4098 		// Match might be after the last line for "\n\zs" matching at
4099 		// the end of the last line.
4100 		if (lnum > curbuf->b_ml.ml_line_count)
4101 		    break;
4102 
4103 		if (sub_firstline == NULL)
4104 		{
4105 		    sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4106 		    if (sub_firstline == NULL)
4107 		    {
4108 			vim_free(new_start);
4109 			goto outofmem;
4110 		    }
4111 		}
4112 
4113 		// Save the line number of the last change for the final
4114 		// cursor position (just like Vi).
4115 		curwin->w_cursor.lnum = lnum;
4116 		do_again = FALSE;
4117 
4118 		/*
4119 		 * 1. Match empty string does not count, except for first
4120 		 * match.  This reproduces the strange vi behaviour.
4121 		 * This also catches endless loops.
4122 		 */
4123 		if (matchcol == prev_matchcol
4124 			&& regmatch.endpos[0].lnum == 0
4125 			&& matchcol == regmatch.endpos[0].col)
4126 		{
4127 		    if (sub_firstline[matchcol] == NUL)
4128 			// We already were at the end of the line.  Don't look
4129 			// for a match in this line again.
4130 			skip_match = TRUE;
4131 		    else
4132 		    {
4133 			 // search for a match at next column
4134 			if (has_mbyte)
4135 			    matchcol += mb_ptr2len(sub_firstline + matchcol);
4136 			else
4137 			    ++matchcol;
4138 		    }
4139 		    goto skip;
4140 		}
4141 
4142 		// Normally we continue searching for a match just after the
4143 		// previous match.
4144 		matchcol = regmatch.endpos[0].col;
4145 		prev_matchcol = matchcol;
4146 
4147 		/*
4148 		 * 2. If do_count is set only increase the counter.
4149 		 *    If do_ask is set, ask for confirmation.
4150 		 */
4151 		if (subflags.do_count)
4152 		{
4153 		    // For a multi-line match, put matchcol at the NUL at
4154 		    // the end of the line and set nmatch to one, so that
4155 		    // we continue looking for a match on the next line.
4156 		    // Avoids that ":s/\nB\@=//gc" get stuck.
4157 		    if (nmatch > 1)
4158 		    {
4159 			matchcol = (colnr_T)STRLEN(sub_firstline);
4160 			nmatch = 1;
4161 			skip_match = TRUE;
4162 		    }
4163 		    sub_nsubs++;
4164 		    did_sub = TRUE;
4165 #ifdef FEAT_EVAL
4166 		    // Skip the substitution, unless an expression is used,
4167 		    // then it is evaluated in the sandbox.
4168 		    if (!(sub[0] == '\\' && sub[1] == '='))
4169 #endif
4170 			goto skip;
4171 		}
4172 
4173 		if (subflags.do_ask)
4174 		{
4175 		    int typed = 0;
4176 
4177 		    // change State to CONFIRM, so that the mouse works
4178 		    // properly
4179 		    save_State = State;
4180 		    State = CONFIRM;
4181 		    setmouse();		// disable mouse in xterm
4182 		    curwin->w_cursor.col = regmatch.startpos[0].col;
4183 		    if (curwin->w_p_crb)
4184 			do_check_cursorbind();
4185 
4186 		    // When 'cpoptions' contains "u" don't sync undo when
4187 		    // asking for confirmation.
4188 		    if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4189 			++no_u_sync;
4190 
4191 		    /*
4192 		     * Loop until 'y', 'n', 'q', CTRL-E or CTRL-Y typed.
4193 		     */
4194 		    while (subflags.do_ask)
4195 		    {
4196 			if (exmode_active)
4197 			{
4198 			    char_u	*resp;
4199 			    colnr_T	sc, ec;
4200 
4201 			    print_line_no_prefix(lnum,
4202 					 subflags.do_number, subflags.do_list);
4203 
4204 			    getvcol(curwin, &curwin->w_cursor, &sc, NULL, NULL);
4205 			    curwin->w_cursor.col = regmatch.endpos[0].col - 1;
4206 			    if (curwin->w_cursor.col < 0)
4207 				curwin->w_cursor.col = 0;
4208 			    getvcol(curwin, &curwin->w_cursor, NULL, NULL, &ec);
4209 			    curwin->w_cursor.col = regmatch.startpos[0].col;
4210 			    if (subflags.do_number || curwin->w_p_nu)
4211 			    {
4212 				int numw = number_width(curwin) + 1;
4213 				sc += numw;
4214 				ec += numw;
4215 			    }
4216 			    msg_start();
4217 			    for (i = 0; i < (long)sc; ++i)
4218 				msg_putchar(' ');
4219 			    for ( ; i <= (long)ec; ++i)
4220 				msg_putchar('^');
4221 
4222 			    resp = getexmodeline('?', NULL, 0, TRUE);
4223 			    if (resp != NULL)
4224 			    {
4225 				typed = *resp;
4226 				vim_free(resp);
4227 			    }
4228 			}
4229 			else
4230 			{
4231 			    char_u *orig_line = NULL;
4232 			    int    len_change = 0;
4233 			    int	   save_p_lz = p_lz;
4234 #ifdef FEAT_FOLDING
4235 			    int save_p_fen = curwin->w_p_fen;
4236 
4237 			    curwin->w_p_fen = FALSE;
4238 #endif
4239 			    // Invert the matched string.
4240 			    // Remove the inversion afterwards.
4241 			    temp = RedrawingDisabled;
4242 			    RedrawingDisabled = 0;
4243 
4244 			    // avoid calling update_screen() in vgetorpeek()
4245 			    p_lz = FALSE;
4246 
4247 			    if (new_start != NULL)
4248 			    {
4249 				// There already was a substitution, we would
4250 				// like to show this to the user.  We cannot
4251 				// really update the line, it would change
4252 				// what matches.  Temporarily replace the line
4253 				// and change it back afterwards.
4254 				orig_line = vim_strsave(ml_get(lnum));
4255 				if (orig_line != NULL)
4256 				{
4257 				    char_u *new_line = concat_str(new_start,
4258 						     sub_firstline + copycol);
4259 
4260 				    if (new_line == NULL)
4261 					VIM_CLEAR(orig_line);
4262 				    else
4263 				    {
4264 					// Position the cursor relative to the
4265 					// end of the line, the previous
4266 					// substitute may have inserted or
4267 					// deleted characters before the
4268 					// cursor.
4269 					len_change = (int)STRLEN(new_line)
4270 						     - (int)STRLEN(orig_line);
4271 					curwin->w_cursor.col += len_change;
4272 					ml_replace(lnum, new_line, FALSE);
4273 				    }
4274 				}
4275 			    }
4276 
4277 			    search_match_lines = regmatch.endpos[0].lnum
4278 						  - regmatch.startpos[0].lnum;
4279 			    search_match_endcol = regmatch.endpos[0].col
4280 								 + len_change;
4281 			    highlight_match = TRUE;
4282 
4283 			    update_topline();
4284 			    validate_cursor();
4285 			    update_screen(SOME_VALID);
4286 			    highlight_match = FALSE;
4287 			    redraw_later(SOME_VALID);
4288 
4289 #ifdef FEAT_FOLDING
4290 			    curwin->w_p_fen = save_p_fen;
4291 #endif
4292 			    if (msg_row == Rows - 1)
4293 				msg_didout = FALSE;	// avoid a scroll-up
4294 			    msg_starthere();
4295 			    i = msg_scroll;
4296 			    msg_scroll = 0;		// truncate msg when
4297 							// needed
4298 			    msg_no_more = TRUE;
4299 			    // write message same highlighting as for
4300 			    // wait_return
4301 			    smsg_attr(HL_ATTR(HLF_R),
4302 				_("replace with %s (y/n/a/q/l/^E/^Y)?"), sub);
4303 			    msg_no_more = FALSE;
4304 			    msg_scroll = i;
4305 			    showruler(TRUE);
4306 			    windgoto(msg_row, msg_col);
4307 			    RedrawingDisabled = temp;
4308 
4309 #ifdef USE_ON_FLY_SCROLL
4310 			    dont_scroll = FALSE; // allow scrolling here
4311 #endif
4312 			    ++no_mapping;	// don't map this key
4313 			    ++allow_keys;	// allow special keys
4314 			    typed = plain_vgetc();
4315 			    --allow_keys;
4316 			    --no_mapping;
4317 
4318 			    // clear the question
4319 			    msg_didout = FALSE;	// don't scroll up
4320 			    msg_col = 0;
4321 			    gotocmdline(TRUE);
4322 			    p_lz = save_p_lz;
4323 
4324 			    // restore the line
4325 			    if (orig_line != NULL)
4326 				ml_replace(lnum, orig_line, FALSE);
4327 			}
4328 
4329 			need_wait_return = FALSE; // no hit-return prompt
4330 			if (typed == 'q' || typed == ESC || typed == Ctrl_C
4331 #ifdef UNIX
4332 				|| typed == intr_char
4333 #endif
4334 				)
4335 			{
4336 			    got_quit = TRUE;
4337 			    break;
4338 			}
4339 			if (typed == 'n')
4340 			    break;
4341 			if (typed == 'y')
4342 			    break;
4343 			if (typed == 'l')
4344 			{
4345 			    // last: replace and then stop
4346 			    subflags.do_all = FALSE;
4347 			    line2 = lnum;
4348 			    break;
4349 			}
4350 			if (typed == 'a')
4351 			{
4352 			    subflags.do_ask = FALSE;
4353 			    break;
4354 			}
4355 			if (typed == Ctrl_E)
4356 			    scrollup_clamp();
4357 			else if (typed == Ctrl_Y)
4358 			    scrolldown_clamp();
4359 		    }
4360 		    State = save_State;
4361 		    setmouse();
4362 		    if (vim_strchr(p_cpo, CPO_UNDO) != NULL)
4363 			--no_u_sync;
4364 
4365 		    if (typed == 'n')
4366 		    {
4367 			// For a multi-line match, put matchcol at the NUL at
4368 			// the end of the line and set nmatch to one, so that
4369 			// we continue looking for a match on the next line.
4370 			// Avoids that ":%s/\nB\@=//gc" and ":%s/\n/,\r/gc"
4371 			// get stuck when pressing 'n'.
4372 			if (nmatch > 1)
4373 			{
4374 			    matchcol = (colnr_T)STRLEN(sub_firstline);
4375 			    skip_match = TRUE;
4376 			}
4377 			goto skip;
4378 		    }
4379 		    if (got_quit)
4380 			goto skip;
4381 		}
4382 
4383 		// Move the cursor to the start of the match, so that we can
4384 		// use "\=col(".").
4385 		curwin->w_cursor.col = regmatch.startpos[0].col;
4386 
4387 		/*
4388 		 * 3. substitute the string.
4389 		 */
4390 #ifdef FEAT_EVAL
4391 		save_ma = curbuf->b_p_ma;
4392 		if (subflags.do_count)
4393 		{
4394 		    // prevent accidentally changing the buffer by a function
4395 		    curbuf->b_p_ma = FALSE;
4396 		    sandbox++;
4397 		}
4398 		// Save flags for recursion.  They can change for e.g.
4399 		// :s/^/\=execute("s#^##gn")
4400 		subflags_save = subflags;
4401 #endif
4402 		// get length of substitution part
4403 		sublen = vim_regsub_multi(&regmatch,
4404 				    sub_firstlnum - regmatch.startpos[0].lnum,
4405 			       sub, sub_firstline, FALSE, magic_isset(), TRUE);
4406 #ifdef FEAT_EVAL
4407 		// If getting the substitute string caused an error, don't do
4408 		// the replacement.
4409 		// Don't keep flags set by a recursive call.
4410 		subflags = subflags_save;
4411 		if (aborting() || subflags.do_count)
4412 		{
4413 		    curbuf->b_p_ma = save_ma;
4414 		    if (sandbox > 0)
4415 			sandbox--;
4416 		    goto skip;
4417 		}
4418 #endif
4419 
4420 		// When the match included the "$" of the last line it may
4421 		// go beyond the last line of the buffer.
4422 		if (nmatch > curbuf->b_ml.ml_line_count - sub_firstlnum + 1)
4423 		{
4424 		    nmatch = curbuf->b_ml.ml_line_count - sub_firstlnum + 1;
4425 		    skip_match = TRUE;
4426 		}
4427 
4428 		// Need room for:
4429 		// - result so far in new_start (not for first sub in line)
4430 		// - original text up to match
4431 		// - length of substituted part
4432 		// - original text after match
4433 		// Adjust text properties here, since we have all information
4434 		// needed.
4435 		if (nmatch == 1)
4436 		{
4437 		    p1 = sub_firstline;
4438 #ifdef FEAT_PROP_POPUP
4439 		    if (curbuf->b_has_textprop)
4440 		    {
4441 			int bytes_added = sublen - 1 - (regmatch.endpos[0].col
4442 						   - regmatch.startpos[0].col);
4443 
4444 			// When text properties are changed, need to save for
4445 			// undo first, unless done already.
4446 			if (adjust_prop_columns(lnum,
4447 					total_added + regmatch.startpos[0].col,
4448 						       bytes_added, apc_flags))
4449 			    apc_flags &= ~APC_SAVE_FOR_UNDO;
4450 			// Offset for column byte number of the text property
4451 			// in the resulting buffer afterwards.
4452 			total_added += bytes_added;
4453 		    }
4454 #endif
4455 		}
4456 		else
4457 		{
4458 		    p1 = ml_get(sub_firstlnum + nmatch - 1);
4459 		    nmatch_tl += nmatch - 1;
4460 		}
4461 		copy_len = regmatch.startpos[0].col - copycol;
4462 		needed_len = copy_len + ((unsigned)STRLEN(p1)
4463 				       - regmatch.endpos[0].col) + sublen + 1;
4464 		if (new_start == NULL)
4465 		{
4466 		    /*
4467 		     * Get some space for a temporary buffer to do the
4468 		     * substitution into (and some extra space to avoid
4469 		     * too many calls to alloc()/free()).
4470 		     */
4471 		    new_start_len = needed_len + 50;
4472 		    if ((new_start = alloc(new_start_len)) == NULL)
4473 			goto outofmem;
4474 		    *new_start = NUL;
4475 		    new_end = new_start;
4476 		}
4477 		else
4478 		{
4479 		    /*
4480 		     * Check if the temporary buffer is long enough to do the
4481 		     * substitution into.  If not, make it larger (with a bit
4482 		     * extra to avoid too many calls to alloc()/free()).
4483 		     */
4484 		    len = (unsigned)STRLEN(new_start);
4485 		    needed_len += len;
4486 		    if (needed_len > (int)new_start_len)
4487 		    {
4488 			new_start_len = needed_len + 50;
4489 			if ((p1 = alloc(new_start_len)) == NULL)
4490 			{
4491 			    vim_free(new_start);
4492 			    goto outofmem;
4493 			}
4494 			mch_memmove(p1, new_start, (size_t)(len + 1));
4495 			vim_free(new_start);
4496 			new_start = p1;
4497 		    }
4498 		    new_end = new_start + len;
4499 		}
4500 
4501 		/*
4502 		 * copy the text up to the part that matched
4503 		 */
4504 		mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);
4505 		new_end += copy_len;
4506 
4507 		(void)vim_regsub_multi(&regmatch,
4508 				    sub_firstlnum - regmatch.startpos[0].lnum,
4509 				      sub, new_end, TRUE, magic_isset(), TRUE);
4510 		sub_nsubs++;
4511 		did_sub = TRUE;
4512 
4513 		// Move the cursor to the start of the line, to avoid that it
4514 		// is beyond the end of the line after the substitution.
4515 		curwin->w_cursor.col = 0;
4516 
4517 		// For a multi-line match, make a copy of the last matched
4518 		// line and continue in that one.
4519 		if (nmatch > 1)
4520 		{
4521 		    sub_firstlnum += nmatch - 1;
4522 		    vim_free(sub_firstline);
4523 		    sub_firstline = vim_strsave(ml_get(sub_firstlnum));
4524 		    // When going beyond the last line, stop substituting.
4525 		    if (sub_firstlnum <= line2)
4526 			do_again = TRUE;
4527 		    else
4528 			subflags.do_all = FALSE;
4529 		}
4530 
4531 		// Remember next character to be copied.
4532 		copycol = regmatch.endpos[0].col;
4533 
4534 		if (skip_match)
4535 		{
4536 		    // Already hit end of the buffer, sub_firstlnum is one
4537 		    // less than what it ought to be.
4538 		    vim_free(sub_firstline);
4539 		    sub_firstline = vim_strsave((char_u *)"");
4540 		    copycol = 0;
4541 		}
4542 
4543 		/*
4544 		 * Now the trick is to replace CTRL-M chars with a real line
4545 		 * break.  This would make it impossible to insert a CTRL-M in
4546 		 * the text.  The line break can be avoided by preceding the
4547 		 * CTRL-M with a backslash.  To be able to insert a backslash,
4548 		 * they must be doubled in the string and are halved here.
4549 		 * That is Vi compatible.
4550 		 */
4551 		for (p1 = new_end; *p1; ++p1)
4552 		{
4553 		    if (p1[0] == '\\' && p1[1] != NUL)  // remove backslash
4554 		    {
4555 			STRMOVE(p1, p1 + 1);
4556 #ifdef FEAT_PROP_POPUP
4557 			if (curbuf->b_has_textprop)
4558 			{
4559 			    // When text properties are changed, need to save
4560 			    // for undo first, unless done already.
4561 			    if (adjust_prop_columns(lnum,
4562 					(colnr_T)(p1 - new_start), -1,
4563 					apc_flags))
4564 				apc_flags &= ~APC_SAVE_FOR_UNDO;
4565 			}
4566 #endif
4567 		    }
4568 		    else if (*p1 == CAR)
4569 		    {
4570 			if (u_inssub(lnum) == OK)   // prepare for undo
4571 			{
4572 			    colnr_T	plen = (colnr_T)(p1 - new_start + 1);
4573 
4574 			    *p1 = NUL;		    // truncate up to the CR
4575 			    ml_append(lnum - 1, new_start, plen, FALSE);
4576 			    mark_adjust(lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
4577 			    if (subflags.do_ask)
4578 				appended_lines(lnum - 1, 1L);
4579 			    else
4580 			    {
4581 				if (first_line == 0)
4582 				    first_line = lnum;
4583 				last_line = lnum + 1;
4584 			    }
4585 #ifdef FEAT_PROP_POPUP
4586 			    adjust_props_for_split(lnum + 1, lnum, plen, 1);
4587 #endif
4588 			    // all line numbers increase
4589 			    ++sub_firstlnum;
4590 			    ++lnum;
4591 			    ++line2;
4592 			    // move the cursor to the new line, like Vi
4593 			    ++curwin->w_cursor.lnum;
4594 			    // copy the rest
4595 			    STRMOVE(new_start, p1 + 1);
4596 			    p1 = new_start - 1;
4597 			}
4598 		    }
4599 		    else if (has_mbyte)
4600 			p1 += (*mb_ptr2len)(p1) - 1;
4601 		}
4602 
4603 		/*
4604 		 * 4. If do_all is set, find next match.
4605 		 * Prevent endless loop with patterns that match empty
4606 		 * strings, e.g. :s/$/pat/g or :s/[a-z]* /(&)/g.
4607 		 * But ":s/\n/#/" is OK.
4608 		 */
4609 skip:
4610 		// We already know that we did the last subst when we are at
4611 		// the end of the line, except that a pattern like
4612 		// "bar\|\nfoo" may match at the NUL.  "lnum" can be below
4613 		// "line2" when there is a \zs in the pattern after a line
4614 		// break.
4615 		lastone = (skip_match
4616 			|| got_int
4617 			|| got_quit
4618 			|| lnum > line2
4619 			|| !(subflags.do_all || do_again)
4620 			|| (sub_firstline[matchcol] == NUL && nmatch <= 1
4621 					 && !re_multiline(regmatch.regprog)));
4622 		nmatch = -1;
4623 
4624 		/*
4625 		 * Replace the line in the buffer when needed.  This is
4626 		 * skipped when there are more matches.
4627 		 * The check for nmatch_tl is needed for when multi-line
4628 		 * matching must replace the lines before trying to do another
4629 		 * match, otherwise "\@<=" won't work.
4630 		 * When the match starts below where we start searching also
4631 		 * need to replace the line first (using \zs after \n).
4632 		 */
4633 		if (lastone
4634 			|| nmatch_tl > 0
4635 			|| (nmatch = vim_regexec_multi(&regmatch, curwin,
4636 							curbuf, sub_firstlnum,
4637 						    matchcol, NULL, NULL)) == 0
4638 			|| regmatch.startpos[0].lnum > 0)
4639 		{
4640 		    if (new_start != NULL)
4641 		    {
4642 			/*
4643 			 * Copy the rest of the line, that didn't match.
4644 			 * "matchcol" has to be adjusted, we use the end of
4645 			 * the line as reference, because the substitute may
4646 			 * have changed the number of characters.  Same for
4647 			 * "prev_matchcol".
4648 			 */
4649 			STRCAT(new_start, sub_firstline + copycol);
4650 			matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4651 			prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4652 							      - prev_matchcol;
4653 
4654 			if (u_savesub(lnum) != OK)
4655 			    break;
4656 			ml_replace(lnum, new_start, TRUE);
4657 
4658 			if (nmatch_tl > 0)
4659 			{
4660 			    /*
4661 			     * Matched lines have now been substituted and are
4662 			     * useless, delete them.  The part after the match
4663 			     * has been appended to new_start, we don't need
4664 			     * it in the buffer.
4665 			     */
4666 			    ++lnum;
4667 			    if (u_savedel(lnum, nmatch_tl) != OK)
4668 				break;
4669 			    for (i = 0; i < nmatch_tl; ++i)
4670 				ml_delete(lnum);
4671 			    mark_adjust(lnum, lnum + nmatch_tl - 1,
4672 						   (long)MAXLNUM, -nmatch_tl);
4673 			    if (subflags.do_ask)
4674 				deleted_lines(lnum, nmatch_tl);
4675 			    --lnum;
4676 			    line2 -= nmatch_tl; // nr of lines decreases
4677 			    nmatch_tl = 0;
4678 			}
4679 
4680 			// When asking, undo is saved each time, must also set
4681 			// changed flag each time.
4682 			if (subflags.do_ask)
4683 			    changed_bytes(lnum, 0);
4684 			else
4685 			{
4686 			    if (first_line == 0)
4687 				first_line = lnum;
4688 			    last_line = lnum + 1;
4689 			}
4690 
4691 			sub_firstlnum = lnum;
4692 			vim_free(sub_firstline);    // free the temp buffer
4693 			sub_firstline = new_start;
4694 			new_start = NULL;
4695 			matchcol = (colnr_T)STRLEN(sub_firstline) - matchcol;
4696 			prev_matchcol = (colnr_T)STRLEN(sub_firstline)
4697 							      - prev_matchcol;
4698 			copycol = 0;
4699 		    }
4700 		    if (nmatch == -1 && !lastone)
4701 			nmatch = vim_regexec_multi(&regmatch, curwin, curbuf,
4702 					  sub_firstlnum, matchcol, NULL, NULL);
4703 
4704 		    /*
4705 		     * 5. break if there isn't another match in this line
4706 		     */
4707 		    if (nmatch <= 0)
4708 		    {
4709 			// If the match found didn't start where we were
4710 			// searching, do the next search in the line where we
4711 			// found the match.
4712 			if (nmatch == -1)
4713 			    lnum -= regmatch.startpos[0].lnum;
4714 			break;
4715 		    }
4716 		}
4717 
4718 		line_breakcheck();
4719 	    }
4720 
4721 	    if (did_sub)
4722 		++sub_nlines;
4723 	    vim_free(new_start);	// for when substitute was cancelled
4724 	    VIM_CLEAR(sub_firstline);	// free the copy of the original line
4725 	}
4726 
4727 	line_breakcheck();
4728     }
4729 
4730     if (first_line != 0)
4731     {
4732 	// Need to subtract the number of added lines from "last_line" to get
4733 	// the line number before the change (same as adding the number of
4734 	// deleted lines).
4735 	i = curbuf->b_ml.ml_line_count - old_line_count;
4736 	changed_lines(first_line, 0, last_line - i, i);
4737     }
4738 
4739 outofmem:
4740     vim_free(sub_firstline); // may have to free allocated copy of the line
4741 
4742     // ":s/pat//n" doesn't move the cursor
4743     if (subflags.do_count)
4744 	curwin->w_cursor = old_cursor;
4745 
4746     if (sub_nsubs > start_nsubs)
4747     {
4748 	if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
4749 	{
4750 	    // Set the '[ and '] marks.
4751 	    curbuf->b_op_start.lnum = eap->line1;
4752 	    curbuf->b_op_end.lnum = line2;
4753 	    curbuf->b_op_start.col = curbuf->b_op_end.col = 0;
4754 	}
4755 
4756 	if (!global_busy)
4757 	{
4758 	    // when interactive leave cursor on the match
4759 	    if (!subflags.do_ask)
4760 	    {
4761 		if (endcolumn)
4762 		    coladvance((colnr_T)MAXCOL);
4763 		else
4764 		    beginline(BL_WHITE | BL_FIX);
4765 	    }
4766 	    if (!do_sub_msg(subflags.do_count) && subflags.do_ask)
4767 		msg("");
4768 	}
4769 	else
4770 	    global_need_beginline = TRUE;
4771 	if (subflags.do_print)
4772 	    print_line(curwin->w_cursor.lnum,
4773 					 subflags.do_number, subflags.do_list);
4774     }
4775     else if (!global_busy)
4776     {
4777 	if (got_int)		// interrupted
4778 	    emsg(_(e_interr));
4779 	else if (got_match)	// did find something but nothing substituted
4780 	    msg("");
4781 	else if (subflags.do_error)	// nothing found
4782 	    semsg(_(e_patnotf2), get_search_pat());
4783     }
4784 
4785 #ifdef FEAT_FOLDING
4786     if (subflags.do_ask && hasAnyFolding(curwin))
4787 	// Cursor position may require updating
4788 	changed_window_setting();
4789 #endif
4790 
4791     vim_regfree(regmatch.regprog);
4792 
4793     // Restore the flag values, they can be used for ":&&".
4794     subflags.do_all = save_do_all;
4795     subflags.do_ask = save_do_ask;
4796 }
4797 
4798 /*
4799  * Give message for number of substitutions.
4800  * Can also be used after a ":global" command.
4801  * Return TRUE if a message was given.
4802  */
4803     int
do_sub_msg(int count_only)4804 do_sub_msg(
4805     int	    count_only)		// used 'n' flag for ":s"
4806 {
4807     /*
4808      * Only report substitutions when:
4809      * - more than 'report' substitutions
4810      * - command was typed by user, or number of changed lines > 'report'
4811      * - giving messages is not disabled by 'lazyredraw'
4812      */
4813     if (((sub_nsubs > p_report && (KeyTyped || sub_nlines > 1 || p_report < 1))
4814 		|| count_only)
4815 	    && messaging())
4816     {
4817 	char	*msg_single;
4818 	char	*msg_plural;
4819 
4820 	if (got_int)
4821 	    STRCPY(msg_buf, _("(Interrupted) "));
4822 	else
4823 	    *msg_buf = NUL;
4824 
4825 	msg_single = count_only
4826 		    ? NGETTEXT("%ld match on %ld line",
4827 					  "%ld matches on %ld line", sub_nsubs)
4828 		    : NGETTEXT("%ld substitution on %ld line",
4829 				   "%ld substitutions on %ld line", sub_nsubs);
4830 	msg_plural = count_only
4831 		    ? NGETTEXT("%ld match on %ld lines",
4832 					 "%ld matches on %ld lines", sub_nsubs)
4833 		    : NGETTEXT("%ld substitution on %ld lines",
4834 				  "%ld substitutions on %ld lines", sub_nsubs);
4835 
4836 	vim_snprintf_add(msg_buf, sizeof(msg_buf),
4837 				 NGETTEXT(msg_single, msg_plural, sub_nlines),
4838 				 sub_nsubs, (long)sub_nlines);
4839 
4840 	if (msg(msg_buf))
4841 	    // save message to display it after redraw
4842 	    set_keep_msg((char_u *)msg_buf, 0);
4843 	return TRUE;
4844     }
4845     if (got_int)
4846     {
4847 	emsg(_(e_interr));
4848 	return TRUE;
4849     }
4850     return FALSE;
4851 }
4852 
4853     static void
global_exe_one(char_u * cmd,linenr_T lnum)4854 global_exe_one(char_u *cmd, linenr_T lnum)
4855 {
4856     curwin->w_cursor.lnum = lnum;
4857     curwin->w_cursor.col = 0;
4858     if (*cmd == NUL || *cmd == '\n')
4859 	do_cmdline((char_u *)"p", NULL, NULL, DOCMD_NOWAIT);
4860     else
4861 	do_cmdline(cmd, NULL, NULL, DOCMD_NOWAIT);
4862 }
4863 
4864 /*
4865  * Execute a global command of the form:
4866  *
4867  * g/pattern/X : execute X on all lines where pattern matches
4868  * v/pattern/X : execute X on all lines where pattern does not match
4869  *
4870  * where 'X' is an EX command
4871  *
4872  * The command character (as well as the trailing slash) is optional, and
4873  * is assumed to be 'p' if missing.
4874  *
4875  * This is implemented in two passes: first we scan the file for the pattern and
4876  * set a mark for each line that (not) matches. Secondly we execute the command
4877  * for each line that has a mark. This is required because after deleting
4878  * lines we do not know where to search for the next match.
4879  */
4880     void
ex_global(exarg_T * eap)4881 ex_global(exarg_T *eap)
4882 {
4883     linenr_T	lnum;		// line number according to old situation
4884     int		ndone = 0;
4885     int		type;		// first char of cmd: 'v' or 'g'
4886     char_u	*cmd;		// command argument
4887 
4888     char_u	delim;		// delimiter, normally '/'
4889     char_u	*pat;
4890     regmmatch_T	regmatch;
4891     int		match;
4892     int		which_pat;
4893 
4894     // When nesting the command works on one line.  This allows for
4895     // ":g/found/v/notfound/command".
4896     if (global_busy && (eap->line1 != 1
4897 				  || eap->line2 != curbuf->b_ml.ml_line_count))
4898     {
4899 	// will increment global_busy to break out of the loop
4900 	emsg(_("E147: Cannot do :global recursive with a range"));
4901 	return;
4902     }
4903 
4904     if (eap->forceit)		    // ":global!" is like ":vglobal"
4905 	type = 'v';
4906     else
4907 	type = *eap->cmd;
4908     cmd = eap->arg;
4909     which_pat = RE_LAST;	    // default: use last used regexp
4910 
4911 #ifdef FEAT_EVAL
4912     if (in_vim9script() && check_global_and_subst(eap->cmd, eap->arg) == FAIL)
4913 	return;
4914 #endif
4915 
4916     /*
4917      * undocumented vi feature:
4918      *	"\/" and "\?": use previous search pattern.
4919      *		 "\&": use previous substitute pattern.
4920      */
4921     if (*cmd == '\\')
4922     {
4923 	++cmd;
4924 	if (vim_strchr((char_u *)"/?&", *cmd) == NULL)
4925 	{
4926 	    emsg(_(e_backslash_should_be_followed_by));
4927 	    return;
4928 	}
4929 	if (*cmd == '&')
4930 	    which_pat = RE_SUBST;	// use previous substitute pattern
4931 	else
4932 	    which_pat = RE_SEARCH;	// use previous search pattern
4933 	++cmd;
4934 	pat = (char_u *)"";
4935     }
4936     else if (*cmd == NUL)
4937     {
4938 	emsg(_("E148: Regular expression missing from global"));
4939 	return;
4940     }
4941     else if (check_regexp_delim(*cmd) == FAIL)
4942     {
4943 	return;
4944     }
4945     else
4946     {
4947 	delim = *cmd;		// get the delimiter
4948 	if (delim)
4949 	    ++cmd;		// skip delimiter if there is one
4950 	pat = cmd;		// remember start of pattern
4951 	cmd = skip_regexp_ex(cmd, delim, magic_isset(), &eap->arg, NULL, NULL);
4952 	if (cmd[0] == delim)		    // end delimiter found
4953 	    *cmd++ = NUL;		    // replace it with a NUL
4954     }
4955 
4956     if (search_regcomp(pat, RE_BOTH, which_pat, SEARCH_HIS, &regmatch) == FAIL)
4957     {
4958 	emsg(_(e_invalid_command));
4959 	return;
4960     }
4961 
4962     if (global_busy)
4963     {
4964 	lnum = curwin->w_cursor.lnum;
4965 	match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
4966 						       (colnr_T)0, NULL, NULL);
4967 	if ((type == 'g' && match) || (type == 'v' && !match))
4968 	    global_exe_one(cmd, lnum);
4969     }
4970     else
4971     {
4972 	/*
4973 	 * pass 1: set marks for each (not) matching line
4974 	 */
4975 	for (lnum = eap->line1; lnum <= eap->line2 && !got_int; ++lnum)
4976 	{
4977 	    // a match on this line?
4978 	    match = vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
4979 						       (colnr_T)0, NULL, NULL);
4980 	    if ((type == 'g' && match) || (type == 'v' && !match))
4981 	    {
4982 		ml_setmarked(lnum);
4983 		ndone++;
4984 	    }
4985 	    line_breakcheck();
4986 	}
4987 
4988 	/*
4989 	 * pass 2: execute the command for each line that has been marked
4990 	 */
4991 	if (got_int)
4992 	    msg(_(e_interr));
4993 	else if (ndone == 0)
4994 	{
4995 	    if (type == 'v')
4996 		smsg(_("Pattern found in every line: %s"), pat);
4997 	    else
4998 		smsg(_("Pattern not found: %s"), pat);
4999 	}
5000 	else
5001 	{
5002 #ifdef FEAT_CLIPBOARD
5003 	    start_global_changes();
5004 #endif
5005 	    global_exe(cmd);
5006 #ifdef FEAT_CLIPBOARD
5007 	    end_global_changes();
5008 #endif
5009 	}
5010 
5011 	ml_clearmarked();	   // clear rest of the marks
5012     }
5013 
5014     vim_regfree(regmatch.regprog);
5015 }
5016 
5017 /*
5018  * Execute "cmd" on lines marked with ml_setmarked().
5019  */
5020     void
global_exe(char_u * cmd)5021 global_exe(char_u *cmd)
5022 {
5023     linenr_T old_lcount;	// b_ml.ml_line_count before the command
5024     buf_T    *old_buf = curbuf;	// remember what buffer we started in
5025     linenr_T lnum;		// line number according to old situation
5026 
5027     /*
5028      * Set current position only once for a global command.
5029      * If global_busy is set, setpcmark() will not do anything.
5030      * If there is an error, global_busy will be incremented.
5031      */
5032     setpcmark();
5033 
5034     // When the command writes a message, don't overwrite the command.
5035     msg_didout = TRUE;
5036 
5037     sub_nsubs = 0;
5038     sub_nlines = 0;
5039     global_need_beginline = FALSE;
5040     global_busy = 1;
5041     old_lcount = curbuf->b_ml.ml_line_count;
5042     while (!got_int && (lnum = ml_firstmarked()) != 0 && global_busy == 1)
5043     {
5044 	global_exe_one(cmd, lnum);
5045 	ui_breakcheck();
5046     }
5047 
5048     global_busy = 0;
5049     if (global_need_beginline)
5050 	beginline(BL_WHITE | BL_FIX);
5051     else
5052 	check_cursor();	// cursor may be beyond the end of the line
5053 
5054     // the cursor may not have moved in the text but a change in a previous
5055     // line may move it on the screen
5056     changed_line_abv_curs();
5057 
5058     // If it looks like no message was written, allow overwriting the
5059     // command with the report for number of changes.
5060     if (msg_col == 0 && msg_scrolled == 0)
5061 	msg_didout = FALSE;
5062 
5063     // If substitutes done, report number of substitutes, otherwise report
5064     // number of extra or deleted lines.
5065     // Don't report extra or deleted lines in the edge case where the buffer
5066     // we are in after execution is different from the buffer we started in.
5067     if (!do_sub_msg(FALSE) && curbuf == old_buf)
5068 	msgmore(curbuf->b_ml.ml_line_count - old_lcount);
5069 }
5070 
5071 #ifdef FEAT_VIMINFO
5072 /*
5073  * Get the previous substitute pattern.
5074  */
5075     char_u *
get_old_sub(void)5076 get_old_sub(void)
5077 {
5078     return old_sub;
5079 }
5080 
5081 /*
5082  * Set the previous substitute pattern.  "val" must be allocated.
5083  */
5084     void
set_old_sub(char_u * val)5085 set_old_sub(char_u *val)
5086 {
5087     vim_free(old_sub);
5088     old_sub = val;
5089 }
5090 #endif // FEAT_VIMINFO
5091 
5092 #if defined(EXITFREE) || defined(PROTO)
5093     void
free_old_sub(void)5094 free_old_sub(void)
5095 {
5096     vim_free(old_sub);
5097 }
5098 #endif
5099 
5100 #if defined(FEAT_QUICKFIX) || defined(PROTO)
5101 /*
5102  * Set up for a tagpreview.
5103  * Makes the preview window the current window.
5104  * Return TRUE when it was created.
5105  */
5106     int
prepare_tagpreview(int undo_sync,int use_previewpopup,use_popup_T use_popup)5107 prepare_tagpreview(
5108     int		undo_sync,	    // sync undo when leaving the window
5109     int		use_previewpopup,   // use popup if 'previewpopup' set
5110     use_popup_T	use_popup)	    // use other popup window
5111 {
5112     win_T	*wp;
5113 
5114 # ifdef FEAT_GUI
5115     need_mouse_correct = TRUE;
5116 # endif
5117 
5118     /*
5119      * If there is already a preview window open, use that one.
5120      */
5121     if (!curwin->w_p_pvw)
5122     {
5123 # ifdef FEAT_PROP_POPUP
5124 	if (use_previewpopup && *p_pvp != NUL)
5125 	{
5126 	    wp = popup_find_preview_window();
5127 	    if (wp != NULL)
5128 		popup_set_wantpos_cursor(wp, wp->w_minwidth, NULL);
5129 	}
5130 	else if (use_popup != USEPOPUP_NONE)
5131 	{
5132 	    wp = popup_find_info_window();
5133 	    if (wp != NULL)
5134 	    {
5135 		if (use_popup == USEPOPUP_NORMAL)
5136 		    popup_show(wp);
5137 		else
5138 		    popup_hide(wp);
5139 		// When the popup moves or resizes it may reveal part of
5140 		// another window.  TODO: can this be done more efficiently?
5141 		redraw_all_later(NOT_VALID);
5142 	    }
5143 	}
5144 	else
5145 # endif
5146 	{
5147 	    FOR_ALL_WINDOWS(wp)
5148 		if (wp->w_p_pvw)
5149 		    break;
5150 	}
5151 	if (wp != NULL)
5152 	    win_enter(wp, undo_sync);
5153 	else
5154 	{
5155 	    /*
5156 	     * There is no preview window open yet.  Create one.
5157 	     */
5158 # ifdef FEAT_PROP_POPUP
5159 	    if ((use_previewpopup && *p_pvp != NUL)
5160 						 || use_popup != USEPOPUP_NONE)
5161 		return popup_create_preview_window(use_popup != USEPOPUP_NONE);
5162 # endif
5163 	    if (win_split(g_do_tagpreview > 0 ? g_do_tagpreview : 0, 0) == FAIL)
5164 		return FALSE;
5165 	    curwin->w_p_pvw = TRUE;
5166 	    curwin->w_p_wfh = TRUE;
5167 	    RESET_BINDING(curwin);	    // don't take over 'scrollbind'
5168 	    // and 'cursorbind'
5169 # ifdef FEAT_DIFF
5170 	    curwin->w_p_diff = FALSE;	    // no 'diff'
5171 # endif
5172 # ifdef FEAT_FOLDING
5173 	    curwin->w_p_fdc = 0;	    // no 'foldcolumn'
5174 # endif
5175 	    return TRUE;
5176 	}
5177     }
5178     return FALSE;
5179 }
5180 
5181 #endif
5182 
5183 /*
5184  * Make the user happy.
5185  */
5186     void
ex_smile(exarg_T * eap UNUSED)5187 ex_smile(exarg_T *eap UNUSED)
5188 {
5189     static char *code[] = {
5190 	"\34 \4o\14$\4ox\30 \2o\30$\1ox\25 \2o\36$\1o\11 \1o\1$\3 \2$\1 \1o\1$x\5 \1o\1 \1$\1 \2o\10 \1o\44$\1o\7 \2$\1 \2$\1 \2$\1o\1$x\2 \2o\1 \1$\1 \1$\1 \1\"\1$\6 \1o\11$\4 \15$\4 \11$\1o\7 \3$\1o\2$\1o\1$x\2 \1\"\6$\1o\1$\5 \1o\11$\6 \13$\6 \12$\1o\4 \10$x\4 \7$\4 \13$\6 \13$\6 \27$x\4 \27$\4 \15$\4 \16$\2 \3\"\3$x\5 \1\"\3$\4\"\61$\5 \1\"\3$x\6 \3$\3 \1o\62$\5 \1\"\3$\1ox\5 \1o\2$\1\"\3 \63$\7 \3$\1ox\5 \3$\4 \55$\1\"\1 \1\"\6$",
5191 	"\5o\4$\1ox\4 \1o\3$\4o\5$\2 \45$\3 \1o\21$x\4 \10$\1\"\4$\3 \42$\5 \4$\10\"x\3 \4\"\7 \4$\4 \1\"\34$\1\"\6 \1o\3$x\16 \1\"\3$\1o\5 \3\"\22$\1\"\2$\1\"\11 \3$x\20 \3$\1o\12 \1\"\2$\2\"\6$\4\"\13 \1o\3$x\21 \4$\1o\40 \1o\3$\1\"x\22 \1\"\4$\1o\6 \1o\6$\1o\1\"\4$\1o\10 \1o\4$x\24 \1\"\5$\2o\5 \2\"\4$\1o\5$\1o\3 \1o\4$\2\"x\27 \2\"\5$\4o\2 \1\"\3$\1o\11$\3\"x\32 \2\"\7$\2o\1 \12$x\42 \4\"\13$x\46 \14$x\47 \12$\1\"x\50 \1\"\3$\4\"x"
5192     };
5193     char *p;
5194     int n;
5195     int i;
5196 
5197     msg_start();
5198     msg_putchar('\n');
5199     for (i = 0; i < 2; ++i)
5200 	for (p = code[i]; *p != NUL; ++p)
5201 	    if (*p == 'x')
5202 		msg_putchar('\n');
5203 	    else
5204 		for (n = *p++; n > 0; --n)
5205 		    if (*p == 'o' || *p == '$')
5206 			msg_putchar_attr(*p, HL_ATTR(HLF_L));
5207 		    else
5208 			msg_putchar(*p);
5209     msg_clr_eos();
5210 }
5211 
5212 /*
5213  * ":drop"
5214  * Opens the first argument in a window.  When there are two or more arguments
5215  * the argument list is redefined.
5216  */
5217     void
ex_drop(exarg_T * eap)5218 ex_drop(exarg_T *eap)
5219 {
5220     int		split = FALSE;
5221     win_T	*wp;
5222     buf_T	*buf;
5223     tabpage_T	*tp;
5224 
5225     if (ERROR_IF_POPUP_WINDOW || ERROR_IF_TERM_POPUP_WINDOW)
5226 	return;
5227 
5228     /*
5229      * Check if the first argument is already being edited in a window.  If
5230      * so, jump to that window.
5231      * We would actually need to check all arguments, but that's complicated
5232      * and mostly only one file is dropped.
5233      * This also ignores wildcards, since it is very unlikely the user is
5234      * editing a file name with a wildcard character.
5235      */
5236     set_arglist(eap->arg);
5237 
5238     /*
5239      * Expanding wildcards may result in an empty argument list.  E.g. when
5240      * editing "foo.pyc" and ".pyc" is in 'wildignore'.  Assume that we
5241      * already did an error message for this.
5242      */
5243     if (ARGCOUNT == 0)
5244 	return;
5245 
5246     if (cmdmod.cmod_tab)
5247     {
5248 	// ":tab drop file ...": open a tab for each argument that isn't
5249 	// edited in a window yet.  It's like ":tab all" but without closing
5250 	// windows or tabs.
5251 	ex_all(eap);
5252     }
5253     else
5254     {
5255 	// ":drop file ...": Edit the first argument.  Jump to an existing
5256 	// window if possible, edit in current window if the current buffer
5257 	// can be abandoned, otherwise open a new window.
5258 	buf = buflist_findnr(ARGLIST[0].ae_fnum);
5259 
5260 	FOR_ALL_TAB_WINDOWS(tp, wp)
5261 	{
5262 	    if (wp->w_buffer == buf)
5263 	    {
5264 		goto_tabpage_win(tp, wp);
5265 		curwin->w_arg_idx = 0;
5266 		if (!bufIsChanged(curbuf))
5267 		{
5268 		    int save_ar = curbuf->b_p_ar;
5269 
5270 		    // reload the file if it is newer
5271 		    curbuf->b_p_ar = TRUE;
5272 		    buf_check_timestamp(curbuf, FALSE);
5273 		    curbuf->b_p_ar = save_ar;
5274 		}
5275 		return;
5276 	    }
5277 	}
5278 
5279 	/*
5280 	 * Check whether the current buffer is changed. If so, we will need
5281 	 * to split the current window or data could be lost.
5282 	 * Skip the check if the 'hidden' option is set, as in this case the
5283 	 * buffer won't be lost.
5284 	 */
5285 	if (!buf_hide(curbuf))
5286 	{
5287 	    ++emsg_off;
5288 	    split = check_changed(curbuf, CCGD_AW | CCGD_EXCMD);
5289 	    --emsg_off;
5290 	}
5291 
5292 	// Fake a ":sfirst" or ":first" command edit the first argument.
5293 	if (split)
5294 	{
5295 	    eap->cmdidx = CMD_sfirst;
5296 	    eap->cmd[0] = 's';
5297 	}
5298 	else
5299 	    eap->cmdidx = CMD_first;
5300 	ex_rewind(eap);
5301     }
5302 }
5303 
5304 /*
5305  * Skip over the pattern argument of ":vimgrep /pat/[g][j]".
5306  * Put the start of the pattern in "*s", unless "s" is NULL.
5307  * If "flags" is not NULL put the flags in it: VGR_GLOBAL, VGR_NOJUMP.
5308  * If "s" is not NULL terminate the pattern with a NUL.
5309  * Return a pointer to the char just past the pattern plus flags.
5310  */
5311     char_u *
skip_vimgrep_pat(char_u * p,char_u ** s,int * flags)5312 skip_vimgrep_pat(char_u *p, char_u **s, int *flags)
5313 {
5314     return skip_vimgrep_pat_ext(p, s, flags, NULL, NULL);
5315 }
5316 
5317 /*
5318  * As skip_vimgrep_pat() and store the character overwritten by NUL in "cp"
5319  * and the pointer to it in "nulp".
5320  */
5321     char_u *
skip_vimgrep_pat_ext(char_u * p,char_u ** s,int * flags,char_u ** nulp,int * cp)5322 skip_vimgrep_pat_ext(char_u *p, char_u **s, int *flags, char_u **nulp, int *cp)
5323 {
5324     int		c;
5325 
5326     if (vim_isIDc(*p))
5327     {
5328 	// ":vimgrep pattern fname"
5329 	if (s != NULL)
5330 	    *s = p;
5331 	p = skiptowhite(p);
5332 	if (s != NULL && *p != NUL)
5333 	{
5334 	    if (nulp != NULL)
5335 	    {
5336 		*nulp = p;
5337 		*cp = *p;
5338 	    }
5339 	    *p++ = NUL;
5340 	}
5341     }
5342     else
5343     {
5344 	// ":vimgrep /pattern/[g][j] fname"
5345 	if (s != NULL)
5346 	    *s = p + 1;
5347 	c = *p;
5348 	p = skip_regexp(p + 1, c, TRUE);
5349 	if (*p != c)
5350 	    return NULL;
5351 
5352 	// Truncate the pattern.
5353 	if (s != NULL)
5354 	{
5355 	    if (nulp != NULL)
5356 	    {
5357 		*nulp = p;
5358 		*cp = *p;
5359 	    }
5360 	    *p = NUL;
5361 	}
5362 	++p;
5363 
5364 	// Find the flags
5365 	while (*p == 'g' || *p == 'j' || *p == 'f')
5366 	{
5367 	    if (flags != NULL)
5368 	    {
5369 		if (*p == 'g')
5370 		    *flags |= VGR_GLOBAL;
5371 		else if (*p == 'j')
5372 		    *flags |= VGR_NOJUMP;
5373 		else
5374 		    *flags |= VGR_FUZZY;
5375 	    }
5376 	    ++p;
5377 	}
5378     }
5379     return p;
5380 }
5381 
5382 #if defined(FEAT_EVAL) || defined(PROTO)
5383 /*
5384  * List v:oldfiles in a nice way.
5385  */
5386     void
ex_oldfiles(exarg_T * eap UNUSED)5387 ex_oldfiles(exarg_T *eap UNUSED)
5388 {
5389     list_T	*l = get_vim_var_list(VV_OLDFILES);
5390     listitem_T	*li;
5391     int		nr = 0;
5392     char_u	*fname;
5393 
5394     if (l == NULL)
5395 	msg(_("No old files"));
5396     else
5397     {
5398 	msg_start();
5399 	msg_scroll = TRUE;
5400 	for (li = l->lv_first; li != NULL && !got_int; li = li->li_next)
5401 	{
5402 	    ++nr;
5403 	    fname = tv_get_string(&li->li_tv);
5404 	    if (!message_filtered(fname))
5405 	    {
5406 		msg_outnum((long)nr);
5407 		msg_puts(": ");
5408 		msg_outtrans(fname);
5409 		msg_clr_eos();
5410 		msg_putchar('\n');
5411 		out_flush();	    // output one line at a time
5412 		ui_breakcheck();
5413 	    }
5414 	}
5415 
5416 	// Assume "got_int" was set to truncate the listing.
5417 	got_int = FALSE;
5418 
5419 # ifdef FEAT_BROWSE_CMD
5420 	if (cmdmod.cmod_flags & CMOD_BROWSE)
5421 	{
5422 	    quit_more = FALSE;
5423 	    nr = prompt_for_number(FALSE);
5424 	    msg_starthere();
5425 	    if (nr > 0)
5426 	    {
5427 		char_u *p = list_find_str(get_vim_var_list(VV_OLDFILES),
5428 								    (long)nr);
5429 
5430 		if (p != NULL)
5431 		{
5432 		    p = expand_env_save(p);
5433 		    eap->arg = p;
5434 		    eap->cmdidx = CMD_edit;
5435 		    cmdmod.cmod_flags &= ~CMOD_BROWSE;
5436 		    do_exedit(eap, NULL);
5437 		    vim_free(p);
5438 		}
5439 	    }
5440 	}
5441 # endif
5442     }
5443 }
5444 #endif
5445