xref: /vim-8.2.3635/src/misc1.c (revision e16b00a1)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
3  * VIM - Vi IMproved	by Bram Moolenaar
4  *
5  * Do ":help uganda"  in Vim to read copying and usage conditions.
6  * Do ":help credits" in Vim to see a list of people who contributed.
7  * See README.txt for an overview of the Vim source code.
8  */
9 
10 /*
11  * misc1.c: functions that didn't seem to fit elsewhere
12  */
13 
14 #include "vim.h"
15 #include "version.h"
16 
17 static char_u *vim_version_dir(char_u *vimdir);
18 static char_u *remove_tail(char_u *p, char_u *pend, char_u *name);
19 #if defined(FEAT_CMDL_COMPL)
20 static void init_users(void);
21 #endif
22 static int copy_indent(int size, char_u	*src);
23 
24 /* All user names (for ~user completion as done by shell). */
25 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
26 static garray_T	ga_users;
27 #endif
28 
29 /*
30  * Count the size (in window cells) of the indent in the current line.
31  */
32     int
33 get_indent(void)
34 {
35     return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts, FALSE);
36 }
37 
38 /*
39  * Count the size (in window cells) of the indent in line "lnum".
40  */
41     int
42 get_indent_lnum(linenr_T lnum)
43 {
44     return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts, FALSE);
45 }
46 
47 #if defined(FEAT_FOLDING) || defined(PROTO)
48 /*
49  * Count the size (in window cells) of the indent in line "lnum" of buffer
50  * "buf".
51  */
52     int
53 get_indent_buf(buf_T *buf, linenr_T lnum)
54 {
55     return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts, FALSE);
56 }
57 #endif
58 
59 /*
60  * count the size (in window cells) of the indent in line "ptr", with
61  * 'tabstop' at "ts"
62  */
63     int
64 get_indent_str(
65     char_u	*ptr,
66     int		ts,
67     int		list) /* if TRUE, count only screen size for tabs */
68 {
69     int		count = 0;
70 
71     for ( ; *ptr; ++ptr)
72     {
73 	if (*ptr == TAB)
74 	{
75 	    if (!list || lcs_tab1)    /* count a tab for what it is worth */
76 		count += ts - (count % ts);
77 	    else
78 		/* In list mode, when tab is not set, count screen char width
79 		 * for Tab, displays: ^I */
80 		count += ptr2cells(ptr);
81 	}
82 	else if (*ptr == ' ')
83 	    ++count;		/* count a space for one */
84 	else
85 	    break;
86     }
87     return count;
88 }
89 
90 /*
91  * Set the indent of the current line.
92  * Leaves the cursor on the first non-blank in the line.
93  * Caller must take care of undo.
94  * "flags":
95  *	SIN_CHANGED:	call changed_bytes() if the line was changed.
96  *	SIN_INSERT:	insert the indent in front of the line.
97  *	SIN_UNDO:	save line for undo before changing it.
98  * Returns TRUE if the line was changed.
99  */
100     int
101 set_indent(
102     int		size,		    /* measured in spaces */
103     int		flags)
104 {
105     char_u	*p;
106     char_u	*newline;
107     char_u	*oldline;
108     char_u	*s;
109     int		todo;
110     int		ind_len;	    /* measured in characters */
111     int		line_len;
112     int		doit = FALSE;
113     int		ind_done = 0;	    /* measured in spaces */
114     int		tab_pad;
115     int		retval = FALSE;
116     int		orig_char_len = -1; /* number of initial whitespace chars when
117 				       'et' and 'pi' are both set */
118 
119     /*
120      * First check if there is anything to do and compute the number of
121      * characters needed for the indent.
122      */
123     todo = size;
124     ind_len = 0;
125     p = oldline = ml_get_curline();
126 
127     /* Calculate the buffer size for the new indent, and check to see if it
128      * isn't already set */
129 
130     /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
131      * 'preserveindent' are set count the number of characters at the
132      * beginning of the line to be copied */
133     if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
134     {
135 	/* If 'preserveindent' is set then reuse as much as possible of
136 	 * the existing indent structure for the new indent */
137 	if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
138 	{
139 	    ind_done = 0;
140 
141 	    /* count as many characters as we can use */
142 	    while (todo > 0 && VIM_ISWHITE(*p))
143 	    {
144 		if (*p == TAB)
145 		{
146 		    tab_pad = (int)curbuf->b_p_ts
147 					   - (ind_done % (int)curbuf->b_p_ts);
148 		    /* stop if this tab will overshoot the target */
149 		    if (todo < tab_pad)
150 			break;
151 		    todo -= tab_pad;
152 		    ++ind_len;
153 		    ind_done += tab_pad;
154 		}
155 		else
156 		{
157 		    --todo;
158 		    ++ind_len;
159 		    ++ind_done;
160 		}
161 		++p;
162 	    }
163 
164 	    /* Set initial number of whitespace chars to copy if we are
165 	     * preserving indent but expandtab is set */
166 	    if (curbuf->b_p_et)
167 		orig_char_len = ind_len;
168 
169 	    /* Fill to next tabstop with a tab, if possible */
170 	    tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
171 	    if (todo >= tab_pad && orig_char_len == -1)
172 	    {
173 		doit = TRUE;
174 		todo -= tab_pad;
175 		++ind_len;
176 		/* ind_done += tab_pad; */
177 	    }
178 	}
179 
180 	/* count tabs required for indent */
181 	while (todo >= (int)curbuf->b_p_ts)
182 	{
183 	    if (*p != TAB)
184 		doit = TRUE;
185 	    else
186 		++p;
187 	    todo -= (int)curbuf->b_p_ts;
188 	    ++ind_len;
189 	    /* ind_done += (int)curbuf->b_p_ts; */
190 	}
191     }
192     /* count spaces required for indent */
193     while (todo > 0)
194     {
195 	if (*p != ' ')
196 	    doit = TRUE;
197 	else
198 	    ++p;
199 	--todo;
200 	++ind_len;
201 	/* ++ind_done; */
202     }
203 
204     /* Return if the indent is OK already. */
205     if (!doit && !VIM_ISWHITE(*p) && !(flags & SIN_INSERT))
206 	return FALSE;
207 
208     /* Allocate memory for the new line. */
209     if (flags & SIN_INSERT)
210 	p = oldline;
211     else
212 	p = skipwhite(p);
213     line_len = (int)STRLEN(p) + 1;
214 
215     /* If 'preserveindent' and 'expandtab' are both set keep the original
216      * characters and allocate accordingly.  We will fill the rest with spaces
217      * after the if (!curbuf->b_p_et) below. */
218     if (orig_char_len != -1)
219     {
220 	newline = alloc(orig_char_len + size - ind_done + line_len);
221 	if (newline == NULL)
222 	    return FALSE;
223 	todo = size - ind_done;
224 	ind_len = orig_char_len + todo;    /* Set total length of indent in
225 					    * characters, which may have been
226 					    * undercounted until now  */
227 	p = oldline;
228 	s = newline;
229 	while (orig_char_len > 0)
230 	{
231 	    *s++ = *p++;
232 	    orig_char_len--;
233 	}
234 
235 	/* Skip over any additional white space (useful when newindent is less
236 	 * than old) */
237 	while (VIM_ISWHITE(*p))
238 	    ++p;
239 
240     }
241     else
242     {
243 	todo = size;
244 	newline = alloc(ind_len + line_len);
245 	if (newline == NULL)
246 	    return FALSE;
247 	s = newline;
248     }
249 
250     /* Put the characters in the new line. */
251     /* if 'expandtab' isn't set: use TABs */
252     if (!curbuf->b_p_et)
253     {
254 	/* If 'preserveindent' is set then reuse as much as possible of
255 	 * the existing indent structure for the new indent */
256 	if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
257 	{
258 	    p = oldline;
259 	    ind_done = 0;
260 
261 	    while (todo > 0 && VIM_ISWHITE(*p))
262 	    {
263 		if (*p == TAB)
264 		{
265 		    tab_pad = (int)curbuf->b_p_ts
266 					   - (ind_done % (int)curbuf->b_p_ts);
267 		    /* stop if this tab will overshoot the target */
268 		    if (todo < tab_pad)
269 			break;
270 		    todo -= tab_pad;
271 		    ind_done += tab_pad;
272 		}
273 		else
274 		{
275 		    --todo;
276 		    ++ind_done;
277 		}
278 		*s++ = *p++;
279 	    }
280 
281 	    /* Fill to next tabstop with a tab, if possible */
282 	    tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
283 	    if (todo >= tab_pad)
284 	    {
285 		*s++ = TAB;
286 		todo -= tab_pad;
287 	    }
288 
289 	    p = skipwhite(p);
290 	}
291 
292 	while (todo >= (int)curbuf->b_p_ts)
293 	{
294 	    *s++ = TAB;
295 	    todo -= (int)curbuf->b_p_ts;
296 	}
297     }
298     while (todo > 0)
299     {
300 	*s++ = ' ';
301 	--todo;
302     }
303     mch_memmove(s, p, (size_t)line_len);
304 
305     /* Replace the line (unless undo fails). */
306     if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
307     {
308 	ml_replace(curwin->w_cursor.lnum, newline, FALSE);
309 	if (flags & SIN_CHANGED)
310 	    changed_bytes(curwin->w_cursor.lnum, 0);
311 	/* Correct saved cursor position if it is in this line. */
312 	if (saved_cursor.lnum == curwin->w_cursor.lnum)
313 	{
314 	    if (saved_cursor.col >= (colnr_T)(p - oldline))
315 		/* cursor was after the indent, adjust for the number of
316 		 * bytes added/removed */
317 		saved_cursor.col += ind_len - (colnr_T)(p - oldline);
318 	    else if (saved_cursor.col >= (colnr_T)(s - newline))
319 		/* cursor was in the indent, and is now after it, put it back
320 		 * at the start of the indent (replacing spaces with TAB) */
321 		saved_cursor.col = (colnr_T)(s - newline);
322 	}
323 	retval = TRUE;
324     }
325     else
326 	vim_free(newline);
327 
328     curwin->w_cursor.col = ind_len;
329     return retval;
330 }
331 
332 /*
333  * Copy the indent from ptr to the current line (and fill to size)
334  * Leaves the cursor on the first non-blank in the line.
335  * Returns TRUE if the line was changed.
336  */
337     static int
338 copy_indent(int size, char_u *src)
339 {
340     char_u	*p = NULL;
341     char_u	*line = NULL;
342     char_u	*s;
343     int		todo;
344     int		ind_len;
345     int		line_len = 0;
346     int		tab_pad;
347     int		ind_done;
348     int		round;
349 
350     /* Round 1: compute the number of characters needed for the indent
351      * Round 2: copy the characters. */
352     for (round = 1; round <= 2; ++round)
353     {
354 	todo = size;
355 	ind_len = 0;
356 	ind_done = 0;
357 	s = src;
358 
359 	/* Count/copy the usable portion of the source line */
360 	while (todo > 0 && VIM_ISWHITE(*s))
361 	{
362 	    if (*s == TAB)
363 	    {
364 		tab_pad = (int)curbuf->b_p_ts
365 					   - (ind_done % (int)curbuf->b_p_ts);
366 		/* Stop if this tab will overshoot the target */
367 		if (todo < tab_pad)
368 		    break;
369 		todo -= tab_pad;
370 		ind_done += tab_pad;
371 	    }
372 	    else
373 	    {
374 		--todo;
375 		++ind_done;
376 	    }
377 	    ++ind_len;
378 	    if (p != NULL)
379 		*p++ = *s;
380 	    ++s;
381 	}
382 
383 	/* Fill to next tabstop with a tab, if possible */
384 	tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
385 	if (todo >= tab_pad && !curbuf->b_p_et)
386 	{
387 	    todo -= tab_pad;
388 	    ++ind_len;
389 	    if (p != NULL)
390 		*p++ = TAB;
391 	}
392 
393 	/* Add tabs required for indent */
394 	while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
395 	{
396 	    todo -= (int)curbuf->b_p_ts;
397 	    ++ind_len;
398 	    if (p != NULL)
399 		*p++ = TAB;
400 	}
401 
402 	/* Count/add spaces required for indent */
403 	while (todo > 0)
404 	{
405 	    --todo;
406 	    ++ind_len;
407 	    if (p != NULL)
408 		*p++ = ' ';
409 	}
410 
411 	if (p == NULL)
412 	{
413 	    /* Allocate memory for the result: the copied indent, new indent
414 	     * and the rest of the line. */
415 	    line_len = (int)STRLEN(ml_get_curline()) + 1;
416 	    line = alloc(ind_len + line_len);
417 	    if (line == NULL)
418 		return FALSE;
419 	    p = line;
420 	}
421     }
422 
423     /* Append the original line */
424     mch_memmove(p, ml_get_curline(), (size_t)line_len);
425 
426     /* Replace the line */
427     ml_replace(curwin->w_cursor.lnum, line, FALSE);
428 
429     /* Put the cursor after the indent. */
430     curwin->w_cursor.col = ind_len;
431     return TRUE;
432 }
433 
434 /*
435  * Return the indent of the current line after a number.  Return -1 if no
436  * number was found.  Used for 'n' in 'formatoptions': numbered list.
437  * Since a pattern is used it can actually handle more than numbers.
438  */
439     int
440 get_number_indent(linenr_T lnum)
441 {
442     colnr_T	col;
443     pos_T	pos;
444 
445     regmatch_T	regmatch;
446     int		lead_len = 0;	/* length of comment leader */
447 
448     if (lnum > curbuf->b_ml.ml_line_count)
449 	return -1;
450     pos.lnum = 0;
451 
452 #ifdef FEAT_COMMENTS
453     /* In format_lines() (i.e. not insert mode), fo+=q is needed too...  */
454     if ((State & INSERT) || has_format_option(FO_Q_COMS))
455 	lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
456 #endif
457     regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
458     if (regmatch.regprog != NULL)
459     {
460 	regmatch.rm_ic = FALSE;
461 
462 	/* vim_regexec() expects a pointer to a line.  This lets us
463 	 * start matching for the flp beyond any comment leader...  */
464 	if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0))
465 	{
466 	    pos.lnum = lnum;
467 	    pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
468 #ifdef FEAT_VIRTUALEDIT
469 	    pos.coladd = 0;
470 #endif
471 	}
472 	vim_regfree(regmatch.regprog);
473     }
474 
475     if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
476 	return -1;
477     getvcol(curwin, &pos, &col, NULL, NULL);
478     return (int)col;
479 }
480 
481 #if defined(FEAT_LINEBREAK) || defined(PROTO)
482 /*
483  * Return appropriate space number for breakindent, taking influencing
484  * parameters into account. Window must be specified, since it is not
485  * necessarily always the current one.
486  */
487     int
488 get_breakindent_win(
489     win_T	*wp,
490     char_u	*line) /* start of the line */
491 {
492     static int	    prev_indent = 0;  /* cached indent value */
493     static long	    prev_ts     = 0L; /* cached tabstop value */
494     static char_u   *prev_line = NULL; /* cached pointer to line */
495     static varnumber_T prev_tick = 0;   /* changedtick of cached value */
496     int		    bri = 0;
497     /* window width minus window margin space, i.e. what rests for text */
498     const int	    eff_wwidth = W_WIDTH(wp)
499 			    - ((wp->w_p_nu || wp->w_p_rnu)
500 				&& (vim_strchr(p_cpo, CPO_NUMCOL) == NULL)
501 						? number_width(wp) + 1 : 0);
502 
503     /* used cached indent, unless pointer or 'tabstop' changed */
504     if (prev_line != line || prev_ts != wp->w_buffer->b_p_ts
505 				  || prev_tick != CHANGEDTICK(wp->w_buffer))
506     {
507 	prev_line = line;
508 	prev_ts = wp->w_buffer->b_p_ts;
509 	prev_tick = CHANGEDTICK(wp->w_buffer);
510 	prev_indent = get_indent_str(line,
511 				     (int)wp->w_buffer->b_p_ts, wp->w_p_list);
512     }
513     bri = prev_indent + wp->w_p_brishift;
514 
515     /* indent minus the length of the showbreak string */
516     if (wp->w_p_brisbr)
517 	bri -= vim_strsize(p_sbr);
518 
519     /* Add offset for number column, if 'n' is in 'cpoptions' */
520     bri += win_col_off2(wp);
521 
522     /* never indent past left window margin */
523     if (bri < 0)
524 	bri = 0;
525     /* always leave at least bri_min characters on the left,
526      * if text width is sufficient */
527     else if (bri > eff_wwidth - wp->w_p_brimin)
528 	bri = (eff_wwidth - wp->w_p_brimin < 0)
529 			    ? 0 : eff_wwidth - wp->w_p_brimin;
530 
531     return bri;
532 }
533 #endif
534 
535 
536 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
537 
538 static int cin_is_cinword(char_u *line);
539 
540 /*
541  * Return TRUE if the string "line" starts with a word from 'cinwords'.
542  */
543     static int
544 cin_is_cinword(char_u *line)
545 {
546     char_u	*cinw;
547     char_u	*cinw_buf;
548     int		cinw_len;
549     int		retval = FALSE;
550     int		len;
551 
552     cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
553     cinw_buf = alloc((unsigned)cinw_len);
554     if (cinw_buf != NULL)
555     {
556 	line = skipwhite(line);
557 	for (cinw = curbuf->b_p_cinw; *cinw; )
558 	{
559 	    len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
560 	    if (STRNCMP(line, cinw_buf, len) == 0
561 		    && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
562 	    {
563 		retval = TRUE;
564 		break;
565 	    }
566 	}
567 	vim_free(cinw_buf);
568     }
569     return retval;
570 }
571 #endif
572 
573 /*
574  * open_line: Add a new line below or above the current line.
575  *
576  * For VREPLACE mode, we only add a new line when we get to the end of the
577  * file, otherwise we just start replacing the next line.
578  *
579  * Caller must take care of undo.  Since VREPLACE may affect any number of
580  * lines however, it may call u_save_cursor() again when starting to change a
581  * new line.
582  * "flags": OPENLINE_DELSPACES	delete spaces after cursor
583  *	    OPENLINE_DO_COM	format comments
584  *	    OPENLINE_KEEPTRAIL	keep trailing spaces
585  *	    OPENLINE_MARKFIX	adjust mark positions after the line break
586  *	    OPENLINE_COM_LIST	format comments with list or 2nd line indent
587  *
588  * "second_line_indent": indent for after ^^D in Insert mode or if flag
589  *			  OPENLINE_COM_LIST
590  *
591  * Return TRUE for success, FALSE for failure
592  */
593     int
594 open_line(
595     int		dir,		/* FORWARD or BACKWARD */
596     int		flags,
597     int		second_line_indent)
598 {
599     char_u	*saved_line;		/* copy of the original line */
600     char_u	*next_line = NULL;	/* copy of the next line */
601     char_u	*p_extra = NULL;	/* what goes to next line */
602     int		less_cols = 0;		/* less columns for mark in new line */
603     int		less_cols_off = 0;	/* columns to skip for mark adjust */
604     pos_T	old_cursor;		/* old cursor position */
605     int		newcol = 0;		/* new cursor column */
606     int		newindent = 0;		/* auto-indent of the new line */
607     int		n;
608     int		trunc_line = FALSE;	/* truncate current line afterwards */
609     int		retval = FALSE;		/* return value, default is FAIL */
610 #ifdef FEAT_COMMENTS
611     int		extra_len = 0;		/* length of p_extra string */
612     int		lead_len;		/* length of comment leader */
613     char_u	*lead_flags;	/* position in 'comments' for comment leader */
614     char_u	*leader = NULL;		/* copy of comment leader */
615 #endif
616     char_u	*allocated = NULL;	/* allocated memory */
617 #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
618 	|| defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
619     char_u	*p;
620 #endif
621     int		saved_char = NUL;	/* init for GCC */
622 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
623     pos_T	*pos;
624 #endif
625 #ifdef FEAT_SMARTINDENT
626     int		do_si = (!p_paste && curbuf->b_p_si
627 # ifdef FEAT_CINDENT
628 					&& !curbuf->b_p_cin
629 # endif
630 # ifdef FEAT_EVAL
631 					&& *curbuf->b_p_inde == NUL
632 # endif
633 			);
634     int		no_si = FALSE;		/* reset did_si afterwards */
635     int		first_char = NUL;	/* init for GCC */
636 #endif
637 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
638     int		vreplace_mode;
639 #endif
640     int		did_append;		/* appended a new line */
641     int		saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
642 
643     /*
644      * make a copy of the current line so we can mess with it
645      */
646     saved_line = vim_strsave(ml_get_curline());
647     if (saved_line == NULL)	    /* out of memory! */
648 	return FALSE;
649 
650 #ifdef FEAT_VREPLACE
651     if (State & VREPLACE_FLAG)
652     {
653 	/*
654 	 * With VREPLACE we make a copy of the next line, which we will be
655 	 * starting to replace.  First make the new line empty and let vim play
656 	 * with the indenting and comment leader to its heart's content.  Then
657 	 * we grab what it ended up putting on the new line, put back the
658 	 * original line, and call ins_char() to put each new character onto
659 	 * the line, replacing what was there before and pushing the right
660 	 * stuff onto the replace stack.  -- webb.
661 	 */
662 	if (curwin->w_cursor.lnum < orig_line_count)
663 	    next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
664 	else
665 	    next_line = vim_strsave((char_u *)"");
666 	if (next_line == NULL)	    /* out of memory! */
667 	    goto theend;
668 
669 	/*
670 	 * In VREPLACE mode, a NL replaces the rest of the line, and starts
671 	 * replacing the next line, so push all of the characters left on the
672 	 * line onto the replace stack.  We'll push any other characters that
673 	 * might be replaced at the start of the next line (due to autoindent
674 	 * etc) a bit later.
675 	 */
676 	replace_push(NUL);  /* Call twice because BS over NL expects it */
677 	replace_push(NUL);
678 	p = saved_line + curwin->w_cursor.col;
679 	while (*p != NUL)
680 	{
681 #ifdef FEAT_MBYTE
682 	    if (has_mbyte)
683 		p += replace_push_mb(p);
684 	    else
685 #endif
686 		replace_push(*p++);
687 	}
688 	saved_line[curwin->w_cursor.col] = NUL;
689     }
690 #endif
691 
692     if ((State & INSERT)
693 #ifdef FEAT_VREPLACE
694 	    && !(State & VREPLACE_FLAG)
695 #endif
696 	    )
697     {
698 	p_extra = saved_line + curwin->w_cursor.col;
699 #ifdef FEAT_SMARTINDENT
700 	if (do_si)		/* need first char after new line break */
701 	{
702 	    p = skipwhite(p_extra);
703 	    first_char = *p;
704 	}
705 #endif
706 #ifdef FEAT_COMMENTS
707 	extra_len = (int)STRLEN(p_extra);
708 #endif
709 	saved_char = *p_extra;
710 	*p_extra = NUL;
711     }
712 
713     u_clearline();		/* cannot do "U" command when adding lines */
714 #ifdef FEAT_SMARTINDENT
715     did_si = FALSE;
716 #endif
717     ai_col = 0;
718 
719     /*
720      * If we just did an auto-indent, then we didn't type anything on
721      * the prior line, and it should be truncated.  Do this even if 'ai' is not
722      * set because automatically inserting a comment leader also sets did_ai.
723      */
724     if (dir == FORWARD && did_ai)
725 	trunc_line = TRUE;
726 
727     /*
728      * If 'autoindent' and/or 'smartindent' is set, try to figure out what
729      * indent to use for the new line.
730      */
731     if (curbuf->b_p_ai
732 #ifdef FEAT_SMARTINDENT
733 			|| do_si
734 #endif
735 					    )
736     {
737 	/*
738 	 * count white space on current line
739 	 */
740 	newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts, FALSE);
741 	if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
742 	    newindent = second_line_indent; /* for ^^D command in insert mode */
743 
744 #ifdef FEAT_SMARTINDENT
745 	/*
746 	 * Do smart indenting.
747 	 * In insert/replace mode (only when dir == FORWARD)
748 	 * we may move some text to the next line. If it starts with '{'
749 	 * don't add an indent. Fixes inserting a NL before '{' in line
750 	 *	"if (condition) {"
751 	 */
752 	if (!trunc_line && do_si && *saved_line != NUL
753 				    && (p_extra == NULL || first_char != '{'))
754 	{
755 	    char_u  *ptr;
756 	    char_u  last_char;
757 
758 	    old_cursor = curwin->w_cursor;
759 	    ptr = saved_line;
760 # ifdef FEAT_COMMENTS
761 	    if (flags & OPENLINE_DO_COM)
762 		lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
763 	    else
764 		lead_len = 0;
765 # endif
766 	    if (dir == FORWARD)
767 	    {
768 		/*
769 		 * Skip preprocessor directives, unless they are
770 		 * recognised as comments.
771 		 */
772 		if (
773 # ifdef FEAT_COMMENTS
774 			lead_len == 0 &&
775 # endif
776 			ptr[0] == '#')
777 		{
778 		    while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
779 			ptr = ml_get(--curwin->w_cursor.lnum);
780 		    newindent = get_indent();
781 		}
782 # ifdef FEAT_COMMENTS
783 		if (flags & OPENLINE_DO_COM)
784 		    lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
785 		else
786 		    lead_len = 0;
787 		if (lead_len > 0)
788 		{
789 		    /*
790 		     * This case gets the following right:
791 		     *	    \*
792 		     *	     * A comment (read '\' as '/').
793 		     *	     *\
794 		     * #define IN_THE_WAY
795 		     *	    This should line up here;
796 		     */
797 		    p = skipwhite(ptr);
798 		    if (p[0] == '/' && p[1] == '*')
799 			p++;
800 		    if (p[0] == '*')
801 		    {
802 			for (p++; *p; p++)
803 			{
804 			    if (p[0] == '/' && p[-1] == '*')
805 			    {
806 				/*
807 				 * End of C comment, indent should line up
808 				 * with the line containing the start of
809 				 * the comment
810 				 */
811 				curwin->w_cursor.col = (colnr_T)(p - ptr);
812 				if ((pos = findmatch(NULL, NUL)) != NULL)
813 				{
814 				    curwin->w_cursor.lnum = pos->lnum;
815 				    newindent = get_indent();
816 				}
817 			    }
818 			}
819 		    }
820 		}
821 		else	/* Not a comment line */
822 # endif
823 		{
824 		    /* Find last non-blank in line */
825 		    p = ptr + STRLEN(ptr) - 1;
826 		    while (p > ptr && VIM_ISWHITE(*p))
827 			--p;
828 		    last_char = *p;
829 
830 		    /*
831 		     * find the character just before the '{' or ';'
832 		     */
833 		    if (last_char == '{' || last_char == ';')
834 		    {
835 			if (p > ptr)
836 			    --p;
837 			while (p > ptr && VIM_ISWHITE(*p))
838 			    --p;
839 		    }
840 		    /*
841 		     * Try to catch lines that are split over multiple
842 		     * lines.  eg:
843 		     *	    if (condition &&
844 		     *			condition) {
845 		     *		Should line up here!
846 		     *	    }
847 		     */
848 		    if (*p == ')')
849 		    {
850 			curwin->w_cursor.col = (colnr_T)(p - ptr);
851 			if ((pos = findmatch(NULL, '(')) != NULL)
852 			{
853 			    curwin->w_cursor.lnum = pos->lnum;
854 			    newindent = get_indent();
855 			    ptr = ml_get_curline();
856 			}
857 		    }
858 		    /*
859 		     * If last character is '{' do indent, without
860 		     * checking for "if" and the like.
861 		     */
862 		    if (last_char == '{')
863 		    {
864 			did_si = TRUE;	/* do indent */
865 			no_si = TRUE;	/* don't delete it when '{' typed */
866 		    }
867 		    /*
868 		     * Look for "if" and the like, use 'cinwords'.
869 		     * Don't do this if the previous line ended in ';' or
870 		     * '}'.
871 		     */
872 		    else if (last_char != ';' && last_char != '}'
873 						       && cin_is_cinword(ptr))
874 			did_si = TRUE;
875 		}
876 	    }
877 	    else /* dir == BACKWARD */
878 	    {
879 		/*
880 		 * Skip preprocessor directives, unless they are
881 		 * recognised as comments.
882 		 */
883 		if (
884 # ifdef FEAT_COMMENTS
885 			lead_len == 0 &&
886 # endif
887 			ptr[0] == '#')
888 		{
889 		    int was_backslashed = FALSE;
890 
891 		    while ((ptr[0] == '#' || was_backslashed) &&
892 			 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
893 		    {
894 			if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
895 			    was_backslashed = TRUE;
896 			else
897 			    was_backslashed = FALSE;
898 			ptr = ml_get(++curwin->w_cursor.lnum);
899 		    }
900 		    if (was_backslashed)
901 			newindent = 0;	    /* Got to end of file */
902 		    else
903 			newindent = get_indent();
904 		}
905 		p = skipwhite(ptr);
906 		if (*p == '}')	    /* if line starts with '}': do indent */
907 		    did_si = TRUE;
908 		else		    /* can delete indent when '{' typed */
909 		    can_si_back = TRUE;
910 	    }
911 	    curwin->w_cursor = old_cursor;
912 	}
913 	if (do_si)
914 	    can_si = TRUE;
915 #endif /* FEAT_SMARTINDENT */
916 
917 	did_ai = TRUE;
918     }
919 
920 #ifdef FEAT_COMMENTS
921     /*
922      * Find out if the current line starts with a comment leader.
923      * This may then be inserted in front of the new line.
924      */
925     end_comment_pending = NUL;
926     if (flags & OPENLINE_DO_COM)
927 	lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
928     else
929 	lead_len = 0;
930     if (lead_len > 0)
931     {
932 	char_u	*lead_repl = NULL;	    /* replaces comment leader */
933 	int	lead_repl_len = 0;	    /* length of *lead_repl */
934 	char_u	lead_middle[COM_MAX_LEN];   /* middle-comment string */
935 	char_u	lead_end[COM_MAX_LEN];	    /* end-comment string */
936 	char_u	*comment_end = NULL;	    /* where lead_end has been found */
937 	int	extra_space = FALSE;	    /* append extra space */
938 	int	current_flag;
939 	int	require_blank = FALSE;	    /* requires blank after middle */
940 	char_u	*p2;
941 
942 	/*
943 	 * If the comment leader has the start, middle or end flag, it may not
944 	 * be used or may be replaced with the middle leader.
945 	 */
946 	for (p = lead_flags; *p && *p != ':'; ++p)
947 	{
948 	    if (*p == COM_BLANK)
949 	    {
950 		require_blank = TRUE;
951 		continue;
952 	    }
953 	    if (*p == COM_START || *p == COM_MIDDLE)
954 	    {
955 		current_flag = *p;
956 		if (*p == COM_START)
957 		{
958 		    /*
959 		     * Doing "O" on a start of comment does not insert leader.
960 		     */
961 		    if (dir == BACKWARD)
962 		    {
963 			lead_len = 0;
964 			break;
965 		    }
966 
967 		    /* find start of middle part */
968 		    (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
969 		    require_blank = FALSE;
970 		}
971 
972 		/*
973 		 * Isolate the strings of the middle and end leader.
974 		 */
975 		while (*p && p[-1] != ':')	/* find end of middle flags */
976 		{
977 		    if (*p == COM_BLANK)
978 			require_blank = TRUE;
979 		    ++p;
980 		}
981 		(void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
982 
983 		while (*p && p[-1] != ':')	/* find end of end flags */
984 		{
985 		    /* Check whether we allow automatic ending of comments */
986 		    if (*p == COM_AUTO_END)
987 			end_comment_pending = -1; /* means we want to set it */
988 		    ++p;
989 		}
990 		n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
991 
992 		if (end_comment_pending == -1)	/* we can set it now */
993 		    end_comment_pending = lead_end[n - 1];
994 
995 		/*
996 		 * If the end of the comment is in the same line, don't use
997 		 * the comment leader.
998 		 */
999 		if (dir == FORWARD)
1000 		{
1001 		    for (p = saved_line + lead_len; *p; ++p)
1002 			if (STRNCMP(p, lead_end, n) == 0)
1003 			{
1004 			    comment_end = p;
1005 			    lead_len = 0;
1006 			    break;
1007 			}
1008 		}
1009 
1010 		/*
1011 		 * Doing "o" on a start of comment inserts the middle leader.
1012 		 */
1013 		if (lead_len > 0)
1014 		{
1015 		    if (current_flag == COM_START)
1016 		    {
1017 			lead_repl = lead_middle;
1018 			lead_repl_len = (int)STRLEN(lead_middle);
1019 		    }
1020 
1021 		    /*
1022 		     * If we have hit RETURN immediately after the start
1023 		     * comment leader, then put a space after the middle
1024 		     * comment leader on the next line.
1025 		     */
1026 		    if (!VIM_ISWHITE(saved_line[lead_len - 1])
1027 			    && ((p_extra != NULL
1028 				    && (int)curwin->w_cursor.col == lead_len)
1029 				|| (p_extra == NULL
1030 				    && saved_line[lead_len] == NUL)
1031 				|| require_blank))
1032 			extra_space = TRUE;
1033 		}
1034 		break;
1035 	    }
1036 	    if (*p == COM_END)
1037 	    {
1038 		/*
1039 		 * Doing "o" on the end of a comment does not insert leader.
1040 		 * Remember where the end is, might want to use it to find the
1041 		 * start (for C-comments).
1042 		 */
1043 		if (dir == FORWARD)
1044 		{
1045 		    comment_end = skipwhite(saved_line);
1046 		    lead_len = 0;
1047 		    break;
1048 		}
1049 
1050 		/*
1051 		 * Doing "O" on the end of a comment inserts the middle leader.
1052 		 * Find the string for the middle leader, searching backwards.
1053 		 */
1054 		while (p > curbuf->b_p_com && *p != ',')
1055 		    --p;
1056 		for (lead_repl = p; lead_repl > curbuf->b_p_com
1057 					 && lead_repl[-1] != ':'; --lead_repl)
1058 		    ;
1059 		lead_repl_len = (int)(p - lead_repl);
1060 
1061 		/* We can probably always add an extra space when doing "O" on
1062 		 * the comment-end */
1063 		extra_space = TRUE;
1064 
1065 		/* Check whether we allow automatic ending of comments */
1066 		for (p2 = p; *p2 && *p2 != ':'; p2++)
1067 		{
1068 		    if (*p2 == COM_AUTO_END)
1069 			end_comment_pending = -1; /* means we want to set it */
1070 		}
1071 		if (end_comment_pending == -1)
1072 		{
1073 		    /* Find last character in end-comment string */
1074 		    while (*p2 && *p2 != ',')
1075 			p2++;
1076 		    end_comment_pending = p2[-1];
1077 		}
1078 		break;
1079 	    }
1080 	    if (*p == COM_FIRST)
1081 	    {
1082 		/*
1083 		 * Comment leader for first line only:	Don't repeat leader
1084 		 * when using "O", blank out leader when using "o".
1085 		 */
1086 		if (dir == BACKWARD)
1087 		    lead_len = 0;
1088 		else
1089 		{
1090 		    lead_repl = (char_u *)"";
1091 		    lead_repl_len = 0;
1092 		}
1093 		break;
1094 	    }
1095 	}
1096 	if (lead_len)
1097 	{
1098 	    /* allocate buffer (may concatenate p_extra later) */
1099 	    leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
1100 		     + (second_line_indent > 0 ? second_line_indent : 0) + 1);
1101 	    allocated = leader;		    /* remember to free it later */
1102 
1103 	    if (leader == NULL)
1104 		lead_len = 0;
1105 	    else
1106 	    {
1107 		vim_strncpy(leader, saved_line, lead_len);
1108 
1109 		/*
1110 		 * Replace leader with lead_repl, right or left adjusted
1111 		 */
1112 		if (lead_repl != NULL)
1113 		{
1114 		    int		c = 0;
1115 		    int		off = 0;
1116 
1117 		    for (p = lead_flags; *p != NUL && *p != ':'; )
1118 		    {
1119 			if (*p == COM_RIGHT || *p == COM_LEFT)
1120 			    c = *p++;
1121 			else if (VIM_ISDIGIT(*p) || *p == '-')
1122 			    off = getdigits(&p);
1123 			else
1124 			    ++p;
1125 		    }
1126 		    if (c == COM_RIGHT)    /* right adjusted leader */
1127 		    {
1128 			/* find last non-white in the leader to line up with */
1129 			for (p = leader + lead_len - 1; p > leader
1130 						      && VIM_ISWHITE(*p); --p)
1131 			    ;
1132 			++p;
1133 
1134 #ifdef FEAT_MBYTE
1135 			/* Compute the length of the replaced characters in
1136 			 * screen characters, not bytes. */
1137 			{
1138 			    int	    repl_size = vim_strnsize(lead_repl,
1139 							       lead_repl_len);
1140 			    int	    old_size = 0;
1141 			    char_u  *endp = p;
1142 			    int	    l;
1143 
1144 			    while (old_size < repl_size && p > leader)
1145 			    {
1146 				MB_PTR_BACK(leader, p);
1147 				old_size += ptr2cells(p);
1148 			    }
1149 			    l = lead_repl_len - (int)(endp - p);
1150 			    if (l != 0)
1151 				mch_memmove(endp + l, endp,
1152 					(size_t)((leader + lead_len) - endp));
1153 			    lead_len += l;
1154 			}
1155 #else
1156 			if (p < leader + lead_repl_len)
1157 			    p = leader;
1158 			else
1159 			    p -= lead_repl_len;
1160 #endif
1161 			mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1162 			if (p + lead_repl_len > leader + lead_len)
1163 			    p[lead_repl_len] = NUL;
1164 
1165 			/* blank-out any other chars from the old leader. */
1166 			while (--p >= leader)
1167 			{
1168 #ifdef FEAT_MBYTE
1169 			    int l = mb_head_off(leader, p);
1170 
1171 			    if (l > 1)
1172 			    {
1173 				p -= l;
1174 				if (ptr2cells(p) > 1)
1175 				{
1176 				    p[1] = ' ';
1177 				    --l;
1178 				}
1179 				mch_memmove(p + 1, p + l + 1,
1180 				   (size_t)((leader + lead_len) - (p + l + 1)));
1181 				lead_len -= l;
1182 				*p = ' ';
1183 			    }
1184 			    else
1185 #endif
1186 			    if (!VIM_ISWHITE(*p))
1187 				*p = ' ';
1188 			}
1189 		    }
1190 		    else		    /* left adjusted leader */
1191 		    {
1192 			p = skipwhite(leader);
1193 #ifdef FEAT_MBYTE
1194 			/* Compute the length of the replaced characters in
1195 			 * screen characters, not bytes. Move the part that is
1196 			 * not to be overwritten. */
1197 			{
1198 			    int	    repl_size = vim_strnsize(lead_repl,
1199 							       lead_repl_len);
1200 			    int	    i;
1201 			    int	    l;
1202 
1203 			    for (i = 0; i < lead_len && p[i] != NUL; i += l)
1204 			    {
1205 				l = (*mb_ptr2len)(p + i);
1206 				if (vim_strnsize(p, i + l) > repl_size)
1207 				    break;
1208 			    }
1209 			    if (i != lead_repl_len)
1210 			    {
1211 				mch_memmove(p + lead_repl_len, p + i,
1212 				       (size_t)(lead_len - i - (p - leader)));
1213 				lead_len += lead_repl_len - i;
1214 			    }
1215 			}
1216 #endif
1217 			mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1218 
1219 			/* Replace any remaining non-white chars in the old
1220 			 * leader by spaces.  Keep Tabs, the indent must
1221 			 * remain the same. */
1222 			for (p += lead_repl_len; p < leader + lead_len; ++p)
1223 			    if (!VIM_ISWHITE(*p))
1224 			    {
1225 				/* Don't put a space before a TAB. */
1226 				if (p + 1 < leader + lead_len && p[1] == TAB)
1227 				{
1228 				    --lead_len;
1229 				    mch_memmove(p, p + 1,
1230 						     (leader + lead_len) - p);
1231 				}
1232 				else
1233 				{
1234 #ifdef FEAT_MBYTE
1235 				    int	    l = (*mb_ptr2len)(p);
1236 
1237 				    if (l > 1)
1238 				    {
1239 					if (ptr2cells(p) > 1)
1240 					{
1241 					    /* Replace a double-wide char with
1242 					     * two spaces */
1243 					    --l;
1244 					    *p++ = ' ';
1245 					}
1246 					mch_memmove(p + 1, p + l,
1247 						     (leader + lead_len) - p);
1248 					lead_len -= l - 1;
1249 				    }
1250 #endif
1251 				    *p = ' ';
1252 				}
1253 			    }
1254 			*p = NUL;
1255 		    }
1256 
1257 		    /* Recompute the indent, it may have changed. */
1258 		    if (curbuf->b_p_ai
1259 #ifdef FEAT_SMARTINDENT
1260 					|| do_si
1261 #endif
1262 							   )
1263 			newindent = get_indent_str(leader, (int)curbuf->b_p_ts, FALSE);
1264 
1265 		    /* Add the indent offset */
1266 		    if (newindent + off < 0)
1267 		    {
1268 			off = -newindent;
1269 			newindent = 0;
1270 		    }
1271 		    else
1272 			newindent += off;
1273 
1274 		    /* Correct trailing spaces for the shift, so that
1275 		     * alignment remains equal. */
1276 		    while (off > 0 && lead_len > 0
1277 					       && leader[lead_len - 1] == ' ')
1278 		    {
1279 			/* Don't do it when there is a tab before the space */
1280 			if (vim_strchr(skipwhite(leader), '\t') != NULL)
1281 			    break;
1282 			--lead_len;
1283 			--off;
1284 		    }
1285 
1286 		    /* If the leader ends in white space, don't add an
1287 		     * extra space */
1288 		    if (lead_len > 0 && VIM_ISWHITE(leader[lead_len - 1]))
1289 			extra_space = FALSE;
1290 		    leader[lead_len] = NUL;
1291 		}
1292 
1293 		if (extra_space)
1294 		{
1295 		    leader[lead_len++] = ' ';
1296 		    leader[lead_len] = NUL;
1297 		}
1298 
1299 		newcol = lead_len;
1300 
1301 		/*
1302 		 * if a new indent will be set below, remove the indent that
1303 		 * is in the comment leader
1304 		 */
1305 		if (newindent
1306 #ifdef FEAT_SMARTINDENT
1307 				|| did_si
1308 #endif
1309 					   )
1310 		{
1311 		    while (lead_len && VIM_ISWHITE(*leader))
1312 		    {
1313 			--lead_len;
1314 			--newcol;
1315 			++leader;
1316 		    }
1317 		}
1318 
1319 	    }
1320 #ifdef FEAT_SMARTINDENT
1321 	    did_si = can_si = FALSE;
1322 #endif
1323 	}
1324 	else if (comment_end != NULL)
1325 	{
1326 	    /*
1327 	     * We have finished a comment, so we don't use the leader.
1328 	     * If this was a C-comment and 'ai' or 'si' is set do a normal
1329 	     * indent to align with the line containing the start of the
1330 	     * comment.
1331 	     */
1332 	    if (comment_end[0] == '*' && comment_end[1] == '/' &&
1333 			(curbuf->b_p_ai
1334 #ifdef FEAT_SMARTINDENT
1335 					|| do_si
1336 #endif
1337 							   ))
1338 	    {
1339 		old_cursor = curwin->w_cursor;
1340 		curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1341 		if ((pos = findmatch(NULL, NUL)) != NULL)
1342 		{
1343 		    curwin->w_cursor.lnum = pos->lnum;
1344 		    newindent = get_indent();
1345 		}
1346 		curwin->w_cursor = old_cursor;
1347 	    }
1348 	}
1349     }
1350 #endif
1351 
1352     /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1353     if (p_extra != NULL)
1354     {
1355 	*p_extra = saved_char;		/* restore char that NUL replaced */
1356 
1357 	/*
1358 	 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1359 	 * non-blank.
1360 	 *
1361 	 * When in REPLACE mode, put the deleted blanks on the replace stack,
1362 	 * preceded by a NUL, so they can be put back when a BS is entered.
1363 	 */
1364 	if (REPLACE_NORMAL(State))
1365 	    replace_push(NUL);	    /* end of extra blanks */
1366 	if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1367 	{
1368 	    while ((*p_extra == ' ' || *p_extra == '\t')
1369 #ifdef FEAT_MBYTE
1370 		    && (!enc_utf8
1371 			       || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1372 #endif
1373 		    )
1374 	    {
1375 		if (REPLACE_NORMAL(State))
1376 		    replace_push(*p_extra);
1377 		++p_extra;
1378 		++less_cols_off;
1379 	    }
1380 	}
1381 	if (*p_extra != NUL)
1382 	    did_ai = FALSE;	    /* append some text, don't truncate now */
1383 
1384 	/* columns for marks adjusted for removed columns */
1385 	less_cols = (int)(p_extra - saved_line);
1386     }
1387 
1388     if (p_extra == NULL)
1389 	p_extra = (char_u *)"";		    /* append empty line */
1390 
1391 #ifdef FEAT_COMMENTS
1392     /* concatenate leader and p_extra, if there is a leader */
1393     if (lead_len)
1394     {
1395 	if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
1396 	{
1397 	    int i;
1398 	    int padding = second_line_indent
1399 					  - (newindent + (int)STRLEN(leader));
1400 
1401 	    /* Here whitespace is inserted after the comment char.
1402 	     * Below, set_indent(newindent, SIN_INSERT) will insert the
1403 	     * whitespace needed before the comment char. */
1404 	    for (i = 0; i < padding; i++)
1405 	    {
1406 		STRCAT(leader, " ");
1407 		less_cols--;
1408 		newcol++;
1409 	    }
1410 	}
1411 	STRCAT(leader, p_extra);
1412 	p_extra = leader;
1413 	did_ai = TRUE;	    /* So truncating blanks works with comments */
1414 	less_cols -= lead_len;
1415     }
1416     else
1417 	end_comment_pending = NUL;  /* turns out there was no leader */
1418 #endif
1419 
1420     old_cursor = curwin->w_cursor;
1421     if (dir == BACKWARD)
1422 	--curwin->w_cursor.lnum;
1423 #ifdef FEAT_VREPLACE
1424     if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1425 #endif
1426     {
1427 	if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1428 								      == FAIL)
1429 	    goto theend;
1430 	/* Postpone calling changed_lines(), because it would mess up folding
1431 	 * with markers.
1432 	 * Skip mark_adjust when adding a line after the last one, there can't
1433 	 * be marks there. But still needed in diff mode. */
1434 	if (curwin->w_cursor.lnum + 1 < curbuf->b_ml.ml_line_count
1435 #ifdef FEAT_DIFF
1436 		|| curwin->w_p_diff
1437 #endif
1438 	    )
1439 	    mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1440 	did_append = TRUE;
1441     }
1442 #ifdef FEAT_VREPLACE
1443     else
1444     {
1445 	/*
1446 	 * In VREPLACE mode we are starting to replace the next line.
1447 	 */
1448 	curwin->w_cursor.lnum++;
1449 	if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1450 	{
1451 	    /* In case we NL to a new line, BS to the previous one, and NL
1452 	     * again, we don't want to save the new line for undo twice.
1453 	     */
1454 	    (void)u_save_cursor();		    /* errors are ignored! */
1455 	    vr_lines_changed++;
1456 	}
1457 	ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1458 	changed_bytes(curwin->w_cursor.lnum, 0);
1459 	curwin->w_cursor.lnum--;
1460 	did_append = FALSE;
1461     }
1462 #endif
1463 
1464     if (newindent
1465 #ifdef FEAT_SMARTINDENT
1466 		    || did_si
1467 #endif
1468 				)
1469     {
1470 	++curwin->w_cursor.lnum;
1471 #ifdef FEAT_SMARTINDENT
1472 	if (did_si)
1473 	{
1474 	    int sw = (int)get_sw_value(curbuf);
1475 
1476 	    if (p_sr)
1477 		newindent -= newindent % sw;
1478 	    newindent += sw;
1479 	}
1480 #endif
1481 	/* Copy the indent */
1482 	if (curbuf->b_p_ci)
1483 	{
1484 	    (void)copy_indent(newindent, saved_line);
1485 
1486 	    /*
1487 	     * Set the 'preserveindent' option so that any further screwing
1488 	     * with the line doesn't entirely destroy our efforts to preserve
1489 	     * it.  It gets restored at the function end.
1490 	     */
1491 	    curbuf->b_p_pi = TRUE;
1492 	}
1493 	else
1494 	    (void)set_indent(newindent, SIN_INSERT);
1495 	less_cols -= curwin->w_cursor.col;
1496 
1497 	ai_col = curwin->w_cursor.col;
1498 
1499 	/*
1500 	 * In REPLACE mode, for each character in the new indent, there must
1501 	 * be a NUL on the replace stack, for when it is deleted with BS
1502 	 */
1503 	if (REPLACE_NORMAL(State))
1504 	    for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1505 		replace_push(NUL);
1506 	newcol += curwin->w_cursor.col;
1507 #ifdef FEAT_SMARTINDENT
1508 	if (no_si)
1509 	    did_si = FALSE;
1510 #endif
1511     }
1512 
1513 #ifdef FEAT_COMMENTS
1514     /*
1515      * In REPLACE mode, for each character in the extra leader, there must be
1516      * a NUL on the replace stack, for when it is deleted with BS.
1517      */
1518     if (REPLACE_NORMAL(State))
1519 	while (lead_len-- > 0)
1520 	    replace_push(NUL);
1521 #endif
1522 
1523     curwin->w_cursor = old_cursor;
1524 
1525     if (dir == FORWARD)
1526     {
1527 	if (trunc_line || (State & INSERT))
1528 	{
1529 	    /* truncate current line at cursor */
1530 	    saved_line[curwin->w_cursor.col] = NUL;
1531 	    /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1532 	    if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1533 		truncate_spaces(saved_line);
1534 	    ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1535 	    saved_line = NULL;
1536 	    if (did_append)
1537 	    {
1538 		changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1539 					       curwin->w_cursor.lnum + 1, 1L);
1540 		did_append = FALSE;
1541 
1542 		/* Move marks after the line break to the new line. */
1543 		if (flags & OPENLINE_MARKFIX)
1544 		    mark_col_adjust(curwin->w_cursor.lnum,
1545 					 curwin->w_cursor.col + less_cols_off,
1546 							1L, (long)-less_cols);
1547 	    }
1548 	    else
1549 		changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1550 	}
1551 
1552 	/*
1553 	 * Put the cursor on the new line.  Careful: the scrollup() above may
1554 	 * have moved w_cursor, we must use old_cursor.
1555 	 */
1556 	curwin->w_cursor.lnum = old_cursor.lnum + 1;
1557     }
1558     if (did_append)
1559 	changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1560 
1561     curwin->w_cursor.col = newcol;
1562 #ifdef FEAT_VIRTUALEDIT
1563     curwin->w_cursor.coladd = 0;
1564 #endif
1565 
1566 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1567     /*
1568      * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1569      * fixthisline() from doing it (via change_indent()) by telling it we're in
1570      * normal INSERT mode.
1571      */
1572     if (State & VREPLACE_FLAG)
1573     {
1574 	vreplace_mode = State;	/* So we know to put things right later */
1575 	State = INSERT;
1576     }
1577     else
1578 	vreplace_mode = 0;
1579 #endif
1580 #ifdef FEAT_LISP
1581     /*
1582      * May do lisp indenting.
1583      */
1584     if (!p_paste
1585 # ifdef FEAT_COMMENTS
1586 	    && leader == NULL
1587 # endif
1588 	    && curbuf->b_p_lisp
1589 	    && curbuf->b_p_ai)
1590     {
1591 	fixthisline(get_lisp_indent);
1592 	p = ml_get_curline();
1593 	ai_col = (colnr_T)(skipwhite(p) - p);
1594     }
1595 #endif
1596 #ifdef FEAT_CINDENT
1597     /*
1598      * May do indenting after opening a new line.
1599      */
1600     if (!p_paste
1601 	    && (curbuf->b_p_cin
1602 #  ifdef FEAT_EVAL
1603 		    || *curbuf->b_p_inde != NUL
1604 #  endif
1605 		)
1606 	    && in_cinkeys(dir == FORWARD
1607 		? KEY_OPEN_FORW
1608 		: KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1609     {
1610 	do_c_expr_indent();
1611 	p = ml_get_curline();
1612 	ai_col = (colnr_T)(skipwhite(p) - p);
1613     }
1614 #endif
1615 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1616     if (vreplace_mode != 0)
1617 	State = vreplace_mode;
1618 #endif
1619 
1620 #ifdef FEAT_VREPLACE
1621     /*
1622      * Finally, VREPLACE gets the stuff on the new line, then puts back the
1623      * original line, and inserts the new stuff char by char, pushing old stuff
1624      * onto the replace stack (via ins_char()).
1625      */
1626     if (State & VREPLACE_FLAG)
1627     {
1628 	/* Put new line in p_extra */
1629 	p_extra = vim_strsave(ml_get_curline());
1630 	if (p_extra == NULL)
1631 	    goto theend;
1632 
1633 	/* Put back original line */
1634 	ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1635 
1636 	/* Insert new stuff into line again */
1637 	curwin->w_cursor.col = 0;
1638 #ifdef FEAT_VIRTUALEDIT
1639 	curwin->w_cursor.coladd = 0;
1640 #endif
1641 	ins_bytes(p_extra);	/* will call changed_bytes() */
1642 	vim_free(p_extra);
1643 	next_line = NULL;
1644     }
1645 #endif
1646 
1647     retval = TRUE;		/* success! */
1648 theend:
1649     curbuf->b_p_pi = saved_pi;
1650     vim_free(saved_line);
1651     vim_free(next_line);
1652     vim_free(allocated);
1653     return retval;
1654 }
1655 
1656 #if defined(FEAT_COMMENTS) || defined(PROTO)
1657 /*
1658  * get_leader_len() returns the length in bytes of the prefix of the given
1659  * string which introduces a comment.  If this string is not a comment then
1660  * 0 is returned.
1661  * When "flags" is not NULL, it is set to point to the flags of the recognized
1662  * comment leader.
1663  * "backward" must be true for the "O" command.
1664  * If "include_space" is set, include trailing whitespace while calculating the
1665  * length.
1666  */
1667     int
1668 get_leader_len(
1669     char_u	*line,
1670     char_u	**flags,
1671     int		backward,
1672     int		include_space)
1673 {
1674     int		i, j;
1675     int		result;
1676     int		got_com = FALSE;
1677     int		found_one;
1678     char_u	part_buf[COM_MAX_LEN];	/* buffer for one option part */
1679     char_u	*string;		/* pointer to comment string */
1680     char_u	*list;
1681     int		middle_match_len = 0;
1682     char_u	*prev_list;
1683     char_u	*saved_flags = NULL;
1684 
1685     result = i = 0;
1686     while (VIM_ISWHITE(line[i]))    /* leading white space is ignored */
1687 	++i;
1688 
1689     /*
1690      * Repeat to match several nested comment strings.
1691      */
1692     while (line[i] != NUL)
1693     {
1694 	/*
1695 	 * scan through the 'comments' option for a match
1696 	 */
1697 	found_one = FALSE;
1698 	for (list = curbuf->b_p_com; *list; )
1699 	{
1700 	    /* Get one option part into part_buf[].  Advance "list" to next
1701 	     * one.  Put "string" at start of string.  */
1702 	    if (!got_com && flags != NULL)
1703 		*flags = list;	    /* remember where flags started */
1704 	    prev_list = list;
1705 	    (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1706 	    string = vim_strchr(part_buf, ':');
1707 	    if (string == NULL)	    /* missing ':', ignore this part */
1708 		continue;
1709 	    *string++ = NUL;	    /* isolate flags from string */
1710 
1711 	    /* If we found a middle match previously, use that match when this
1712 	     * is not a middle or end. */
1713 	    if (middle_match_len != 0
1714 		    && vim_strchr(part_buf, COM_MIDDLE) == NULL
1715 		    && vim_strchr(part_buf, COM_END) == NULL)
1716 		break;
1717 
1718 	    /* When we already found a nested comment, only accept further
1719 	     * nested comments. */
1720 	    if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1721 		continue;
1722 
1723 	    /* When 'O' flag present and using "O" command skip this one. */
1724 	    if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1725 		continue;
1726 
1727 	    /* Line contents and string must match.
1728 	     * When string starts with white space, must have some white space
1729 	     * (but the amount does not need to match, there might be a mix of
1730 	     * TABs and spaces). */
1731 	    if (VIM_ISWHITE(string[0]))
1732 	    {
1733 		if (i == 0 || !VIM_ISWHITE(line[i - 1]))
1734 		    continue;  /* missing white space */
1735 		while (VIM_ISWHITE(string[0]))
1736 		    ++string;
1737 	    }
1738 	    for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1739 		;
1740 	    if (string[j] != NUL)
1741 		continue;  /* string doesn't match */
1742 
1743 	    /* When 'b' flag used, there must be white space or an
1744 	     * end-of-line after the string in the line. */
1745 	    if (vim_strchr(part_buf, COM_BLANK) != NULL
1746 			   && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
1747 		continue;
1748 
1749 	    /* We have found a match, stop searching unless this is a middle
1750 	     * comment. The middle comment can be a substring of the end
1751 	     * comment in which case it's better to return the length of the
1752 	     * end comment and its flags.  Thus we keep searching with middle
1753 	     * and end matches and use an end match if it matches better. */
1754 	    if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1755 	    {
1756 		if (middle_match_len == 0)
1757 		{
1758 		    middle_match_len = j;
1759 		    saved_flags = prev_list;
1760 		}
1761 		continue;
1762 	    }
1763 	    if (middle_match_len != 0 && j > middle_match_len)
1764 		/* Use this match instead of the middle match, since it's a
1765 		 * longer thus better match. */
1766 		middle_match_len = 0;
1767 
1768 	    if (middle_match_len == 0)
1769 		i += j;
1770 	    found_one = TRUE;
1771 	    break;
1772 	}
1773 
1774 	if (middle_match_len != 0)
1775 	{
1776 	    /* Use the previously found middle match after failing to find a
1777 	     * match with an end. */
1778 	    if (!got_com && flags != NULL)
1779 		*flags = saved_flags;
1780 	    i += middle_match_len;
1781 	    found_one = TRUE;
1782 	}
1783 
1784 	/* No match found, stop scanning. */
1785 	if (!found_one)
1786 	    break;
1787 
1788 	result = i;
1789 
1790 	/* Include any trailing white space. */
1791 	while (VIM_ISWHITE(line[i]))
1792 	    ++i;
1793 
1794 	if (include_space)
1795 	    result = i;
1796 
1797 	/* If this comment doesn't nest, stop here. */
1798 	got_com = TRUE;
1799 	if (vim_strchr(part_buf, COM_NEST) == NULL)
1800 	    break;
1801     }
1802     return result;
1803 }
1804 
1805 /*
1806  * Return the offset at which the last comment in line starts. If there is no
1807  * comment in the whole line, -1 is returned.
1808  *
1809  * When "flags" is not null, it is set to point to the flags describing the
1810  * recognized comment leader.
1811  */
1812     int
1813 get_last_leader_offset(char_u *line, char_u **flags)
1814 {
1815     int		result = -1;
1816     int		i, j;
1817     int		lower_check_bound = 0;
1818     char_u	*string;
1819     char_u	*com_leader;
1820     char_u	*com_flags;
1821     char_u	*list;
1822     int		found_one;
1823     char_u	part_buf[COM_MAX_LEN];	/* buffer for one option part */
1824 
1825     /*
1826      * Repeat to match several nested comment strings.
1827      */
1828     i = (int)STRLEN(line);
1829     while (--i >= lower_check_bound)
1830     {
1831 	/*
1832 	 * scan through the 'comments' option for a match
1833 	 */
1834 	found_one = FALSE;
1835 	for (list = curbuf->b_p_com; *list; )
1836 	{
1837 	    char_u *flags_save = list;
1838 
1839 	    /*
1840 	     * Get one option part into part_buf[].  Advance list to next one.
1841 	     * put string at start of string.
1842 	     */
1843 	    (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1844 	    string = vim_strchr(part_buf, ':');
1845 	    if (string == NULL)	/* If everything is fine, this cannot actually
1846 				 * happen. */
1847 	    {
1848 		continue;
1849 	    }
1850 	    *string++ = NUL;	/* Isolate flags from string. */
1851 	    com_leader = string;
1852 
1853 	    /*
1854 	     * Line contents and string must match.
1855 	     * When string starts with white space, must have some white space
1856 	     * (but the amount does not need to match, there might be a mix of
1857 	     * TABs and spaces).
1858 	     */
1859 	    if (VIM_ISWHITE(string[0]))
1860 	    {
1861 		if (i == 0 || !VIM_ISWHITE(line[i - 1]))
1862 		    continue;
1863 		while (VIM_ISWHITE(string[0]))
1864 		    ++string;
1865 	    }
1866 	    for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1867 		/* do nothing */;
1868 	    if (string[j] != NUL)
1869 		continue;
1870 
1871 	    /*
1872 	     * When 'b' flag used, there must be white space or an
1873 	     * end-of-line after the string in the line.
1874 	     */
1875 	    if (vim_strchr(part_buf, COM_BLANK) != NULL
1876 		    && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
1877 	    {
1878 		continue;
1879 	    }
1880 
1881 	    /*
1882 	     * We have found a match, stop searching.
1883 	     */
1884 	    found_one = TRUE;
1885 
1886 	    if (flags)
1887 		*flags = flags_save;
1888 	    com_flags = flags_save;
1889 
1890 	    break;
1891 	}
1892 
1893 	if (found_one)
1894 	{
1895 	    char_u  part_buf2[COM_MAX_LEN];	/* buffer for one option part */
1896 	    int     len1, len2, off;
1897 
1898 	    result = i;
1899 	    /*
1900 	     * If this comment nests, continue searching.
1901 	     */
1902 	    if (vim_strchr(part_buf, COM_NEST) != NULL)
1903 		continue;
1904 
1905 	    lower_check_bound = i;
1906 
1907 	    /* Let's verify whether the comment leader found is a substring
1908 	     * of other comment leaders. If it is, let's adjust the
1909 	     * lower_check_bound so that we make sure that we have determined
1910 	     * the comment leader correctly.
1911 	     */
1912 
1913 	    while (VIM_ISWHITE(*com_leader))
1914 		++com_leader;
1915 	    len1 = (int)STRLEN(com_leader);
1916 
1917 	    for (list = curbuf->b_p_com; *list; )
1918 	    {
1919 		char_u *flags_save = list;
1920 
1921 		(void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1922 		if (flags_save == com_flags)
1923 		    continue;
1924 		string = vim_strchr(part_buf2, ':');
1925 		++string;
1926 		while (VIM_ISWHITE(*string))
1927 		    ++string;
1928 		len2 = (int)STRLEN(string);
1929 		if (len2 == 0)
1930 		    continue;
1931 
1932 		/* Now we have to verify whether string ends with a substring
1933 		 * beginning the com_leader. */
1934 		for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1935 		{
1936 		    --off;
1937 		    if (!STRNCMP(string + off, com_leader, len2 - off))
1938 		    {
1939 			if (i - off < lower_check_bound)
1940 			    lower_check_bound = i - off;
1941 		    }
1942 		}
1943 	    }
1944 	}
1945     }
1946     return result;
1947 }
1948 #endif
1949 
1950 /*
1951  * Return the number of window lines occupied by buffer line "lnum".
1952  */
1953     int
1954 plines(linenr_T lnum)
1955 {
1956     return plines_win(curwin, lnum, TRUE);
1957 }
1958 
1959     int
1960 plines_win(
1961     win_T	*wp,
1962     linenr_T	lnum,
1963     int		winheight)	/* when TRUE limit to window height */
1964 {
1965 #if defined(FEAT_DIFF) || defined(PROTO)
1966     /* Check for filler lines above this buffer line.  When folded the result
1967      * is one line anyway. */
1968     return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1969 }
1970 
1971     int
1972 plines_nofill(linenr_T lnum)
1973 {
1974     return plines_win_nofill(curwin, lnum, TRUE);
1975 }
1976 
1977     int
1978 plines_win_nofill(
1979     win_T	*wp,
1980     linenr_T	lnum,
1981     int		winheight)	/* when TRUE limit to window height */
1982 {
1983 #endif
1984     int		lines;
1985 
1986     if (!wp->w_p_wrap)
1987 	return 1;
1988 
1989 #ifdef FEAT_WINDOWS
1990     if (wp->w_width == 0)
1991 	return 1;
1992 #endif
1993 
1994 #ifdef FEAT_FOLDING
1995     /* A folded lines is handled just like an empty line. */
1996     /* NOTE: Caller must handle lines that are MAYBE folded. */
1997     if (lineFolded(wp, lnum) == TRUE)
1998 	return 1;
1999 #endif
2000 
2001     lines = plines_win_nofold(wp, lnum);
2002     if (winheight > 0 && lines > wp->w_height)
2003 	return (int)wp->w_height;
2004     return lines;
2005 }
2006 
2007 /*
2008  * Return number of window lines physical line "lnum" will occupy in window
2009  * "wp".  Does not care about folding, 'wrap' or 'diff'.
2010  */
2011     int
2012 plines_win_nofold(win_T *wp, linenr_T lnum)
2013 {
2014     char_u	*s;
2015     long	col;
2016     int		width;
2017 
2018     s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2019     if (*s == NUL)		/* empty line */
2020 	return 1;
2021     col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
2022 
2023     /*
2024      * If list mode is on, then the '$' at the end of the line may take up one
2025      * extra column.
2026      */
2027     if (wp->w_p_list && lcs_eol != NUL)
2028 	col += 1;
2029 
2030     /*
2031      * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
2032      */
2033     width = W_WIDTH(wp) - win_col_off(wp);
2034     if (width <= 0)
2035 	return 32000;
2036     if (col <= width)
2037 	return 1;
2038     col -= width;
2039     width += win_col_off2(wp);
2040     return (col + (width - 1)) / width + 1;
2041 }
2042 
2043 /*
2044  * Like plines_win(), but only reports the number of physical screen lines
2045  * used from the start of the line to the given column number.
2046  */
2047     int
2048 plines_win_col(win_T *wp, linenr_T lnum, long column)
2049 {
2050     long	col;
2051     char_u	*s;
2052     int		lines = 0;
2053     int		width;
2054     char_u	*line;
2055 
2056 #ifdef FEAT_DIFF
2057     /* Check for filler lines above this buffer line.  When folded the result
2058      * is one line anyway. */
2059     lines = diff_check_fill(wp, lnum);
2060 #endif
2061 
2062     if (!wp->w_p_wrap)
2063 	return lines + 1;
2064 
2065 #ifdef FEAT_WINDOWS
2066     if (wp->w_width == 0)
2067 	return lines + 1;
2068 #endif
2069 
2070     line = s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2071 
2072     col = 0;
2073     while (*s != NUL && --column >= 0)
2074     {
2075 	col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL);
2076 	MB_PTR_ADV(s);
2077     }
2078 
2079     /*
2080      * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2081      * INSERT mode, then col must be adjusted so that it represents the last
2082      * screen position of the TAB.  This only fixes an error when the TAB wraps
2083      * from one screen line to the next (when 'columns' is not a multiple of
2084      * 'ts') -- webb.
2085      */
2086     if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2087 	col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL) - 1;
2088 
2089     /*
2090      * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
2091      */
2092     width = W_WIDTH(wp) - win_col_off(wp);
2093     if (width <= 0)
2094 	return 9999;
2095 
2096     lines += 1;
2097     if (col > width)
2098 	lines += (col - width) / (width + win_col_off2(wp)) + 1;
2099     return lines;
2100 }
2101 
2102     int
2103 plines_m_win(win_T *wp, linenr_T first, linenr_T last)
2104 {
2105     int		count = 0;
2106 
2107     while (first <= last)
2108     {
2109 #ifdef FEAT_FOLDING
2110 	int	x;
2111 
2112 	/* Check if there are any really folded lines, but also included lines
2113 	 * that are maybe folded. */
2114 	x = foldedCount(wp, first, NULL);
2115 	if (x > 0)
2116 	{
2117 	    ++count;	    /* count 1 for "+-- folded" line */
2118 	    first += x;
2119 	}
2120 	else
2121 #endif
2122 	{
2123 #ifdef FEAT_DIFF
2124 	    if (first == wp->w_topline)
2125 		count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2126 	    else
2127 #endif
2128 		count += plines_win(wp, first, TRUE);
2129 	    ++first;
2130 	}
2131     }
2132     return (count);
2133 }
2134 
2135 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2136 /*
2137  * Insert string "p" at the cursor position.  Stops at a NUL byte.
2138  * Handles Replace mode and multi-byte characters.
2139  */
2140     void
2141 ins_bytes(char_u *p)
2142 {
2143     ins_bytes_len(p, (int)STRLEN(p));
2144 }
2145 #endif
2146 
2147 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2148 	|| defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2149 /*
2150  * Insert string "p" with length "len" at the cursor position.
2151  * Handles Replace mode and multi-byte characters.
2152  */
2153     void
2154 ins_bytes_len(char_u *p, int len)
2155 {
2156     int		i;
2157 # ifdef FEAT_MBYTE
2158     int		n;
2159 
2160     if (has_mbyte)
2161 	for (i = 0; i < len; i += n)
2162 	{
2163 	    if (enc_utf8)
2164 		/* avoid reading past p[len] */
2165 		n = utfc_ptr2len_len(p + i, len - i);
2166 	    else
2167 		n = (*mb_ptr2len)(p + i);
2168 	    ins_char_bytes(p + i, n);
2169 	}
2170     else
2171 # endif
2172 	for (i = 0; i < len; ++i)
2173 	    ins_char(p[i]);
2174 }
2175 #endif
2176 
2177 /*
2178  * Insert or replace a single character at the cursor position.
2179  * When in REPLACE or VREPLACE mode, replace any existing character.
2180  * Caller must have prepared for undo.
2181  * For multi-byte characters we get the whole character, the caller must
2182  * convert bytes to a character.
2183  */
2184     void
2185 ins_char(int c)
2186 {
2187     char_u	buf[MB_MAXBYTES + 1];
2188     int		n = 1;
2189 
2190 #ifdef FEAT_MBYTE
2191     n = (*mb_char2bytes)(c, buf);
2192 
2193     /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2194      * Happens for CTRL-Vu9900. */
2195     if (buf[0] == 0)
2196 	buf[0] = '\n';
2197 #else
2198     buf[0] = c;
2199 #endif
2200 
2201     ins_char_bytes(buf, n);
2202 }
2203 
2204     void
2205 ins_char_bytes(char_u *buf, int charlen)
2206 {
2207     int		c = buf[0];
2208     int		newlen;		/* nr of bytes inserted */
2209     int		oldlen;		/* nr of bytes deleted (0 when not replacing) */
2210     char_u	*p;
2211     char_u	*newp;
2212     char_u	*oldp;
2213     int		linelen;	/* length of old line including NUL */
2214     colnr_T	col;
2215     linenr_T	lnum = curwin->w_cursor.lnum;
2216     int		i;
2217 
2218 #ifdef FEAT_VIRTUALEDIT
2219     /* Break tabs if needed. */
2220     if (virtual_active() && curwin->w_cursor.coladd > 0)
2221 	coladvance_force(getviscol());
2222 #endif
2223 
2224     col = curwin->w_cursor.col;
2225     oldp = ml_get(lnum);
2226     linelen = (int)STRLEN(oldp) + 1;
2227 
2228     /* The lengths default to the values for when not replacing. */
2229     oldlen = 0;
2230     newlen = charlen;
2231 
2232     if (State & REPLACE_FLAG)
2233     {
2234 #ifdef FEAT_VREPLACE
2235 	if (State & VREPLACE_FLAG)
2236 	{
2237 	    colnr_T	new_vcol = 0;   /* init for GCC */
2238 	    colnr_T	vcol;
2239 	    int		old_list;
2240 #ifndef FEAT_MBYTE
2241 	    char_u	buf[2];
2242 #endif
2243 
2244 	    /*
2245 	     * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2246 	     * Returns the old value of list, so when finished,
2247 	     * curwin->w_p_list should be set back to this.
2248 	     */
2249 	    old_list = curwin->w_p_list;
2250 	    if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2251 		curwin->w_p_list = FALSE;
2252 
2253 	    /*
2254 	     * In virtual replace mode each character may replace one or more
2255 	     * characters (zero if it's a TAB).  Count the number of bytes to
2256 	     * be deleted to make room for the new character, counting screen
2257 	     * cells.  May result in adding spaces to fill a gap.
2258 	     */
2259 	    getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2260 #ifndef FEAT_MBYTE
2261 	    buf[0] = c;
2262 	    buf[1] = NUL;
2263 #endif
2264 	    new_vcol = vcol + chartabsize(buf, vcol);
2265 	    while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2266 	    {
2267 		vcol += chartabsize(oldp + col + oldlen, vcol);
2268 		/* Don't need to remove a TAB that takes us to the right
2269 		 * position. */
2270 		if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2271 		    break;
2272 #ifdef FEAT_MBYTE
2273 		oldlen += (*mb_ptr2len)(oldp + col + oldlen);
2274 #else
2275 		++oldlen;
2276 #endif
2277 		/* Deleted a bit too much, insert spaces. */
2278 		if (vcol > new_vcol)
2279 		    newlen += vcol - new_vcol;
2280 	    }
2281 	    curwin->w_p_list = old_list;
2282 	}
2283 	else
2284 #endif
2285 	    if (oldp[col] != NUL)
2286 	{
2287 	    /* normal replace */
2288 #ifdef FEAT_MBYTE
2289 	    oldlen = (*mb_ptr2len)(oldp + col);
2290 #else
2291 	    oldlen = 1;
2292 #endif
2293 	}
2294 
2295 
2296 	/* Push the replaced bytes onto the replace stack, so that they can be
2297 	 * put back when BS is used.  The bytes of a multi-byte character are
2298 	 * done the other way around, so that the first byte is popped off
2299 	 * first (it tells the byte length of the character). */
2300 	replace_push(NUL);
2301 	for (i = 0; i < oldlen; ++i)
2302 	{
2303 #ifdef FEAT_MBYTE
2304 	    if (has_mbyte)
2305 		i += replace_push_mb(oldp + col + i) - 1;
2306 	    else
2307 #endif
2308 		replace_push(oldp[col + i]);
2309 	}
2310     }
2311 
2312     newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2313     if (newp == NULL)
2314 	return;
2315 
2316     /* Copy bytes before the cursor. */
2317     if (col > 0)
2318 	mch_memmove(newp, oldp, (size_t)col);
2319 
2320     /* Copy bytes after the changed character(s). */
2321     p = newp + col;
2322     mch_memmove(p + newlen, oldp + col + oldlen,
2323 					    (size_t)(linelen - col - oldlen));
2324 
2325     /* Insert or overwrite the new character. */
2326 #ifdef FEAT_MBYTE
2327     mch_memmove(p, buf, charlen);
2328     i = charlen;
2329 #else
2330     *p = c;
2331     i = 1;
2332 #endif
2333 
2334     /* Fill with spaces when necessary. */
2335     while (i < newlen)
2336 	p[i++] = ' ';
2337 
2338     /* Replace the line in the buffer. */
2339     ml_replace(lnum, newp, FALSE);
2340 
2341     /* mark the buffer as changed and prepare for displaying */
2342     changed_bytes(lnum, col);
2343 
2344     /*
2345      * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2346      * show the match for right parens and braces.
2347      */
2348     if (p_sm && (State & INSERT)
2349 	    && msg_silent == 0
2350 #ifdef FEAT_INS_EXPAND
2351 	    && !ins_compl_active()
2352 #endif
2353        )
2354     {
2355 #ifdef FEAT_MBYTE
2356 	if (has_mbyte)
2357 	    showmatch(mb_ptr2char(buf));
2358 	else
2359 #endif
2360 	    showmatch(c);
2361     }
2362 
2363 #ifdef FEAT_RIGHTLEFT
2364     if (!p_ri || (State & REPLACE_FLAG))
2365 #endif
2366     {
2367 	/* Normal insert: move cursor right */
2368 #ifdef FEAT_MBYTE
2369 	curwin->w_cursor.col += charlen;
2370 #else
2371 	++curwin->w_cursor.col;
2372 #endif
2373     }
2374     /*
2375      * TODO: should try to update w_row here, to avoid recomputing it later.
2376      */
2377 }
2378 
2379 /*
2380  * Insert a string at the cursor position.
2381  * Note: Does NOT handle Replace mode.
2382  * Caller must have prepared for undo.
2383  */
2384     void
2385 ins_str(char_u *s)
2386 {
2387     char_u	*oldp, *newp;
2388     int		newlen = (int)STRLEN(s);
2389     int		oldlen;
2390     colnr_T	col;
2391     linenr_T	lnum = curwin->w_cursor.lnum;
2392 
2393 #ifdef FEAT_VIRTUALEDIT
2394     if (virtual_active() && curwin->w_cursor.coladd > 0)
2395 	coladvance_force(getviscol());
2396 #endif
2397 
2398     col = curwin->w_cursor.col;
2399     oldp = ml_get(lnum);
2400     oldlen = (int)STRLEN(oldp);
2401 
2402     newp = alloc_check((unsigned)(oldlen + newlen + 1));
2403     if (newp == NULL)
2404 	return;
2405     if (col > 0)
2406 	mch_memmove(newp, oldp, (size_t)col);
2407     mch_memmove(newp + col, s, (size_t)newlen);
2408     mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2409     ml_replace(lnum, newp, FALSE);
2410     changed_bytes(lnum, col);
2411     curwin->w_cursor.col += newlen;
2412 }
2413 
2414 /*
2415  * Delete one character under the cursor.
2416  * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2417  * Caller must have prepared for undo.
2418  *
2419  * return FAIL for failure, OK otherwise
2420  */
2421     int
2422 del_char(int fixpos)
2423 {
2424 #ifdef FEAT_MBYTE
2425     if (has_mbyte)
2426     {
2427 	/* Make sure the cursor is at the start of a character. */
2428 	mb_adjust_cursor();
2429 	if (*ml_get_cursor() == NUL)
2430 	    return FAIL;
2431 	return del_chars(1L, fixpos);
2432     }
2433 #endif
2434     return del_bytes(1L, fixpos, TRUE);
2435 }
2436 
2437 #if defined(FEAT_MBYTE) || defined(PROTO)
2438 /*
2439  * Like del_bytes(), but delete characters instead of bytes.
2440  */
2441     int
2442 del_chars(long count, int fixpos)
2443 {
2444     long	bytes = 0;
2445     long	i;
2446     char_u	*p;
2447     int		l;
2448 
2449     p = ml_get_cursor();
2450     for (i = 0; i < count && *p != NUL; ++i)
2451     {
2452 	l = (*mb_ptr2len)(p);
2453 	bytes += l;
2454 	p += l;
2455     }
2456     return del_bytes(bytes, fixpos, TRUE);
2457 }
2458 #endif
2459 
2460 /*
2461  * Delete "count" bytes under the cursor.
2462  * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2463  * Caller must have prepared for undo.
2464  *
2465  * return FAIL for failure, OK otherwise
2466  */
2467     int
2468 del_bytes(
2469     long	count,
2470     int		fixpos_arg,
2471     int		use_delcombine UNUSED)	    /* 'delcombine' option applies */
2472 {
2473     char_u	*oldp, *newp;
2474     colnr_T	oldlen;
2475     linenr_T	lnum = curwin->w_cursor.lnum;
2476     colnr_T	col = curwin->w_cursor.col;
2477     int		was_alloced;
2478     long	movelen;
2479     int		fixpos = fixpos_arg;
2480 
2481     oldp = ml_get(lnum);
2482     oldlen = (int)STRLEN(oldp);
2483 
2484     /*
2485      * Can't do anything when the cursor is on the NUL after the line.
2486      */
2487     if (col >= oldlen)
2488 	return FAIL;
2489 
2490 #ifdef FEAT_MBYTE
2491     /* If 'delcombine' is set and deleting (less than) one character, only
2492      * delete the last combining character. */
2493     if (p_deco && use_delcombine && enc_utf8
2494 					 && utfc_ptr2len(oldp + col) >= count)
2495     {
2496 	int	cc[MAX_MCO];
2497 	int	n;
2498 
2499 	(void)utfc_ptr2char(oldp + col, cc);
2500 	if (cc[0] != NUL)
2501 	{
2502 	    /* Find the last composing char, there can be several. */
2503 	    n = col;
2504 	    do
2505 	    {
2506 		col = n;
2507 		count = utf_ptr2len(oldp + n);
2508 		n += count;
2509 	    } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2510 	    fixpos = 0;
2511 	}
2512     }
2513 #endif
2514 
2515     /*
2516      * When count is too big, reduce it.
2517      */
2518     movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2519     if (movelen <= 1)
2520     {
2521 	/*
2522 	 * If we just took off the last character of a non-blank line, and
2523 	 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2524 	 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2525 	 */
2526 	if (col > 0 && fixpos && restart_edit == 0
2527 #ifdef FEAT_VIRTUALEDIT
2528 					      && (ve_flags & VE_ONEMORE) == 0
2529 #endif
2530 					      )
2531 	{
2532 	    --curwin->w_cursor.col;
2533 #ifdef FEAT_VIRTUALEDIT
2534 	    curwin->w_cursor.coladd = 0;
2535 #endif
2536 #ifdef FEAT_MBYTE
2537 	    if (has_mbyte)
2538 		curwin->w_cursor.col -=
2539 			    (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2540 #endif
2541 	}
2542 	count = oldlen - col;
2543 	movelen = 1;
2544     }
2545 
2546     /*
2547      * If the old line has been allocated the deletion can be done in the
2548      * existing line. Otherwise a new line has to be allocated
2549      * Can't do this when using Netbeans, because we would need to invoke
2550      * netbeans_removed(), which deallocates the line.  Let ml_replace() take
2551      * care of notifying Netbeans.
2552      */
2553 #ifdef FEAT_NETBEANS_INTG
2554     if (netbeans_active())
2555 	was_alloced = FALSE;
2556     else
2557 #endif
2558 	was_alloced = ml_line_alloced();    /* check if oldp was allocated */
2559     if (was_alloced)
2560 	newp = oldp;			    /* use same allocated memory */
2561     else
2562     {					    /* need to allocate a new line */
2563 	newp = alloc((unsigned)(oldlen + 1 - count));
2564 	if (newp == NULL)
2565 	    return FAIL;
2566 	mch_memmove(newp, oldp, (size_t)col);
2567     }
2568     mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2569     if (!was_alloced)
2570 	ml_replace(lnum, newp, FALSE);
2571 
2572     /* mark the buffer as changed and prepare for displaying */
2573     changed_bytes(lnum, curwin->w_cursor.col);
2574 
2575     return OK;
2576 }
2577 
2578 /*
2579  * Delete from cursor to end of line.
2580  * Caller must have prepared for undo.
2581  *
2582  * return FAIL for failure, OK otherwise
2583  */
2584     int
2585 truncate_line(
2586     int		fixpos)	    /* if TRUE fix the cursor position when done */
2587 {
2588     char_u	*newp;
2589     linenr_T	lnum = curwin->w_cursor.lnum;
2590     colnr_T	col = curwin->w_cursor.col;
2591 
2592     if (col == 0)
2593 	newp = vim_strsave((char_u *)"");
2594     else
2595 	newp = vim_strnsave(ml_get(lnum), col);
2596 
2597     if (newp == NULL)
2598 	return FAIL;
2599 
2600     ml_replace(lnum, newp, FALSE);
2601 
2602     /* mark the buffer as changed and prepare for displaying */
2603     changed_bytes(lnum, curwin->w_cursor.col);
2604 
2605     /*
2606      * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2607      */
2608     if (fixpos && curwin->w_cursor.col > 0)
2609 	--curwin->w_cursor.col;
2610 
2611     return OK;
2612 }
2613 
2614 /*
2615  * Delete "nlines" lines at the cursor.
2616  * Saves the lines for undo first if "undo" is TRUE.
2617  */
2618     void
2619 del_lines(
2620     long	nlines,		/* number of lines to delete */
2621     int		undo)		/* if TRUE, prepare for undo */
2622 {
2623     long	n;
2624     linenr_T	first = curwin->w_cursor.lnum;
2625 
2626     if (nlines <= 0)
2627 	return;
2628 
2629     /* save the deleted lines for undo */
2630     if (undo && u_savedel(first, nlines) == FAIL)
2631 	return;
2632 
2633     for (n = 0; n < nlines; )
2634     {
2635 	if (curbuf->b_ml.ml_flags & ML_EMPTY)	    /* nothing to delete */
2636 	    break;
2637 
2638 	ml_delete(first, TRUE);
2639 	++n;
2640 
2641 	/* If we delete the last line in the file, stop */
2642 	if (first > curbuf->b_ml.ml_line_count)
2643 	    break;
2644     }
2645 
2646     /* Correct the cursor position before calling deleted_lines_mark(), it may
2647      * trigger a callback to display the cursor. */
2648     curwin->w_cursor.col = 0;
2649     check_cursor_lnum();
2650 
2651     /* adjust marks, mark the buffer as changed and prepare for displaying */
2652     deleted_lines_mark(first, n);
2653 }
2654 
2655     int
2656 gchar_pos(pos_T *pos)
2657 {
2658     char_u	*ptr = ml_get_pos(pos);
2659 
2660 #ifdef FEAT_MBYTE
2661     if (has_mbyte)
2662 	return (*mb_ptr2char)(ptr);
2663 #endif
2664     return (int)*ptr;
2665 }
2666 
2667     int
2668 gchar_cursor(void)
2669 {
2670 #ifdef FEAT_MBYTE
2671     if (has_mbyte)
2672 	return (*mb_ptr2char)(ml_get_cursor());
2673 #endif
2674     return (int)*ml_get_cursor();
2675 }
2676 
2677 /*
2678  * Write a character at the current cursor position.
2679  * It is directly written into the block.
2680  */
2681     void
2682 pchar_cursor(int c)
2683 {
2684     *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2685 						  + curwin->w_cursor.col) = c;
2686 }
2687 
2688 /*
2689  * When extra == 0: Return TRUE if the cursor is before or on the first
2690  *		    non-blank in the line.
2691  * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2692  *		    the line.
2693  */
2694     int
2695 inindent(int extra)
2696 {
2697     char_u	*ptr;
2698     colnr_T	col;
2699 
2700     for (col = 0, ptr = ml_get_curline(); VIM_ISWHITE(*ptr); ++col)
2701 	++ptr;
2702     if (col >= curwin->w_cursor.col + extra)
2703 	return TRUE;
2704     else
2705 	return FALSE;
2706 }
2707 
2708 /*
2709  * Skip to next part of an option argument: Skip space and comma.
2710  */
2711     char_u *
2712 skip_to_option_part(char_u *p)
2713 {
2714     if (*p == ',')
2715 	++p;
2716     while (*p == ' ')
2717 	++p;
2718     return p;
2719 }
2720 
2721 /*
2722  * Call this function when something in the current buffer is changed.
2723  *
2724  * Most often called through changed_bytes() and changed_lines(), which also
2725  * mark the area of the display to be redrawn.
2726  *
2727  * Careful: may trigger autocommands that reload the buffer.
2728  */
2729     void
2730 changed(void)
2731 {
2732 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2733     /* The text of the preediting area is inserted, but this doesn't
2734      * mean a change of the buffer yet.  That is delayed until the
2735      * text is committed. (this means preedit becomes empty) */
2736     if (im_is_preediting() && !xim_changed_while_preediting)
2737 	return;
2738     xim_changed_while_preediting = FALSE;
2739 #endif
2740 
2741     if (!curbuf->b_changed)
2742     {
2743 	int	save_msg_scroll = msg_scroll;
2744 
2745 	/* Give a warning about changing a read-only file.  This may also
2746 	 * check-out the file, thus change "curbuf"! */
2747 	change_warning(0);
2748 
2749 	/* Create a swap file if that is wanted.
2750 	 * Don't do this for "nofile" and "nowrite" buffer types. */
2751 	if (curbuf->b_may_swap
2752 #ifdef FEAT_QUICKFIX
2753 		&& !bt_dontwrite(curbuf)
2754 #endif
2755 		)
2756 	{
2757 	    int save_need_wait_return = need_wait_return;
2758 
2759 	    need_wait_return = FALSE;
2760 	    ml_open_file(curbuf);
2761 
2762 	    /* The ml_open_file() can cause an ATTENTION message.
2763 	     * Wait two seconds, to make sure the user reads this unexpected
2764 	     * message.  Since we could be anywhere, call wait_return() now,
2765 	     * and don't let the emsg() set msg_scroll. */
2766 	    if (need_wait_return && emsg_silent == 0)
2767 	    {
2768 		out_flush();
2769 		ui_delay(2000L, TRUE);
2770 		wait_return(TRUE);
2771 		msg_scroll = save_msg_scroll;
2772 	    }
2773 	    else
2774 		need_wait_return = save_need_wait_return;
2775 	}
2776 	changed_int();
2777     }
2778     ++CHANGEDTICK(curbuf);
2779 }
2780 
2781 /*
2782  * Internal part of changed(), no user interaction.
2783  */
2784     void
2785 changed_int(void)
2786 {
2787     curbuf->b_changed = TRUE;
2788     ml_setflags(curbuf);
2789 #ifdef FEAT_WINDOWS
2790     check_status(curbuf);
2791     redraw_tabline = TRUE;
2792 #endif
2793 #ifdef FEAT_TITLE
2794     need_maketitle = TRUE;	    /* set window title later */
2795 #endif
2796 }
2797 
2798 static void changedOneline(buf_T *buf, linenr_T lnum);
2799 static void changed_lines_buf(buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra);
2800 static void changed_common(linenr_T lnum, colnr_T col, linenr_T lnume, long xtra);
2801 
2802 /*
2803  * Changed bytes within a single line for the current buffer.
2804  * - marks the windows on this buffer to be redisplayed
2805  * - marks the buffer changed by calling changed()
2806  * - invalidates cached values
2807  * Careful: may trigger autocommands that reload the buffer.
2808  */
2809     void
2810 changed_bytes(linenr_T lnum, colnr_T col)
2811 {
2812     changedOneline(curbuf, lnum);
2813     changed_common(lnum, col, lnum + 1, 0L);
2814 
2815 #ifdef FEAT_DIFF
2816     /* Diff highlighting in other diff windows may need to be updated too. */
2817     if (curwin->w_p_diff)
2818     {
2819 	win_T	    *wp;
2820 	linenr_T    wlnum;
2821 
2822 	FOR_ALL_WINDOWS(wp)
2823 	    if (wp->w_p_diff && wp != curwin)
2824 	    {
2825 		redraw_win_later(wp, VALID);
2826 		wlnum = diff_lnum_win(lnum, wp);
2827 		if (wlnum > 0)
2828 		    changedOneline(wp->w_buffer, wlnum);
2829 	    }
2830     }
2831 #endif
2832 }
2833 
2834     static void
2835 changedOneline(buf_T *buf, linenr_T lnum)
2836 {
2837     if (buf->b_mod_set)
2838     {
2839 	/* find the maximum area that must be redisplayed */
2840 	if (lnum < buf->b_mod_top)
2841 	    buf->b_mod_top = lnum;
2842 	else if (lnum >= buf->b_mod_bot)
2843 	    buf->b_mod_bot = lnum + 1;
2844     }
2845     else
2846     {
2847 	/* set the area that must be redisplayed to one line */
2848 	buf->b_mod_set = TRUE;
2849 	buf->b_mod_top = lnum;
2850 	buf->b_mod_bot = lnum + 1;
2851 	buf->b_mod_xlines = 0;
2852     }
2853 }
2854 
2855 /*
2856  * Appended "count" lines below line "lnum" in the current buffer.
2857  * Must be called AFTER the change and after mark_adjust().
2858  * Takes care of marking the buffer to be redrawn and sets the changed flag.
2859  */
2860     void
2861 appended_lines(linenr_T lnum, long count)
2862 {
2863     changed_lines(lnum + 1, 0, lnum + 1, count);
2864 }
2865 
2866 /*
2867  * Like appended_lines(), but adjust marks first.
2868  */
2869     void
2870 appended_lines_mark(linenr_T lnum, long count)
2871 {
2872     /* Skip mark_adjust when adding a line after the last one, there can't
2873      * be marks there. But it's still needed in diff mode. */
2874     if (lnum + count < curbuf->b_ml.ml_line_count
2875 #ifdef FEAT_DIFF
2876 	    || curwin->w_p_diff
2877 #endif
2878 	)
2879 	mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2880     changed_lines(lnum + 1, 0, lnum + 1, count);
2881 }
2882 
2883 /*
2884  * Deleted "count" lines at line "lnum" in the current buffer.
2885  * Must be called AFTER the change and after mark_adjust().
2886  * Takes care of marking the buffer to be redrawn and sets the changed flag.
2887  */
2888     void
2889 deleted_lines(linenr_T lnum, long count)
2890 {
2891     changed_lines(lnum, 0, lnum + count, -count);
2892 }
2893 
2894 /*
2895  * Like deleted_lines(), but adjust marks first.
2896  * Make sure the cursor is on a valid line before calling, a GUI callback may
2897  * be triggered to display the cursor.
2898  */
2899     void
2900 deleted_lines_mark(linenr_T lnum, long count)
2901 {
2902     mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2903     changed_lines(lnum, 0, lnum + count, -count);
2904 }
2905 
2906 /*
2907  * Changed lines for the current buffer.
2908  * Must be called AFTER the change and after mark_adjust().
2909  * - mark the buffer changed by calling changed()
2910  * - mark the windows on this buffer to be redisplayed
2911  * - invalidate cached values
2912  * "lnum" is the first line that needs displaying, "lnume" the first line
2913  * below the changed lines (BEFORE the change).
2914  * When only inserting lines, "lnum" and "lnume" are equal.
2915  * Takes care of calling changed() and updating b_mod_*.
2916  * Careful: may trigger autocommands that reload the buffer.
2917  */
2918     void
2919 changed_lines(
2920     linenr_T	lnum,	    /* first line with change */
2921     colnr_T	col,	    /* column in first line with change */
2922     linenr_T	lnume,	    /* line below last changed line */
2923     long	xtra)	    /* number of extra lines (negative when deleting) */
2924 {
2925     changed_lines_buf(curbuf, lnum, lnume, xtra);
2926 
2927 #ifdef FEAT_DIFF
2928     if (xtra == 0 && curwin->w_p_diff)
2929     {
2930 	/* When the number of lines doesn't change then mark_adjust() isn't
2931 	 * called and other diff buffers still need to be marked for
2932 	 * displaying. */
2933 	win_T	    *wp;
2934 	linenr_T    wlnum;
2935 
2936 	FOR_ALL_WINDOWS(wp)
2937 	    if (wp->w_p_diff && wp != curwin)
2938 	    {
2939 		redraw_win_later(wp, VALID);
2940 		wlnum = diff_lnum_win(lnum, wp);
2941 		if (wlnum > 0)
2942 		    changed_lines_buf(wp->w_buffer, wlnum,
2943 						    lnume - lnum + wlnum, 0L);
2944 	    }
2945     }
2946 #endif
2947 
2948     changed_common(lnum, col, lnume, xtra);
2949 }
2950 
2951     static void
2952 changed_lines_buf(
2953     buf_T	*buf,
2954     linenr_T	lnum,	    /* first line with change */
2955     linenr_T	lnume,	    /* line below last changed line */
2956     long	xtra)	    /* number of extra lines (negative when deleting) */
2957 {
2958     if (buf->b_mod_set)
2959     {
2960 	/* find the maximum area that must be redisplayed */
2961 	if (lnum < buf->b_mod_top)
2962 	    buf->b_mod_top = lnum;
2963 	if (lnum < buf->b_mod_bot)
2964 	{
2965 	    /* adjust old bot position for xtra lines */
2966 	    buf->b_mod_bot += xtra;
2967 	    if (buf->b_mod_bot < lnum)
2968 		buf->b_mod_bot = lnum;
2969 	}
2970 	if (lnume + xtra > buf->b_mod_bot)
2971 	    buf->b_mod_bot = lnume + xtra;
2972 	buf->b_mod_xlines += xtra;
2973     }
2974     else
2975     {
2976 	/* set the area that must be redisplayed */
2977 	buf->b_mod_set = TRUE;
2978 	buf->b_mod_top = lnum;
2979 	buf->b_mod_bot = lnume + xtra;
2980 	buf->b_mod_xlines = xtra;
2981     }
2982 }
2983 
2984 /*
2985  * Common code for when a change is was made.
2986  * See changed_lines() for the arguments.
2987  * Careful: may trigger autocommands that reload the buffer.
2988  */
2989     static void
2990 changed_common(
2991     linenr_T	lnum,
2992     colnr_T	col,
2993     linenr_T	lnume,
2994     long	xtra)
2995 {
2996     win_T	*wp;
2997 #ifdef FEAT_WINDOWS
2998     tabpage_T	*tp;
2999 #endif
3000     int		i;
3001 #ifdef FEAT_JUMPLIST
3002     int		cols;
3003     pos_T	*p;
3004     int		add;
3005 #endif
3006 
3007     /* mark the buffer as modified */
3008     changed();
3009 
3010     /* set the '. mark */
3011     if (!cmdmod.keepjumps)
3012     {
3013 	curbuf->b_last_change.lnum = lnum;
3014 	curbuf->b_last_change.col = col;
3015 
3016 #ifdef FEAT_JUMPLIST
3017 	/* Create a new entry if a new undo-able change was started or we
3018 	 * don't have an entry yet. */
3019 	if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
3020 	{
3021 	    if (curbuf->b_changelistlen == 0)
3022 		add = TRUE;
3023 	    else
3024 	    {
3025 		/* Don't create a new entry when the line number is the same
3026 		 * as the last one and the column is not too far away.  Avoids
3027 		 * creating many entries for typing "xxxxx". */
3028 		p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
3029 		if (p->lnum != lnum)
3030 		    add = TRUE;
3031 		else
3032 		{
3033 		    cols = comp_textwidth(FALSE);
3034 		    if (cols == 0)
3035 			cols = 79;
3036 		    add = (p->col + cols < col || col + cols < p->col);
3037 		}
3038 	    }
3039 	    if (add)
3040 	    {
3041 		/* This is the first of a new sequence of undo-able changes
3042 		 * and it's at some distance of the last change.  Use a new
3043 		 * position in the changelist. */
3044 		curbuf->b_new_change = FALSE;
3045 
3046 		if (curbuf->b_changelistlen == JUMPLISTSIZE)
3047 		{
3048 		    /* changelist is full: remove oldest entry */
3049 		    curbuf->b_changelistlen = JUMPLISTSIZE - 1;
3050 		    mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
3051 					  sizeof(pos_T) * (JUMPLISTSIZE - 1));
3052 		    FOR_ALL_TAB_WINDOWS(tp, wp)
3053 		    {
3054 			/* Correct position in changelist for other windows on
3055 			 * this buffer. */
3056 			if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
3057 			    --wp->w_changelistidx;
3058 		    }
3059 		}
3060 		FOR_ALL_TAB_WINDOWS(tp, wp)
3061 		{
3062 		    /* For other windows, if the position in the changelist is
3063 		     * at the end it stays at the end. */
3064 		    if (wp->w_buffer == curbuf
3065 			    && wp->w_changelistidx == curbuf->b_changelistlen)
3066 			++wp->w_changelistidx;
3067 		}
3068 		++curbuf->b_changelistlen;
3069 	    }
3070 	}
3071 	curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3072 							curbuf->b_last_change;
3073 	/* The current window is always after the last change, so that "g,"
3074 	 * takes you back to it. */
3075 	curwin->w_changelistidx = curbuf->b_changelistlen;
3076 #endif
3077     }
3078 
3079     FOR_ALL_TAB_WINDOWS(tp, wp)
3080     {
3081 	if (wp->w_buffer == curbuf)
3082 	{
3083 	    /* Mark this window to be redrawn later. */
3084 	    if (wp->w_redr_type < VALID)
3085 		wp->w_redr_type = VALID;
3086 
3087 	    /* Check if a change in the buffer has invalidated the cached
3088 	     * values for the cursor. */
3089 #ifdef FEAT_FOLDING
3090 	    /*
3091 	     * Update the folds for this window.  Can't postpone this, because
3092 	     * a following operator might work on the whole fold: ">>dd".
3093 	     */
3094 	    foldUpdate(wp, lnum, lnume + xtra - 1);
3095 
3096 	    /* The change may cause lines above or below the change to become
3097 	     * included in a fold.  Set lnum/lnume to the first/last line that
3098 	     * might be displayed differently.
3099 	     * Set w_cline_folded here as an efficient way to update it when
3100 	     * inserting lines just above a closed fold. */
3101 	    i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3102 	    if (wp->w_cursor.lnum == lnum)
3103 		wp->w_cline_folded = i;
3104 	    i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3105 	    if (wp->w_cursor.lnum == lnume)
3106 		wp->w_cline_folded = i;
3107 
3108 	    /* If the changed line is in a range of previously folded lines,
3109 	     * compare with the first line in that range. */
3110 	    if (wp->w_cursor.lnum <= lnum)
3111 	    {
3112 		i = find_wl_entry(wp, lnum);
3113 		if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3114 		    changed_line_abv_curs_win(wp);
3115 	    }
3116 #endif
3117 
3118 	    if (wp->w_cursor.lnum > lnum)
3119 		changed_line_abv_curs_win(wp);
3120 	    else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3121 		changed_cline_bef_curs_win(wp);
3122 	    if (wp->w_botline >= lnum)
3123 	    {
3124 		/* Assume that botline doesn't change (inserted lines make
3125 		 * other lines scroll down below botline). */
3126 		approximate_botline_win(wp);
3127 	    }
3128 
3129 	    /* Check if any w_lines[] entries have become invalid.
3130 	     * For entries below the change: Correct the lnums for
3131 	     * inserted/deleted lines.  Makes it possible to stop displaying
3132 	     * after the change. */
3133 	    for (i = 0; i < wp->w_lines_valid; ++i)
3134 		if (wp->w_lines[i].wl_valid)
3135 		{
3136 		    if (wp->w_lines[i].wl_lnum >= lnum)
3137 		    {
3138 			if (wp->w_lines[i].wl_lnum < lnume)
3139 			{
3140 			    /* line included in change */
3141 			    wp->w_lines[i].wl_valid = FALSE;
3142 			}
3143 			else if (xtra != 0)
3144 			{
3145 			    /* line below change */
3146 			    wp->w_lines[i].wl_lnum += xtra;
3147 #ifdef FEAT_FOLDING
3148 			    wp->w_lines[i].wl_lastlnum += xtra;
3149 #endif
3150 			}
3151 		    }
3152 #ifdef FEAT_FOLDING
3153 		    else if (wp->w_lines[i].wl_lastlnum >= lnum)
3154 		    {
3155 			/* change somewhere inside this range of folded lines,
3156 			 * may need to be redrawn */
3157 			wp->w_lines[i].wl_valid = FALSE;
3158 		    }
3159 #endif
3160 		}
3161 
3162 #ifdef FEAT_FOLDING
3163 	    /* Take care of side effects for setting w_topline when folds have
3164 	     * changed.  Esp. when the buffer was changed in another window. */
3165 	    if (hasAnyFolding(wp))
3166 		set_topline(wp, wp->w_topline);
3167 #endif
3168 	    /* relative numbering may require updating more */
3169 	    if (wp->w_p_rnu)
3170 		redraw_win_later(wp, SOME_VALID);
3171 	}
3172     }
3173 
3174     /* Call update_screen() later, which checks out what needs to be redrawn,
3175      * since it notices b_mod_set and then uses b_mod_*. */
3176     if (must_redraw < VALID)
3177 	must_redraw = VALID;
3178 
3179 #ifdef FEAT_AUTOCMD
3180     /* when the cursor line is changed always trigger CursorMoved */
3181     if (lnum <= curwin->w_cursor.lnum
3182 		 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
3183 	last_cursormoved.lnum = 0;
3184 #endif
3185 }
3186 
3187 /*
3188  * unchanged() is called when the changed flag must be reset for buffer 'buf'
3189  */
3190     void
3191 unchanged(
3192     buf_T	*buf,
3193     int		ff)	/* also reset 'fileformat' */
3194 {
3195     if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
3196     {
3197 	buf->b_changed = 0;
3198 	ml_setflags(buf);
3199 	if (ff)
3200 	    save_file_ff(buf);
3201 #ifdef FEAT_WINDOWS
3202 	check_status(buf);
3203 	redraw_tabline = TRUE;
3204 #endif
3205 #ifdef FEAT_TITLE
3206 	need_maketitle = TRUE;	    /* set window title later */
3207 #endif
3208     }
3209     ++CHANGEDTICK(buf);
3210 #ifdef FEAT_NETBEANS_INTG
3211     netbeans_unmodified(buf);
3212 #endif
3213 }
3214 
3215 #if defined(FEAT_WINDOWS) || defined(PROTO)
3216 /*
3217  * check_status: called when the status bars for the buffer 'buf'
3218  *		 need to be updated
3219  */
3220     void
3221 check_status(buf_T *buf)
3222 {
3223     win_T	*wp;
3224 
3225     FOR_ALL_WINDOWS(wp)
3226 	if (wp->w_buffer == buf && wp->w_status_height)
3227 	{
3228 	    wp->w_redr_status = TRUE;
3229 	    if (must_redraw < VALID)
3230 		must_redraw = VALID;
3231 	}
3232 }
3233 #endif
3234 
3235 /*
3236  * If the file is readonly, give a warning message with the first change.
3237  * Don't do this for autocommands.
3238  * Don't use emsg(), because it flushes the macro buffer.
3239  * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
3240  * will be TRUE.
3241  * Careful: may trigger autocommands that reload the buffer.
3242  */
3243     void
3244 change_warning(
3245     int	    col)		/* column for message; non-zero when in insert
3246 				   mode and 'showmode' is on */
3247 {
3248     static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3249 
3250     if (curbuf->b_did_warn == FALSE
3251 	    && curbufIsChanged() == 0
3252 #ifdef FEAT_AUTOCMD
3253 	    && !autocmd_busy
3254 #endif
3255 	    && curbuf->b_p_ro)
3256     {
3257 #ifdef FEAT_AUTOCMD
3258 	++curbuf_lock;
3259 	apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
3260 	--curbuf_lock;
3261 	if (!curbuf->b_p_ro)
3262 	    return;
3263 #endif
3264 	/*
3265 	 * Do what msg() does, but with a column offset if the warning should
3266 	 * be after the mode message.
3267 	 */
3268 	msg_start();
3269 	if (msg_row == Rows - 1)
3270 	    msg_col = col;
3271 	msg_source(HL_ATTR(HLF_W));
3272 	MSG_PUTS_ATTR(_(w_readonly), HL_ATTR(HLF_W) | MSG_HIST);
3273 #ifdef FEAT_EVAL
3274 	set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3275 #endif
3276 	msg_clr_eos();
3277 	(void)msg_end();
3278 	if (msg_silent == 0 && !silent_mode
3279 #ifdef FEAT_EVAL
3280 		&& time_for_testing != 1
3281 #endif
3282 		)
3283 	{
3284 	    out_flush();
3285 	    ui_delay(1000L, TRUE); /* give the user time to think about it */
3286 	}
3287 	curbuf->b_did_warn = TRUE;
3288 	redraw_cmdline = FALSE;	/* don't redraw and erase the message */
3289 	if (msg_row < Rows - 1)
3290 	    showmode();
3291     }
3292 }
3293 
3294 /*
3295  * Ask for a reply from the user, a 'y' or a 'n'.
3296  * No other characters are accepted, the message is repeated until a valid
3297  * reply is entered or CTRL-C is hit.
3298  * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3299  * from any buffers but directly from the user.
3300  *
3301  * return the 'y' or 'n'
3302  */
3303     int
3304 ask_yesno(char_u *str, int direct)
3305 {
3306     int	    r = ' ';
3307     int	    save_State = State;
3308 
3309     if (exiting)		/* put terminal in raw mode for this question */
3310 	settmode(TMODE_RAW);
3311     ++no_wait_return;
3312 #ifdef USE_ON_FLY_SCROLL
3313     dont_scroll = TRUE;		/* disallow scrolling here */
3314 #endif
3315     State = CONFIRM;		/* mouse behaves like with :confirm */
3316 #ifdef FEAT_MOUSE
3317     setmouse();			/* disables mouse for xterm */
3318 #endif
3319     ++no_mapping;
3320     ++allow_keys;		/* no mapping here, but recognize keys */
3321 
3322     while (r != 'y' && r != 'n')
3323     {
3324 	/* same highlighting as for wait_return */
3325 	smsg_attr(HL_ATTR(HLF_R), (char_u *)"%s (y/n)?", str);
3326 	if (direct)
3327 	    r = get_keystroke();
3328 	else
3329 	    r = plain_vgetc();
3330 	if (r == Ctrl_C || r == ESC)
3331 	    r = 'n';
3332 	msg_putchar(r);	    /* show what you typed */
3333 	out_flush();
3334     }
3335     --no_wait_return;
3336     State = save_State;
3337 #ifdef FEAT_MOUSE
3338     setmouse();
3339 #endif
3340     --no_mapping;
3341     --allow_keys;
3342 
3343     return r;
3344 }
3345 
3346 #if defined(FEAT_MOUSE) || defined(PROTO)
3347 /*
3348  * Return TRUE if "c" is a mouse key.
3349  */
3350     int
3351 is_mouse_key(int c)
3352 {
3353     return c == K_LEFTMOUSE
3354 	|| c == K_LEFTMOUSE_NM
3355 	|| c == K_LEFTDRAG
3356 	|| c == K_LEFTRELEASE
3357 	|| c == K_LEFTRELEASE_NM
3358 	|| c == K_MIDDLEMOUSE
3359 	|| c == K_MIDDLEDRAG
3360 	|| c == K_MIDDLERELEASE
3361 	|| c == K_RIGHTMOUSE
3362 	|| c == K_RIGHTDRAG
3363 	|| c == K_RIGHTRELEASE
3364 	|| c == K_MOUSEDOWN
3365 	|| c == K_MOUSEUP
3366 	|| c == K_MOUSELEFT
3367 	|| c == K_MOUSERIGHT
3368 	|| c == K_X1MOUSE
3369 	|| c == K_X1DRAG
3370 	|| c == K_X1RELEASE
3371 	|| c == K_X2MOUSE
3372 	|| c == K_X2DRAG
3373 	|| c == K_X2RELEASE;
3374 }
3375 #endif
3376 
3377 /*
3378  * Get a key stroke directly from the user.
3379  * Ignores mouse clicks and scrollbar events, except a click for the left
3380  * button (used at the more prompt).
3381  * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3382  * Disadvantage: typeahead is ignored.
3383  * Translates the interrupt character for unix to ESC.
3384  */
3385     int
3386 get_keystroke(void)
3387 {
3388     char_u	*buf = NULL;
3389     int		buflen = 150;
3390     int		maxlen;
3391     int		len = 0;
3392     int		n;
3393     int		save_mapped_ctrl_c = mapped_ctrl_c;
3394     int		waited = 0;
3395 
3396     mapped_ctrl_c = FALSE;	/* mappings are not used here */
3397     for (;;)
3398     {
3399 	cursor_on();
3400 	out_flush();
3401 
3402 	/* Leave some room for check_termcode() to insert a key code into (max
3403 	 * 5 chars plus NUL).  And fix_input_buffer() can triple the number of
3404 	 * bytes. */
3405 	maxlen = (buflen - 6 - len) / 3;
3406 	if (buf == NULL)
3407 	    buf = alloc(buflen);
3408 	else if (maxlen < 10)
3409 	{
3410 	    char_u  *t_buf = buf;
3411 
3412 	    /* Need some more space. This might happen when receiving a long
3413 	     * escape sequence. */
3414 	    buflen += 100;
3415 	    buf = vim_realloc(buf, buflen);
3416 	    if (buf == NULL)
3417 		vim_free(t_buf);
3418 	    maxlen = (buflen - 6 - len) / 3;
3419 	}
3420 	if (buf == NULL)
3421 	{
3422 	    do_outofmem_msg((long_u)buflen);
3423 	    return ESC;  /* panic! */
3424 	}
3425 
3426 	/* First time: blocking wait.  Second time: wait up to 100ms for a
3427 	 * terminal code to complete. */
3428 	n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
3429 	if (n > 0)
3430 	{
3431 	    /* Replace zero and CSI by a special key code. */
3432 	    n = fix_input_buffer(buf + len, n);
3433 	    len += n;
3434 	    waited = 0;
3435 	}
3436 	else if (len > 0)
3437 	    ++waited;	    /* keep track of the waiting time */
3438 
3439 	/* Incomplete termcode and not timed out yet: get more characters */
3440 	if ((n = check_termcode(1, buf, buflen, &len)) < 0
3441 	       && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
3442 	    continue;
3443 
3444 	if (n == KEYLEN_REMOVED)  /* key code removed */
3445 	{
3446 	    if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
3447 	    {
3448 		/* Redrawing was postponed, do it now. */
3449 		update_screen(0);
3450 		setcursor(); /* put cursor back where it belongs */
3451 	    }
3452 	    continue;
3453 	}
3454 	if (n > 0)		/* found a termcode: adjust length */
3455 	    len = n;
3456 	if (len == 0)		/* nothing typed yet */
3457 	    continue;
3458 
3459 	/* Handle modifier and/or special key code. */
3460 	n = buf[0];
3461 	if (n == K_SPECIAL)
3462 	{
3463 	    n = TO_SPECIAL(buf[1], buf[2]);
3464 	    if (buf[1] == KS_MODIFIER
3465 		    || n == K_IGNORE
3466 #ifdef FEAT_MOUSE
3467 		    || (is_mouse_key(n) && n != K_LEFTMOUSE)
3468 #endif
3469 #ifdef FEAT_GUI
3470 		    || n == K_VER_SCROLLBAR
3471 		    || n == K_HOR_SCROLLBAR
3472 #endif
3473 	       )
3474 	    {
3475 		if (buf[1] == KS_MODIFIER)
3476 		    mod_mask = buf[2];
3477 		len -= 3;
3478 		if (len > 0)
3479 		    mch_memmove(buf, buf + 3, (size_t)len);
3480 		continue;
3481 	    }
3482 	    break;
3483 	}
3484 #ifdef FEAT_MBYTE
3485 	if (has_mbyte)
3486 	{
3487 	    if (MB_BYTE2LEN(n) > len)
3488 		continue;	/* more bytes to get */
3489 	    buf[len >= buflen ? buflen - 1 : len] = NUL;
3490 	    n = (*mb_ptr2char)(buf);
3491 	}
3492 #endif
3493 #ifdef UNIX
3494 	if (n == intr_char)
3495 	    n = ESC;
3496 #endif
3497 	break;
3498     }
3499     vim_free(buf);
3500 
3501     mapped_ctrl_c = save_mapped_ctrl_c;
3502     return n;
3503 }
3504 
3505 /*
3506  * Get a number from the user.
3507  * When "mouse_used" is not NULL allow using the mouse.
3508  */
3509     int
3510 get_number(
3511     int	    colon,			/* allow colon to abort */
3512     int	    *mouse_used)
3513 {
3514     int	n = 0;
3515     int	c;
3516     int typed = 0;
3517 
3518     if (mouse_used != NULL)
3519 	*mouse_used = FALSE;
3520 
3521     /* When not printing messages, the user won't know what to type, return a
3522      * zero (as if CR was hit). */
3523     if (msg_silent != 0)
3524 	return 0;
3525 
3526 #ifdef USE_ON_FLY_SCROLL
3527     dont_scroll = TRUE;		/* disallow scrolling here */
3528 #endif
3529     ++no_mapping;
3530     ++allow_keys;		/* no mapping here, but recognize keys */
3531     for (;;)
3532     {
3533 	windgoto(msg_row, msg_col);
3534 	c = safe_vgetc();
3535 	if (VIM_ISDIGIT(c))
3536 	{
3537 	    n = n * 10 + c - '0';
3538 	    msg_putchar(c);
3539 	    ++typed;
3540 	}
3541 	else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3542 	{
3543 	    if (typed > 0)
3544 	    {
3545 		MSG_PUTS("\b \b");
3546 		--typed;
3547 	    }
3548 	    n /= 10;
3549 	}
3550 #ifdef FEAT_MOUSE
3551 	else if (mouse_used != NULL && c == K_LEFTMOUSE)
3552 	{
3553 	    *mouse_used = TRUE;
3554 	    n = mouse_row + 1;
3555 	    break;
3556 	}
3557 #endif
3558 	else if (n == 0 && c == ':' && colon)
3559 	{
3560 	    stuffcharReadbuff(':');
3561 	    if (!exmode_active)
3562 		cmdline_row = msg_row;
3563 	    skip_redraw = TRUE;	    /* skip redraw once */
3564 	    do_redraw = FALSE;
3565 	    break;
3566 	}
3567 	else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3568 	    break;
3569     }
3570     --no_mapping;
3571     --allow_keys;
3572     return n;
3573 }
3574 
3575 /*
3576  * Ask the user to enter a number.
3577  * When "mouse_used" is not NULL allow using the mouse and in that case return
3578  * the line number.
3579  */
3580     int
3581 prompt_for_number(int *mouse_used)
3582 {
3583     int		i;
3584     int		save_cmdline_row;
3585     int		save_State;
3586 
3587     /* When using ":silent" assume that <CR> was entered. */
3588     if (mouse_used != NULL)
3589 	MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
3590     else
3591 	MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
3592 
3593     /* Set the state such that text can be selected/copied/pasted and we still
3594      * get mouse events. */
3595     save_cmdline_row = cmdline_row;
3596     cmdline_row = 0;
3597     save_State = State;
3598     State = ASKMORE;	/* prevents a screen update when using a timer */
3599 
3600     i = get_number(TRUE, mouse_used);
3601     if (KeyTyped)
3602     {
3603 	/* don't call wait_return() now */
3604 	/* msg_putchar('\n'); */
3605 	cmdline_row = msg_row - 1;
3606 	need_wait_return = FALSE;
3607 	msg_didany = FALSE;
3608 	msg_didout = FALSE;
3609     }
3610     else
3611 	cmdline_row = save_cmdline_row;
3612     State = save_State;
3613 
3614     return i;
3615 }
3616 
3617     void
3618 msgmore(long n)
3619 {
3620     long pn;
3621 
3622     if (global_busy	    /* no messages now, wait until global is finished */
3623 	    || !messaging())  /* 'lazyredraw' set, don't do messages now */
3624 	return;
3625 
3626     /* We don't want to overwrite another important message, but do overwrite
3627      * a previous "more lines" or "fewer lines" message, so that "5dd" and
3628      * then "put" reports the last action. */
3629     if (keep_msg != NULL && !keep_msg_more)
3630 	return;
3631 
3632     if (n > 0)
3633 	pn = n;
3634     else
3635 	pn = -n;
3636 
3637     if (pn > p_report)
3638     {
3639 	if (pn == 1)
3640 	{
3641 	    if (n > 0)
3642 		vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3643 							     MSG_BUF_LEN - 1);
3644 	    else
3645 		vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3646 							     MSG_BUF_LEN - 1);
3647 	}
3648 	else
3649 	{
3650 	    if (n > 0)
3651 		vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3652 						     _("%ld more lines"), pn);
3653 	    else
3654 		vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3655 						    _("%ld fewer lines"), pn);
3656 	}
3657 	if (got_int)
3658 	    vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
3659 	if (msg(msg_buf))
3660 	{
3661 	    set_keep_msg(msg_buf, 0);
3662 	    keep_msg_more = TRUE;
3663 	}
3664     }
3665 }
3666 
3667 /*
3668  * flush map and typeahead buffers and give a warning for an error
3669  */
3670     void
3671 beep_flush(void)
3672 {
3673     if (emsg_silent == 0)
3674     {
3675 	flush_buffers(FALSE);
3676 	vim_beep(BO_ERROR);
3677     }
3678 }
3679 
3680 /*
3681  * Give a warning for an error.
3682  */
3683     void
3684 vim_beep(
3685     unsigned val) /* one of the BO_ values, e.g., BO_OPER */
3686 {
3687     if (emsg_silent == 0)
3688     {
3689 	if (!((bo_flags & val) || (bo_flags & BO_ALL)))
3690 	{
3691 #ifdef ELAPSED_FUNC
3692 	    static int		did_init = FALSE;
3693 	    static ELAPSED_TYPE	start_tv;
3694 
3695 	    /* Only beep once per half a second, otherwise a sequence of beeps
3696 	     * would freeze Vim. */
3697 	    if (!did_init || ELAPSED_FUNC(start_tv) > 500)
3698 	    {
3699 		did_init = TRUE;
3700 		ELAPSED_INIT(start_tv);
3701 #endif
3702 		if (p_vb
3703 #ifdef FEAT_GUI
3704 			/* While the GUI is starting up the termcap is set for
3705 			 * the GUI but the output still goes to a terminal. */
3706 			&& !(gui.in_use && gui.starting)
3707 #endif
3708 			)
3709 		    out_str_cf(T_VB);
3710 		else
3711 		    out_char(BELL);
3712 #ifdef ELAPSED_FUNC
3713 	    }
3714 #endif
3715 	}
3716 
3717 	/* When 'verbose' is set and we are sourcing a script or executing a
3718 	 * function give the user a hint where the beep comes from. */
3719 	if (vim_strchr(p_debug, 'e') != NULL)
3720 	{
3721 	    msg_source(HL_ATTR(HLF_W));
3722 	    msg_attr((char_u *)_("Beep!"), HL_ATTR(HLF_W));
3723 	}
3724     }
3725 }
3726 
3727 /*
3728  * To get the "real" home directory:
3729  * - get value of $HOME
3730  * For Unix:
3731  *  - go to that directory
3732  *  - do mch_dirname() to get the real name of that directory.
3733  *  This also works with mounts and links.
3734  *  Don't do this for MS-DOS, it will change the "current dir" for a drive.
3735  */
3736 static char_u	*homedir = NULL;
3737 
3738     void
3739 init_homedir(void)
3740 {
3741     char_u  *var;
3742 
3743     /* In case we are called a second time (when 'encoding' changes). */
3744     vim_free(homedir);
3745     homedir = NULL;
3746 
3747 #ifdef VMS
3748     var = mch_getenv((char_u *)"SYS$LOGIN");
3749 #else
3750     var = mch_getenv((char_u *)"HOME");
3751 #endif
3752 
3753     if (var != NULL && *var == NUL)	/* empty is same as not set */
3754 	var = NULL;
3755 
3756 #ifdef WIN3264
3757     /*
3758      * Weird but true: $HOME may contain an indirect reference to another
3759      * variable, esp. "%USERPROFILE%".  Happens when $USERPROFILE isn't set
3760      * when $HOME is being set.
3761      */
3762     if (var != NULL && *var == '%')
3763     {
3764 	char_u	*p;
3765 	char_u	*exp;
3766 
3767 	p = vim_strchr(var + 1, '%');
3768 	if (p != NULL)
3769 	{
3770 	    vim_strncpy(NameBuff, var + 1, p - (var + 1));
3771 	    exp = mch_getenv(NameBuff);
3772 	    if (exp != NULL && *exp != NUL
3773 					&& STRLEN(exp) + STRLEN(p) < MAXPATHL)
3774 	    {
3775 		vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
3776 		var = NameBuff;
3777 		/* Also set $HOME, it's needed for _viminfo. */
3778 		vim_setenv((char_u *)"HOME", NameBuff);
3779 	    }
3780 	}
3781     }
3782 
3783     /*
3784      * Typically, $HOME is not defined on Windows, unless the user has
3785      * specifically defined it for Vim's sake.  However, on Windows NT
3786      * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3787      * each user.  Try constructing $HOME from these.
3788      */
3789     if (var == NULL)
3790     {
3791 	char_u *homedrive, *homepath;
3792 
3793 	homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3794 	homepath = mch_getenv((char_u *)"HOMEPATH");
3795 	if (homepath == NULL || *homepath == NUL)
3796 	    homepath = (char_u *)"\\";
3797 	if (homedrive != NULL
3798 			   && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3799 	{
3800 	    sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3801 	    if (NameBuff[0] != NUL)
3802 	    {
3803 		var = NameBuff;
3804 		/* Also set $HOME, it's needed for _viminfo. */
3805 		vim_setenv((char_u *)"HOME", NameBuff);
3806 	    }
3807 	}
3808     }
3809 
3810 # if defined(FEAT_MBYTE)
3811     if (enc_utf8 && var != NULL)
3812     {
3813 	int	len;
3814 	char_u  *pp = NULL;
3815 
3816 	/* Convert from active codepage to UTF-8.  Other conversions are
3817 	 * not done, because they would fail for non-ASCII characters. */
3818 	acp_to_enc(var, (int)STRLEN(var), &pp, &len);
3819 	if (pp != NULL)
3820 	{
3821 	    homedir = pp;
3822 	    return;
3823 	}
3824     }
3825 # endif
3826 #endif
3827 
3828 #if defined(MSWIN)
3829     /*
3830      * Default home dir is C:/
3831      * Best assumption we can make in such a situation.
3832      */
3833     if (var == NULL)
3834 	var = (char_u *)"C:/";
3835 #endif
3836     if (var != NULL)
3837     {
3838 #ifdef UNIX
3839 	/*
3840 	 * Change to the directory and get the actual path.  This resolves
3841 	 * links.  Don't do it when we can't return.
3842 	 */
3843 	if (mch_dirname(NameBuff, MAXPATHL) == OK
3844 					  && mch_chdir((char *)NameBuff) == 0)
3845 	{
3846 	    if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3847 		var = IObuff;
3848 	    if (mch_chdir((char *)NameBuff) != 0)
3849 		EMSG(_(e_prev_dir));
3850 	}
3851 #endif
3852 	homedir = vim_strsave(var);
3853     }
3854 }
3855 
3856 #if defined(EXITFREE) || defined(PROTO)
3857     void
3858 free_homedir(void)
3859 {
3860     vim_free(homedir);
3861 }
3862 
3863 # ifdef FEAT_CMDL_COMPL
3864     void
3865 free_users(void)
3866 {
3867     ga_clear_strings(&ga_users);
3868 }
3869 # endif
3870 #endif
3871 
3872 /*
3873  * Call expand_env() and store the result in an allocated string.
3874  * This is not very memory efficient, this expects the result to be freed
3875  * again soon.
3876  */
3877     char_u *
3878 expand_env_save(char_u *src)
3879 {
3880     return expand_env_save_opt(src, FALSE);
3881 }
3882 
3883 /*
3884  * Idem, but when "one" is TRUE handle the string as one file name, only
3885  * expand "~" at the start.
3886  */
3887     char_u *
3888 expand_env_save_opt(char_u *src, int one)
3889 {
3890     char_u	*p;
3891 
3892     p = alloc(MAXPATHL);
3893     if (p != NULL)
3894 	expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3895     return p;
3896 }
3897 
3898 /*
3899  * Expand environment variable with path name.
3900  * "~/" is also expanded, using $HOME.	For Unix "~user/" is expanded.
3901  * Skips over "\ ", "\~" and "\$" (not for Win32 though).
3902  * If anything fails no expansion is done and dst equals src.
3903  */
3904     void
3905 expand_env(
3906     char_u	*src,		/* input string e.g. "$HOME/vim.hlp" */
3907     char_u	*dst,		/* where to put the result */
3908     int		dstlen)		/* maximum length of the result */
3909 {
3910     expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
3911 }
3912 
3913     void
3914 expand_env_esc(
3915     char_u	*srcp,		/* input string e.g. "$HOME/vim.hlp" */
3916     char_u	*dst,		/* where to put the result */
3917     int		dstlen,		/* maximum length of the result */
3918     int		esc,		/* escape spaces in expanded variables */
3919     int		one,		/* "srcp" is one file name */
3920     char_u	*startstr)	/* start again after this (can be NULL) */
3921 {
3922     char_u	*src;
3923     char_u	*tail;
3924     int		c;
3925     char_u	*var;
3926     int		copy_char;
3927     int		mustfree;	/* var was allocated, need to free it later */
3928     int		at_start = TRUE; /* at start of a name */
3929     int		startstr_len = 0;
3930 
3931     if (startstr != NULL)
3932 	startstr_len = (int)STRLEN(startstr);
3933 
3934     src = skipwhite(srcp);
3935     --dstlen;		    /* leave one char space for "\," */
3936     while (*src && dstlen > 0)
3937     {
3938 #ifdef FEAT_EVAL
3939 	/* Skip over `=expr`. */
3940 	if (src[0] == '`' && src[1] == '=')
3941 	{
3942 	    size_t len;
3943 
3944 	    var = src;
3945 	    src += 2;
3946 	    (void)skip_expr(&src);
3947 	    if (*src == '`')
3948 		++src;
3949 	    len = src - var;
3950 	    if (len > (size_t)dstlen)
3951 		len = dstlen;
3952 	    vim_strncpy(dst, var, len);
3953 	    dst += len;
3954 	    dstlen -= (int)len;
3955 	    continue;
3956 	}
3957 #endif
3958 	copy_char = TRUE;
3959 	if ((*src == '$'
3960 #ifdef VMS
3961 		    && at_start
3962 #endif
3963 	   )
3964 #if defined(MSWIN)
3965 		|| *src == '%'
3966 #endif
3967 		|| (*src == '~' && at_start))
3968 	{
3969 	    mustfree = FALSE;
3970 
3971 	    /*
3972 	     * The variable name is copied into dst temporarily, because it may
3973 	     * be a string in read-only memory and a NUL needs to be appended.
3974 	     */
3975 	    if (*src != '~')				/* environment var */
3976 	    {
3977 		tail = src + 1;
3978 		var = dst;
3979 		c = dstlen - 1;
3980 
3981 #ifdef UNIX
3982 		/* Unix has ${var-name} type environment vars */
3983 		if (*tail == '{' && !vim_isIDc('{'))
3984 		{
3985 		    tail++;	/* ignore '{' */
3986 		    while (c-- > 0 && *tail && *tail != '}')
3987 			*var++ = *tail++;
3988 		}
3989 		else
3990 #endif
3991 		{
3992 		    while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3993 #if defined(MSWIN)
3994 			    || (*src == '%' && *tail != '%')
3995 #endif
3996 			    ))
3997 		    {
3998 			*var++ = *tail++;
3999 		    }
4000 		}
4001 
4002 #if defined(MSWIN) || defined(UNIX)
4003 # ifdef UNIX
4004 		if (src[1] == '{' && *tail != '}')
4005 # else
4006 		if (*src == '%' && *tail != '%')
4007 # endif
4008 		    var = NULL;
4009 		else
4010 		{
4011 # ifdef UNIX
4012 		    if (src[1] == '{')
4013 # else
4014 		    if (*src == '%')
4015 #endif
4016 			++tail;
4017 #endif
4018 		    *var = NUL;
4019 		    var = vim_getenv(dst, &mustfree);
4020 #if defined(MSWIN) || defined(UNIX)
4021 		}
4022 #endif
4023 	    }
4024 							/* home directory */
4025 	    else if (  src[1] == NUL
4026 		    || vim_ispathsep(src[1])
4027 		    || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
4028 	    {
4029 		var = homedir;
4030 		tail = src + 1;
4031 	    }
4032 	    else					/* user directory */
4033 	    {
4034 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
4035 		/*
4036 		 * Copy ~user to dst[], so we can put a NUL after it.
4037 		 */
4038 		tail = src;
4039 		var = dst;
4040 		c = dstlen - 1;
4041 		while (	   c-- > 0
4042 			&& *tail
4043 			&& vim_isfilec(*tail)
4044 			&& !vim_ispathsep(*tail))
4045 		    *var++ = *tail++;
4046 		*var = NUL;
4047 # ifdef UNIX
4048 		/*
4049 		 * If the system supports getpwnam(), use it.
4050 		 * Otherwise, or if getpwnam() fails, the shell is used to
4051 		 * expand ~user.  This is slower and may fail if the shell
4052 		 * does not support ~user (old versions of /bin/sh).
4053 		 */
4054 #  if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
4055 		{
4056 		    /* Note: memory allocated by getpwnam() is never freed.
4057 		     * Calling endpwent() apparently doesn't help. */
4058 		    struct passwd *pw = (*dst == NUL)
4059 					? NULL : getpwnam((char *)dst + 1);
4060 
4061 		    var = (pw == NULL) ? NULL : (char_u *)pw->pw_dir;
4062 		}
4063 		if (var == NULL)
4064 #  endif
4065 		{
4066 		    expand_T	xpc;
4067 
4068 		    ExpandInit(&xpc);
4069 		    xpc.xp_context = EXPAND_FILES;
4070 		    var = ExpandOne(&xpc, dst, NULL,
4071 				WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
4072 		    mustfree = TRUE;
4073 		}
4074 
4075 # else	/* !UNIX, thus VMS */
4076 		/*
4077 		 * USER_HOME is a comma-separated list of
4078 		 * directories to search for the user account in.
4079 		 */
4080 		{
4081 		    char_u	test[MAXPATHL], paths[MAXPATHL];
4082 		    char_u	*path, *next_path, *ptr;
4083 		    stat_T	st;
4084 
4085 		    STRCPY(paths, USER_HOME);
4086 		    next_path = paths;
4087 		    while (*next_path)
4088 		    {
4089 			for (path = next_path; *next_path && *next_path != ',';
4090 				next_path++);
4091 			if (*next_path)
4092 			    *next_path++ = NUL;
4093 			STRCPY(test, path);
4094 			STRCAT(test, "/");
4095 			STRCAT(test, dst + 1);
4096 			if (mch_stat(test, &st) == 0)
4097 			{
4098 			    var = alloc(STRLEN(test) + 1);
4099 			    STRCPY(var, test);
4100 			    mustfree = TRUE;
4101 			    break;
4102 			}
4103 		    }
4104 		}
4105 # endif /* UNIX */
4106 #else
4107 		/* cannot expand user's home directory, so don't try */
4108 		var = NULL;
4109 		tail = (char_u *)"";	/* for gcc */
4110 #endif /* UNIX || VMS */
4111 	    }
4112 
4113 #ifdef BACKSLASH_IN_FILENAME
4114 	    /* If 'shellslash' is set change backslashes to forward slashes.
4115 	     * Can't use slash_adjust(), p_ssl may be set temporarily. */
4116 	    if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4117 	    {
4118 		char_u	*p = vim_strsave(var);
4119 
4120 		if (p != NULL)
4121 		{
4122 		    if (mustfree)
4123 			vim_free(var);
4124 		    var = p;
4125 		    mustfree = TRUE;
4126 		    forward_slash(var);
4127 		}
4128 	    }
4129 #endif
4130 
4131 	    /* If "var" contains white space, escape it with a backslash.
4132 	     * Required for ":e ~/tt" when $HOME includes a space. */
4133 	    if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4134 	    {
4135 		char_u	*p = vim_strsave_escaped(var, (char_u *)" \t");
4136 
4137 		if (p != NULL)
4138 		{
4139 		    if (mustfree)
4140 			vim_free(var);
4141 		    var = p;
4142 		    mustfree = TRUE;
4143 		}
4144 	    }
4145 
4146 	    if (var != NULL && *var != NUL
4147 		    && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4148 	    {
4149 		STRCPY(dst, var);
4150 		dstlen -= (int)STRLEN(var);
4151 		c = (int)STRLEN(var);
4152 		/* if var[] ends in a path separator and tail[] starts
4153 		 * with it, skip a character */
4154 		if (*var != NUL && after_pathsep(dst, dst + c)
4155 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4156 			&& dst[-1] != ':'
4157 #endif
4158 			&& vim_ispathsep(*tail))
4159 		    ++tail;
4160 		dst += c;
4161 		src = tail;
4162 		copy_char = FALSE;
4163 	    }
4164 	    if (mustfree)
4165 		vim_free(var);
4166 	}
4167 
4168 	if (copy_char)	    /* copy at least one char */
4169 	{
4170 	    /*
4171 	     * Recognize the start of a new name, for '~'.
4172 	     * Don't do this when "one" is TRUE, to avoid expanding "~" in
4173 	     * ":edit foo ~ foo".
4174 	     */
4175 	    at_start = FALSE;
4176 	    if (src[0] == '\\' && src[1] != NUL)
4177 	    {
4178 		*dst++ = *src++;
4179 		--dstlen;
4180 	    }
4181 	    else if ((src[0] == ' ' || src[0] == ',') && !one)
4182 		at_start = TRUE;
4183 	    *dst++ = *src++;
4184 	    --dstlen;
4185 
4186 	    if (startstr != NULL && src - startstr_len >= srcp
4187 		    && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4188 		at_start = TRUE;
4189 	}
4190     }
4191     *dst = NUL;
4192 }
4193 
4194 /*
4195  * Vim's version of getenv().
4196  * Special handling of $HOME, $VIM and $VIMRUNTIME.
4197  * Also does ACP to 'enc' conversion for Win32.
4198  * "mustfree" is set to TRUE when returned is allocated, it must be
4199  * initialized to FALSE by the caller.
4200  */
4201     char_u *
4202 vim_getenv(char_u *name, int *mustfree)
4203 {
4204     char_u	*p;
4205     char_u	*pend;
4206     int		vimruntime;
4207 
4208 #if defined(MSWIN)
4209     /* use "C:/" when $HOME is not set */
4210     if (STRCMP(name, "HOME") == 0)
4211 	return homedir;
4212 #endif
4213 
4214     p = mch_getenv(name);
4215     if (p != NULL && *p == NUL)	    /* empty is the same as not set */
4216 	p = NULL;
4217 
4218     if (p != NULL)
4219     {
4220 #if defined(FEAT_MBYTE) && defined(WIN3264)
4221 	if (enc_utf8)
4222 	{
4223 	    int	    len;
4224 	    char_u  *pp = NULL;
4225 
4226 	    /* Convert from active codepage to UTF-8.  Other conversions are
4227 	     * not done, because they would fail for non-ASCII characters. */
4228 	    acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4229 	    if (pp != NULL)
4230 	    {
4231 		p = pp;
4232 		*mustfree = TRUE;
4233 	    }
4234 	}
4235 #endif
4236 	return p;
4237     }
4238 
4239     vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4240     if (!vimruntime && STRCMP(name, "VIM") != 0)
4241 	return NULL;
4242 
4243     /*
4244      * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4245      * Don't do this when default_vimruntime_dir is non-empty.
4246      */
4247     if (vimruntime
4248 #ifdef HAVE_PATHDEF
4249 	    && *default_vimruntime_dir == NUL
4250 #endif
4251        )
4252     {
4253 	p = mch_getenv((char_u *)"VIM");
4254 	if (p != NULL && *p == NUL)	    /* empty is the same as not set */
4255 	    p = NULL;
4256 	if (p != NULL)
4257 	{
4258 	    p = vim_version_dir(p);
4259 	    if (p != NULL)
4260 		*mustfree = TRUE;
4261 	    else
4262 		p = mch_getenv((char_u *)"VIM");
4263 
4264 #if defined(FEAT_MBYTE) && defined(WIN3264)
4265 	    if (enc_utf8)
4266 	    {
4267 		int	len;
4268 		char_u  *pp = NULL;
4269 
4270 		/* Convert from active codepage to UTF-8.  Other conversions
4271 		 * are not done, because they would fail for non-ASCII
4272 		 * characters. */
4273 		acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4274 		if (pp != NULL)
4275 		{
4276 		    if (*mustfree)
4277 			vim_free(p);
4278 		    p = pp;
4279 		    *mustfree = TRUE;
4280 		}
4281 	    }
4282 #endif
4283 	}
4284     }
4285 
4286     /*
4287      * When expanding $VIM or $VIMRUNTIME fails, try using:
4288      * - the directory name from 'helpfile' (unless it contains '$')
4289      * - the executable name from argv[0]
4290      */
4291     if (p == NULL)
4292     {
4293 	if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4294 	    p = p_hf;
4295 #ifdef USE_EXE_NAME
4296 	/*
4297 	 * Use the name of the executable, obtained from argv[0].
4298 	 */
4299 	else
4300 	    p = exe_name;
4301 #endif
4302 	if (p != NULL)
4303 	{
4304 	    /* remove the file name */
4305 	    pend = gettail(p);
4306 
4307 	    /* remove "doc/" from 'helpfile', if present */
4308 	    if (p == p_hf)
4309 		pend = remove_tail(p, pend, (char_u *)"doc");
4310 
4311 #ifdef USE_EXE_NAME
4312 # ifdef MACOS_X
4313 	    /* remove "MacOS" from exe_name and add "Resources/vim" */
4314 	    if (p == exe_name)
4315 	    {
4316 		char_u	*pend1;
4317 		char_u	*pnew;
4318 
4319 		pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4320 		if (pend1 != pend)
4321 		{
4322 		    pnew = alloc((unsigned)(pend1 - p) + 15);
4323 		    if (pnew != NULL)
4324 		    {
4325 			STRNCPY(pnew, p, (pend1 - p));
4326 			STRCPY(pnew + (pend1 - p), "Resources/vim");
4327 			p = pnew;
4328 			pend = p + STRLEN(p);
4329 		    }
4330 		}
4331 	    }
4332 # endif
4333 	    /* remove "src/" from exe_name, if present */
4334 	    if (p == exe_name)
4335 		pend = remove_tail(p, pend, (char_u *)"src");
4336 #endif
4337 
4338 	    /* for $VIM, remove "runtime/" or "vim54/", if present */
4339 	    if (!vimruntime)
4340 	    {
4341 		pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4342 		pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4343 	    }
4344 
4345 	    /* remove trailing path separator */
4346 #ifndef MACOS_CLASSIC
4347 	    /* With MacOS path (with  colons) the final colon is required */
4348 	    /* to avoid confusion between absolute and relative path */
4349 	    if (pend > p && after_pathsep(p, pend))
4350 		--pend;
4351 #endif
4352 
4353 #ifdef MACOS_X
4354 	    if (p == exe_name || p == p_hf)
4355 #endif
4356 		/* check that the result is a directory name */
4357 		p = vim_strnsave(p, (int)(pend - p));
4358 
4359 	    if (p != NULL && !mch_isdir(p))
4360 	    {
4361 		vim_free(p);
4362 		p = NULL;
4363 	    }
4364 	    else
4365 	    {
4366 #ifdef USE_EXE_NAME
4367 		/* may add "/vim54" or "/runtime" if it exists */
4368 		if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4369 		{
4370 		    vim_free(p);
4371 		    p = pend;
4372 		}
4373 #endif
4374 		*mustfree = TRUE;
4375 	    }
4376 	}
4377     }
4378 
4379 #ifdef HAVE_PATHDEF
4380     /* When there is a pathdef.c file we can use default_vim_dir and
4381      * default_vimruntime_dir */
4382     if (p == NULL)
4383     {
4384 	/* Only use default_vimruntime_dir when it is not empty */
4385 	if (vimruntime && *default_vimruntime_dir != NUL)
4386 	{
4387 	    p = default_vimruntime_dir;
4388 	    *mustfree = FALSE;
4389 	}
4390 	else if (*default_vim_dir != NUL)
4391 	{
4392 	    if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4393 		*mustfree = TRUE;
4394 	    else
4395 	    {
4396 		p = default_vim_dir;
4397 		*mustfree = FALSE;
4398 	    }
4399 	}
4400     }
4401 #endif
4402 
4403     /*
4404      * Set the environment variable, so that the new value can be found fast
4405      * next time, and others can also use it (e.g. Perl).
4406      */
4407     if (p != NULL)
4408     {
4409 	if (vimruntime)
4410 	{
4411 	    vim_setenv((char_u *)"VIMRUNTIME", p);
4412 	    didset_vimruntime = TRUE;
4413 	}
4414 	else
4415 	{
4416 	    vim_setenv((char_u *)"VIM", p);
4417 	    didset_vim = TRUE;
4418 	}
4419     }
4420     return p;
4421 }
4422 
4423 /*
4424  * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4425  * Return NULL if not, return its name in allocated memory otherwise.
4426  */
4427     static char_u *
4428 vim_version_dir(char_u *vimdir)
4429 {
4430     char_u	*p;
4431 
4432     if (vimdir == NULL || *vimdir == NUL)
4433 	return NULL;
4434     p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4435     if (p != NULL && mch_isdir(p))
4436 	return p;
4437     vim_free(p);
4438     p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4439     if (p != NULL && mch_isdir(p))
4440 	return p;
4441     vim_free(p);
4442     return NULL;
4443 }
4444 
4445 /*
4446  * If the string between "p" and "pend" ends in "name/", return "pend" minus
4447  * the length of "name/".  Otherwise return "pend".
4448  */
4449     static char_u *
4450 remove_tail(char_u *p, char_u *pend, char_u *name)
4451 {
4452     int		len = (int)STRLEN(name) + 1;
4453     char_u	*newend = pend - len;
4454 
4455     if (newend >= p
4456 	    && fnamencmp(newend, name, len - 1) == 0
4457 	    && (newend == p || after_pathsep(p, newend)))
4458 	return newend;
4459     return pend;
4460 }
4461 
4462 /*
4463  * Our portable version of setenv.
4464  */
4465     void
4466 vim_setenv(char_u *name, char_u *val)
4467 {
4468 #ifdef HAVE_SETENV
4469     mch_setenv((char *)name, (char *)val, 1);
4470 #else
4471     char_u	*envbuf;
4472 
4473     /*
4474      * Putenv does not copy the string, it has to remain
4475      * valid.  The allocated memory will never be freed.
4476      */
4477     envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4478     if (envbuf != NULL)
4479     {
4480 	sprintf((char *)envbuf, "%s=%s", name, val);
4481 	putenv((char *)envbuf);
4482     }
4483 #endif
4484 #ifdef FEAT_GETTEXT
4485     /*
4486      * When setting $VIMRUNTIME adjust the directory to find message
4487      * translations to $VIMRUNTIME/lang.
4488      */
4489     if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4490     {
4491 	char_u	*buf = concat_str(val, (char_u *)"/lang");
4492 
4493 	if (buf != NULL)
4494 	{
4495 	    bindtextdomain(VIMPACKAGE, (char *)buf);
4496 	    vim_free(buf);
4497 	}
4498     }
4499 #endif
4500 }
4501 
4502 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4503 /*
4504  * Function given to ExpandGeneric() to obtain an environment variable name.
4505  */
4506     char_u *
4507 get_env_name(
4508     expand_T	*xp UNUSED,
4509     int		idx)
4510 {
4511 # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4512     /*
4513      * No environ[] on the Amiga and on the Mac (using MPW).
4514      */
4515     return NULL;
4516 # else
4517 # ifndef __WIN32__
4518     /* Borland C++ 5.2 has this in a header file. */
4519     extern char		**environ;
4520 # endif
4521 # define ENVNAMELEN 100
4522     static char_u	name[ENVNAMELEN];
4523     char_u		*str;
4524     int			n;
4525 
4526     str = (char_u *)environ[idx];
4527     if (str == NULL)
4528 	return NULL;
4529 
4530     for (n = 0; n < ENVNAMELEN - 1; ++n)
4531     {
4532 	if (str[n] == '=' || str[n] == NUL)
4533 	    break;
4534 	name[n] = str[n];
4535     }
4536     name[n] = NUL;
4537     return name;
4538 # endif
4539 }
4540 
4541 /*
4542  * Find all user names for user completion.
4543  * Done only once and then cached.
4544  */
4545     static void
4546 init_users(void)
4547 {
4548     static int	lazy_init_done = FALSE;
4549 
4550     if (lazy_init_done)
4551 	return;
4552 
4553     lazy_init_done = TRUE;
4554     ga_init2(&ga_users, sizeof(char_u *), 20);
4555 
4556 # if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
4557     {
4558 	char_u*		user;
4559 	struct passwd*	pw;
4560 
4561 	setpwent();
4562 	while ((pw = getpwent()) != NULL)
4563 	    /* pw->pw_name shouldn't be NULL but just in case... */
4564 	    if (pw->pw_name != NULL)
4565 	    {
4566 		if (ga_grow(&ga_users, 1) == FAIL)
4567 		    break;
4568 		user = vim_strsave((char_u*)pw->pw_name);
4569 		if (user == NULL)
4570 		    break;
4571 		((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user;
4572 	    }
4573 	endpwent();
4574     }
4575 # endif
4576 }
4577 
4578 /*
4579  * Function given to ExpandGeneric() to obtain an user names.
4580  */
4581     char_u*
4582 get_users(expand_T *xp UNUSED, int idx)
4583 {
4584     init_users();
4585     if (idx < ga_users.ga_len)
4586 	return ((char_u **)ga_users.ga_data)[idx];
4587     return NULL;
4588 }
4589 
4590 /*
4591  * Check whether name matches a user name. Return:
4592  * 0 if name does not match any user name.
4593  * 1 if name partially matches the beginning of a user name.
4594  * 2 is name fully matches a user name.
4595  */
4596 int match_user(char_u* name)
4597 {
4598     int i;
4599     int n = (int)STRLEN(name);
4600     int result = 0;
4601 
4602     init_users();
4603     for (i = 0; i < ga_users.ga_len; i++)
4604     {
4605 	if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
4606 	    return 2; /* full match */
4607 	if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
4608 	    result = 1; /* partial match */
4609     }
4610     return result;
4611 }
4612 #endif
4613 
4614 /*
4615  * Replace home directory by "~" in each space or comma separated file name in
4616  * 'src'.
4617  * If anything fails (except when out of space) dst equals src.
4618  */
4619     void
4620 home_replace(
4621     buf_T	*buf,	/* when not NULL, check for help files */
4622     char_u	*src,	/* input file name */
4623     char_u	*dst,	/* where to put the result */
4624     int		dstlen,	/* maximum length of the result */
4625     int		one)	/* if TRUE, only replace one file name, include
4626 			   spaces and commas in the file name. */
4627 {
4628     size_t	dirlen = 0, envlen = 0;
4629     size_t	len;
4630     char_u	*homedir_env, *homedir_env_orig;
4631     char_u	*p;
4632 
4633     if (src == NULL)
4634     {
4635 	*dst = NUL;
4636 	return;
4637     }
4638 
4639     /*
4640      * If the file is a help file, remove the path completely.
4641      */
4642     if (buf != NULL && buf->b_help)
4643     {
4644 	vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
4645 	return;
4646     }
4647 
4648     /*
4649      * We check both the value of the $HOME environment variable and the
4650      * "real" home directory.
4651      */
4652     if (homedir != NULL)
4653 	dirlen = STRLEN(homedir);
4654 
4655 #ifdef VMS
4656     homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4657 #else
4658     homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4659 #endif
4660     /* Empty is the same as not set. */
4661     if (homedir_env != NULL && *homedir_env == NUL)
4662 	homedir_env = NULL;
4663 
4664 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL)
4665     if (homedir_env != NULL && vim_strchr(homedir_env, '~') != NULL)
4666     {
4667 	int	usedlen = 0;
4668 	int	flen;
4669 	char_u	*fbuf = NULL;
4670 
4671 	flen = (int)STRLEN(homedir_env);
4672 	(void)modify_fname((char_u *)":p", &usedlen,
4673 						  &homedir_env, &fbuf, &flen);
4674 	flen = (int)STRLEN(homedir_env);
4675 	if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4676 	    /* Remove the trailing / that is added to a directory. */
4677 	    homedir_env[flen - 1] = NUL;
4678     }
4679 #endif
4680 
4681     if (homedir_env != NULL)
4682 	envlen = STRLEN(homedir_env);
4683 
4684     if (!one)
4685 	src = skipwhite(src);
4686     while (*src && dstlen > 0)
4687     {
4688 	/*
4689 	 * Here we are at the beginning of a file name.
4690 	 * First, check to see if the beginning of the file name matches
4691 	 * $HOME or the "real" home directory. Check that there is a '/'
4692 	 * after the match (so that if e.g. the file is "/home/pieter/bla",
4693 	 * and the home directory is "/home/piet", the file does not end up
4694 	 * as "~er/bla" (which would seem to indicate the file "bla" in user
4695 	 * er's home directory)).
4696 	 */
4697 	p = homedir;
4698 	len = dirlen;
4699 	for (;;)
4700 	{
4701 	    if (   len
4702 		&& fnamencmp(src, p, len) == 0
4703 		&& (vim_ispathsep(src[len])
4704 		    || (!one && (src[len] == ',' || src[len] == ' '))
4705 		    || src[len] == NUL))
4706 	    {
4707 		src += len;
4708 		if (--dstlen > 0)
4709 		    *dst++ = '~';
4710 
4711 		/*
4712 		 * If it's just the home directory, add  "/".
4713 		 */
4714 		if (!vim_ispathsep(src[0]) && --dstlen > 0)
4715 		    *dst++ = '/';
4716 		break;
4717 	    }
4718 	    if (p == homedir_env)
4719 		break;
4720 	    p = homedir_env;
4721 	    len = envlen;
4722 	}
4723 
4724 	/* if (!one) skip to separator: space or comma */
4725 	while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4726 	    *dst++ = *src++;
4727 	/* skip separator */
4728 	while ((*src == ' ' || *src == ',') && --dstlen > 0)
4729 	    *dst++ = *src++;
4730     }
4731     /* if (dstlen == 0) out of space, what to do??? */
4732 
4733     *dst = NUL;
4734 
4735     if (homedir_env != homedir_env_orig)
4736 	vim_free(homedir_env);
4737 }
4738 
4739 /*
4740  * Like home_replace, store the replaced string in allocated memory.
4741  * When something fails, NULL is returned.
4742  */
4743     char_u  *
4744 home_replace_save(
4745     buf_T	*buf,	/* when not NULL, check for help files */
4746     char_u	*src)	/* input file name */
4747 {
4748     char_u	*dst;
4749     unsigned	len;
4750 
4751     len = 3;			/* space for "~/" and trailing NUL */
4752     if (src != NULL)		/* just in case */
4753 	len += (unsigned)STRLEN(src);
4754     dst = alloc(len);
4755     if (dst != NULL)
4756 	home_replace(buf, src, dst, len, TRUE);
4757     return dst;
4758 }
4759 
4760 /*
4761  * Compare two file names and return:
4762  * FPC_SAME   if they both exist and are the same file.
4763  * FPC_SAMEX  if they both don't exist and have the same file name.
4764  * FPC_DIFF   if they both exist and are different files.
4765  * FPC_NOTX   if they both don't exist.
4766  * FPC_DIFFX  if one of them doesn't exist.
4767  * For the first name environment variables are expanded
4768  */
4769     int
4770 fullpathcmp(
4771     char_u *s1,
4772     char_u *s2,
4773     int	    checkname)		/* when both don't exist, check file names */
4774 {
4775 #ifdef UNIX
4776     char_u	    exp1[MAXPATHL];
4777     char_u	    full1[MAXPATHL];
4778     char_u	    full2[MAXPATHL];
4779     stat_T	    st1, st2;
4780     int		    r1, r2;
4781 
4782     expand_env(s1, exp1, MAXPATHL);
4783     r1 = mch_stat((char *)exp1, &st1);
4784     r2 = mch_stat((char *)s2, &st2);
4785     if (r1 != 0 && r2 != 0)
4786     {
4787 	/* if mch_stat() doesn't work, may compare the names */
4788 	if (checkname)
4789 	{
4790 	    if (fnamecmp(exp1, s2) == 0)
4791 		return FPC_SAMEX;
4792 	    r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4793 	    r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4794 	    if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4795 		return FPC_SAMEX;
4796 	}
4797 	return FPC_NOTX;
4798     }
4799     if (r1 != 0 || r2 != 0)
4800 	return FPC_DIFFX;
4801     if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4802 	return FPC_SAME;
4803     return FPC_DIFF;
4804 #else
4805     char_u  *exp1;		/* expanded s1 */
4806     char_u  *full1;		/* full path of s1 */
4807     char_u  *full2;		/* full path of s2 */
4808     int	    retval = FPC_DIFF;
4809     int	    r1, r2;
4810 
4811     /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4812     if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4813     {
4814 	full1 = exp1 + MAXPATHL;
4815 	full2 = full1 + MAXPATHL;
4816 
4817 	expand_env(s1, exp1, MAXPATHL);
4818 	r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4819 	r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4820 
4821 	/* If vim_FullName() fails, the file probably doesn't exist. */
4822 	if (r1 != OK && r2 != OK)
4823 	{
4824 	    if (checkname && fnamecmp(exp1, s2) == 0)
4825 		retval = FPC_SAMEX;
4826 	    else
4827 		retval = FPC_NOTX;
4828 	}
4829 	else if (r1 != OK || r2 != OK)
4830 	    retval = FPC_DIFFX;
4831 	else if (fnamecmp(full1, full2))
4832 	    retval = FPC_DIFF;
4833 	else
4834 	    retval = FPC_SAME;
4835 	vim_free(exp1);
4836     }
4837     return retval;
4838 #endif
4839 }
4840 
4841 /*
4842  * Get the tail of a path: the file name.
4843  * When the path ends in a path separator the tail is the NUL after it.
4844  * Fail safe: never returns NULL.
4845  */
4846     char_u *
4847 gettail(char_u *fname)
4848 {
4849     char_u  *p1, *p2;
4850 
4851     if (fname == NULL)
4852 	return (char_u *)"";
4853     for (p1 = p2 = get_past_head(fname); *p2; )	/* find last part of path */
4854     {
4855 	if (vim_ispathsep_nocolon(*p2))
4856 	    p1 = p2 + 1;
4857 	MB_PTR_ADV(p2);
4858     }
4859     return p1;
4860 }
4861 
4862 #if defined(FEAT_SEARCHPATH)
4863 static char_u *gettail_dir(char_u *fname);
4864 
4865 /*
4866  * Return the end of the directory name, on the first path
4867  * separator:
4868  * "/path/file", "/path/dir/", "/path//dir", "/file"
4869  *	 ^	       ^	     ^	      ^
4870  */
4871     static char_u *
4872 gettail_dir(char_u *fname)
4873 {
4874     char_u	*dir_end = fname;
4875     char_u	*next_dir_end = fname;
4876     int		look_for_sep = TRUE;
4877     char_u	*p;
4878 
4879     for (p = fname; *p != NUL; )
4880     {
4881 	if (vim_ispathsep(*p))
4882 	{
4883 	    if (look_for_sep)
4884 	    {
4885 		next_dir_end = p;
4886 		look_for_sep = FALSE;
4887 	    }
4888 	}
4889 	else
4890 	{
4891 	    if (!look_for_sep)
4892 		dir_end = next_dir_end;
4893 	    look_for_sep = TRUE;
4894 	}
4895 	MB_PTR_ADV(p);
4896     }
4897     return dir_end;
4898 }
4899 #endif
4900 
4901 /*
4902  * Get pointer to tail of "fname", including path separators.  Putting a NUL
4903  * here leaves the directory name.  Takes care of "c:/" and "//".
4904  * Always returns a valid pointer.
4905  */
4906     char_u *
4907 gettail_sep(char_u *fname)
4908 {
4909     char_u	*p;
4910     char_u	*t;
4911 
4912     p = get_past_head(fname);	/* don't remove the '/' from "c:/file" */
4913     t = gettail(fname);
4914     while (t > p && after_pathsep(fname, t))
4915 	--t;
4916 #ifdef VMS
4917     /* path separator is part of the path */
4918     ++t;
4919 #endif
4920     return t;
4921 }
4922 
4923 /*
4924  * get the next path component (just after the next path separator).
4925  */
4926     char_u *
4927 getnextcomp(char_u *fname)
4928 {
4929     while (*fname && !vim_ispathsep(*fname))
4930 	MB_PTR_ADV(fname);
4931     if (*fname)
4932 	++fname;
4933     return fname;
4934 }
4935 
4936 /*
4937  * Get a pointer to one character past the head of a path name.
4938  * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4939  * If there is no head, path is returned.
4940  */
4941     char_u *
4942 get_past_head(char_u *path)
4943 {
4944     char_u  *retval;
4945 
4946 #if defined(MSWIN)
4947     /* may skip "c:" */
4948     if (isalpha(path[0]) && path[1] == ':')
4949 	retval = path + 2;
4950     else
4951 	retval = path;
4952 #else
4953 # if defined(AMIGA)
4954     /* may skip "label:" */
4955     retval = vim_strchr(path, ':');
4956     if (retval == NULL)
4957 	retval = path;
4958 # else	/* Unix */
4959     retval = path;
4960 # endif
4961 #endif
4962 
4963     while (vim_ispathsep(*retval))
4964 	++retval;
4965 
4966     return retval;
4967 }
4968 
4969 /*
4970  * Return TRUE if 'c' is a path separator.
4971  * Note that for MS-Windows this includes the colon.
4972  */
4973     int
4974 vim_ispathsep(int c)
4975 {
4976 #ifdef UNIX
4977     return (c == '/');	    /* UNIX has ':' inside file names */
4978 #else
4979 # ifdef BACKSLASH_IN_FILENAME
4980     return (c == ':' || c == '/' || c == '\\');
4981 # else
4982 #  ifdef VMS
4983     /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4984     return (c == ':' || c == '[' || c == ']' || c == '/'
4985 	    || c == '<' || c == '>' || c == '"' );
4986 #  else
4987     return (c == ':' || c == '/');
4988 #  endif /* VMS */
4989 # endif
4990 #endif
4991 }
4992 
4993 /*
4994  * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
4995  */
4996     int
4997 vim_ispathsep_nocolon(int c)
4998 {
4999     return vim_ispathsep(c)
5000 #ifdef BACKSLASH_IN_FILENAME
5001 	&& c != ':'
5002 #endif
5003 	;
5004 }
5005 
5006 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
5007 /*
5008  * return TRUE if 'c' is a path list separator.
5009  */
5010     int
5011 vim_ispathlistsep(int c)
5012 {
5013 #ifdef UNIX
5014     return (c == ':');
5015 #else
5016     return (c == ';');	/* might not be right for every system... */
5017 #endif
5018 }
5019 #endif
5020 
5021 #if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
5022 	|| defined(FEAT_EVAL) || defined(PROTO)
5023 /*
5024  * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
5025  * It's done in-place.
5026  */
5027     void
5028 shorten_dir(char_u *str)
5029 {
5030     char_u	*tail, *s, *d;
5031     int		skip = FALSE;
5032 
5033     tail = gettail(str);
5034     d = str;
5035     for (s = str; ; ++s)
5036     {
5037 	if (s >= tail)		    /* copy the whole tail */
5038 	{
5039 	    *d++ = *s;
5040 	    if (*s == NUL)
5041 		break;
5042 	}
5043 	else if (vim_ispathsep(*s))	    /* copy '/' and next char */
5044 	{
5045 	    *d++ = *s;
5046 	    skip = FALSE;
5047 	}
5048 	else if (!skip)
5049 	{
5050 	    *d++ = *s;		    /* copy next char */
5051 	    if (*s != '~' && *s != '.') /* and leading "~" and "." */
5052 		skip = TRUE;
5053 # ifdef FEAT_MBYTE
5054 	    if (has_mbyte)
5055 	    {
5056 		int l = mb_ptr2len(s);
5057 
5058 		while (--l > 0)
5059 		    *d++ = *++s;
5060 	    }
5061 # endif
5062 	}
5063     }
5064 }
5065 #endif
5066 
5067 /*
5068  * Return TRUE if the directory of "fname" exists, FALSE otherwise.
5069  * Also returns TRUE if there is no directory name.
5070  * "fname" must be writable!.
5071  */
5072     int
5073 dir_of_file_exists(char_u *fname)
5074 {
5075     char_u	*p;
5076     int		c;
5077     int		retval;
5078 
5079     p = gettail_sep(fname);
5080     if (p == fname)
5081 	return TRUE;
5082     c = *p;
5083     *p = NUL;
5084     retval = mch_isdir(fname);
5085     *p = c;
5086     return retval;
5087 }
5088 
5089 /*
5090  * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
5091  * and deal with 'fileignorecase'.
5092  */
5093     int
5094 vim_fnamecmp(char_u *x, char_u *y)
5095 {
5096 #ifdef BACKSLASH_IN_FILENAME
5097     return vim_fnamencmp(x, y, MAXPATHL);
5098 #else
5099     if (p_fic)
5100 	return MB_STRICMP(x, y);
5101     return STRCMP(x, y);
5102 #endif
5103 }
5104 
5105     int
5106 vim_fnamencmp(char_u *x, char_u *y, size_t len)
5107 {
5108 #ifdef BACKSLASH_IN_FILENAME
5109     char_u	*px = x;
5110     char_u	*py = y;
5111     int		cx = NUL;
5112     int		cy = NUL;
5113 
5114     while (len > 0)
5115     {
5116 	cx = PTR2CHAR(px);
5117 	cy = PTR2CHAR(py);
5118 	if (cx == NUL || cy == NUL
5119 	    || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
5120 		&& !(cx == '/' && cy == '\\')
5121 		&& !(cx == '\\' && cy == '/')))
5122 	    break;
5123 	len -= MB_PTR2LEN(px);
5124 	px += MB_PTR2LEN(px);
5125 	py += MB_PTR2LEN(py);
5126     }
5127     if (len == 0)
5128 	return 0;
5129     return (cx - cy);
5130 #else
5131     if (p_fic)
5132 	return MB_STRNICMP(x, y, len);
5133     return STRNCMP(x, y, len);
5134 #endif
5135 }
5136 
5137 /*
5138  * Concatenate file names fname1 and fname2 into allocated memory.
5139  * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
5140  */
5141     char_u  *
5142 concat_fnames(char_u *fname1, char_u *fname2, int sep)
5143 {
5144     char_u  *dest;
5145 
5146     dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
5147     if (dest != NULL)
5148     {
5149 	STRCPY(dest, fname1);
5150 	if (sep)
5151 	    add_pathsep(dest);
5152 	STRCAT(dest, fname2);
5153     }
5154     return dest;
5155 }
5156 
5157 /*
5158  * Concatenate two strings and return the result in allocated memory.
5159  * Returns NULL when out of memory.
5160  */
5161     char_u  *
5162 concat_str(char_u *str1, char_u *str2)
5163 {
5164     char_u  *dest;
5165     size_t  l = STRLEN(str1);
5166 
5167     dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5168     if (dest != NULL)
5169     {
5170 	STRCPY(dest, str1);
5171 	STRCPY(dest + l, str2);
5172     }
5173     return dest;
5174 }
5175 
5176 /*
5177  * Add a path separator to a file name, unless it already ends in a path
5178  * separator.
5179  */
5180     void
5181 add_pathsep(char_u *p)
5182 {
5183     if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
5184 	STRCAT(p, PATHSEPSTR);
5185 }
5186 
5187 /*
5188  * FullName_save - Make an allocated copy of a full file name.
5189  * Returns NULL when out of memory.
5190  */
5191     char_u  *
5192 FullName_save(
5193     char_u	*fname,
5194     int		force)		/* force expansion, even when it already looks
5195 				 * like a full path name */
5196 {
5197     char_u	*buf;
5198     char_u	*new_fname = NULL;
5199 
5200     if (fname == NULL)
5201 	return NULL;
5202 
5203     buf = alloc((unsigned)MAXPATHL);
5204     if (buf != NULL)
5205     {
5206 	if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5207 	    new_fname = vim_strsave(buf);
5208 	else
5209 	    new_fname = vim_strsave(fname);
5210 	vim_free(buf);
5211     }
5212     return new_fname;
5213 }
5214 
5215 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5216 
5217 static char_u	*skip_string(char_u *p);
5218 static pos_T *ind_find_start_comment(void);
5219 static pos_T *ind_find_start_CORS(void);
5220 static pos_T *find_start_rawstring(int ind_maxcomment);
5221 
5222 /*
5223  * Find the start of a comment, not knowing if we are in a comment right now.
5224  * Search starts at w_cursor.lnum and goes backwards.
5225  * Return NULL when not inside a comment.
5226  */
5227     static pos_T *
5228 ind_find_start_comment(void)	    /* XXX */
5229 {
5230     return find_start_comment(curbuf->b_ind_maxcomment);
5231 }
5232 
5233     pos_T *
5234 find_start_comment(int ind_maxcomment)	/* XXX */
5235 {
5236     pos_T	*pos;
5237     char_u	*line;
5238     char_u	*p;
5239     int		cur_maxcomment = ind_maxcomment;
5240 
5241     for (;;)
5242     {
5243 	pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5244 	if (pos == NULL)
5245 	    break;
5246 
5247 	/*
5248 	 * Check if the comment start we found is inside a string.
5249 	 * If it is then restrict the search to below this line and try again.
5250 	 */
5251 	line = ml_get(pos->lnum);
5252 	for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
5253 	    p = skip_string(p);
5254 	if ((colnr_T)(p - line) <= pos->col)
5255 	    break;
5256 	cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5257 	if (cur_maxcomment <= 0)
5258 	{
5259 	    pos = NULL;
5260 	    break;
5261 	}
5262     }
5263     return pos;
5264 }
5265 
5266 /*
5267  * Find the start of a comment or raw string, not knowing if we are in a
5268  * comment or raw string right now.
5269  * Search starts at w_cursor.lnum and goes backwards.
5270  * Return NULL when not inside a comment or raw string.
5271  * "CORS" -> Comment Or Raw String
5272  */
5273     static pos_T *
5274 ind_find_start_CORS(void)	    /* XXX */
5275 {
5276     static pos_T comment_pos_copy;
5277     pos_T	*comment_pos;
5278     pos_T	*rs_pos;
5279 
5280     comment_pos = find_start_comment(curbuf->b_ind_maxcomment);
5281     if (comment_pos != NULL)
5282     {
5283 	/* Need to make a copy of the static pos in findmatchlimit(),
5284 	 * calling find_start_rawstring() may change it. */
5285 	comment_pos_copy = *comment_pos;
5286 	comment_pos = &comment_pos_copy;
5287     }
5288     rs_pos = find_start_rawstring(curbuf->b_ind_maxcomment);
5289 
5290     /* If comment_pos is before rs_pos the raw string is inside the comment.
5291      * If rs_pos is before comment_pos the comment is inside the raw string. */
5292     if (comment_pos == NULL || (rs_pos != NULL
5293 					     && LT_POS(*rs_pos, *comment_pos)))
5294 	return rs_pos;
5295     return comment_pos;
5296 }
5297 
5298 /*
5299  * Find the start of a raw string, not knowing if we are in one right now.
5300  * Search starts at w_cursor.lnum and goes backwards.
5301  * Return NULL when not inside a raw string.
5302  */
5303     static pos_T *
5304 find_start_rawstring(int ind_maxcomment)	/* XXX */
5305 {
5306     pos_T	*pos;
5307     char_u	*line;
5308     char_u	*p;
5309     int		cur_maxcomment = ind_maxcomment;
5310 
5311     for (;;)
5312     {
5313 	pos = findmatchlimit(NULL, 'R', FM_BACKWARD, cur_maxcomment);
5314 	if (pos == NULL)
5315 	    break;
5316 
5317 	/*
5318 	 * Check if the raw string start we found is inside a string.
5319 	 * If it is then restrict the search to below this line and try again.
5320 	 */
5321 	line = ml_get(pos->lnum);
5322 	for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
5323 	    p = skip_string(p);
5324 	if ((colnr_T)(p - line) <= pos->col)
5325 	    break;
5326 	cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5327 	if (cur_maxcomment <= 0)
5328 	{
5329 	    pos = NULL;
5330 	    break;
5331 	}
5332     }
5333     return pos;
5334 }
5335 
5336 /*
5337  * Skip to the end of a "string" and a 'c' character.
5338  * If there is no string or character, return argument unmodified.
5339  */
5340     static char_u *
5341 skip_string(char_u *p)
5342 {
5343     int	    i;
5344 
5345     /*
5346      * We loop, because strings may be concatenated: "date""time".
5347      */
5348     for ( ; ; ++p)
5349     {
5350 	if (p[0] == '\'')		    /* 'c' or '\n' or '\000' */
5351 	{
5352 	    if (!p[1])			    /* ' at end of line */
5353 		break;
5354 	    i = 2;
5355 	    if (p[1] == '\\')		    /* '\n' or '\000' */
5356 	    {
5357 		++i;
5358 		while (vim_isdigit(p[i - 1]))   /* '\000' */
5359 		    ++i;
5360 	    }
5361 	    if (p[i] == '\'')		    /* check for trailing ' */
5362 	    {
5363 		p += i;
5364 		continue;
5365 	    }
5366 	}
5367 	else if (p[0] == '"')		    /* start of string */
5368 	{
5369 	    for (++p; p[0]; ++p)
5370 	    {
5371 		if (p[0] == '\\' && p[1] != NUL)
5372 		    ++p;
5373 		else if (p[0] == '"')	    /* end of string */
5374 		    break;
5375 	    }
5376 	    if (p[0] == '"')
5377 		continue; /* continue for another string */
5378 	}
5379 	else if (p[0] == 'R' && p[1] == '"')
5380 	{
5381 	    /* Raw string: R"[delim](...)[delim]" */
5382 	    char_u *delim = p + 2;
5383 	    char_u *paren = vim_strchr(delim, '(');
5384 
5385 	    if (paren != NULL)
5386 	    {
5387 		size_t delim_len = paren - delim;
5388 
5389 		for (p += 3; *p; ++p)
5390 		    if (p[0] == ')' && STRNCMP(p + 1, delim, delim_len) == 0
5391 			    && p[delim_len + 1] == '"')
5392 		    {
5393 			p += delim_len + 1;
5394 			break;
5395 		    }
5396 		if (p[0] == '"')
5397 		    continue; /* continue for another string */
5398 	    }
5399 	}
5400 	break;				    /* no string found */
5401     }
5402     if (!*p)
5403 	--p;				    /* backup from NUL */
5404     return p;
5405 }
5406 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
5407 
5408 #if defined(FEAT_CINDENT) || defined(PROTO)
5409 
5410 /*
5411  * Do C or expression indenting on the current line.
5412  */
5413     void
5414 do_c_expr_indent(void)
5415 {
5416 # ifdef FEAT_EVAL
5417     if (*curbuf->b_p_inde != NUL)
5418 	fixthisline(get_expr_indent);
5419     else
5420 # endif
5421 	fixthisline(get_c_indent);
5422 }
5423 
5424 /* Find result cache for cpp_baseclass */
5425 typedef struct {
5426     int	    found;
5427     lpos_T  lpos;
5428 } cpp_baseclass_cache_T;
5429 
5430 /*
5431  * Functions for C-indenting.
5432  * Most of this originally comes from Eric Fischer.
5433  */
5434 /*
5435  * Below "XXX" means that this function may unlock the current line.
5436  */
5437 
5438 static char_u	*cin_skipcomment(char_u *);
5439 static int	cin_nocode(char_u *);
5440 static pos_T	*find_line_comment(void);
5441 static int	cin_has_js_key(char_u *text);
5442 static int	cin_islabel_skip(char_u **);
5443 static int	cin_isdefault(char_u *);
5444 static char_u	*after_label(char_u *l);
5445 static int	get_indent_nolabel(linenr_T lnum);
5446 static int	skip_label(linenr_T, char_u **pp);
5447 static int	cin_first_id_amount(void);
5448 static int	cin_get_equal_amount(linenr_T lnum);
5449 static int	cin_ispreproc(char_u *);
5450 static int	cin_iscomment(char_u *);
5451 static int	cin_islinecomment(char_u *);
5452 static int	cin_isterminated(char_u *, int, int);
5453 static int	cin_isinit(void);
5454 static int	cin_isfuncdecl(char_u **, linenr_T, linenr_T);
5455 static int	cin_isif(char_u *);
5456 static int	cin_iselse(char_u *);
5457 static int	cin_isdo(char_u *);
5458 static int	cin_iswhileofdo(char_u *, linenr_T);
5459 static int	cin_is_if_for_while_before_offset(char_u *line, int *poffset);
5460 static int	cin_iswhileofdo_end(int terminated);
5461 static int	cin_isbreak(char_u *);
5462 static int	cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached);
5463 static int	get_baseclass_amount(int col);
5464 static int	cin_ends_in(char_u *, char_u *, char_u *);
5465 static int	cin_starts_with(char_u *s, char *word);
5466 static int	cin_skip2pos(pos_T *trypos);
5467 static pos_T	*find_start_brace(void);
5468 static pos_T	*find_match_paren(int);
5469 static pos_T	*find_match_char(int c, int ind_maxparen);
5470 static int	corr_ind_maxparen(pos_T *startpos);
5471 static int	find_last_paren(char_u *l, int start, int end);
5472 static int	find_match(int lookfor, linenr_T ourscope);
5473 static int	cin_is_cpp_namespace(char_u *);
5474 
5475 /*
5476  * Skip over white space and C comments within the line.
5477  * Also skip over Perl/shell comments if desired.
5478  */
5479     static char_u *
5480 cin_skipcomment(char_u *s)
5481 {
5482     while (*s)
5483     {
5484 	char_u *prev_s = s;
5485 
5486 	s = skipwhite(s);
5487 
5488 	/* Perl/shell # comment comment continues until eol.  Require a space
5489 	 * before # to avoid recognizing $#array. */
5490 	if (curbuf->b_ind_hash_comment != 0 && s != prev_s && *s == '#')
5491 	{
5492 	    s += STRLEN(s);
5493 	    break;
5494 	}
5495 	if (*s != '/')
5496 	    break;
5497 	++s;
5498 	if (*s == '/')		/* slash-slash comment continues till eol */
5499 	{
5500 	    s += STRLEN(s);
5501 	    break;
5502 	}
5503 	if (*s != '*')
5504 	    break;
5505 	for (++s; *s; ++s)	/* skip slash-star comment */
5506 	    if (s[0] == '*' && s[1] == '/')
5507 	    {
5508 		s += 2;
5509 		break;
5510 	    }
5511     }
5512     return s;
5513 }
5514 
5515 /*
5516  * Return TRUE if there is no code at *s.  White space and comments are
5517  * not considered code.
5518  */
5519     static int
5520 cin_nocode(char_u *s)
5521 {
5522     return *cin_skipcomment(s) == NUL;
5523 }
5524 
5525 /*
5526  * Check previous lines for a "//" line comment, skipping over blank lines.
5527  */
5528     static pos_T *
5529 find_line_comment(void) /* XXX */
5530 {
5531     static pos_T pos;
5532     char_u	 *line;
5533     char_u	 *p;
5534 
5535     pos = curwin->w_cursor;
5536     while (--pos.lnum > 0)
5537     {
5538 	line = ml_get(pos.lnum);
5539 	p = skipwhite(line);
5540 	if (cin_islinecomment(p))
5541 	{
5542 	    pos.col = (int)(p - line);
5543 	    return &pos;
5544 	}
5545 	if (*p != NUL)
5546 	    break;
5547     }
5548     return NULL;
5549 }
5550 
5551 /*
5552  * Return TRUE if "text" starts with "key:".
5553  */
5554     static int
5555 cin_has_js_key(char_u *text)
5556 {
5557     char_u *s = skipwhite(text);
5558     int	    quote = -1;
5559 
5560     if (*s == '\'' || *s == '"')
5561     {
5562 	/* can be 'key': or "key": */
5563 	quote = *s;
5564 	++s;
5565     }
5566     if (!vim_isIDc(*s))	    /* need at least one ID character */
5567 	return FALSE;
5568 
5569     while (vim_isIDc(*s))
5570 	++s;
5571     if (*s == quote)
5572 	++s;
5573 
5574     s = cin_skipcomment(s);
5575 
5576     /* "::" is not a label, it's C++ */
5577     return (*s == ':' && s[1] != ':');
5578 }
5579 
5580 /*
5581  * Check if string matches "label:"; move to character after ':' if true.
5582  * "*s" must point to the start of the label, if there is one.
5583  */
5584     static int
5585 cin_islabel_skip(char_u **s)
5586 {
5587     if (!vim_isIDc(**s))	    /* need at least one ID character */
5588 	return FALSE;
5589 
5590     while (vim_isIDc(**s))
5591 	(*s)++;
5592 
5593     *s = cin_skipcomment(*s);
5594 
5595     /* "::" is not a label, it's C++ */
5596     return (**s == ':' && *++*s != ':');
5597 }
5598 
5599 /*
5600  * Recognize a label: "label:".
5601  * Note: curwin->w_cursor must be where we are looking for the label.
5602  */
5603     int
5604 cin_islabel(void)		/* XXX */
5605 {
5606     char_u	*s;
5607 
5608     s = cin_skipcomment(ml_get_curline());
5609 
5610     /*
5611      * Exclude "default" from labels, since it should be indented
5612      * like a switch label.  Same for C++ scope declarations.
5613      */
5614     if (cin_isdefault(s))
5615 	return FALSE;
5616     if (cin_isscopedecl(s))
5617 	return FALSE;
5618 
5619     if (cin_islabel_skip(&s))
5620     {
5621 	/*
5622 	 * Only accept a label if the previous line is terminated or is a case
5623 	 * label.
5624 	 */
5625 	pos_T	cursor_save;
5626 	pos_T	*trypos;
5627 	char_u	*line;
5628 
5629 	cursor_save = curwin->w_cursor;
5630 	while (curwin->w_cursor.lnum > 1)
5631 	{
5632 	    --curwin->w_cursor.lnum;
5633 
5634 	    /*
5635 	     * If we're in a comment or raw string now, skip to the start of
5636 	     * it.
5637 	     */
5638 	    curwin->w_cursor.col = 0;
5639 	    if ((trypos = ind_find_start_CORS()) != NULL) /* XXX */
5640 		curwin->w_cursor = *trypos;
5641 
5642 	    line = ml_get_curline();
5643 	    if (cin_ispreproc(line))	/* ignore #defines, #if, etc. */
5644 		continue;
5645 	    if (*(line = cin_skipcomment(line)) == NUL)
5646 		continue;
5647 
5648 	    curwin->w_cursor = cursor_save;
5649 	    if (cin_isterminated(line, TRUE, FALSE)
5650 		    || cin_isscopedecl(line)
5651 		    || cin_iscase(line, TRUE)
5652 		    || (cin_islabel_skip(&line) && cin_nocode(line)))
5653 		return TRUE;
5654 	    return FALSE;
5655 	}
5656 	curwin->w_cursor = cursor_save;
5657 	return TRUE;		/* label at start of file??? */
5658     }
5659     return FALSE;
5660 }
5661 
5662 /*
5663  * Recognize structure initialization and enumerations:
5664  * "[typedef] [static|public|protected|private] enum"
5665  * "[typedef] [static|public|protected|private] = {"
5666  */
5667     static int
5668 cin_isinit(void)
5669 {
5670     char_u	*s;
5671     static char *skip[] = {"static", "public", "protected", "private"};
5672 
5673     s = cin_skipcomment(ml_get_curline());
5674 
5675     if (cin_starts_with(s, "typedef"))
5676 	s = cin_skipcomment(s + 7);
5677 
5678     for (;;)
5679     {
5680 	int i, l;
5681 
5682 	for (i = 0; i < (int)(sizeof(skip) / sizeof(char *)); ++i)
5683 	{
5684 	    l = (int)strlen(skip[i]);
5685 	    if (cin_starts_with(s, skip[i]))
5686 	    {
5687 		s = cin_skipcomment(s + l);
5688 		l = 0;
5689 		break;
5690 	    }
5691 	}
5692 	if (l != 0)
5693 	    break;
5694     }
5695 
5696     if (cin_starts_with(s, "enum"))
5697 	return TRUE;
5698 
5699     if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5700 	return TRUE;
5701 
5702     return FALSE;
5703 }
5704 
5705 /*
5706  * Recognize a switch label: "case .*:" or "default:".
5707  */
5708      int
5709 cin_iscase(
5710     char_u *s,
5711     int strict) /* Allow relaxed check of case statement for JS */
5712 {
5713     s = cin_skipcomment(s);
5714     if (cin_starts_with(s, "case"))
5715     {
5716 	for (s += 4; *s; ++s)
5717 	{
5718 	    s = cin_skipcomment(s);
5719 	    if (*s == ':')
5720 	    {
5721 		if (s[1] == ':')	/* skip over "::" for C++ */
5722 		    ++s;
5723 		else
5724 		    return TRUE;
5725 	    }
5726 	    if (*s == '\'' && s[1] && s[2] == '\'')
5727 		s += 2;			/* skip over ':' */
5728 	    else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5729 		return FALSE;		/* stop at comment */
5730 	    else if (*s == '"')
5731 	    {
5732 		/* JS etc. */
5733 		if (strict)
5734 		    return FALSE;		/* stop at string */
5735 		else
5736 		    return TRUE;
5737 	    }
5738 	}
5739 	return FALSE;
5740     }
5741 
5742     if (cin_isdefault(s))
5743 	return TRUE;
5744     return FALSE;
5745 }
5746 
5747 /*
5748  * Recognize a "default" switch label.
5749  */
5750     static int
5751 cin_isdefault(char_u *s)
5752 {
5753     return (STRNCMP(s, "default", 7) == 0
5754 	    && *(s = cin_skipcomment(s + 7)) == ':'
5755 	    && s[1] != ':');
5756 }
5757 
5758 /*
5759  * Recognize a "public/private/protected" scope declaration label.
5760  */
5761     int
5762 cin_isscopedecl(char_u *s)
5763 {
5764     int		i;
5765 
5766     s = cin_skipcomment(s);
5767     if (STRNCMP(s, "public", 6) == 0)
5768 	i = 6;
5769     else if (STRNCMP(s, "protected", 9) == 0)
5770 	i = 9;
5771     else if (STRNCMP(s, "private", 7) == 0)
5772 	i = 7;
5773     else
5774 	return FALSE;
5775     return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5776 }
5777 
5778 /* Maximum number of lines to search back for a "namespace" line. */
5779 #define FIND_NAMESPACE_LIM 20
5780 
5781 /*
5782  * Recognize a "namespace" scope declaration.
5783  */
5784     static int
5785 cin_is_cpp_namespace(char_u *s)
5786 {
5787     char_u	*p;
5788     int		has_name = FALSE;
5789     int		has_name_start = FALSE;
5790 
5791     s = cin_skipcomment(s);
5792     if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5793     {
5794 	p = cin_skipcomment(skipwhite(s + 9));
5795 	while (*p != NUL)
5796 	{
5797 	    if (VIM_ISWHITE(*p))
5798 	    {
5799 		has_name = TRUE; /* found end of a name */
5800 		p = cin_skipcomment(skipwhite(p));
5801 	    }
5802 	    else if (*p == '{')
5803 	    {
5804 		break;
5805 	    }
5806 	    else if (vim_iswordc(*p))
5807 	    {
5808 		has_name_start = TRUE;
5809 		if (has_name)
5810 		    return FALSE; /* word character after skipping past name */
5811 		++p;
5812 	    }
5813 	    else if (p[0] == ':' && p[1] == ':' && vim_iswordc(p[2]))
5814 	    {
5815 		if (!has_name_start || has_name)
5816 		    return FALSE;
5817 		/* C++ 17 nested namespace */
5818 		p += 3;
5819 	    }
5820 	    else
5821 	    {
5822 		return FALSE;
5823 	    }
5824 	}
5825 	return TRUE;
5826     }
5827     return FALSE;
5828 }
5829 
5830 /*
5831  * Recognize a `extern "C"` or `extern "C++"` linkage specifications.
5832  */
5833     static int
5834 cin_is_cpp_extern_c(char_u *s)
5835 {
5836     char_u	*p;
5837     int		has_string_literal = FALSE;
5838 
5839     s = cin_skipcomment(s);
5840     if (STRNCMP(s, "extern", 6) == 0 && (s[6] == NUL || !vim_iswordc(s[6])))
5841     {
5842 	p = cin_skipcomment(skipwhite(s + 6));
5843 	while (*p != NUL)
5844 	{
5845 	    if (VIM_ISWHITE(*p))
5846 	    {
5847 		p = cin_skipcomment(skipwhite(p));
5848 	    }
5849 	    else if (*p == '{')
5850 	    {
5851 		break;
5852 	    }
5853 	    else if (p[0] == '"' && p[1] == 'C' && p[2] == '"')
5854 	    {
5855 		if (has_string_literal)
5856 		    return FALSE;
5857 		has_string_literal = TRUE;
5858 		p += 3;
5859 	    }
5860 	    else if (p[0] == '"' && p[1] == 'C' && p[2] == '+' && p[3] == '+'
5861 		    && p[4] == '"')
5862 	    {
5863 		if (has_string_literal)
5864 		    return FALSE;
5865 		has_string_literal = TRUE;
5866 		p += 5;
5867 	    }
5868 	    else
5869 	    {
5870 		return FALSE;
5871 	    }
5872 	}
5873 	return has_string_literal ? TRUE : FALSE;
5874     }
5875     return FALSE;
5876 }
5877 
5878 /*
5879  * Return a pointer to the first non-empty non-comment character after a ':'.
5880  * Return NULL if not found.
5881  *	  case 234:    a = b;
5882  *		       ^
5883  */
5884     static char_u *
5885 after_label(char_u *l)
5886 {
5887     for ( ; *l; ++l)
5888     {
5889 	if (*l == ':')
5890 	{
5891 	    if (l[1] == ':')	    /* skip over "::" for C++ */
5892 		++l;
5893 	    else if (!cin_iscase(l + 1, FALSE))
5894 		break;
5895 	}
5896 	else if (*l == '\'' && l[1] && l[2] == '\'')
5897 	    l += 2;		    /* skip over 'x' */
5898     }
5899     if (*l == NUL)
5900 	return NULL;
5901     l = cin_skipcomment(l + 1);
5902     if (*l == NUL)
5903 	return NULL;
5904     return l;
5905 }
5906 
5907 /*
5908  * Get indent of line "lnum", skipping a label.
5909  * Return 0 if there is nothing after the label.
5910  */
5911     static int
5912 get_indent_nolabel (linenr_T lnum)	/* XXX */
5913 {
5914     char_u	*l;
5915     pos_T	fp;
5916     colnr_T	col;
5917     char_u	*p;
5918 
5919     l = ml_get(lnum);
5920     p = after_label(l);
5921     if (p == NULL)
5922 	return 0;
5923 
5924     fp.col = (colnr_T)(p - l);
5925     fp.lnum = lnum;
5926     getvcol(curwin, &fp, &col, NULL, NULL);
5927     return (int)col;
5928 }
5929 
5930 /*
5931  * Find indent for line "lnum", ignoring any case or jump label.
5932  * Also return a pointer to the text (after the label) in "pp".
5933  *   label:	if (asdf && asdfasdf)
5934  *		^
5935  */
5936     static int
5937 skip_label(linenr_T lnum, char_u **pp)
5938 {
5939     char_u	*l;
5940     int		amount;
5941     pos_T	cursor_save;
5942 
5943     cursor_save = curwin->w_cursor;
5944     curwin->w_cursor.lnum = lnum;
5945     l = ml_get_curline();
5946 				    /* XXX */
5947     if (cin_iscase(l, FALSE) || cin_isscopedecl(l) || cin_islabel())
5948     {
5949 	amount = get_indent_nolabel(lnum);
5950 	l = after_label(ml_get_curline());
5951 	if (l == NULL)		/* just in case */
5952 	    l = ml_get_curline();
5953     }
5954     else
5955     {
5956 	amount = get_indent();
5957 	l = ml_get_curline();
5958     }
5959     *pp = l;
5960 
5961     curwin->w_cursor = cursor_save;
5962     return amount;
5963 }
5964 
5965 /*
5966  * Return the indent of the first variable name after a type in a declaration.
5967  *  int	    a,			indent of "a"
5968  *  static struct foo    b,	indent of "b"
5969  *  enum bla    c,		indent of "c"
5970  * Returns zero when it doesn't look like a declaration.
5971  */
5972     static int
5973 cin_first_id_amount(void)
5974 {
5975     char_u	*line, *p, *s;
5976     int		len;
5977     pos_T	fp;
5978     colnr_T	col;
5979 
5980     line = ml_get_curline();
5981     p = skipwhite(line);
5982     len = (int)(skiptowhite(p) - p);
5983     if (len == 6 && STRNCMP(p, "static", 6) == 0)
5984     {
5985 	p = skipwhite(p + 6);
5986 	len = (int)(skiptowhite(p) - p);
5987     }
5988     if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5989 	p = skipwhite(p + 6);
5990     else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5991 	p = skipwhite(p + 4);
5992     else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5993 	    || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5994     {
5995 	s = skipwhite(p + len);
5996 	if ((STRNCMP(s, "int", 3) == 0 && VIM_ISWHITE(s[3]))
5997 		|| (STRNCMP(s, "long", 4) == 0 && VIM_ISWHITE(s[4]))
5998 		|| (STRNCMP(s, "short", 5) == 0 && VIM_ISWHITE(s[5]))
5999 		|| (STRNCMP(s, "char", 4) == 0 && VIM_ISWHITE(s[4])))
6000 	    p = s;
6001     }
6002     for (len = 0; vim_isIDc(p[len]); ++len)
6003 	;
6004     if (len == 0 || !VIM_ISWHITE(p[len]) || cin_nocode(p))
6005 	return 0;
6006 
6007     p = skipwhite(p + len);
6008     fp.lnum = curwin->w_cursor.lnum;
6009     fp.col = (colnr_T)(p - line);
6010     getvcol(curwin, &fp, &col, NULL, NULL);
6011     return (int)col;
6012 }
6013 
6014 /*
6015  * Return the indent of the first non-blank after an equal sign.
6016  *       char *foo = "here";
6017  * Return zero if no (useful) equal sign found.
6018  * Return -1 if the line above "lnum" ends in a backslash.
6019  *      foo = "asdf\
6020  *	       asdf\
6021  *	       here";
6022  */
6023     static int
6024 cin_get_equal_amount(linenr_T lnum)
6025 {
6026     char_u	*line;
6027     char_u	*s;
6028     colnr_T	col;
6029     pos_T	fp;
6030 
6031     if (lnum > 1)
6032     {
6033 	line = ml_get(lnum - 1);
6034 	if (*line != NUL && line[STRLEN(line) - 1] == '\\')
6035 	    return -1;
6036     }
6037 
6038     line = s = ml_get(lnum);
6039     while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
6040     {
6041 	if (cin_iscomment(s))	/* ignore comments */
6042 	    s = cin_skipcomment(s);
6043 	else
6044 	    ++s;
6045     }
6046     if (*s != '=')
6047 	return 0;
6048 
6049     s = skipwhite(s + 1);
6050     if (cin_nocode(s))
6051 	return 0;
6052 
6053     if (*s == '"')	/* nice alignment for continued strings */
6054 	++s;
6055 
6056     fp.lnum = lnum;
6057     fp.col = (colnr_T)(s - line);
6058     getvcol(curwin, &fp, &col, NULL, NULL);
6059     return (int)col;
6060 }
6061 
6062 /*
6063  * Recognize a preprocessor statement: Any line that starts with '#'.
6064  */
6065     static int
6066 cin_ispreproc(char_u *s)
6067 {
6068     if (*skipwhite(s) == '#')
6069 	return TRUE;
6070     return FALSE;
6071 }
6072 
6073 /*
6074  * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
6075  * continuation line of a preprocessor statement.  Decrease "*lnump" to the
6076  * start and return the line in "*pp".
6077  * Put the amount of indent in "*amount".
6078  */
6079     static int
6080 cin_ispreproc_cont(char_u **pp, linenr_T *lnump, int *amount)
6081 {
6082     char_u	*line = *pp;
6083     linenr_T	lnum = *lnump;
6084     int		retval = FALSE;
6085     int		candidate_amount = *amount;
6086 
6087     if (*line != NUL && line[STRLEN(line) - 1] == '\\')
6088 	candidate_amount = get_indent_lnum(lnum);
6089 
6090     for (;;)
6091     {
6092 	if (cin_ispreproc(line))
6093 	{
6094 	    retval = TRUE;
6095 	    *lnump = lnum;
6096 	    break;
6097 	}
6098 	if (lnum == 1)
6099 	    break;
6100 	line = ml_get(--lnum);
6101 	if (*line == NUL || line[STRLEN(line) - 1] != '\\')
6102 	    break;
6103     }
6104 
6105     if (lnum != *lnump)
6106 	*pp = ml_get(*lnump);
6107     if (retval)
6108 	*amount = candidate_amount;
6109     return retval;
6110 }
6111 
6112 /*
6113  * Recognize the start of a C or C++ comment.
6114  */
6115     static int
6116 cin_iscomment(char_u *p)
6117 {
6118     return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
6119 }
6120 
6121 /*
6122  * Recognize the start of a "//" comment.
6123  */
6124     static int
6125 cin_islinecomment(char_u *p)
6126 {
6127     return (p[0] == '/' && p[1] == '/');
6128 }
6129 
6130 /*
6131  * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
6132  * '}'.
6133  * Don't consider "} else" a terminated line.
6134  * If a line begins with an "else", only consider it terminated if no unmatched
6135  * opening braces follow (handle "else { foo();" correctly).
6136  * Return the character terminating the line (ending char's have precedence if
6137  * both apply in order to determine initializations).
6138  */
6139     static int
6140 cin_isterminated(
6141     char_u	*s,
6142     int		incl_open,	/* include '{' at the end as terminator */
6143     int		incl_comma)	/* recognize a trailing comma */
6144 {
6145     char_u	found_start = 0;
6146     unsigned	n_open = 0;
6147     int		is_else = FALSE;
6148 
6149     s = cin_skipcomment(s);
6150 
6151     if (*s == '{' || (*s == '}' && !cin_iselse(s)))
6152 	found_start = *s;
6153 
6154     if (!found_start)
6155 	is_else = cin_iselse(s);
6156 
6157     while (*s)
6158     {
6159 	/* skip over comments, "" strings and 'c'haracters */
6160 	s = skip_string(cin_skipcomment(s));
6161 	if (*s == '}' && n_open > 0)
6162 	    --n_open;
6163 	if ((!is_else || n_open == 0)
6164 		&& (*s == ';' || *s == '}' || (incl_comma && *s == ','))
6165 		&& cin_nocode(s + 1))
6166 	    return *s;
6167 	else if (*s == '{')
6168 	{
6169 	    if (incl_open && cin_nocode(s + 1))
6170 		return *s;
6171 	    else
6172 		++n_open;
6173 	}
6174 
6175 	if (*s)
6176 	    s++;
6177     }
6178     return found_start;
6179 }
6180 
6181 /*
6182  * Recognize the basic picture of a function declaration -- it needs to
6183  * have an open paren somewhere and a close paren at the end of the line and
6184  * no semicolons anywhere.
6185  * When a line ends in a comma we continue looking in the next line.
6186  * "sp" points to a string with the line.  When looking at other lines it must
6187  * be restored to the line.  When it's NULL fetch lines here.
6188  * "first_lnum" is where we start looking.
6189  * "min_lnum" is the line before which we will not be looking.
6190  */
6191     static int
6192 cin_isfuncdecl(
6193     char_u	**sp,
6194     linenr_T	first_lnum,
6195     linenr_T	min_lnum)
6196 {
6197     char_u	*s;
6198     linenr_T	lnum = first_lnum;
6199     linenr_T	save_lnum = curwin->w_cursor.lnum;
6200     int		retval = FALSE;
6201     pos_T	*trypos;
6202     int		just_started = TRUE;
6203 
6204     if (sp == NULL)
6205 	s = ml_get(lnum);
6206     else
6207 	s = *sp;
6208 
6209     curwin->w_cursor.lnum = lnum;
6210     if (find_last_paren(s, '(', ')')
6211 	&& (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
6212     {
6213 	lnum = trypos->lnum;
6214 	if (lnum < min_lnum)
6215 	{
6216 	    curwin->w_cursor.lnum = save_lnum;
6217 	    return FALSE;
6218 	}
6219 
6220 	s = ml_get(lnum);
6221     }
6222     curwin->w_cursor.lnum = save_lnum;
6223 
6224     /* Ignore line starting with #. */
6225     if (cin_ispreproc(s))
6226 	return FALSE;
6227 
6228     while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
6229     {
6230 	if (cin_iscomment(s))	/* ignore comments */
6231 	    s = cin_skipcomment(s);
6232 	else if (*s == ':')
6233 	{
6234 	    if (*(s + 1) == ':')
6235 		s += 2;
6236 	    else
6237 		/* To avoid a mistake in the following situation:
6238 		 * A::A(int a, int b)
6239 		 *     : a(0)  // <--not a function decl
6240 		 *     , b(0)
6241 		 * {...
6242 		 */
6243 		return FALSE;
6244 	}
6245 	else
6246 	    ++s;
6247     }
6248     if (*s != '(')
6249 	return FALSE;		/* ';', ' or "  before any () or no '(' */
6250 
6251     while (*s && *s != ';' && *s != '\'' && *s != '"')
6252     {
6253 	if (*s == ')' && cin_nocode(s + 1))
6254 	{
6255 	    /* ')' at the end: may have found a match
6256 	     * Check for he previous line not to end in a backslash:
6257 	     *       #if defined(x) && \
6258 	     *		 defined(y)
6259 	     */
6260 	    lnum = first_lnum - 1;
6261 	    s = ml_get(lnum);
6262 	    if (*s == NUL || s[STRLEN(s) - 1] != '\\')
6263 		retval = TRUE;
6264 	    goto done;
6265 	}
6266 	if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
6267 	{
6268 	    int comma = (*s == ',');
6269 
6270 	    /* ',' at the end: continue looking in the next line.
6271 	     * At the end: check for ',' in the next line, for this style:
6272 	     * func(arg1
6273 	     *       , arg2) */
6274 	    for (;;)
6275 	    {
6276 		if (lnum >= curbuf->b_ml.ml_line_count)
6277 		    break;
6278 		s = ml_get(++lnum);
6279 		if (!cin_ispreproc(s))
6280 		    break;
6281 	    }
6282 	    if (lnum >= curbuf->b_ml.ml_line_count)
6283 		break;
6284 	    /* Require a comma at end of the line or a comma or ')' at the
6285 	     * start of next line. */
6286 	    s = skipwhite(s);
6287 	    if (!just_started && (!comma && *s != ',' && *s != ')'))
6288 		break;
6289 	    just_started = FALSE;
6290 	}
6291 	else if (cin_iscomment(s))	/* ignore comments */
6292 	    s = cin_skipcomment(s);
6293 	else
6294 	{
6295 	    ++s;
6296 	    just_started = FALSE;
6297 	}
6298     }
6299 
6300 done:
6301     if (lnum != first_lnum && sp != NULL)
6302 	*sp = ml_get(first_lnum);
6303 
6304     return retval;
6305 }
6306 
6307     static int
6308 cin_isif(char_u *p)
6309 {
6310  return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
6311 }
6312 
6313     static int
6314 cin_iselse(
6315     char_u  *p)
6316 {
6317     if (*p == '}')	    /* accept "} else" */
6318 	p = cin_skipcomment(p + 1);
6319     return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
6320 }
6321 
6322     static int
6323 cin_isdo(char_u *p)
6324 {
6325     return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
6326 }
6327 
6328 /*
6329  * Check if this is a "while" that should have a matching "do".
6330  * We only accept a "while (condition) ;", with only white space between the
6331  * ')' and ';'. The condition may be spread over several lines.
6332  */
6333     static int
6334 cin_iswhileofdo (char_u *p, linenr_T lnum)	/* XXX */
6335 {
6336     pos_T	cursor_save;
6337     pos_T	*trypos;
6338     int		retval = FALSE;
6339 
6340     p = cin_skipcomment(p);
6341     if (*p == '}')		/* accept "} while (cond);" */
6342 	p = cin_skipcomment(p + 1);
6343     if (cin_starts_with(p, "while"))
6344     {
6345 	cursor_save = curwin->w_cursor;
6346 	curwin->w_cursor.lnum = lnum;
6347 	curwin->w_cursor.col = 0;
6348 	p = ml_get_curline();
6349 	while (*p && *p != 'w')	/* skip any '}', until the 'w' of the "while" */
6350 	{
6351 	    ++p;
6352 	    ++curwin->w_cursor.col;
6353 	}
6354 	if ((trypos = findmatchlimit(NULL, 0, 0,
6355 					      curbuf->b_ind_maxparen)) != NULL
6356 		&& *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
6357 	    retval = TRUE;
6358 	curwin->w_cursor = cursor_save;
6359     }
6360     return retval;
6361 }
6362 
6363 /*
6364  * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
6365  * Return 0 if there is none.
6366  * Otherwise return !0 and update "*poffset" to point to the place where the
6367  * string was found.
6368  */
6369     static int
6370 cin_is_if_for_while_before_offset(char_u *line, int *poffset)
6371 {
6372     int offset = *poffset;
6373 
6374     if (offset-- < 2)
6375 	return 0;
6376     while (offset > 2 && VIM_ISWHITE(line[offset]))
6377 	--offset;
6378 
6379     offset -= 1;
6380     if (!STRNCMP(line + offset, "if", 2))
6381 	goto probablyFound;
6382 
6383     if (offset >= 1)
6384     {
6385 	offset -= 1;
6386 	if (!STRNCMP(line + offset, "for", 3))
6387 	    goto probablyFound;
6388 
6389 	if (offset >= 2)
6390 	{
6391 	    offset -= 2;
6392 	    if (!STRNCMP(line + offset, "while", 5))
6393 		goto probablyFound;
6394 	}
6395     }
6396     return 0;
6397 
6398 probablyFound:
6399     if (!offset || !vim_isIDc(line[offset - 1]))
6400     {
6401 	*poffset = offset;
6402 	return 1;
6403     }
6404     return 0;
6405 }
6406 
6407 /*
6408  * Return TRUE if we are at the end of a do-while.
6409  *    do
6410  *       nothing;
6411  *    while (foo
6412  *	       && bar);  <-- here
6413  * Adjust the cursor to the line with "while".
6414  */
6415     static int
6416 cin_iswhileofdo_end(int terminated)
6417 {
6418     char_u	*line;
6419     char_u	*p;
6420     char_u	*s;
6421     pos_T	*trypos;
6422     int		i;
6423 
6424     if (terminated != ';')	/* there must be a ';' at the end */
6425 	return FALSE;
6426 
6427     p = line = ml_get_curline();
6428     while (*p != NUL)
6429     {
6430 	p = cin_skipcomment(p);
6431 	if (*p == ')')
6432 	{
6433 	    s = skipwhite(p + 1);
6434 	    if (*s == ';' && cin_nocode(s + 1))
6435 	    {
6436 		/* Found ");" at end of the line, now check there is "while"
6437 		 * before the matching '('.  XXX */
6438 		i = (int)(p - line);
6439 		curwin->w_cursor.col = i;
6440 		trypos = find_match_paren(curbuf->b_ind_maxparen);
6441 		if (trypos != NULL)
6442 		{
6443 		    s = cin_skipcomment(ml_get(trypos->lnum));
6444 		    if (*s == '}')		/* accept "} while (cond);" */
6445 			s = cin_skipcomment(s + 1);
6446 		    if (cin_starts_with(s, "while"))
6447 		    {
6448 			curwin->w_cursor.lnum = trypos->lnum;
6449 			return TRUE;
6450 		    }
6451 		}
6452 
6453 		/* Searching may have made "line" invalid, get it again. */
6454 		line = ml_get_curline();
6455 		p = line + i;
6456 	    }
6457 	}
6458 	if (*p != NUL)
6459 	    ++p;
6460     }
6461     return FALSE;
6462 }
6463 
6464     static int
6465 cin_isbreak(char_u *p)
6466 {
6467     return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6468 }
6469 
6470 /*
6471  * Find the position of a C++ base-class declaration or
6472  * constructor-initialization. eg:
6473  *
6474  * class MyClass :
6475  *	baseClass		<-- here
6476  * class MyClass : public baseClass,
6477  *	anotherBaseClass	<-- here (should probably lineup ??)
6478  * MyClass::MyClass(...) :
6479  *	baseClass(...)		<-- here (constructor-initialization)
6480  *
6481  * This is a lot of guessing.  Watch out for "cond ? func() : foo".
6482  */
6483     static int
6484 cin_is_cpp_baseclass(
6485     cpp_baseclass_cache_T *cached) /* input and output */
6486 {
6487     lpos_T	*pos = &cached->lpos;	    /* find position */
6488     char_u	*s;
6489     int		class_or_struct, lookfor_ctor_init, cpp_base_class;
6490     linenr_T	lnum = curwin->w_cursor.lnum;
6491     char_u	*line = ml_get_curline();
6492 
6493     if (pos->lnum <= lnum)
6494 	return cached->found;	/* Use the cached result */
6495 
6496     pos->col = 0;
6497 
6498     s = skipwhite(line);
6499     if (*s == '#')		/* skip #define FOO x ? (x) : x */
6500 	return FALSE;
6501     s = cin_skipcomment(s);
6502     if (*s == NUL)
6503 	return FALSE;
6504 
6505     cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6506 
6507     /* Search for a line starting with '#', empty, ending in ';' or containing
6508      * '{' or '}' and start below it.  This handles the following situations:
6509      *	a = cond ?
6510      *	      func() :
6511      *		   asdf;
6512      *	func::foo()
6513      *	      : something
6514      *	{}
6515      *	Foo::Foo (int one, int two)
6516      *		: something(4),
6517      *		somethingelse(3)
6518      *	{}
6519      */
6520     while (lnum > 1)
6521     {
6522 	line = ml_get(lnum - 1);
6523 	s = skipwhite(line);
6524 	if (*s == '#' || *s == NUL)
6525 	    break;
6526 	while (*s != NUL)
6527 	{
6528 	    s = cin_skipcomment(s);
6529 	    if (*s == '{' || *s == '}'
6530 		    || (*s == ';' && cin_nocode(s + 1)))
6531 		break;
6532 	    if (*s != NUL)
6533 		++s;
6534 	}
6535 	if (*s != NUL)
6536 	    break;
6537 	--lnum;
6538     }
6539 
6540     pos->lnum = lnum;
6541     line = ml_get(lnum);
6542     s = line;
6543     for (;;)
6544     {
6545 	if (*s == NUL)
6546 	{
6547 	    if (lnum == curwin->w_cursor.lnum)
6548 		break;
6549 	    /* Continue in the cursor line. */
6550 	    line = ml_get(++lnum);
6551 	    s = line;
6552 	}
6553 	if (s == line)
6554 	{
6555 	    /* don't recognize "case (foo):" as a baseclass */
6556 	    if (cin_iscase(s, FALSE))
6557 		break;
6558 	    s = cin_skipcomment(line);
6559 	    if (*s == NUL)
6560 		continue;
6561 	}
6562 
6563 	if (s[0] == '"' || (s[0] == 'R' && s[1] == '"'))
6564 	    s = skip_string(s) + 1;
6565 	else if (s[0] == ':')
6566 	{
6567 	    if (s[1] == ':')
6568 	    {
6569 		/* skip double colon. It can't be a constructor
6570 		 * initialization any more */
6571 		lookfor_ctor_init = FALSE;
6572 		s = cin_skipcomment(s + 2);
6573 	    }
6574 	    else if (lookfor_ctor_init || class_or_struct)
6575 	    {
6576 		/* we have something found, that looks like the start of
6577 		 * cpp-base-class-declaration or constructor-initialization */
6578 		cpp_base_class = TRUE;
6579 		lookfor_ctor_init = class_or_struct = FALSE;
6580 		pos->col = 0;
6581 		s = cin_skipcomment(s + 1);
6582 	    }
6583 	    else
6584 		s = cin_skipcomment(s + 1);
6585 	}
6586 	else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6587 		|| (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6588 	{
6589 	    class_or_struct = TRUE;
6590 	    lookfor_ctor_init = FALSE;
6591 
6592 	    if (*s == 'c')
6593 		s = cin_skipcomment(s + 5);
6594 	    else
6595 		s = cin_skipcomment(s + 6);
6596 	}
6597 	else
6598 	{
6599 	    if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6600 	    {
6601 		cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6602 	    }
6603 	    else if (s[0] == ')')
6604 	    {
6605 		/* Constructor-initialization is assumed if we come across
6606 		 * something like "):" */
6607 		class_or_struct = FALSE;
6608 		lookfor_ctor_init = TRUE;
6609 	    }
6610 	    else if (s[0] == '?')
6611 	    {
6612 		/* Avoid seeing '() :' after '?' as constructor init. */
6613 		return FALSE;
6614 	    }
6615 	    else if (!vim_isIDc(s[0]))
6616 	    {
6617 		/* if it is not an identifier, we are wrong */
6618 		class_or_struct = FALSE;
6619 		lookfor_ctor_init = FALSE;
6620 	    }
6621 	    else if (pos->col == 0)
6622 	    {
6623 		/* it can't be a constructor-initialization any more */
6624 		lookfor_ctor_init = FALSE;
6625 
6626 		/* the first statement starts here: lineup with this one... */
6627 		if (cpp_base_class)
6628 		    pos->col = (colnr_T)(s - line);
6629 	    }
6630 
6631 	    /* When the line ends in a comma don't align with it. */
6632 	    if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6633 		pos->col = 0;
6634 
6635 	    s = cin_skipcomment(s + 1);
6636 	}
6637     }
6638 
6639     cached->found = cpp_base_class;
6640     if (cpp_base_class)
6641 	pos->lnum = lnum;
6642     return cpp_base_class;
6643 }
6644 
6645     static int
6646 get_baseclass_amount(int col)
6647 {
6648     int		amount;
6649     colnr_T	vcol;
6650     pos_T	*trypos;
6651 
6652     if (col == 0)
6653     {
6654 	amount = get_indent();
6655 	if (find_last_paren(ml_get_curline(), '(', ')')
6656 		&& (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
6657 	    amount = get_indent_lnum(trypos->lnum); /* XXX */
6658 	if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6659 	    amount += curbuf->b_ind_cpp_baseclass;
6660     }
6661     else
6662     {
6663 	curwin->w_cursor.col = col;
6664 	getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6665 	amount = (int)vcol;
6666     }
6667     if (amount < curbuf->b_ind_cpp_baseclass)
6668 	amount = curbuf->b_ind_cpp_baseclass;
6669     return amount;
6670 }
6671 
6672 /*
6673  * Return TRUE if string "s" ends with the string "find", possibly followed by
6674  * white space and comments.  Skip strings and comments.
6675  * Ignore "ignore" after "find" if it's not NULL.
6676  */
6677     static int
6678 cin_ends_in(char_u *s, char_u *find, char_u *ignore)
6679 {
6680     char_u	*p = s;
6681     char_u	*r;
6682     int		len = (int)STRLEN(find);
6683 
6684     while (*p != NUL)
6685     {
6686 	p = cin_skipcomment(p);
6687 	if (STRNCMP(p, find, len) == 0)
6688 	{
6689 	    r = skipwhite(p + len);
6690 	    if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6691 		r = skipwhite(r + STRLEN(ignore));
6692 	    if (cin_nocode(r))
6693 		return TRUE;
6694 	}
6695 	if (*p != NUL)
6696 	    ++p;
6697     }
6698     return FALSE;
6699 }
6700 
6701 /*
6702  * Return TRUE when "s" starts with "word" and then a non-ID character.
6703  */
6704     static int
6705 cin_starts_with(char_u *s, char *word)
6706 {
6707     int l = (int)STRLEN(word);
6708 
6709     return (STRNCMP(s, word, l) == 0 && !vim_isIDc(s[l]));
6710 }
6711 
6712 /*
6713  * Skip strings, chars and comments until at or past "trypos".
6714  * Return the column found.
6715  */
6716     static int
6717 cin_skip2pos(pos_T *trypos)
6718 {
6719     char_u	*line;
6720     char_u	*p;
6721     char_u	*new_p;
6722 
6723     p = line = ml_get(trypos->lnum);
6724     while (*p && (colnr_T)(p - line) < trypos->col)
6725     {
6726 	if (cin_iscomment(p))
6727 	    p = cin_skipcomment(p);
6728 	else
6729 	{
6730 	    new_p = skip_string(p);
6731 	    if (new_p == p)
6732 		++p;
6733 	    else
6734 		p = new_p;
6735 	}
6736     }
6737     return (int)(p - line);
6738 }
6739 
6740 /*
6741  * Find the '{' at the start of the block we are in.
6742  * Return NULL if no match found.
6743  * Ignore a '{' that is in a comment, makes indenting the next three lines
6744  * work. */
6745 /* foo()    */
6746 /* {	    */
6747 /* }	    */
6748 
6749     static pos_T *
6750 find_start_brace(void)	    /* XXX */
6751 {
6752     pos_T	cursor_save;
6753     pos_T	*trypos;
6754     pos_T	*pos;
6755     static pos_T	pos_copy;
6756 
6757     cursor_save = curwin->w_cursor;
6758     while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6759     {
6760 	pos_copy = *trypos;	/* copy pos_T, next findmatch will change it */
6761 	trypos = &pos_copy;
6762 	curwin->w_cursor = *trypos;
6763 	pos = NULL;
6764 	/* ignore the { if it's in a // or / *  * / comment */
6765 	if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6766 		       && (pos = ind_find_start_CORS()) == NULL) /* XXX */
6767 	    break;
6768 	if (pos != NULL)
6769 	    curwin->w_cursor.lnum = pos->lnum;
6770     }
6771     curwin->w_cursor = cursor_save;
6772     return trypos;
6773 }
6774 
6775 /*
6776  * Find the matching '(', ignoring it if it is in a comment.
6777  * Return NULL if no match found.
6778  */
6779     static pos_T *
6780 find_match_paren(int ind_maxparen)	/* XXX */
6781 {
6782     return find_match_char('(', ind_maxparen);
6783 }
6784 
6785     static pos_T *
6786 find_match_char (int c, int ind_maxparen)	/* XXX */
6787 {
6788     pos_T	cursor_save;
6789     pos_T	*trypos;
6790     static pos_T pos_copy;
6791     int		ind_maxp_wk;
6792 
6793     cursor_save = curwin->w_cursor;
6794     ind_maxp_wk = ind_maxparen;
6795 retry:
6796     if ((trypos = findmatchlimit(NULL, c, 0, ind_maxp_wk)) != NULL)
6797     {
6798 	/* check if the ( is in a // comment */
6799 	if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6800 	{
6801 	    ind_maxp_wk = ind_maxparen - (int)(cursor_save.lnum - trypos->lnum);
6802 	    if (ind_maxp_wk > 0)
6803 	    {
6804 		curwin->w_cursor = *trypos;
6805 		curwin->w_cursor.col = 0;	/* XXX */
6806 		goto retry;
6807 	    }
6808 	    trypos = NULL;
6809 	}
6810 	else
6811 	{
6812 	    pos_T	*trypos_wk;
6813 
6814 	    pos_copy = *trypos;	    /* copy trypos, findmatch will change it */
6815 	    trypos = &pos_copy;
6816 	    curwin->w_cursor = *trypos;
6817 	    if ((trypos_wk = ind_find_start_CORS()) != NULL) /* XXX */
6818 	    {
6819 		ind_maxp_wk = ind_maxparen - (int)(cursor_save.lnum
6820 			- trypos_wk->lnum);
6821 		if (ind_maxp_wk > 0)
6822 		{
6823 		    curwin->w_cursor = *trypos_wk;
6824 		    goto retry;
6825 		}
6826 		trypos = NULL;
6827 	    }
6828 	}
6829     }
6830     curwin->w_cursor = cursor_save;
6831     return trypos;
6832 }
6833 
6834 /*
6835  * Find the matching '(', ignoring it if it is in a comment or before an
6836  * unmatched {.
6837  * Return NULL if no match found.
6838  */
6839     static pos_T *
6840 find_match_paren_after_brace (int ind_maxparen)	    /* XXX */
6841 {
6842     pos_T	*trypos = find_match_paren(ind_maxparen);
6843 
6844     if (trypos != NULL)
6845     {
6846 	pos_T	*tryposBrace = find_start_brace();
6847 
6848 	/* If both an unmatched '(' and '{' is found.  Ignore the '('
6849 	 * position if the '{' is further down. */
6850 	if (tryposBrace != NULL
6851 		&& (trypos->lnum != tryposBrace->lnum
6852 		    ? trypos->lnum < tryposBrace->lnum
6853 		    : trypos->col < tryposBrace->col))
6854 	    trypos = NULL;
6855     }
6856     return trypos;
6857 }
6858 
6859 /*
6860  * Return ind_maxparen corrected for the difference in line number between the
6861  * cursor position and "startpos".  This makes sure that searching for a
6862  * matching paren above the cursor line doesn't find a match because of
6863  * looking a few lines further.
6864  */
6865     static int
6866 corr_ind_maxparen(pos_T *startpos)
6867 {
6868     long	n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6869 
6870     if (n > 0 && n < curbuf->b_ind_maxparen / 2)
6871 	return curbuf->b_ind_maxparen - (int)n;
6872     return curbuf->b_ind_maxparen;
6873 }
6874 
6875 /*
6876  * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
6877  * line "l".  "l" must point to the start of the line.
6878  */
6879     static int
6880 find_last_paren(char_u *l, int start, int end)
6881 {
6882     int		i;
6883     int		retval = FALSE;
6884     int		open_count = 0;
6885 
6886     curwin->w_cursor.col = 0;		    /* default is start of line */
6887 
6888     for (i = 0; l[i] != NUL; i++)
6889     {
6890 	i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6891 	i = (int)(skip_string(l + i) - l);    /* ignore parens in quotes */
6892 	if (l[i] == start)
6893 	    ++open_count;
6894 	else if (l[i] == end)
6895 	{
6896 	    if (open_count > 0)
6897 		--open_count;
6898 	    else
6899 	    {
6900 		curwin->w_cursor.col = i;
6901 		retval = TRUE;
6902 	    }
6903 	}
6904     }
6905     return retval;
6906 }
6907 
6908 /*
6909  * Parse 'cinoptions' and set the values in "curbuf".
6910  * Must be called when 'cinoptions', 'shiftwidth' and/or 'tabstop' changes.
6911  */
6912     void
6913 parse_cino(buf_T *buf)
6914 {
6915     char_u	*p;
6916     char_u	*l;
6917     char_u	*digits;
6918     int		n;
6919     int		divider;
6920     int		fraction = 0;
6921     int		sw = (int)get_sw_value(buf);
6922 
6923     /*
6924      * Set the default values.
6925      */
6926     /* Spaces from a block's opening brace the prevailing indent for that
6927      * block should be. */
6928     buf->b_ind_level = sw;
6929 
6930     /* Spaces from the edge of the line an open brace that's at the end of a
6931      * line is imagined to be. */
6932     buf->b_ind_open_imag = 0;
6933 
6934     /* Spaces from the prevailing indent for a line that is not preceded by
6935      * an opening brace. */
6936     buf->b_ind_no_brace = 0;
6937 
6938     /* Column where the first { of a function should be located }. */
6939     buf->b_ind_first_open = 0;
6940 
6941     /* Spaces from the prevailing indent a leftmost open brace should be
6942      * located. */
6943     buf->b_ind_open_extra = 0;
6944 
6945     /* Spaces from the matching open brace (real location for one at the left
6946      * edge; imaginary location from one that ends a line) the matching close
6947      * brace should be located. */
6948     buf->b_ind_close_extra = 0;
6949 
6950     /* Spaces from the edge of the line an open brace sitting in the leftmost
6951      * column is imagined to be. */
6952     buf->b_ind_open_left_imag = 0;
6953 
6954     /* Spaces jump labels should be shifted to the left if N is non-negative,
6955      * otherwise the jump label will be put to column 1. */
6956     buf->b_ind_jump_label = -1;
6957 
6958     /* Spaces from the switch() indent a "case xx" label should be located. */
6959     buf->b_ind_case = sw;
6960 
6961     /* Spaces from the "case xx:" code after a switch() should be located. */
6962     buf->b_ind_case_code = sw;
6963 
6964     /* Lineup break at end of case in switch() with case label. */
6965     buf->b_ind_case_break = 0;
6966 
6967     /* Spaces from the class declaration indent a scope declaration label
6968      * should be located. */
6969     buf->b_ind_scopedecl = sw;
6970 
6971     /* Spaces from the scope declaration label code should be located. */
6972     buf->b_ind_scopedecl_code = sw;
6973 
6974     /* Amount K&R-style parameters should be indented. */
6975     buf->b_ind_param = sw;
6976 
6977     /* Amount a function type spec should be indented. */
6978     buf->b_ind_func_type = sw;
6979 
6980     /* Amount a cpp base class declaration or constructor initialization
6981      * should be indented. */
6982     buf->b_ind_cpp_baseclass = sw;
6983 
6984     /* additional spaces beyond the prevailing indent a continuation line
6985      * should be located. */
6986     buf->b_ind_continuation = sw;
6987 
6988     /* Spaces from the indent of the line with an unclosed parentheses. */
6989     buf->b_ind_unclosed = sw * 2;
6990 
6991     /* Spaces from the indent of the line with an unclosed parentheses, which
6992      * itself is also unclosed. */
6993     buf->b_ind_unclosed2 = sw;
6994 
6995     /* Suppress ignoring spaces from the indent of a line starting with an
6996      * unclosed parentheses. */
6997     buf->b_ind_unclosed_noignore = 0;
6998 
6999     /* If the opening paren is the last nonwhite character on the line, and
7000      * b_ind_unclosed_wrapped is nonzero, use this indent relative to the outer
7001      * context (for very long lines). */
7002     buf->b_ind_unclosed_wrapped = 0;
7003 
7004     /* Suppress ignoring white space when lining up with the character after
7005      * an unclosed parentheses. */
7006     buf->b_ind_unclosed_whiteok = 0;
7007 
7008     /* Indent a closing parentheses under the line start of the matching
7009      * opening parentheses. */
7010     buf->b_ind_matching_paren = 0;
7011 
7012     /* Indent a closing parentheses under the previous line. */
7013     buf->b_ind_paren_prev = 0;
7014 
7015     /* Extra indent for comments. */
7016     buf->b_ind_comment = 0;
7017 
7018     /* Spaces from the comment opener when there is nothing after it. */
7019     buf->b_ind_in_comment = 3;
7020 
7021     /* Boolean: if non-zero, use b_ind_in_comment even if there is something
7022      * after the comment opener. */
7023     buf->b_ind_in_comment2 = 0;
7024 
7025     /* Max lines to search for an open paren. */
7026     buf->b_ind_maxparen = 20;
7027 
7028     /* Max lines to search for an open comment. */
7029     buf->b_ind_maxcomment = 70;
7030 
7031     /* Handle braces for java code. */
7032     buf->b_ind_java = 0;
7033 
7034     /* Not to confuse JS object properties with labels. */
7035     buf->b_ind_js = 0;
7036 
7037     /* Handle blocked cases correctly. */
7038     buf->b_ind_keep_case_label = 0;
7039 
7040     /* Handle C++ namespace. */
7041     buf->b_ind_cpp_namespace = 0;
7042 
7043     /* Handle continuation lines containing conditions of if(), for() and
7044      * while(). */
7045     buf->b_ind_if_for_while = 0;
7046 
7047     /* indentation for # comments */
7048     buf->b_ind_hash_comment = 0;
7049 
7050     /* Handle C++ extern "C" or "C++" */
7051     buf->b_ind_cpp_extern_c = 0;
7052 
7053     for (p = buf->b_p_cino; *p; )
7054     {
7055 	l = p++;
7056 	if (*p == '-')
7057 	    ++p;
7058 	digits = p;	    /* remember where the digits start */
7059 	n = getdigits(&p);
7060 	divider = 0;
7061 	if (*p == '.')	    /* ".5s" means a fraction */
7062 	{
7063 	    fraction = atol((char *)++p);
7064 	    while (VIM_ISDIGIT(*p))
7065 	    {
7066 		++p;
7067 		if (divider)
7068 		    divider *= 10;
7069 		else
7070 		    divider = 10;
7071 	    }
7072 	}
7073 	if (*p == 's')	    /* "2s" means two times 'shiftwidth' */
7074 	{
7075 	    if (p == digits)
7076 		n = sw;	/* just "s" is one 'shiftwidth' */
7077 	    else
7078 	    {
7079 		n *= sw;
7080 		if (divider)
7081 		    n += (sw * fraction + divider / 2) / divider;
7082 	    }
7083 	    ++p;
7084 	}
7085 	if (l[1] == '-')
7086 	    n = -n;
7087 
7088 	/* When adding an entry here, also update the default 'cinoptions' in
7089 	 * doc/indent.txt, and add explanation for it! */
7090 	switch (*l)
7091 	{
7092 	    case '>': buf->b_ind_level = n; break;
7093 	    case 'e': buf->b_ind_open_imag = n; break;
7094 	    case 'n': buf->b_ind_no_brace = n; break;
7095 	    case 'f': buf->b_ind_first_open = n; break;
7096 	    case '{': buf->b_ind_open_extra = n; break;
7097 	    case '}': buf->b_ind_close_extra = n; break;
7098 	    case '^': buf->b_ind_open_left_imag = n; break;
7099 	    case 'L': buf->b_ind_jump_label = n; break;
7100 	    case ':': buf->b_ind_case = n; break;
7101 	    case '=': buf->b_ind_case_code = n; break;
7102 	    case 'b': buf->b_ind_case_break = n; break;
7103 	    case 'p': buf->b_ind_param = n; break;
7104 	    case 't': buf->b_ind_func_type = n; break;
7105 	    case '/': buf->b_ind_comment = n; break;
7106 	    case 'c': buf->b_ind_in_comment = n; break;
7107 	    case 'C': buf->b_ind_in_comment2 = n; break;
7108 	    case 'i': buf->b_ind_cpp_baseclass = n; break;
7109 	    case '+': buf->b_ind_continuation = n; break;
7110 	    case '(': buf->b_ind_unclosed = n; break;
7111 	    case 'u': buf->b_ind_unclosed2 = n; break;
7112 	    case 'U': buf->b_ind_unclosed_noignore = n; break;
7113 	    case 'W': buf->b_ind_unclosed_wrapped = n; break;
7114 	    case 'w': buf->b_ind_unclosed_whiteok = n; break;
7115 	    case 'm': buf->b_ind_matching_paren = n; break;
7116 	    case 'M': buf->b_ind_paren_prev = n; break;
7117 	    case ')': buf->b_ind_maxparen = n; break;
7118 	    case '*': buf->b_ind_maxcomment = n; break;
7119 	    case 'g': buf->b_ind_scopedecl = n; break;
7120 	    case 'h': buf->b_ind_scopedecl_code = n; break;
7121 	    case 'j': buf->b_ind_java = n; break;
7122 	    case 'J': buf->b_ind_js = n; break;
7123 	    case 'l': buf->b_ind_keep_case_label = n; break;
7124 	    case '#': buf->b_ind_hash_comment = n; break;
7125 	    case 'N': buf->b_ind_cpp_namespace = n; break;
7126 	    case 'k': buf->b_ind_if_for_while = n; break;
7127 	    case 'E': buf->b_ind_cpp_extern_c = n; break;
7128 	}
7129 	if (*p == ',')
7130 	    ++p;
7131     }
7132 }
7133 
7134 /*
7135  * Return the desired indent for C code.
7136  * Return -1 if the indent should be left alone (inside a raw string).
7137  */
7138     int
7139 get_c_indent(void)
7140 {
7141     pos_T	cur_curpos;
7142     int		amount;
7143     int		scope_amount;
7144     int		cur_amount = MAXCOL;
7145     colnr_T	col;
7146     char_u	*theline;
7147     char_u	*linecopy;
7148     pos_T	*trypos;
7149     pos_T	*comment_pos;
7150     pos_T	*tryposBrace = NULL;
7151     pos_T	tryposCopy;
7152     pos_T	our_paren_pos;
7153     char_u	*start;
7154     int		start_brace;
7155 #define BRACE_IN_COL0		1	    /* '{' is in column 0 */
7156 #define BRACE_AT_START		2	    /* '{' is at start of line */
7157 #define BRACE_AT_END		3	    /* '{' is at end of line */
7158     linenr_T	ourscope;
7159     char_u	*l;
7160     char_u	*look;
7161     char_u	terminated;
7162     int		lookfor;
7163 #define LOOKFOR_INITIAL		0
7164 #define LOOKFOR_IF		1
7165 #define LOOKFOR_DO		2
7166 #define LOOKFOR_CASE		3
7167 #define LOOKFOR_ANY		4
7168 #define LOOKFOR_TERM		5
7169 #define LOOKFOR_UNTERM		6
7170 #define LOOKFOR_SCOPEDECL	7
7171 #define LOOKFOR_NOBREAK		8
7172 #define LOOKFOR_CPP_BASECLASS	9
7173 #define LOOKFOR_ENUM_OR_INIT	10
7174 #define LOOKFOR_JS_KEY		11
7175 #define LOOKFOR_COMMA		12
7176 
7177     int		whilelevel;
7178     linenr_T	lnum;
7179     int		n;
7180     int		iscase;
7181     int		lookfor_break;
7182     int		lookfor_cpp_namespace = FALSE;
7183     int		cont_amount = 0;    /* amount for continuation line */
7184     int		original_line_islabel;
7185     int		added_to_amount = 0;
7186     int		js_cur_has_key = 0;
7187     cpp_baseclass_cache_T cache_cpp_baseclass = { FALSE, { MAXLNUM, 0 } };
7188 
7189     /* make a copy, value is changed below */
7190     int		ind_continuation = curbuf->b_ind_continuation;
7191 
7192     /* remember where the cursor was when we started */
7193     cur_curpos = curwin->w_cursor;
7194 
7195     /* if we are at line 1 zero indent is fine, right? */
7196     if (cur_curpos.lnum == 1)
7197 	return 0;
7198 
7199     /* Get a copy of the current contents of the line.
7200      * This is required, because only the most recent line obtained with
7201      * ml_get is valid! */
7202     linecopy = vim_strsave(ml_get(cur_curpos.lnum));
7203     if (linecopy == NULL)
7204 	return 0;
7205 
7206     /*
7207      * In insert mode and the cursor is on a ')' truncate the line at the
7208      * cursor position.  We don't want to line up with the matching '(' when
7209      * inserting new stuff.
7210      * For unknown reasons the cursor might be past the end of the line, thus
7211      * check for that.
7212      */
7213     if ((State & INSERT)
7214 	    && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
7215 	    && linecopy[curwin->w_cursor.col] == ')')
7216 	linecopy[curwin->w_cursor.col] = NUL;
7217 
7218     theline = skipwhite(linecopy);
7219 
7220     /* move the cursor to the start of the line */
7221 
7222     curwin->w_cursor.col = 0;
7223 
7224     original_line_islabel = cin_islabel();  /* XXX */
7225 
7226     /*
7227      * If we are inside a raw string don't change the indent.
7228      * Ignore a raw string inside a comment.
7229      */
7230     comment_pos = ind_find_start_comment();
7231     if (comment_pos != NULL)
7232     {
7233 	/* findmatchlimit() static pos is overwritten, make a copy */
7234 	tryposCopy = *comment_pos;
7235 	comment_pos = &tryposCopy;
7236     }
7237     trypos = find_start_rawstring(curbuf->b_ind_maxcomment);
7238     if (trypos != NULL && (comment_pos == NULL
7239 					     || LT_POS(*trypos, *comment_pos)))
7240     {
7241 	amount = -1;
7242 	goto laterend;
7243     }
7244 
7245     /*
7246      * #defines and so on always go at the left when included in 'cinkeys'.
7247      */
7248     if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
7249     {
7250 	amount = curbuf->b_ind_hash_comment;
7251 	goto theend;
7252     }
7253 
7254     /*
7255      * Is it a non-case label?	Then that goes at the left margin too unless:
7256      *  - JS flag is set.
7257      *  - 'L' item has a positive value.
7258      */
7259     if (original_line_islabel && !curbuf->b_ind_js
7260 					      && curbuf->b_ind_jump_label < 0)
7261     {
7262 	amount = 0;
7263 	goto theend;
7264     }
7265 
7266     /*
7267      * If we're inside a "//" comment and there is a "//" comment in a
7268      * previous line, lineup with that one.
7269      */
7270     if (cin_islinecomment(theline)
7271 	    && (trypos = find_line_comment()) != NULL) /* XXX */
7272     {
7273 	/* find how indented the line beginning the comment is */
7274 	getvcol(curwin, trypos, &col, NULL, NULL);
7275 	amount = col;
7276 	goto theend;
7277     }
7278 
7279     /*
7280      * If we're inside a comment and not looking at the start of the
7281      * comment, try using the 'comments' option.
7282      */
7283     if (!cin_iscomment(theline) && comment_pos != NULL) /* XXX */
7284     {
7285 	int	lead_start_len = 2;
7286 	int	lead_middle_len = 1;
7287 	char_u	lead_start[COM_MAX_LEN];	/* start-comment string */
7288 	char_u	lead_middle[COM_MAX_LEN];	/* middle-comment string */
7289 	char_u	lead_end[COM_MAX_LEN];		/* end-comment string */
7290 	char_u	*p;
7291 	int	start_align = 0;
7292 	int	start_off = 0;
7293 	int	done = FALSE;
7294 
7295 	/* find how indented the line beginning the comment is */
7296 	getvcol(curwin, comment_pos, &col, NULL, NULL);
7297 	amount = col;
7298 	*lead_start = NUL;
7299 	*lead_middle = NUL;
7300 
7301 	p = curbuf->b_p_com;
7302 	while (*p != NUL)
7303 	{
7304 	    int	align = 0;
7305 	    int	off = 0;
7306 	    int what = 0;
7307 
7308 	    while (*p != NUL && *p != ':')
7309 	    {
7310 		if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
7311 		    what = *p++;
7312 		else if (*p == COM_LEFT || *p == COM_RIGHT)
7313 		    align = *p++;
7314 		else if (VIM_ISDIGIT(*p) || *p == '-')
7315 		    off = getdigits(&p);
7316 		else
7317 		    ++p;
7318 	    }
7319 
7320 	    if (*p == ':')
7321 		++p;
7322 	    (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
7323 	    if (what == COM_START)
7324 	    {
7325 		STRCPY(lead_start, lead_end);
7326 		lead_start_len = (int)STRLEN(lead_start);
7327 		start_off = off;
7328 		start_align = align;
7329 	    }
7330 	    else if (what == COM_MIDDLE)
7331 	    {
7332 		STRCPY(lead_middle, lead_end);
7333 		lead_middle_len = (int)STRLEN(lead_middle);
7334 	    }
7335 	    else if (what == COM_END)
7336 	    {
7337 		/* If our line starts with the middle comment string, line it
7338 		 * up with the comment opener per the 'comments' option. */
7339 		if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
7340 			&& STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
7341 		{
7342 		    done = TRUE;
7343 		    if (curwin->w_cursor.lnum > 1)
7344 		    {
7345 			/* If the start comment string matches in the previous
7346 			 * line, use the indent of that line plus offset.  If
7347 			 * the middle comment string matches in the previous
7348 			 * line, use the indent of that line.  XXX */
7349 			look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
7350 			if (STRNCMP(look, lead_start, lead_start_len) == 0)
7351 			    amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7352 			else if (STRNCMP(look, lead_middle,
7353 							lead_middle_len) == 0)
7354 			{
7355 			    amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7356 			    break;
7357 			}
7358 			/* If the start comment string doesn't match with the
7359 			 * start of the comment, skip this entry. XXX */
7360 			else if (STRNCMP(ml_get(comment_pos->lnum) + comment_pos->col,
7361 					     lead_start, lead_start_len) != 0)
7362 			    continue;
7363 		    }
7364 		    if (start_off != 0)
7365 			amount += start_off;
7366 		    else if (start_align == COM_RIGHT)
7367 			amount += vim_strsize(lead_start)
7368 						   - vim_strsize(lead_middle);
7369 		    break;
7370 		}
7371 
7372 		/* If our line starts with the end comment string, line it up
7373 		 * with the middle comment */
7374 		if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
7375 			&& STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
7376 		{
7377 		    amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7378 								     /* XXX */
7379 		    if (off != 0)
7380 			amount += off;
7381 		    else if (align == COM_RIGHT)
7382 			amount += vim_strsize(lead_start)
7383 						   - vim_strsize(lead_middle);
7384 		    done = TRUE;
7385 		    break;
7386 		}
7387 	    }
7388 	}
7389 
7390 	/* If our line starts with an asterisk, line up with the
7391 	 * asterisk in the comment opener; otherwise, line up
7392 	 * with the first character of the comment text.
7393 	 */
7394 	if (done)
7395 	    ;
7396 	else if (theline[0] == '*')
7397 	    amount += 1;
7398 	else
7399 	{
7400 	    /*
7401 	     * If we are more than one line away from the comment opener, take
7402 	     * the indent of the previous non-empty line.  If 'cino' has "CO"
7403 	     * and we are just below the comment opener and there are any
7404 	     * white characters after it line up with the text after it;
7405 	     * otherwise, add the amount specified by "c" in 'cino'
7406 	     */
7407 	    amount = -1;
7408 	    for (lnum = cur_curpos.lnum - 1; lnum > comment_pos->lnum; --lnum)
7409 	    {
7410 		if (linewhite(lnum))		    /* skip blank lines */
7411 		    continue;
7412 		amount = get_indent_lnum(lnum);	    /* XXX */
7413 		break;
7414 	    }
7415 	    if (amount == -1)			    /* use the comment opener */
7416 	    {
7417 		if (!curbuf->b_ind_in_comment2)
7418 		{
7419 		    start = ml_get(comment_pos->lnum);
7420 		    look = start + comment_pos->col + 2; /* skip / and * */
7421 		    if (*look != NUL)		    /* if something after it */
7422 			comment_pos->col = (colnr_T)(skipwhite(look) - start);
7423 		}
7424 		getvcol(curwin, comment_pos, &col, NULL, NULL);
7425 		amount = col;
7426 		if (curbuf->b_ind_in_comment2 || *look == NUL)
7427 		    amount += curbuf->b_ind_in_comment;
7428 	    }
7429 	}
7430 	goto theend;
7431     }
7432 
7433     /*
7434      * Are we looking at a ']' that has a match?
7435      */
7436     if (*skipwhite(theline) == ']'
7437 	    && (trypos = find_match_char('[', curbuf->b_ind_maxparen)) != NULL)
7438     {
7439 	/* align with the line containing the '['. */
7440 	amount = get_indent_lnum(trypos->lnum);
7441 	goto theend;
7442     }
7443 
7444     /*
7445      * Are we inside parentheses or braces?
7446      */						    /* XXX */
7447     if (((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL
7448 		&& curbuf->b_ind_java == 0)
7449 	    || (tryposBrace = find_start_brace()) != NULL
7450 	    || trypos != NULL)
7451     {
7452       if (trypos != NULL && tryposBrace != NULL)
7453       {
7454 	  /* Both an unmatched '(' and '{' is found.  Use the one which is
7455 	   * closer to the current cursor position, set the other to NULL. */
7456 	  if (trypos->lnum != tryposBrace->lnum
7457 		  ? trypos->lnum < tryposBrace->lnum
7458 		  : trypos->col < tryposBrace->col)
7459 	      trypos = NULL;
7460 	  else
7461 	      tryposBrace = NULL;
7462       }
7463 
7464       if (trypos != NULL)
7465       {
7466 	/*
7467 	 * If the matching paren is more than one line away, use the indent of
7468 	 * a previous non-empty line that matches the same paren.
7469 	 */
7470 	if (theline[0] == ')' && curbuf->b_ind_paren_prev)
7471 	{
7472 	    /* Line up with the start of the matching paren line. */
7473 	    amount = get_indent_lnum(curwin->w_cursor.lnum - 1);  /* XXX */
7474 	}
7475 	else
7476 	{
7477 	    amount = -1;
7478 	    our_paren_pos = *trypos;
7479 	    for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
7480 	    {
7481 		l = skipwhite(ml_get(lnum));
7482 		if (cin_nocode(l))		/* skip comment lines */
7483 		    continue;
7484 		if (cin_ispreproc_cont(&l, &lnum, &amount))
7485 		    continue;			/* ignore #define, #if, etc. */
7486 		curwin->w_cursor.lnum = lnum;
7487 
7488 		/* Skip a comment or raw string. XXX */
7489 		if ((trypos = ind_find_start_CORS()) != NULL)
7490 		{
7491 		    lnum = trypos->lnum + 1;
7492 		    continue;
7493 		}
7494 
7495 		/* XXX */
7496 		if ((trypos = find_match_paren(
7497 			corr_ind_maxparen(&cur_curpos))) != NULL
7498 			&& trypos->lnum == our_paren_pos.lnum
7499 			&& trypos->col == our_paren_pos.col)
7500 		{
7501 			amount = get_indent_lnum(lnum);	/* XXX */
7502 
7503 			if (theline[0] == ')')
7504 			{
7505 			    if (our_paren_pos.lnum != lnum
7506 						       && cur_amount > amount)
7507 				cur_amount = amount;
7508 			    amount = -1;
7509 			}
7510 		    break;
7511 		}
7512 	    }
7513 	}
7514 
7515 	/*
7516 	 * Line up with line where the matching paren is. XXX
7517 	 * If the line starts with a '(' or the indent for unclosed
7518 	 * parentheses is zero, line up with the unclosed parentheses.
7519 	 */
7520 	if (amount == -1)
7521 	{
7522 	    int	    ignore_paren_col = 0;
7523 	    int	    is_if_for_while = 0;
7524 
7525 	    if (curbuf->b_ind_if_for_while)
7526 	    {
7527 		/* Look for the outermost opening parenthesis on this line
7528 		 * and check whether it belongs to an "if", "for" or "while". */
7529 
7530 		pos_T	    cursor_save = curwin->w_cursor;
7531 		pos_T	    outermost;
7532 		char_u	    *line;
7533 
7534 		trypos = &our_paren_pos;
7535 		do {
7536 		    outermost = *trypos;
7537 		    curwin->w_cursor.lnum = outermost.lnum;
7538 		    curwin->w_cursor.col = outermost.col;
7539 
7540 		    trypos = find_match_paren(curbuf->b_ind_maxparen);
7541 		} while (trypos && trypos->lnum == outermost.lnum);
7542 
7543 		curwin->w_cursor = cursor_save;
7544 
7545 		line = ml_get(outermost.lnum);
7546 
7547 		is_if_for_while =
7548 		    cin_is_if_for_while_before_offset(line, &outermost.col);
7549 	    }
7550 
7551 	    amount = skip_label(our_paren_pos.lnum, &look);
7552 	    look = skipwhite(look);
7553 	    if (*look == '(')
7554 	    {
7555 		linenr_T    save_lnum = curwin->w_cursor.lnum;
7556 		char_u	    *line;
7557 		int	    look_col;
7558 
7559 		/* Ignore a '(' in front of the line that has a match before
7560 		 * our matching '('. */
7561 		curwin->w_cursor.lnum = our_paren_pos.lnum;
7562 		line = ml_get_curline();
7563 		look_col = (int)(look - line);
7564 		curwin->w_cursor.col = look_col + 1;
7565 		if ((trypos = findmatchlimit(NULL, ')', 0,
7566 						      curbuf->b_ind_maxparen))
7567 								      != NULL
7568 			  && trypos->lnum == our_paren_pos.lnum
7569 			  && trypos->col < our_paren_pos.col)
7570 		    ignore_paren_col = trypos->col + 1;
7571 
7572 		curwin->w_cursor.lnum = save_lnum;
7573 		look = ml_get(our_paren_pos.lnum) + look_col;
7574 	    }
7575 	    if (theline[0] == ')' || (curbuf->b_ind_unclosed == 0
7576 						      && is_if_for_while == 0)
7577 		    || (!curbuf->b_ind_unclosed_noignore && *look == '('
7578 						    && ignore_paren_col == 0))
7579 	    {
7580 		/*
7581 		 * If we're looking at a close paren, line up right there;
7582 		 * otherwise, line up with the next (non-white) character.
7583 		 * When b_ind_unclosed_wrapped is set and the matching paren is
7584 		 * the last nonwhite character of the line, use either the
7585 		 * indent of the current line or the indentation of the next
7586 		 * outer paren and add b_ind_unclosed_wrapped (for very long
7587 		 * lines).
7588 		 */
7589 		if (theline[0] != ')')
7590 		{
7591 		    cur_amount = MAXCOL;
7592 		    l = ml_get(our_paren_pos.lnum);
7593 		    if (curbuf->b_ind_unclosed_wrapped
7594 				       && cin_ends_in(l, (char_u *)"(", NULL))
7595 		    {
7596 			/* look for opening unmatched paren, indent one level
7597 			 * for each additional level */
7598 			n = 1;
7599 			for (col = 0; col < our_paren_pos.col; ++col)
7600 			{
7601 			    switch (l[col])
7602 			    {
7603 				case '(':
7604 				case '{': ++n;
7605 					  break;
7606 
7607 				case ')':
7608 				case '}': if (n > 1)
7609 					      --n;
7610 					  break;
7611 			    }
7612 			}
7613 
7614 			our_paren_pos.col = 0;
7615 			amount += n * curbuf->b_ind_unclosed_wrapped;
7616 		    }
7617 		    else if (curbuf->b_ind_unclosed_whiteok)
7618 			our_paren_pos.col++;
7619 		    else
7620 		    {
7621 			col = our_paren_pos.col + 1;
7622 			while (VIM_ISWHITE(l[col]))
7623 			    col++;
7624 			if (l[col] != NUL)	/* In case of trailing space */
7625 			    our_paren_pos.col = col;
7626 			else
7627 			    our_paren_pos.col++;
7628 		    }
7629 		}
7630 
7631 		/*
7632 		 * Find how indented the paren is, or the character after it
7633 		 * if we did the above "if".
7634 		 */
7635 		if (our_paren_pos.col > 0)
7636 		{
7637 		    getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7638 		    if (cur_amount > (int)col)
7639 			cur_amount = col;
7640 		}
7641 	    }
7642 
7643 	    if (theline[0] == ')' && curbuf->b_ind_matching_paren)
7644 	    {
7645 		/* Line up with the start of the matching paren line. */
7646 	    }
7647 	    else if ((curbuf->b_ind_unclosed == 0 && is_if_for_while == 0)
7648 		     || (!curbuf->b_ind_unclosed_noignore
7649 				    && *look == '(' && ignore_paren_col == 0))
7650 	    {
7651 		if (cur_amount != MAXCOL)
7652 		    amount = cur_amount;
7653 	    }
7654 	    else
7655 	    {
7656 		/* Add b_ind_unclosed2 for each '(' before our matching one,
7657 		 * but ignore (void) before the line (ignore_paren_col). */
7658 		col = our_paren_pos.col;
7659 		while ((int)our_paren_pos.col > ignore_paren_col)
7660 		{
7661 		    --our_paren_pos.col;
7662 		    switch (*ml_get_pos(&our_paren_pos))
7663 		    {
7664 			case '(': amount += curbuf->b_ind_unclosed2;
7665 				  col = our_paren_pos.col;
7666 				  break;
7667 			case ')': amount -= curbuf->b_ind_unclosed2;
7668 				  col = MAXCOL;
7669 				  break;
7670 		    }
7671 		}
7672 
7673 		/* Use b_ind_unclosed once, when the first '(' is not inside
7674 		 * braces */
7675 		if (col == MAXCOL)
7676 		    amount += curbuf->b_ind_unclosed;
7677 		else
7678 		{
7679 		    curwin->w_cursor.lnum = our_paren_pos.lnum;
7680 		    curwin->w_cursor.col = col;
7681 		    if (find_match_paren_after_brace(curbuf->b_ind_maxparen)
7682 								      != NULL)
7683 			amount += curbuf->b_ind_unclosed2;
7684 		    else
7685 		    {
7686 			if (is_if_for_while)
7687 			    amount += curbuf->b_ind_if_for_while;
7688 			else
7689 			    amount += curbuf->b_ind_unclosed;
7690 		    }
7691 		}
7692 		/*
7693 		 * For a line starting with ')' use the minimum of the two
7694 		 * positions, to avoid giving it more indent than the previous
7695 		 * lines:
7696 		 *  func_long_name(		    if (x
7697 		 *	arg				    && yy
7698 		 *	)	  ^ not here	       )    ^ not here
7699 		 */
7700 		if (cur_amount < amount)
7701 		    amount = cur_amount;
7702 	    }
7703 	}
7704 
7705 	/* add extra indent for a comment */
7706 	if (cin_iscomment(theline))
7707 	    amount += curbuf->b_ind_comment;
7708       }
7709       else
7710       {
7711 	/*
7712 	 * We are inside braces, there is a { before this line at the position
7713 	 * stored in tryposBrace.
7714 	 * Make a copy of tryposBrace, it may point to pos_copy inside
7715 	 * find_start_brace(), which may be changed somewhere.
7716 	 */
7717 	tryposCopy = *tryposBrace;
7718 	tryposBrace = &tryposCopy;
7719 	trypos = tryposBrace;
7720 	ourscope = trypos->lnum;
7721 	start = ml_get(ourscope);
7722 
7723 	/*
7724 	 * Now figure out how indented the line is in general.
7725 	 * If the brace was at the start of the line, we use that;
7726 	 * otherwise, check out the indentation of the line as
7727 	 * a whole and then add the "imaginary indent" to that.
7728 	 */
7729 	look = skipwhite(start);
7730 	if (*look == '{')
7731 	{
7732 	    getvcol(curwin, trypos, &col, NULL, NULL);
7733 	    amount = col;
7734 	    if (*start == '{')
7735 		start_brace = BRACE_IN_COL0;
7736 	    else
7737 		start_brace = BRACE_AT_START;
7738 	}
7739 	else
7740 	{
7741 	    /* That opening brace might have been on a continuation
7742 	     * line.  if so, find the start of the line. */
7743 	    curwin->w_cursor.lnum = ourscope;
7744 
7745 	    /* Position the cursor over the rightmost paren, so that
7746 	     * matching it will take us back to the start of the line. */
7747 	    lnum = ourscope;
7748 	    if (find_last_paren(start, '(', ')')
7749 			&& (trypos = find_match_paren(curbuf->b_ind_maxparen))
7750 								      != NULL)
7751 		lnum = trypos->lnum;
7752 
7753 	    /* It could have been something like
7754 	     *	   case 1: if (asdf &&
7755 	     *			ldfd) {
7756 	     *		    }
7757 	     */
7758 	    if ((curbuf->b_ind_js || curbuf->b_ind_keep_case_label)
7759 			   && cin_iscase(skipwhite(ml_get_curline()), FALSE))
7760 		amount = get_indent();
7761 	    else if (curbuf->b_ind_js)
7762 		amount = get_indent_lnum(lnum);
7763 	    else
7764 		amount = skip_label(lnum, &l);
7765 
7766 	    start_brace = BRACE_AT_END;
7767 	}
7768 
7769 	/* For Javascript check if the line starts with "key:". */
7770 	if (curbuf->b_ind_js)
7771 	    js_cur_has_key = cin_has_js_key(theline);
7772 
7773 	/*
7774 	 * If we're looking at a closing brace, that's where
7775 	 * we want to be.  otherwise, add the amount of room
7776 	 * that an indent is supposed to be.
7777 	 */
7778 	if (theline[0] == '}')
7779 	{
7780 	    /*
7781 	     * they may want closing braces to line up with something
7782 	     * other than the open brace.  indulge them, if so.
7783 	     */
7784 	    amount += curbuf->b_ind_close_extra;
7785 	}
7786 	else
7787 	{
7788 	    /*
7789 	     * If we're looking at an "else", try to find an "if"
7790 	     * to match it with.
7791 	     * If we're looking at a "while", try to find a "do"
7792 	     * to match it with.
7793 	     */
7794 	    lookfor = LOOKFOR_INITIAL;
7795 	    if (cin_iselse(theline))
7796 		lookfor = LOOKFOR_IF;
7797 	    else if (cin_iswhileofdo(theline, cur_curpos.lnum)) /* XXX */
7798 		lookfor = LOOKFOR_DO;
7799 	    if (lookfor != LOOKFOR_INITIAL)
7800 	    {
7801 		curwin->w_cursor.lnum = cur_curpos.lnum;
7802 		if (find_match(lookfor, ourscope) == OK)
7803 		{
7804 		    amount = get_indent();	/* XXX */
7805 		    goto theend;
7806 		}
7807 	    }
7808 
7809 	    /*
7810 	     * We get here if we are not on an "while-of-do" or "else" (or
7811 	     * failed to find a matching "if").
7812 	     * Search backwards for something to line up with.
7813 	     * First set amount for when we don't find anything.
7814 	     */
7815 
7816 	    /*
7817 	     * if the '{' is  _really_ at the left margin, use the imaginary
7818 	     * location of a left-margin brace.  Otherwise, correct the
7819 	     * location for b_ind_open_extra.
7820 	     */
7821 
7822 	    if (start_brace == BRACE_IN_COL0)	    /* '{' is in column 0 */
7823 	    {
7824 		amount = curbuf->b_ind_open_left_imag;
7825 		lookfor_cpp_namespace = TRUE;
7826 	    }
7827 	    else if (start_brace == BRACE_AT_START &&
7828 		    lookfor_cpp_namespace)	  /* '{' is at start */
7829 	    {
7830 
7831 		lookfor_cpp_namespace = TRUE;
7832 	    }
7833 	    else
7834 	    {
7835 		if (start_brace == BRACE_AT_END)    /* '{' is at end of line */
7836 		{
7837 		    amount += curbuf->b_ind_open_imag;
7838 
7839 		    l = skipwhite(ml_get_curline());
7840 		    if (cin_is_cpp_namespace(l))
7841 			amount += curbuf->b_ind_cpp_namespace;
7842 		    else if (cin_is_cpp_extern_c(l))
7843 			amount += curbuf->b_ind_cpp_extern_c;
7844 		}
7845 		else
7846 		{
7847 		    /* Compensate for adding b_ind_open_extra later. */
7848 		    amount -= curbuf->b_ind_open_extra;
7849 		    if (amount < 0)
7850 			amount = 0;
7851 		}
7852 	    }
7853 
7854 	    lookfor_break = FALSE;
7855 
7856 	    if (cin_iscase(theline, FALSE))	/* it's a switch() label */
7857 	    {
7858 		lookfor = LOOKFOR_CASE;	/* find a previous switch() label */
7859 		amount += curbuf->b_ind_case;
7860 	    }
7861 	    else if (cin_isscopedecl(theline))	/* private:, ... */
7862 	    {
7863 		lookfor = LOOKFOR_SCOPEDECL;	/* class decl is this block */
7864 		amount += curbuf->b_ind_scopedecl;
7865 	    }
7866 	    else
7867 	    {
7868 		if (curbuf->b_ind_case_break && cin_isbreak(theline))
7869 		    /* break; ... */
7870 		    lookfor_break = TRUE;
7871 
7872 		lookfor = LOOKFOR_INITIAL;
7873 		/* b_ind_level from start of block */
7874 		amount += curbuf->b_ind_level;
7875 	    }
7876 	    scope_amount = amount;
7877 	    whilelevel = 0;
7878 
7879 	    /*
7880 	     * Search backwards.  If we find something we recognize, line up
7881 	     * with that.
7882 	     *
7883 	     * If we're looking at an open brace, indent
7884 	     * the usual amount relative to the conditional
7885 	     * that opens the block.
7886 	     */
7887 	    curwin->w_cursor = cur_curpos;
7888 	    for (;;)
7889 	    {
7890 		curwin->w_cursor.lnum--;
7891 		curwin->w_cursor.col = 0;
7892 
7893 		/*
7894 		 * If we went all the way back to the start of our scope, line
7895 		 * up with it.
7896 		 */
7897 		if (curwin->w_cursor.lnum <= ourscope)
7898 		{
7899 		    /* We reached end of scope:
7900 		     * If looking for a enum or structure initialization
7901 		     * go further back:
7902 		     * If it is an initializer (enum xxx or xxx =), then
7903 		     * don't add ind_continuation, otherwise it is a variable
7904 		     * declaration:
7905 		     * int x,
7906 		     *     here; <-- add ind_continuation
7907 		     */
7908 		    if (lookfor == LOOKFOR_ENUM_OR_INIT)
7909 		    {
7910 			if (curwin->w_cursor.lnum == 0
7911 				|| curwin->w_cursor.lnum
7912 					  < ourscope - curbuf->b_ind_maxparen)
7913 			{
7914 			    /* nothing found (abuse curbuf->b_ind_maxparen as
7915 			     * limit) assume terminated line (i.e. a variable
7916 			     * initialization) */
7917 			    if (cont_amount > 0)
7918 				amount = cont_amount;
7919 			    else if (!curbuf->b_ind_js)
7920 				amount += ind_continuation;
7921 			    break;
7922 			}
7923 
7924 			l = ml_get_curline();
7925 
7926 			/*
7927 			 * If we're in a comment or raw string now, skip to
7928 			 * the start of it.
7929 			 */
7930 			trypos = ind_find_start_CORS();
7931 			if (trypos != NULL)
7932 			{
7933 			    curwin->w_cursor.lnum = trypos->lnum + 1;
7934 			    curwin->w_cursor.col = 0;
7935 			    continue;
7936 			}
7937 
7938 			/*
7939 			 * Skip preprocessor directives and blank lines.
7940 			 */
7941 			if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum,
7942 								    &amount))
7943 			    continue;
7944 
7945 			if (cin_nocode(l))
7946 			    continue;
7947 
7948 			terminated = cin_isterminated(l, FALSE, TRUE);
7949 
7950 			/*
7951 			 * If we are at top level and the line looks like a
7952 			 * function declaration, we are done
7953 			 * (it's a variable declaration).
7954 			 */
7955 			if (start_brace != BRACE_IN_COL0
7956 			     || !cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0))
7957 			{
7958 			    /* if the line is terminated with another ','
7959 			     * it is a continued variable initialization.
7960 			     * don't add extra indent.
7961 			     * TODO: does not work, if  a function
7962 			     * declaration is split over multiple lines:
7963 			     * cin_isfuncdecl returns FALSE then.
7964 			     */
7965 			    if (terminated == ',')
7966 				break;
7967 
7968 			    /* if it es a enum declaration or an assignment,
7969 			     * we are done.
7970 			     */
7971 			    if (terminated != ';' && cin_isinit())
7972 				break;
7973 
7974 			    /* nothing useful found */
7975 			    if (terminated == 0 || terminated == '{')
7976 				continue;
7977 			}
7978 
7979 			if (terminated != ';')
7980 			{
7981 			    /* Skip parens and braces. Position the cursor
7982 			     * over the rightmost paren, so that matching it
7983 			     * will take us back to the start of the line.
7984 			     */					/* XXX */
7985 			    trypos = NULL;
7986 			    if (find_last_paren(l, '(', ')'))
7987 				trypos = find_match_paren(
7988 						      curbuf->b_ind_maxparen);
7989 
7990 			    if (trypos == NULL && find_last_paren(l, '{', '}'))
7991 				trypos = find_start_brace();
7992 
7993 			    if (trypos != NULL)
7994 			    {
7995 				curwin->w_cursor.lnum = trypos->lnum + 1;
7996 				curwin->w_cursor.col = 0;
7997 				continue;
7998 			    }
7999 			}
8000 
8001 			/* it's a variable declaration, add indentation
8002 			 * like in
8003 			 * int a,
8004 			 *    b;
8005 			 */
8006 			if (cont_amount > 0)
8007 			    amount = cont_amount;
8008 			else
8009 			    amount += ind_continuation;
8010 		    }
8011 		    else if (lookfor == LOOKFOR_UNTERM)
8012 		    {
8013 			if (cont_amount > 0)
8014 			    amount = cont_amount;
8015 			else
8016 			    amount += ind_continuation;
8017 		    }
8018 		    else
8019 		    {
8020 			if (lookfor != LOOKFOR_TERM
8021 					&& lookfor != LOOKFOR_CPP_BASECLASS
8022 					&& lookfor != LOOKFOR_COMMA)
8023 			{
8024 			    amount = scope_amount;
8025 			    if (theline[0] == '{')
8026 			    {
8027 				amount += curbuf->b_ind_open_extra;
8028 				added_to_amount = curbuf->b_ind_open_extra;
8029 			    }
8030 			}
8031 
8032 			if (lookfor_cpp_namespace)
8033 			{
8034 			    /*
8035 			     * Looking for C++ namespace, need to look further
8036 			     * back.
8037 			     */
8038 			    if (curwin->w_cursor.lnum == ourscope)
8039 				continue;
8040 
8041 			    if (curwin->w_cursor.lnum == 0
8042 				    || curwin->w_cursor.lnum
8043 					      < ourscope - FIND_NAMESPACE_LIM)
8044 				break;
8045 
8046 			    l = ml_get_curline();
8047 
8048 			    /* If we're in a comment or raw string now, skip
8049 			     * to the start of it. */
8050 			    trypos = ind_find_start_CORS();
8051 			    if (trypos != NULL)
8052 			    {
8053 				curwin->w_cursor.lnum = trypos->lnum + 1;
8054 				curwin->w_cursor.col = 0;
8055 				continue;
8056 			    }
8057 
8058 			    /* Skip preprocessor directives and blank lines. */
8059 			    if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum,
8060 								    &amount))
8061 				continue;
8062 
8063 			    /* Finally the actual check for "namespace". */
8064 			    if (cin_is_cpp_namespace(l))
8065 			    {
8066 				amount += curbuf->b_ind_cpp_namespace
8067 							    - added_to_amount;
8068 				break;
8069 			    }
8070 			    else if (cin_is_cpp_extern_c(l))
8071 			    {
8072 				amount += curbuf->b_ind_cpp_extern_c
8073 							    - added_to_amount;
8074 				break;
8075 			    }
8076 
8077 			    if (cin_nocode(l))
8078 				continue;
8079 			}
8080 		    }
8081 		    break;
8082 		}
8083 
8084 		/*
8085 		 * If we're in a comment or raw string now, skip to the start
8086 		 * of it.
8087 		 */					    /* XXX */
8088 		if ((trypos = ind_find_start_CORS()) != NULL)
8089 		{
8090 		    curwin->w_cursor.lnum = trypos->lnum + 1;
8091 		    curwin->w_cursor.col = 0;
8092 		    continue;
8093 		}
8094 
8095 		l = ml_get_curline();
8096 
8097 		/*
8098 		 * If this is a switch() label, may line up relative to that.
8099 		 * If this is a C++ scope declaration, do the same.
8100 		 */
8101 		iscase = cin_iscase(l, FALSE);
8102 		if (iscase || cin_isscopedecl(l))
8103 		{
8104 		    /* we are only looking for cpp base class
8105 		     * declaration/initialization any longer */
8106 		    if (lookfor == LOOKFOR_CPP_BASECLASS)
8107 			break;
8108 
8109 		    /* When looking for a "do" we are not interested in
8110 		     * labels. */
8111 		    if (whilelevel > 0)
8112 			continue;
8113 
8114 		    /*
8115 		     *	case xx:
8116 		     *	    c = 99 +	    <- this indent plus continuation
8117 		     *->	   here;
8118 		     */
8119 		    if (lookfor == LOOKFOR_UNTERM
8120 					   || lookfor == LOOKFOR_ENUM_OR_INIT)
8121 		    {
8122 			if (cont_amount > 0)
8123 			    amount = cont_amount;
8124 			else
8125 			    amount += ind_continuation;
8126 			break;
8127 		    }
8128 
8129 		    /*
8130 		     *	case xx:	<- line up with this case
8131 		     *	    x = 333;
8132 		     *	case yy:
8133 		     */
8134 		    if (       (iscase && lookfor == LOOKFOR_CASE)
8135 			    || (iscase && lookfor_break)
8136 			    || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
8137 		    {
8138 			/*
8139 			 * Check that this case label is not for another
8140 			 * switch()
8141 			 */				    /* XXX */
8142 			if ((trypos = find_start_brace()) == NULL
8143 						  || trypos->lnum == ourscope)
8144 			{
8145 			    amount = get_indent();	/* XXX */
8146 			    break;
8147 			}
8148 			continue;
8149 		    }
8150 
8151 		    n = get_indent_nolabel(curwin->w_cursor.lnum);  /* XXX */
8152 
8153 		    /*
8154 		     *	 case xx: if (cond)	    <- line up with this if
8155 		     *		      y = y + 1;
8156 		     * ->	  s = 99;
8157 		     *
8158 		     *	 case xx:
8159 		     *	     if (cond)		<- line up with this line
8160 		     *		 y = y + 1;
8161 		     * ->    s = 99;
8162 		     */
8163 		    if (lookfor == LOOKFOR_TERM)
8164 		    {
8165 			if (n)
8166 			    amount = n;
8167 
8168 			if (!lookfor_break)
8169 			    break;
8170 		    }
8171 
8172 		    /*
8173 		     *	 case xx: x = x + 1;	    <- line up with this x
8174 		     * ->	  y = y + 1;
8175 		     *
8176 		     *	 case xx: if (cond)	    <- line up with this if
8177 		     * ->	       y = y + 1;
8178 		     */
8179 		    if (n)
8180 		    {
8181 			amount = n;
8182 			l = after_label(ml_get_curline());
8183 			if (l != NULL && cin_is_cinword(l))
8184 			{
8185 			    if (theline[0] == '{')
8186 				amount += curbuf->b_ind_open_extra;
8187 			    else
8188 				amount += curbuf->b_ind_level
8189 						     + curbuf->b_ind_no_brace;
8190 			}
8191 			break;
8192 		    }
8193 
8194 		    /*
8195 		     * Try to get the indent of a statement before the switch
8196 		     * label.  If nothing is found, line up relative to the
8197 		     * switch label.
8198 		     *	    break;		<- may line up with this line
8199 		     *	 case xx:
8200 		     * ->   y = 1;
8201 		     */
8202 		    scope_amount = get_indent() + (iscase    /* XXX */
8203 					? curbuf->b_ind_case_code
8204 					: curbuf->b_ind_scopedecl_code);
8205 		    lookfor = curbuf->b_ind_case_break
8206 					      ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
8207 		    continue;
8208 		}
8209 
8210 		/*
8211 		 * Looking for a switch() label or C++ scope declaration,
8212 		 * ignore other lines, skip {}-blocks.
8213 		 */
8214 		if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
8215 		{
8216 		    if (find_last_paren(l, '{', '}')
8217 				     && (trypos = find_start_brace()) != NULL)
8218 		    {
8219 			curwin->w_cursor.lnum = trypos->lnum + 1;
8220 			curwin->w_cursor.col = 0;
8221 		    }
8222 		    continue;
8223 		}
8224 
8225 		/*
8226 		 * Ignore jump labels with nothing after them.
8227 		 */
8228 		if (!curbuf->b_ind_js && cin_islabel())
8229 		{
8230 		    l = after_label(ml_get_curline());
8231 		    if (l == NULL || cin_nocode(l))
8232 			continue;
8233 		}
8234 
8235 		/*
8236 		 * Ignore #defines, #if, etc.
8237 		 * Ignore comment and empty lines.
8238 		 * (need to get the line again, cin_islabel() may have
8239 		 * unlocked it)
8240 		 */
8241 		l = ml_get_curline();
8242 		if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount)
8243 							     || cin_nocode(l))
8244 		    continue;
8245 
8246 		/*
8247 		 * Are we at the start of a cpp base class declaration or
8248 		 * constructor initialization?
8249 		 */						    /* XXX */
8250 		n = FALSE;
8251 		if (lookfor != LOOKFOR_TERM && curbuf->b_ind_cpp_baseclass > 0)
8252 		{
8253 		    n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
8254 		    l = ml_get_curline();
8255 		}
8256 		if (n)
8257 		{
8258 		    if (lookfor == LOOKFOR_UNTERM)
8259 		    {
8260 			if (cont_amount > 0)
8261 			    amount = cont_amount;
8262 			else
8263 			    amount += ind_continuation;
8264 		    }
8265 		    else if (theline[0] == '{')
8266 		    {
8267 			/* Need to find start of the declaration. */
8268 			lookfor = LOOKFOR_UNTERM;
8269 			ind_continuation = 0;
8270 			continue;
8271 		    }
8272 		    else
8273 								     /* XXX */
8274 			amount = get_baseclass_amount(
8275 						cache_cpp_baseclass.lpos.col);
8276 		    break;
8277 		}
8278 		else if (lookfor == LOOKFOR_CPP_BASECLASS)
8279 		{
8280 		    /* only look, whether there is a cpp base class
8281 		     * declaration or initialization before the opening brace.
8282 		     */
8283 		    if (cin_isterminated(l, TRUE, FALSE))
8284 			break;
8285 		    else
8286 			continue;
8287 		}
8288 
8289 		/*
8290 		 * What happens next depends on the line being terminated.
8291 		 * If terminated with a ',' only consider it terminating if
8292 		 * there is another unterminated statement behind, eg:
8293 		 *   123,
8294 		 *   sizeof
8295 		 *	  here
8296 		 * Otherwise check whether it is a enumeration or structure
8297 		 * initialisation (not indented) or a variable declaration
8298 		 * (indented).
8299 		 */
8300 		terminated = cin_isterminated(l, FALSE, TRUE);
8301 
8302 		if (js_cur_has_key)
8303 		{
8304 		    js_cur_has_key = 0; /* only check the first line */
8305 		    if (curbuf->b_ind_js && terminated == ',')
8306 		    {
8307 			/* For Javascript we might be inside an object:
8308 			 *   key: something,  <- align with this
8309 			 *   key: something
8310 			 * or:
8311 			 *   key: something +  <- align with this
8312 			 *       something,
8313 			 *   key: something
8314 			 */
8315 			lookfor = LOOKFOR_JS_KEY;
8316 		    }
8317 		}
8318 		if (lookfor == LOOKFOR_JS_KEY && cin_has_js_key(l))
8319 		{
8320 		    amount = get_indent();
8321 		    break;
8322 		}
8323 		if (lookfor == LOOKFOR_COMMA)
8324 		{
8325 		    if (tryposBrace != NULL && tryposBrace->lnum
8326 						    >= curwin->w_cursor.lnum)
8327 			break;
8328 		    if (terminated == ',')
8329 			/* line below current line is the one that starts a
8330 			 * (possibly broken) line ending in a comma. */
8331 			break;
8332 		    else
8333 		    {
8334 			amount = get_indent();
8335 			if (curwin->w_cursor.lnum - 1 == ourscope)
8336 			    /* line above is start of the scope, thus current
8337 			     * line is the one that stars a (possibly broken)
8338 			     * line ending in a comma. */
8339 			    break;
8340 		    }
8341 		}
8342 
8343 		if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
8344 							&& terminated == ','))
8345 		{
8346 		    if (lookfor != LOOKFOR_ENUM_OR_INIT &&
8347 			    (*skipwhite(l) == '[' || l[STRLEN(l) - 1] == '['))
8348 			amount += ind_continuation;
8349 		    /*
8350 		     * if we're in the middle of a paren thing,
8351 		     * go back to the line that starts it so
8352 		     * we can get the right prevailing indent
8353 		     *	   if ( foo &&
8354 		     *		    bar )
8355 		     */
8356 		    /*
8357 		     * Position the cursor over the rightmost paren, so that
8358 		     * matching it will take us back to the start of the line.
8359 		     * Ignore a match before the start of the block.
8360 		     */
8361 		    (void)find_last_paren(l, '(', ')');
8362 		    trypos = find_match_paren(corr_ind_maxparen(&cur_curpos));
8363 		    if (trypos != NULL && (trypos->lnum < tryposBrace->lnum
8364 				|| (trypos->lnum == tryposBrace->lnum
8365 				    && trypos->col < tryposBrace->col)))
8366 			trypos = NULL;
8367 
8368 		    /*
8369 		     * If we are looking for ',', we also look for matching
8370 		     * braces.
8371 		     */
8372 		    if (trypos == NULL && terminated == ','
8373 					      && find_last_paren(l, '{', '}'))
8374 			trypos = find_start_brace();
8375 
8376 		    if (trypos != NULL)
8377 		    {
8378 			/*
8379 			 * Check if we are on a case label now.  This is
8380 			 * handled above.
8381 			 *     case xx:  if ( asdf &&
8382 			 *			asdf)
8383 			 */
8384 			curwin->w_cursor = *trypos;
8385 			l = ml_get_curline();
8386 			if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
8387 			{
8388 			    ++curwin->w_cursor.lnum;
8389 			    curwin->w_cursor.col = 0;
8390 			    continue;
8391 			}
8392 		    }
8393 
8394 		    /*
8395 		     * Skip over continuation lines to find the one to get the
8396 		     * indent from
8397 		     * char *usethis = "bla\
8398 		     *		 bla",
8399 		     *      here;
8400 		     */
8401 		    if (terminated == ',')
8402 		    {
8403 			while (curwin->w_cursor.lnum > 1)
8404 			{
8405 			    l = ml_get(curwin->w_cursor.lnum - 1);
8406 			    if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8407 				break;
8408 			    --curwin->w_cursor.lnum;
8409 			    curwin->w_cursor.col = 0;
8410 			}
8411 		    }
8412 
8413 		    /*
8414 		     * Get indent and pointer to text for current line,
8415 		     * ignoring any jump label.	    XXX
8416 		     */
8417 		    if (curbuf->b_ind_js)
8418 			cur_amount = get_indent();
8419 		    else
8420 			cur_amount = skip_label(curwin->w_cursor.lnum, &l);
8421 		    /*
8422 		     * If this is just above the line we are indenting, and it
8423 		     * starts with a '{', line it up with this line.
8424 		     *		while (not)
8425 		     * ->	{
8426 		     *		}
8427 		     */
8428 		    if (terminated != ',' && lookfor != LOOKFOR_TERM
8429 							 && theline[0] == '{')
8430 		    {
8431 			amount = cur_amount;
8432 			/*
8433 			 * Only add b_ind_open_extra when the current line
8434 			 * doesn't start with a '{', which must have a match
8435 			 * in the same line (scope is the same).  Probably:
8436 			 *	{ 1, 2 },
8437 			 * ->	{ 3, 4 }
8438 			 */
8439 			if (*skipwhite(l) != '{')
8440 			    amount += curbuf->b_ind_open_extra;
8441 
8442 			if (curbuf->b_ind_cpp_baseclass && !curbuf->b_ind_js)
8443 			{
8444 			    /* have to look back, whether it is a cpp base
8445 			     * class declaration or initialization */
8446 			    lookfor = LOOKFOR_CPP_BASECLASS;
8447 			    continue;
8448 			}
8449 			break;
8450 		    }
8451 
8452 		    /*
8453 		     * Check if we are after an "if", "while", etc.
8454 		     * Also allow "   } else".
8455 		     */
8456 		    if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
8457 		    {
8458 			/*
8459 			 * Found an unterminated line after an if (), line up
8460 			 * with the last one.
8461 			 *   if (cond)
8462 			 *	    100 +
8463 			 * ->		here;
8464 			 */
8465 			if (lookfor == LOOKFOR_UNTERM
8466 					   || lookfor == LOOKFOR_ENUM_OR_INIT)
8467 			{
8468 			    if (cont_amount > 0)
8469 				amount = cont_amount;
8470 			    else
8471 				amount += ind_continuation;
8472 			    break;
8473 			}
8474 
8475 			/*
8476 			 * If this is just above the line we are indenting, we
8477 			 * are finished.
8478 			 *	    while (not)
8479 			 * ->		here;
8480 			 * Otherwise this indent can be used when the line
8481 			 * before this is terminated.
8482 			 *	yyy;
8483 			 *	if (stat)
8484 			 *	    while (not)
8485 			 *		xxx;
8486 			 * ->	here;
8487 			 */
8488 			amount = cur_amount;
8489 			if (theline[0] == '{')
8490 			    amount += curbuf->b_ind_open_extra;
8491 			if (lookfor != LOOKFOR_TERM)
8492 			{
8493 			    amount += curbuf->b_ind_level
8494 						     + curbuf->b_ind_no_brace;
8495 			    break;
8496 			}
8497 
8498 			/*
8499 			 * Special trick: when expecting the while () after a
8500 			 * do, line up with the while()
8501 			 *     do
8502 			 *	    x = 1;
8503 			 * ->  here
8504 			 */
8505 			l = skipwhite(ml_get_curline());
8506 			if (cin_isdo(l))
8507 			{
8508 			    if (whilelevel == 0)
8509 				break;
8510 			    --whilelevel;
8511 			}
8512 
8513 			/*
8514 			 * When searching for a terminated line, don't use the
8515 			 * one between the "if" and the matching "else".
8516 			 * Need to use the scope of this "else".  XXX
8517 			 * If whilelevel != 0 continue looking for a "do {".
8518 			 */
8519 			if (cin_iselse(l) && whilelevel == 0)
8520 			{
8521 			    /* If we're looking at "} else", let's make sure we
8522 			     * find the opening brace of the enclosing scope,
8523 			     * not the one from "if () {". */
8524 			    if (*l == '}')
8525 				curwin->w_cursor.col =
8526 					  (colnr_T)(l - ml_get_curline()) + 1;
8527 
8528 			    if ((trypos = find_start_brace()) == NULL
8529 				       || find_match(LOOKFOR_IF, trypos->lnum)
8530 								      == FAIL)
8531 				break;
8532 			}
8533 		    }
8534 
8535 		    /*
8536 		     * If we're below an unterminated line that is not an
8537 		     * "if" or something, we may line up with this line or
8538 		     * add something for a continuation line, depending on
8539 		     * the line before this one.
8540 		     */
8541 		    else
8542 		    {
8543 			/*
8544 			 * Found two unterminated lines on a row, line up with
8545 			 * the last one.
8546 			 *   c = 99 +
8547 			 *	    100 +
8548 			 * ->	    here;
8549 			 */
8550 			if (lookfor == LOOKFOR_UNTERM)
8551 			{
8552 			    /* When line ends in a comma add extra indent */
8553 			    if (terminated == ',')
8554 				amount += ind_continuation;
8555 			    break;
8556 			}
8557 
8558 			if (lookfor == LOOKFOR_ENUM_OR_INIT)
8559 			{
8560 			    /* Found two lines ending in ',', lineup with the
8561 			     * lowest one, but check for cpp base class
8562 			     * declaration/initialization, if it is an
8563 			     * opening brace or we are looking just for
8564 			     * enumerations/initializations. */
8565 			    if (terminated == ',')
8566 			    {
8567 				if (curbuf->b_ind_cpp_baseclass == 0)
8568 				    break;
8569 
8570 				lookfor = LOOKFOR_CPP_BASECLASS;
8571 				continue;
8572 			    }
8573 
8574 			    /* Ignore unterminated lines in between, but
8575 			     * reduce indent. */
8576 			    if (amount > cur_amount)
8577 				amount = cur_amount;
8578 			}
8579 			else
8580 			{
8581 			    /*
8582 			     * Found first unterminated line on a row, may
8583 			     * line up with this line, remember its indent
8584 			     *	    100 +
8585 			     * ->	    here;
8586 			     */
8587 			    l = ml_get_curline();
8588 			    amount = cur_amount;
8589 
8590 			    n = (int)STRLEN(l);
8591 			    if (terminated == ',' && (*skipwhite(l) == ']'
8592 					|| (n >=2 && l[n - 2] == ']')))
8593 				break;
8594 
8595 			    /*
8596 			     * If previous line ends in ',', check whether we
8597 			     * are in an initialization or enum
8598 			     * struct xxx =
8599 			     * {
8600 			     *      sizeof a,
8601 			     *      124 };
8602 			     * or a normal possible continuation line.
8603 			     * but only, of no other statement has been found
8604 			     * yet.
8605 			     */
8606 			    if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8607 			    {
8608 				if (curbuf->b_ind_js)
8609 				{
8610 				    /* Search for a line ending in a comma
8611 				     * and line up with the line below it
8612 				     * (could be the current line).
8613 				     * some = [
8614 				     *     1,     <- line up here
8615 				     *     2,
8616 				     * some = [
8617 				     *     3 +    <- line up here
8618 				     *       4 *
8619 				     *        5,
8620 				     *     6,
8621 				     */
8622 				    if (cin_iscomment(skipwhite(l)))
8623 					break;
8624 				    lookfor = LOOKFOR_COMMA;
8625 				    trypos = find_match_char('[',
8626 						      curbuf->b_ind_maxparen);
8627 				    if (trypos != NULL)
8628 				    {
8629 					if (trypos->lnum
8630 						 == curwin->w_cursor.lnum - 1)
8631 					{
8632 					    /* Current line is first inside
8633 					     * [], line up with it. */
8634 					    break;
8635 					}
8636 					ourscope = trypos->lnum;
8637 				    }
8638 				}
8639 				else
8640 				{
8641 				    lookfor = LOOKFOR_ENUM_OR_INIT;
8642 				    cont_amount = cin_first_id_amount();
8643 				}
8644 			    }
8645 			    else
8646 			    {
8647 				if (lookfor == LOOKFOR_INITIAL
8648 					&& *l != NUL
8649 					&& l[STRLEN(l) - 1] == '\\')
8650 								/* XXX */
8651 				    cont_amount = cin_get_equal_amount(
8652 						       curwin->w_cursor.lnum);
8653 				if (lookfor != LOOKFOR_TERM
8654 						&& lookfor != LOOKFOR_JS_KEY
8655 						&& lookfor != LOOKFOR_COMMA)
8656 				    lookfor = LOOKFOR_UNTERM;
8657 			    }
8658 			}
8659 		    }
8660 		}
8661 
8662 		/*
8663 		 * Check if we are after a while (cond);
8664 		 * If so: Ignore until the matching "do".
8665 		 */
8666 		else if (cin_iswhileofdo_end(terminated)) /* XXX */
8667 		{
8668 		    /*
8669 		     * Found an unterminated line after a while ();, line up
8670 		     * with the last one.
8671 		     *	    while (cond);
8672 		     *	    100 +		<- line up with this one
8673 		     * ->	    here;
8674 		     */
8675 		    if (lookfor == LOOKFOR_UNTERM
8676 					   || lookfor == LOOKFOR_ENUM_OR_INIT)
8677 		    {
8678 			if (cont_amount > 0)
8679 			    amount = cont_amount;
8680 			else
8681 			    amount += ind_continuation;
8682 			break;
8683 		    }
8684 
8685 		    if (whilelevel == 0)
8686 		    {
8687 			lookfor = LOOKFOR_TERM;
8688 			amount = get_indent();	    /* XXX */
8689 			if (theline[0] == '{')
8690 			    amount += curbuf->b_ind_open_extra;
8691 		    }
8692 		    ++whilelevel;
8693 		}
8694 
8695 		/*
8696 		 * We are after a "normal" statement.
8697 		 * If we had another statement we can stop now and use the
8698 		 * indent of that other statement.
8699 		 * Otherwise the indent of the current statement may be used,
8700 		 * search backwards for the next "normal" statement.
8701 		 */
8702 		else
8703 		{
8704 		    /*
8705 		     * Skip single break line, if before a switch label. It
8706 		     * may be lined up with the case label.
8707 		     */
8708 		    if (lookfor == LOOKFOR_NOBREAK
8709 				  && cin_isbreak(skipwhite(ml_get_curline())))
8710 		    {
8711 			lookfor = LOOKFOR_ANY;
8712 			continue;
8713 		    }
8714 
8715 		    /*
8716 		     * Handle "do {" line.
8717 		     */
8718 		    if (whilelevel > 0)
8719 		    {
8720 			l = cin_skipcomment(ml_get_curline());
8721 			if (cin_isdo(l))
8722 			{
8723 			    amount = get_indent();	/* XXX */
8724 			    --whilelevel;
8725 			    continue;
8726 			}
8727 		    }
8728 
8729 		    /*
8730 		     * Found a terminated line above an unterminated line. Add
8731 		     * the amount for a continuation line.
8732 		     *	 x = 1;
8733 		     *	 y = foo +
8734 		     * ->	here;
8735 		     * or
8736 		     *	 int x = 1;
8737 		     *	 int foo,
8738 		     * ->	here;
8739 		     */
8740 		    if (lookfor == LOOKFOR_UNTERM
8741 					   || lookfor == LOOKFOR_ENUM_OR_INIT)
8742 		    {
8743 			if (cont_amount > 0)
8744 			    amount = cont_amount;
8745 			else
8746 			    amount += ind_continuation;
8747 			break;
8748 		    }
8749 
8750 		    /*
8751 		     * Found a terminated line above a terminated line or "if"
8752 		     * etc. line. Use the amount of the line below us.
8753 		     *	 x = 1;				x = 1;
8754 		     *	 if (asdf)		    y = 2;
8755 		     *	     while (asdf)	  ->here;
8756 		     *		here;
8757 		     * ->foo;
8758 		     */
8759 		    if (lookfor == LOOKFOR_TERM)
8760 		    {
8761 			if (!lookfor_break && whilelevel == 0)
8762 			    break;
8763 		    }
8764 
8765 		    /*
8766 		     * First line above the one we're indenting is terminated.
8767 		     * To know what needs to be done look further backward for
8768 		     * a terminated line.
8769 		     */
8770 		    else
8771 		    {
8772 			/*
8773 			 * position the cursor over the rightmost paren, so
8774 			 * that matching it will take us back to the start of
8775 			 * the line.  Helps for:
8776 			 *     func(asdr,
8777 			 *	      asdfasdf);
8778 			 *     here;
8779 			 */
8780 term_again:
8781 			l = ml_get_curline();
8782 			if (find_last_paren(l, '(', ')')
8783 				&& (trypos = find_match_paren(
8784 					   curbuf->b_ind_maxparen)) != NULL)
8785 			{
8786 			    /*
8787 			     * Check if we are on a case label now.  This is
8788 			     * handled above.
8789 			     *	   case xx:  if ( asdf &&
8790 			     *			    asdf)
8791 			     */
8792 			    curwin->w_cursor = *trypos;
8793 			    l = ml_get_curline();
8794 			    if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
8795 			    {
8796 				++curwin->w_cursor.lnum;
8797 				curwin->w_cursor.col = 0;
8798 				continue;
8799 			    }
8800 			}
8801 
8802 			/* When aligning with the case statement, don't align
8803 			 * with a statement after it.
8804 			 *  case 1: {   <-- don't use this { position
8805 			 *	stat;
8806 			 *  }
8807 			 *  case 2:
8808 			 *	stat;
8809 			 * }
8810 			 */
8811 			iscase = (curbuf->b_ind_keep_case_label
8812 						     && cin_iscase(l, FALSE));
8813 
8814 			/*
8815 			 * Get indent and pointer to text for current line,
8816 			 * ignoring any jump label.
8817 			 */
8818 			amount = skip_label(curwin->w_cursor.lnum, &l);
8819 
8820 			if (theline[0] == '{')
8821 			    amount += curbuf->b_ind_open_extra;
8822 			/* See remark above: "Only add b_ind_open_extra.." */
8823 			l = skipwhite(l);
8824 			if (*l == '{')
8825 			    amount -= curbuf->b_ind_open_extra;
8826 			lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8827 
8828 			/*
8829 			 * When a terminated line starts with "else" skip to
8830 			 * the matching "if":
8831 			 *       else 3;
8832 			 *	     indent this;
8833 			 * Need to use the scope of this "else".  XXX
8834 			 * If whilelevel != 0 continue looking for a "do {".
8835 			 */
8836 			if (lookfor == LOOKFOR_TERM
8837 				&& *l != '}'
8838 				&& cin_iselse(l)
8839 				&& whilelevel == 0)
8840 			{
8841 			    if ((trypos = find_start_brace()) == NULL
8842 				       || find_match(LOOKFOR_IF, trypos->lnum)
8843 								      == FAIL)
8844 				break;
8845 			    continue;
8846 			}
8847 
8848 			/*
8849 			 * If we're at the end of a block, skip to the start of
8850 			 * that block.
8851 			 */
8852 			l = ml_get_curline();
8853 			if (find_last_paren(l, '{', '}') /* XXX */
8854 				     && (trypos = find_start_brace()) != NULL)
8855 			{
8856 			    curwin->w_cursor = *trypos;
8857 			    /* if not "else {" check for terminated again */
8858 			    /* but skip block for "} else {" */
8859 			    l = cin_skipcomment(ml_get_curline());
8860 			    if (*l == '}' || !cin_iselse(l))
8861 				goto term_again;
8862 			    ++curwin->w_cursor.lnum;
8863 			    curwin->w_cursor.col = 0;
8864 			}
8865 		    }
8866 		}
8867 	    }
8868 	}
8869       }
8870 
8871       /* add extra indent for a comment */
8872       if (cin_iscomment(theline))
8873 	  amount += curbuf->b_ind_comment;
8874 
8875       /* subtract extra left-shift for jump labels */
8876       if (curbuf->b_ind_jump_label > 0 && original_line_islabel)
8877 	  amount -= curbuf->b_ind_jump_label;
8878 
8879       goto theend;
8880     }
8881 
8882     /*
8883      * ok -- we're not inside any sort of structure at all!
8884      *
8885      * This means we're at the top level, and everything should
8886      * basically just match where the previous line is, except
8887      * for the lines immediately following a function declaration,
8888      * which are K&R-style parameters and need to be indented.
8889      *
8890      * if our line starts with an open brace, forget about any
8891      * prevailing indent and make sure it looks like the start
8892      * of a function
8893      */
8894 
8895     if (theline[0] == '{')
8896     {
8897 	amount = curbuf->b_ind_first_open;
8898 	goto theend;
8899     }
8900 
8901     /*
8902      * If the NEXT line is a function declaration, the current
8903      * line needs to be indented as a function type spec.
8904      * Don't do this if the current line looks like a comment or if the
8905      * current line is terminated, ie. ends in ';', or if the current line
8906      * contains { or }: "void f() {\n if (1)"
8907      */
8908     if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8909 	    && !cin_nocode(theline)
8910 	    && vim_strchr(theline, '{') == NULL
8911 	    && vim_strchr(theline, '}') == NULL
8912 	    && !cin_ends_in(theline, (char_u *)":", NULL)
8913 	    && !cin_ends_in(theline, (char_u *)",", NULL)
8914 	    && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8915 			      cur_curpos.lnum + 1)
8916 	    && !cin_isterminated(theline, FALSE, TRUE))
8917     {
8918 	amount = curbuf->b_ind_func_type;
8919 	goto theend;
8920     }
8921 
8922     /* search backwards until we find something we recognize */
8923     amount = 0;
8924     curwin->w_cursor = cur_curpos;
8925     while (curwin->w_cursor.lnum > 1)
8926     {
8927 	curwin->w_cursor.lnum--;
8928 	curwin->w_cursor.col = 0;
8929 
8930 	l = ml_get_curline();
8931 
8932 	/*
8933 	 * If we're in a comment or raw string now, skip to the start
8934 	 * of it.
8935 	 */						/* XXX */
8936 	if ((trypos = ind_find_start_CORS()) != NULL)
8937 	{
8938 	    curwin->w_cursor.lnum = trypos->lnum + 1;
8939 	    curwin->w_cursor.col = 0;
8940 	    continue;
8941 	}
8942 
8943 	/*
8944 	 * Are we at the start of a cpp base class declaration or
8945 	 * constructor initialization?
8946 	 */						    /* XXX */
8947 	n = FALSE;
8948 	if (curbuf->b_ind_cpp_baseclass != 0 && theline[0] != '{')
8949 	{
8950 	    n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
8951 	    l = ml_get_curline();
8952 	}
8953 	if (n)
8954 	{
8955 							     /* XXX */
8956 	    amount = get_baseclass_amount(cache_cpp_baseclass.lpos.col);
8957 	    break;
8958 	}
8959 
8960 	/*
8961 	 * Skip preprocessor directives and blank lines.
8962 	 */
8963 	if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount))
8964 	    continue;
8965 
8966 	if (cin_nocode(l))
8967 	    continue;
8968 
8969 	/*
8970 	 * If the previous line ends in ',', use one level of
8971 	 * indentation:
8972 	 * int foo,
8973 	 *     bar;
8974 	 * do this before checking for '}' in case of eg.
8975 	 * enum foobar
8976 	 * {
8977 	 *   ...
8978 	 * } foo,
8979 	 *   bar;
8980 	 */
8981 	n = 0;
8982 	if (cin_ends_in(l, (char_u *)",", NULL)
8983 		     || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8984 	{
8985 	    /* take us back to opening paren */
8986 	    if (find_last_paren(l, '(', ')')
8987 		    && (trypos = find_match_paren(
8988 				     curbuf->b_ind_maxparen)) != NULL)
8989 		curwin->w_cursor = *trypos;
8990 
8991 	    /* For a line ending in ',' that is a continuation line go
8992 	     * back to the first line with a backslash:
8993 	     * char *foo = "bla\
8994 	     *		 bla",
8995 	     *      here;
8996 	     */
8997 	    while (n == 0 && curwin->w_cursor.lnum > 1)
8998 	    {
8999 		l = ml_get(curwin->w_cursor.lnum - 1);
9000 		if (*l == NUL || l[STRLEN(l) - 1] != '\\')
9001 		    break;
9002 		--curwin->w_cursor.lnum;
9003 		curwin->w_cursor.col = 0;
9004 	    }
9005 
9006 	    amount = get_indent();	    /* XXX */
9007 
9008 	    if (amount == 0)
9009 		amount = cin_first_id_amount();
9010 	    if (amount == 0)
9011 		amount = ind_continuation;
9012 	    break;
9013 	}
9014 
9015 	/*
9016 	 * If the line looks like a function declaration, and we're
9017 	 * not in a comment, put it the left margin.
9018 	 */
9019 	if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0))  /* XXX */
9020 	    break;
9021 	l = ml_get_curline();
9022 
9023 	/*
9024 	 * Finding the closing '}' of a previous function.  Put
9025 	 * current line at the left margin.  For when 'cino' has "fs".
9026 	 */
9027 	if (*skipwhite(l) == '}')
9028 	    break;
9029 
9030 	/*			    (matching {)
9031 	 * If the previous line ends on '};' (maybe followed by
9032 	 * comments) align at column 0.  For example:
9033 	 * char *string_array[] = { "foo",
9034 	 *     / * x * / "b};ar" }; / * foobar * /
9035 	 */
9036 	if (cin_ends_in(l, (char_u *)"};", NULL))
9037 	    break;
9038 
9039 	/*
9040 	 * If the previous line ends on '[' we are probably in an
9041 	 * array constant:
9042 	 * something = [
9043 	 *     234,  <- extra indent
9044 	 */
9045 	if (cin_ends_in(l, (char_u *)"[", NULL))
9046 	{
9047 	    amount = get_indent() + ind_continuation;
9048 	    break;
9049 	}
9050 
9051 	/*
9052 	 * Find a line only has a semicolon that belongs to a previous
9053 	 * line ending in '}', e.g. before an #endif.  Don't increase
9054 	 * indent then.
9055 	 */
9056 	if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
9057 	{
9058 	    pos_T curpos_save = curwin->w_cursor;
9059 
9060 	    while (curwin->w_cursor.lnum > 1)
9061 	    {
9062 		look = ml_get(--curwin->w_cursor.lnum);
9063 		if (!(cin_nocode(look) || cin_ispreproc_cont(
9064 				      &look, &curwin->w_cursor.lnum, &amount)))
9065 		    break;
9066 	    }
9067 	    if (curwin->w_cursor.lnum > 0
9068 			    && cin_ends_in(look, (char_u *)"}", NULL))
9069 		break;
9070 
9071 	    curwin->w_cursor = curpos_save;
9072 	}
9073 
9074 	/*
9075 	 * If the PREVIOUS line is a function declaration, the current
9076 	 * line (and the ones that follow) needs to be indented as
9077 	 * parameters.
9078 	 */
9079 	if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0))
9080 	{
9081 	    amount = curbuf->b_ind_param;
9082 	    break;
9083 	}
9084 
9085 	/*
9086 	 * If the previous line ends in ';' and the line before the
9087 	 * previous line ends in ',' or '\', ident to column zero:
9088 	 * int foo,
9089 	 *     bar;
9090 	 * indent_to_0 here;
9091 	 */
9092 	if (cin_ends_in(l, (char_u *)";", NULL))
9093 	{
9094 	    l = ml_get(curwin->w_cursor.lnum - 1);
9095 	    if (cin_ends_in(l, (char_u *)",", NULL)
9096 		    || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
9097 		break;
9098 	    l = ml_get_curline();
9099 	}
9100 
9101 	/*
9102 	 * Doesn't look like anything interesting -- so just
9103 	 * use the indent of this line.
9104 	 *
9105 	 * Position the cursor over the rightmost paren, so that
9106 	 * matching it will take us back to the start of the line.
9107 	 */
9108 	find_last_paren(l, '(', ')');
9109 
9110 	if ((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
9111 	    curwin->w_cursor = *trypos;
9112 	amount = get_indent();	    /* XXX */
9113 	break;
9114     }
9115 
9116     /* add extra indent for a comment */
9117     if (cin_iscomment(theline))
9118 	amount += curbuf->b_ind_comment;
9119 
9120     /* add extra indent if the previous line ended in a backslash:
9121      *	      "asdfasdf\
9122      *		  here";
9123      *	    char *foo = "asdf\
9124      *			 here";
9125      */
9126     if (cur_curpos.lnum > 1)
9127     {
9128 	l = ml_get(cur_curpos.lnum - 1);
9129 	if (*l != NUL && l[STRLEN(l) - 1] == '\\')
9130 	{
9131 	    cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
9132 	    if (cur_amount > 0)
9133 		amount = cur_amount;
9134 	    else if (cur_amount == 0)
9135 		amount += ind_continuation;
9136 	}
9137     }
9138 
9139 theend:
9140     if (amount < 0)
9141 	amount = 0;
9142 
9143 laterend:
9144     /* put the cursor back where it belongs */
9145     curwin->w_cursor = cur_curpos;
9146 
9147     vim_free(linecopy);
9148 
9149     return amount;
9150 }
9151 
9152     static int
9153 find_match(int lookfor, linenr_T ourscope)
9154 {
9155     char_u	*look;
9156     pos_T	*theirscope;
9157     char_u	*mightbeif;
9158     int		elselevel;
9159     int		whilelevel;
9160 
9161     if (lookfor == LOOKFOR_IF)
9162     {
9163 	elselevel = 1;
9164 	whilelevel = 0;
9165     }
9166     else
9167     {
9168 	elselevel = 0;
9169 	whilelevel = 1;
9170     }
9171 
9172     curwin->w_cursor.col = 0;
9173 
9174     while (curwin->w_cursor.lnum > ourscope + 1)
9175     {
9176 	curwin->w_cursor.lnum--;
9177 	curwin->w_cursor.col = 0;
9178 
9179 	look = cin_skipcomment(ml_get_curline());
9180 	if (cin_iselse(look)
9181 		|| cin_isif(look)
9182 		|| cin_isdo(look)			    /* XXX */
9183 		|| cin_iswhileofdo(look, curwin->w_cursor.lnum))
9184 	{
9185 	    /*
9186 	     * if we've gone outside the braces entirely,
9187 	     * we must be out of scope...
9188 	     */
9189 	    theirscope = find_start_brace();  /* XXX */
9190 	    if (theirscope == NULL)
9191 		break;
9192 
9193 	    /*
9194 	     * and if the brace enclosing this is further
9195 	     * back than the one enclosing the else, we're
9196 	     * out of luck too.
9197 	     */
9198 	    if (theirscope->lnum < ourscope)
9199 		break;
9200 
9201 	    /*
9202 	     * and if they're enclosed in a *deeper* brace,
9203 	     * then we can ignore it because it's in a
9204 	     * different scope...
9205 	     */
9206 	    if (theirscope->lnum > ourscope)
9207 		continue;
9208 
9209 	    /*
9210 	     * if it was an "else" (that's not an "else if")
9211 	     * then we need to go back to another if, so
9212 	     * increment elselevel
9213 	     */
9214 	    look = cin_skipcomment(ml_get_curline());
9215 	    if (cin_iselse(look))
9216 	    {
9217 		mightbeif = cin_skipcomment(look + 4);
9218 		if (!cin_isif(mightbeif))
9219 		    ++elselevel;
9220 		continue;
9221 	    }
9222 
9223 	    /*
9224 	     * if it was a "while" then we need to go back to
9225 	     * another "do", so increment whilelevel.  XXX
9226 	     */
9227 	    if (cin_iswhileofdo(look, curwin->w_cursor.lnum))
9228 	    {
9229 		++whilelevel;
9230 		continue;
9231 	    }
9232 
9233 	    /* If it's an "if" decrement elselevel */
9234 	    look = cin_skipcomment(ml_get_curline());
9235 	    if (cin_isif(look))
9236 	    {
9237 		elselevel--;
9238 		/*
9239 		 * When looking for an "if" ignore "while"s that
9240 		 * get in the way.
9241 		 */
9242 		if (elselevel == 0 && lookfor == LOOKFOR_IF)
9243 		    whilelevel = 0;
9244 	    }
9245 
9246 	    /* If it's a "do" decrement whilelevel */
9247 	    if (cin_isdo(look))
9248 		whilelevel--;
9249 
9250 	    /*
9251 	     * if we've used up all the elses, then
9252 	     * this must be the if that we want!
9253 	     * match the indent level of that if.
9254 	     */
9255 	    if (elselevel <= 0 && whilelevel <= 0)
9256 	    {
9257 		return OK;
9258 	    }
9259 	}
9260     }
9261     return FAIL;
9262 }
9263 
9264 # if defined(FEAT_EVAL) || defined(PROTO)
9265 /*
9266  * Get indent level from 'indentexpr'.
9267  */
9268     int
9269 get_expr_indent(void)
9270 {
9271     int		indent = -1;
9272     char_u	*inde_copy;
9273     pos_T	save_pos;
9274     colnr_T	save_curswant;
9275     int		save_set_curswant;
9276     int		save_State;
9277     int		use_sandbox = was_set_insecurely((char_u *)"indentexpr",
9278 								   OPT_LOCAL);
9279 
9280     /* Save and restore cursor position and curswant, in case it was changed
9281      * via :normal commands */
9282     save_pos = curwin->w_cursor;
9283     save_curswant = curwin->w_curswant;
9284     save_set_curswant = curwin->w_set_curswant;
9285     set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
9286     if (use_sandbox)
9287 	++sandbox;
9288     ++textlock;
9289 
9290     /* Need to make a copy, the 'indentexpr' option could be changed while
9291      * evaluating it. */
9292     inde_copy = vim_strsave(curbuf->b_p_inde);
9293     if (inde_copy != NULL)
9294     {
9295 	indent = (int)eval_to_number(inde_copy);
9296 	vim_free(inde_copy);
9297     }
9298 
9299     if (use_sandbox)
9300 	--sandbox;
9301     --textlock;
9302 
9303     /* Restore the cursor position so that 'indentexpr' doesn't need to.
9304      * Pretend to be in Insert mode, allow cursor past end of line for "o"
9305      * command. */
9306     save_State = State;
9307     State = INSERT;
9308     curwin->w_cursor = save_pos;
9309     curwin->w_curswant = save_curswant;
9310     curwin->w_set_curswant = save_set_curswant;
9311     check_cursor();
9312     State = save_State;
9313 
9314     /* If there is an error, just keep the current indent. */
9315     if (indent < 0)
9316 	indent = get_indent();
9317 
9318     return indent;
9319 }
9320 # endif
9321 
9322 #endif /* FEAT_CINDENT */
9323 
9324 #if defined(FEAT_LISP) || defined(PROTO)
9325 
9326 static int lisp_match(char_u *p);
9327 
9328     static int
9329 lisp_match(char_u *p)
9330 {
9331     char_u	buf[LSIZE];
9332     int		len;
9333     char_u	*word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords;
9334 
9335     while (*word != NUL)
9336     {
9337 	(void)copy_option_part(&word, buf, LSIZE, ",");
9338 	len = (int)STRLEN(buf);
9339 	if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
9340 	    return TRUE;
9341     }
9342     return FALSE;
9343 }
9344 
9345 /*
9346  * When 'p' is present in 'cpoptions, a Vi compatible method is used.
9347  * The incompatible newer method is quite a bit better at indenting
9348  * code in lisp-like languages than the traditional one; it's still
9349  * mostly heuristics however -- Dirk van Deun, [email protected]
9350  *
9351  * TODO:
9352  * Findmatch() should be adapted for lisp, also to make showmatch
9353  * work correctly: now (v5.3) it seems all C/C++ oriented:
9354  * - it does not recognize the #\( and #\) notations as character literals
9355  * - it doesn't know about comments starting with a semicolon
9356  * - it incorrectly interprets '(' as a character literal
9357  * All this messes up get_lisp_indent in some rare cases.
9358  * Update from Sergey Khorev:
9359  * I tried to fix the first two issues.
9360  */
9361     int
9362 get_lisp_indent(void)
9363 {
9364     pos_T	*pos, realpos, paren;
9365     int		amount;
9366     char_u	*that;
9367     colnr_T	col;
9368     colnr_T	firsttry;
9369     int		parencount, quotecount;
9370     int		vi_lisp;
9371 
9372     /* Set vi_lisp to use the vi-compatible method */
9373     vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
9374 
9375     realpos = curwin->w_cursor;
9376     curwin->w_cursor.col = 0;
9377 
9378     if ((pos = findmatch(NULL, '(')) == NULL)
9379 	pos = findmatch(NULL, '[');
9380     else
9381     {
9382 	paren = *pos;
9383 	pos = findmatch(NULL, '[');
9384 	if (pos == NULL || LT_POSP(pos, &paren))
9385 	    pos = &paren;
9386     }
9387     if (pos != NULL)
9388     {
9389 	/* Extra trick: Take the indent of the first previous non-white
9390 	 * line that is at the same () level. */
9391 	amount = -1;
9392 	parencount = 0;
9393 
9394 	while (--curwin->w_cursor.lnum >= pos->lnum)
9395 	{
9396 	    if (linewhite(curwin->w_cursor.lnum))
9397 		continue;
9398 	    for (that = ml_get_curline(); *that != NUL; ++that)
9399 	    {
9400 		if (*that == ';')
9401 		{
9402 		    while (*(that + 1) != NUL)
9403 			++that;
9404 		    continue;
9405 		}
9406 		if (*that == '\\')
9407 		{
9408 		    if (*(that + 1) != NUL)
9409 			++that;
9410 		    continue;
9411 		}
9412 		if (*that == '"' && *(that + 1) != NUL)
9413 		{
9414 		    while (*++that && *that != '"')
9415 		    {
9416 			/* skipping escaped characters in the string */
9417 			if (*that == '\\')
9418 			{
9419 			    if (*++that == NUL)
9420 				break;
9421 			    if (that[1] == NUL)
9422 			    {
9423 				++that;
9424 				break;
9425 			    }
9426 			}
9427 		    }
9428 		}
9429 		if (*that == '(' || *that == '[')
9430 		    ++parencount;
9431 		else if (*that == ')' || *that == ']')
9432 		    --parencount;
9433 	    }
9434 	    if (parencount == 0)
9435 	    {
9436 		amount = get_indent();
9437 		break;
9438 	    }
9439 	}
9440 
9441 	if (amount == -1)
9442 	{
9443 	    curwin->w_cursor.lnum = pos->lnum;
9444 	    curwin->w_cursor.col = pos->col;
9445 	    col = pos->col;
9446 
9447 	    that = ml_get_curline();
9448 
9449 	    if (vi_lisp && get_indent() == 0)
9450 		amount = 2;
9451 	    else
9452 	    {
9453 		char_u *line = that;
9454 
9455 		amount = 0;
9456 		while (*that && col)
9457 		{
9458 		    amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);
9459 		    col--;
9460 		}
9461 
9462 		/*
9463 		 * Some keywords require "body" indenting rules (the
9464 		 * non-standard-lisp ones are Scheme special forms):
9465 		 *
9466 		 * (let ((a 1))    instead    (let ((a 1))
9467 		 *   (...))	      of	   (...))
9468 		 */
9469 
9470 		if (!vi_lisp && (*that == '(' || *that == '[')
9471 						      && lisp_match(that + 1))
9472 		    amount += 2;
9473 		else
9474 		{
9475 		    that++;
9476 		    amount++;
9477 		    firsttry = amount;
9478 
9479 		    while (VIM_ISWHITE(*that))
9480 		    {
9481 			amount += lbr_chartabsize(line, that, (colnr_T)amount);
9482 			++that;
9483 		    }
9484 
9485 		    if (*that && *that != ';') /* not a comment line */
9486 		    {
9487 			/* test *that != '(' to accommodate first let/do
9488 			 * argument if it is more than one line */
9489 			if (!vi_lisp && *that != '(' && *that != '[')
9490 			    firsttry++;
9491 
9492 			parencount = 0;
9493 			quotecount = 0;
9494 
9495 			if (vi_lisp
9496 				|| (*that != '"'
9497 				    && *that != '\''
9498 				    && *that != '#'
9499 				    && (*that < '0' || *that > '9')))
9500 			{
9501 			    while (*that
9502 				    && (!VIM_ISWHITE(*that)
9503 					|| quotecount
9504 					|| parencount)
9505 				    && (!((*that == '(' || *that == '[')
9506 					    && !quotecount
9507 					    && !parencount
9508 					    && vi_lisp)))
9509 			    {
9510 				if (*that == '"')
9511 				    quotecount = !quotecount;
9512 				if ((*that == '(' || *that == '[')
9513 							       && !quotecount)
9514 				    ++parencount;
9515 				if ((*that == ')' || *that == ']')
9516 							       && !quotecount)
9517 				    --parencount;
9518 				if (*that == '\\' && *(that+1) != NUL)
9519 				    amount += lbr_chartabsize_adv(
9520 						line, &that, (colnr_T)amount);
9521 				amount += lbr_chartabsize_adv(
9522 						line, &that, (colnr_T)amount);
9523 			    }
9524 			}
9525 			while (VIM_ISWHITE(*that))
9526 			{
9527 			    amount += lbr_chartabsize(
9528 						 line, that, (colnr_T)amount);
9529 			    that++;
9530 			}
9531 			if (!*that || *that == ';')
9532 			    amount = firsttry;
9533 		    }
9534 		}
9535 	    }
9536 	}
9537     }
9538     else
9539 	amount = 0;	/* no matching '(' or '[' found, use zero indent */
9540 
9541     curwin->w_cursor = realpos;
9542 
9543     return amount;
9544 }
9545 #endif /* FEAT_LISP */
9546 
9547     void
9548 prepare_to_exit(void)
9549 {
9550 #if defined(SIGHUP) && defined(SIG_IGN)
9551     /* Ignore SIGHUP, because a dropped connection causes a read error, which
9552      * makes Vim exit and then handling SIGHUP causes various reentrance
9553      * problems. */
9554     signal(SIGHUP, SIG_IGN);
9555 #endif
9556 
9557 #ifdef FEAT_GUI
9558     if (gui.in_use)
9559     {
9560 	gui.dying = TRUE;
9561 	out_trash();	/* trash any pending output */
9562     }
9563     else
9564 #endif
9565     {
9566 	windgoto((int)Rows - 1, 0);
9567 
9568 	/*
9569 	 * Switch terminal mode back now, so messages end up on the "normal"
9570 	 * screen (if there are two screens).
9571 	 */
9572 	settmode(TMODE_COOK);
9573 	stoptermcap();
9574 	out_flush();
9575     }
9576 }
9577 
9578 /*
9579  * Preserve files and exit.
9580  * When called IObuff must contain a message.
9581  * NOTE: This may be called from deathtrap() in a signal handler, avoid unsafe
9582  * functions, such as allocating memory.
9583  */
9584     void
9585 preserve_exit(void)
9586 {
9587     buf_T	*buf;
9588 
9589     prepare_to_exit();
9590 
9591     /* Setting this will prevent free() calls.  That avoids calling free()
9592      * recursively when free() was invoked with a bad pointer. */
9593     really_exiting = TRUE;
9594 
9595     out_str(IObuff);
9596     screen_start();		    /* don't know where cursor is now */
9597     out_flush();
9598 
9599     ml_close_notmod();		    /* close all not-modified buffers */
9600 
9601     FOR_ALL_BUFFERS(buf)
9602     {
9603 	if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9604 	{
9605 	    OUT_STR("Vim: preserving files...\n");
9606 	    screen_start();	    /* don't know where cursor is now */
9607 	    out_flush();
9608 	    ml_sync_all(FALSE, FALSE);	/* preserve all swap files */
9609 	    break;
9610 	}
9611     }
9612 
9613     ml_close_all(FALSE);	    /* close all memfiles, without deleting */
9614 
9615     OUT_STR("Vim: Finished.\n");
9616 
9617     getout(1);
9618 }
9619 
9620 /*
9621  * return TRUE if "fname" exists.
9622  */
9623     int
9624 vim_fexists(char_u *fname)
9625 {
9626     stat_T st;
9627 
9628     if (mch_stat((char *)fname, &st))
9629 	return FALSE;
9630     return TRUE;
9631 }
9632 
9633 /*
9634  * Check for CTRL-C pressed, but only once in a while.
9635  * Should be used instead of ui_breakcheck() for functions that check for
9636  * each line in the file.  Calling ui_breakcheck() each time takes too much
9637  * time, because it can be a system call.
9638  */
9639 
9640 #ifndef BREAKCHECK_SKIP
9641 # ifdef FEAT_GUI		    /* assume the GUI only runs on fast computers */
9642 #  define BREAKCHECK_SKIP 200
9643 # else
9644 #  define BREAKCHECK_SKIP 32
9645 # endif
9646 #endif
9647 
9648 static int	breakcheck_count = 0;
9649 
9650     void
9651 line_breakcheck(void)
9652 {
9653     if (++breakcheck_count >= BREAKCHECK_SKIP)
9654     {
9655 	breakcheck_count = 0;
9656 	ui_breakcheck();
9657     }
9658 }
9659 
9660 /*
9661  * Like line_breakcheck() but check 10 times less often.
9662  */
9663     void
9664 fast_breakcheck(void)
9665 {
9666     if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9667     {
9668 	breakcheck_count = 0;
9669 	ui_breakcheck();
9670     }
9671 }
9672 
9673 /*
9674  * Invoke expand_wildcards() for one pattern.
9675  * Expand items like "%:h" before the expansion.
9676  * Returns OK or FAIL.
9677  */
9678     int
9679 expand_wildcards_eval(
9680     char_u	 **pat,		/* pointer to input pattern */
9681     int		  *num_file,	/* resulting number of files */
9682     char_u	***file,	/* array of resulting files */
9683     int		   flags)	/* EW_DIR, etc. */
9684 {
9685     int		ret = FAIL;
9686     char_u	*eval_pat = NULL;
9687     char_u	*exp_pat = *pat;
9688     char_u      *ignored_msg;
9689     int		usedlen;
9690 
9691     if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9692     {
9693 	++emsg_off;
9694 	eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9695 						    NULL, &ignored_msg, NULL);
9696 	--emsg_off;
9697 	if (eval_pat != NULL)
9698 	    exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9699     }
9700 
9701     if (exp_pat != NULL)
9702 	ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9703 
9704     if (eval_pat != NULL)
9705     {
9706 	vim_free(exp_pat);
9707 	vim_free(eval_pat);
9708     }
9709 
9710     return ret;
9711 }
9712 
9713 /*
9714  * Expand wildcards.  Calls gen_expand_wildcards() and removes files matching
9715  * 'wildignore'.
9716  * Returns OK or FAIL.  When FAIL then "num_files" won't be set.
9717  */
9718     int
9719 expand_wildcards(
9720     int		   num_pat,	/* number of input patterns */
9721     char_u	 **pat,		/* array of input patterns */
9722     int		  *num_files,	/* resulting number of files */
9723     char_u	***files,	/* array of resulting files */
9724     int		   flags)	/* EW_DIR, etc. */
9725 {
9726     int		retval;
9727     int		i, j;
9728     char_u	*p;
9729     int		non_suf_match;	/* number without matching suffix */
9730 
9731     retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
9732 
9733     /* When keeping all matches, return here */
9734     if ((flags & EW_KEEPALL) || retval == FAIL)
9735 	return retval;
9736 
9737 #ifdef FEAT_WILDIGN
9738     /*
9739      * Remove names that match 'wildignore'.
9740      */
9741     if (*p_wig)
9742     {
9743 	char_u	*ffname;
9744 
9745 	/* check all files in (*files)[] */
9746 	for (i = 0; i < *num_files; ++i)
9747 	{
9748 	    ffname = FullName_save((*files)[i], FALSE);
9749 	    if (ffname == NULL)		/* out of memory */
9750 		break;
9751 # ifdef VMS
9752 	    vms_remove_version(ffname);
9753 # endif
9754 	    if (match_file_list(p_wig, (*files)[i], ffname))
9755 	    {
9756 		/* remove this matching file from the list */
9757 		vim_free((*files)[i]);
9758 		for (j = i; j + 1 < *num_files; ++j)
9759 		    (*files)[j] = (*files)[j + 1];
9760 		--*num_files;
9761 		--i;
9762 	    }
9763 	    vim_free(ffname);
9764 	}
9765 
9766 	/* If the number of matches is now zero, we fail. */
9767 	if (*num_files == 0)
9768 	{
9769 	    vim_free(*files);
9770 	    *files = NULL;
9771 	    return FAIL;
9772 	}
9773     }
9774 #endif
9775 
9776     /*
9777      * Move the names where 'suffixes' match to the end.
9778      */
9779     if (*num_files > 1)
9780     {
9781 	non_suf_match = 0;
9782 	for (i = 0; i < *num_files; ++i)
9783 	{
9784 	    if (!match_suffix((*files)[i]))
9785 	    {
9786 		/*
9787 		 * Move the name without matching suffix to the front
9788 		 * of the list.
9789 		 */
9790 		p = (*files)[i];
9791 		for (j = i; j > non_suf_match; --j)
9792 		    (*files)[j] = (*files)[j - 1];
9793 		(*files)[non_suf_match++] = p;
9794 	    }
9795 	}
9796     }
9797 
9798     return retval;
9799 }
9800 
9801 /*
9802  * Return TRUE if "fname" matches with an entry in 'suffixes'.
9803  */
9804     int
9805 match_suffix(char_u *fname)
9806 {
9807     int		fnamelen, setsuflen;
9808     char_u	*setsuf;
9809 #define MAXSUFLEN 30	    /* maximum length of a file suffix */
9810     char_u	suf_buf[MAXSUFLEN];
9811 
9812     fnamelen = (int)STRLEN(fname);
9813     setsuflen = 0;
9814     for (setsuf = p_su; *setsuf; )
9815     {
9816 	setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
9817 	if (setsuflen == 0)
9818 	{
9819 	    char_u *tail = gettail(fname);
9820 
9821 	    /* empty entry: match name without a '.' */
9822 	    if (vim_strchr(tail, '.') == NULL)
9823 	    {
9824 		setsuflen = 1;
9825 		break;
9826 	    }
9827 	}
9828 	else
9829 	{
9830 	    if (fnamelen >= setsuflen
9831 		    && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9832 						  (size_t)setsuflen) == 0)
9833 		break;
9834 	    setsuflen = 0;
9835 	}
9836     }
9837     return (setsuflen != 0);
9838 }
9839 
9840 #if !defined(NO_EXPANDPATH) || defined(PROTO)
9841 
9842 # ifdef VIM_BACKTICK
9843 static int vim_backtick(char_u *p);
9844 static int expand_backtick(garray_T *gap, char_u *pat, int flags);
9845 # endif
9846 
9847 # if defined(WIN3264)
9848 /*
9849  * File name expansion code for MS-DOS, Win16 and Win32.  It's here because
9850  * it's shared between these systems.
9851  */
9852 # if defined(PROTO)
9853 #  define _cdecl
9854 # else
9855 #  ifdef __BORLANDC__
9856 #   define _cdecl _RTLENTRYF
9857 #  endif
9858 # endif
9859 
9860 /*
9861  * comparison function for qsort in dos_expandpath()
9862  */
9863     static int _cdecl
9864 pstrcmp(const void *a, const void *b)
9865 {
9866     return (pathcmp(*(char **)a, *(char **)b, -1));
9867 }
9868 
9869 /*
9870  * Recursively expand one path component into all matching files and/or
9871  * directories.  Adds matches to "gap".  Handles "*", "?", "[a-z]", "**", etc.
9872  * Return the number of matches found.
9873  * "path" has backslashes before chars that are not to be expanded, starting
9874  * at "path[wildoff]".
9875  * Return the number of matches found.
9876  * NOTE: much of this is identical to unix_expandpath(), keep in sync!
9877  */
9878     static int
9879 dos_expandpath(
9880     garray_T	*gap,
9881     char_u	*path,
9882     int		wildoff,
9883     int		flags,		/* EW_* flags */
9884     int		didstar)	/* expanded "**" once already */
9885 {
9886     char_u	*buf;
9887     char_u	*path_end;
9888     char_u	*p, *s, *e;
9889     int		start_len = gap->ga_len;
9890     char_u	*pat;
9891     regmatch_T	regmatch;
9892     int		starts_with_dot;
9893     int		matches;
9894     int		len;
9895     int		starstar = FALSE;
9896     static int	stardepth = 0;	    /* depth for "**" expansion */
9897     WIN32_FIND_DATA	fb;
9898     HANDLE		hFind = (HANDLE)0;
9899 # ifdef FEAT_MBYTE
9900     WIN32_FIND_DATAW    wfb;
9901     WCHAR		*wn = NULL;	/* UCS-2 name, NULL when not used. */
9902 # endif
9903     char_u		*matchname;
9904     int			ok;
9905 
9906     /* Expanding "**" may take a long time, check for CTRL-C. */
9907     if (stardepth > 0)
9908     {
9909 	ui_breakcheck();
9910 	if (got_int)
9911 	    return 0;
9912     }
9913 
9914     /* Make room for file name.  When doing encoding conversion the actual
9915      * length may be quite a bit longer, thus use the maximum possible length. */
9916     buf = alloc((int)MAXPATHL);
9917     if (buf == NULL)
9918 	return 0;
9919 
9920     /*
9921      * Find the first part in the path name that contains a wildcard or a ~1.
9922      * Copy it into buf, including the preceding characters.
9923      */
9924     p = buf;
9925     s = buf;
9926     e = NULL;
9927     path_end = path;
9928     while (*path_end != NUL)
9929     {
9930 	/* May ignore a wildcard that has a backslash before it; it will
9931 	 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9932 	if (path_end >= path + wildoff && rem_backslash(path_end))
9933 	    *p++ = *path_end++;
9934 	else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9935 	{
9936 	    if (e != NULL)
9937 		break;
9938 	    s = p + 1;
9939 	}
9940 	else if (path_end >= path + wildoff
9941 			 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9942 	    e = p;
9943 # ifdef FEAT_MBYTE
9944 	if (has_mbyte)
9945 	{
9946 	    len = (*mb_ptr2len)(path_end);
9947 	    STRNCPY(p, path_end, len);
9948 	    p += len;
9949 	    path_end += len;
9950 	}
9951 	else
9952 # endif
9953 	    *p++ = *path_end++;
9954     }
9955     e = p;
9956     *e = NUL;
9957 
9958     /* now we have one wildcard component between s and e */
9959     /* Remove backslashes between "wildoff" and the start of the wildcard
9960      * component. */
9961     for (p = buf + wildoff; p < s; ++p)
9962 	if (rem_backslash(p))
9963 	{
9964 	    STRMOVE(p, p + 1);
9965 	    --e;
9966 	    --s;
9967 	}
9968 
9969     /* Check for "**" between "s" and "e". */
9970     for (p = s; p < e; ++p)
9971 	if (p[0] == '*' && p[1] == '*')
9972 	    starstar = TRUE;
9973 
9974     starts_with_dot = *s == '.';
9975     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9976     if (pat == NULL)
9977     {
9978 	vim_free(buf);
9979 	return 0;
9980     }
9981 
9982     /* compile the regexp into a program */
9983     if (flags & (EW_NOERROR | EW_NOTWILD))
9984 	++emsg_silent;
9985     regmatch.rm_ic = TRUE;		/* Always ignore case */
9986     regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9987     if (flags & (EW_NOERROR | EW_NOTWILD))
9988 	--emsg_silent;
9989     vim_free(pat);
9990 
9991     if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
9992     {
9993 	vim_free(buf);
9994 	return 0;
9995     }
9996 
9997     /* remember the pattern or file name being looked for */
9998     matchname = vim_strsave(s);
9999 
10000     /* If "**" is by itself, this is the first time we encounter it and more
10001      * is following then find matches without any directory. */
10002     if (!didstar && stardepth < 100 && starstar && e - s == 2
10003 							  && *path_end == '/')
10004     {
10005 	STRCPY(s, path_end + 1);
10006 	++stardepth;
10007 	(void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
10008 	--stardepth;
10009     }
10010 
10011     /* Scan all files in the directory with "dir/ *.*" */
10012     STRCPY(s, "*.*");
10013 # ifdef FEAT_MBYTE
10014     if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
10015     {
10016 	/* The active codepage differs from 'encoding'.  Attempt using the
10017 	 * wide function.  If it fails because it is not implemented fall back
10018 	 * to the non-wide version (for Windows 98) */
10019 	wn = enc_to_utf16(buf, NULL);
10020 	if (wn != NULL)
10021 	{
10022 	    hFind = FindFirstFileW(wn, &wfb);
10023 	    if (hFind == INVALID_HANDLE_VALUE
10024 			      && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
10025 	    {
10026 		vim_free(wn);
10027 		wn = NULL;
10028 	    }
10029 	}
10030     }
10031 
10032     if (wn == NULL)
10033 # endif
10034 	hFind = FindFirstFile((LPCSTR)buf, &fb);
10035     ok = (hFind != INVALID_HANDLE_VALUE);
10036 
10037     while (ok)
10038     {
10039 # ifdef FEAT_MBYTE
10040 	if (wn != NULL)
10041 	    p = utf16_to_enc(wfb.cFileName, NULL);   /* p is allocated here */
10042 	else
10043 # endif
10044 	    p = (char_u *)fb.cFileName;
10045 	/* Ignore entries starting with a dot, unless when asked for.  Accept
10046 	 * all entries found with "matchname". */
10047 	if ((p[0] != '.' || starts_with_dot
10048 			 || ((flags & EW_DODOT)
10049 			     && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
10050 		&& (matchname == NULL
10051 		  || (regmatch.regprog != NULL
10052 				     && vim_regexec(&regmatch, p, (colnr_T)0))
10053 		  || ((flags & EW_NOTWILD)
10054 		     && fnamencmp(path + (s - buf), p, e - s) == 0)))
10055 	{
10056 	    STRCPY(s, p);
10057 	    len = (int)STRLEN(buf);
10058 
10059 	    if (starstar && stardepth < 100)
10060 	    {
10061 		/* For "**" in the pattern first go deeper in the tree to
10062 		 * find matches. */
10063 		STRCPY(buf + len, "/**");
10064 		STRCPY(buf + len + 3, path_end);
10065 		++stardepth;
10066 		(void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
10067 		--stardepth;
10068 	    }
10069 
10070 	    STRCPY(buf + len, path_end);
10071 	    if (mch_has_exp_wildcard(path_end))
10072 	    {
10073 		/* need to expand another component of the path */
10074 		/* remove backslashes for the remaining components only */
10075 		(void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
10076 	    }
10077 	    else
10078 	    {
10079 		/* no more wildcards, check if there is a match */
10080 		/* remove backslashes for the remaining components only */
10081 		if (*path_end != 0)
10082 		    backslash_halve(buf + len + 1);
10083 		if (mch_getperm(buf) >= 0)	/* add existing file */
10084 		    addfile(gap, buf, flags);
10085 	    }
10086 	}
10087 
10088 # ifdef FEAT_MBYTE
10089 	if (wn != NULL)
10090 	{
10091 	    vim_free(p);
10092 	    ok = FindNextFileW(hFind, &wfb);
10093 	}
10094 	else
10095 # endif
10096 	    ok = FindNextFile(hFind, &fb);
10097 
10098 	/* If no more matches and no match was used, try expanding the name
10099 	 * itself.  Finds the long name of a short filename. */
10100 	if (!ok && matchname != NULL && gap->ga_len == start_len)
10101 	{
10102 	    STRCPY(s, matchname);
10103 	    FindClose(hFind);
10104 # ifdef FEAT_MBYTE
10105 	    if (wn != NULL)
10106 	    {
10107 		vim_free(wn);
10108 		wn = enc_to_utf16(buf, NULL);
10109 		if (wn != NULL)
10110 		    hFind = FindFirstFileW(wn, &wfb);
10111 	    }
10112 	    if (wn == NULL)
10113 # endif
10114 		hFind = FindFirstFile((LPCSTR)buf, &fb);
10115 	    ok = (hFind != INVALID_HANDLE_VALUE);
10116 	    vim_free(matchname);
10117 	    matchname = NULL;
10118 	}
10119     }
10120 
10121     FindClose(hFind);
10122 # ifdef FEAT_MBYTE
10123     vim_free(wn);
10124 # endif
10125     vim_free(buf);
10126     vim_regfree(regmatch.regprog);
10127     vim_free(matchname);
10128 
10129     matches = gap->ga_len - start_len;
10130     if (matches > 0)
10131 	qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
10132 						   sizeof(char_u *), pstrcmp);
10133     return matches;
10134 }
10135 
10136     int
10137 mch_expandpath(
10138     garray_T	*gap,
10139     char_u	*path,
10140     int		flags)		/* EW_* flags */
10141 {
10142     return dos_expandpath(gap, path, 0, flags, FALSE);
10143 }
10144 # endif /* WIN3264 */
10145 
10146 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
10147 	|| defined(PROTO)
10148 /*
10149  * Unix style wildcard expansion code.
10150  * It's here because it's used both for Unix and Mac.
10151  */
10152 static int	pstrcmp(const void *, const void *);
10153 
10154     static int
10155 pstrcmp(const void *a, const void *b)
10156 {
10157     return (pathcmp(*(char **)a, *(char **)b, -1));
10158 }
10159 
10160 /*
10161  * Recursively expand one path component into all matching files and/or
10162  * directories.  Adds matches to "gap".  Handles "*", "?", "[a-z]", "**", etc.
10163  * "path" has backslashes before chars that are not to be expanded, starting
10164  * at "path + wildoff".
10165  * Return the number of matches found.
10166  * NOTE: much of this is identical to dos_expandpath(), keep in sync!
10167  */
10168     int
10169 unix_expandpath(
10170     garray_T	*gap,
10171     char_u	*path,
10172     int		wildoff,
10173     int		flags,		/* EW_* flags */
10174     int		didstar)	/* expanded "**" once already */
10175 {
10176     char_u	*buf;
10177     char_u	*path_end;
10178     char_u	*p, *s, *e;
10179     int		start_len = gap->ga_len;
10180     char_u	*pat;
10181     regmatch_T	regmatch;
10182     int		starts_with_dot;
10183     int		matches;
10184     int		len;
10185     int		starstar = FALSE;
10186     static int	stardepth = 0;	    /* depth for "**" expansion */
10187 
10188     DIR		*dirp;
10189     struct dirent *dp;
10190 
10191     /* Expanding "**" may take a long time, check for CTRL-C. */
10192     if (stardepth > 0)
10193     {
10194 	ui_breakcheck();
10195 	if (got_int)
10196 	    return 0;
10197     }
10198 
10199     /* make room for file name */
10200     buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
10201     if (buf == NULL)
10202 	return 0;
10203 
10204     /*
10205      * Find the first part in the path name that contains a wildcard.
10206      * When EW_ICASE is set every letter is considered to be a wildcard.
10207      * Copy it into "buf", including the preceding characters.
10208      */
10209     p = buf;
10210     s = buf;
10211     e = NULL;
10212     path_end = path;
10213     while (*path_end != NUL)
10214     {
10215 	/* May ignore a wildcard that has a backslash before it; it will
10216 	 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
10217 	if (path_end >= path + wildoff && rem_backslash(path_end))
10218 	    *p++ = *path_end++;
10219 	else if (*path_end == '/')
10220 	{
10221 	    if (e != NULL)
10222 		break;
10223 	    s = p + 1;
10224 	}
10225 	else if (path_end >= path + wildoff
10226 			 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
10227 			     || (!p_fic && (flags & EW_ICASE)
10228 					     && isalpha(PTR2CHAR(path_end)))))
10229 	    e = p;
10230 #ifdef FEAT_MBYTE
10231 	if (has_mbyte)
10232 	{
10233 	    len = (*mb_ptr2len)(path_end);
10234 	    STRNCPY(p, path_end, len);
10235 	    p += len;
10236 	    path_end += len;
10237 	}
10238 	else
10239 #endif
10240 	    *p++ = *path_end++;
10241     }
10242     e = p;
10243     *e = NUL;
10244 
10245     /* Now we have one wildcard component between "s" and "e". */
10246     /* Remove backslashes between "wildoff" and the start of the wildcard
10247      * component. */
10248     for (p = buf + wildoff; p < s; ++p)
10249 	if (rem_backslash(p))
10250 	{
10251 	    STRMOVE(p, p + 1);
10252 	    --e;
10253 	    --s;
10254 	}
10255 
10256     /* Check for "**" between "s" and "e". */
10257     for (p = s; p < e; ++p)
10258 	if (p[0] == '*' && p[1] == '*')
10259 	    starstar = TRUE;
10260 
10261     /* convert the file pattern to a regexp pattern */
10262     starts_with_dot = *s == '.';
10263     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
10264     if (pat == NULL)
10265     {
10266 	vim_free(buf);
10267 	return 0;
10268     }
10269 
10270     /* compile the regexp into a program */
10271     if (flags & EW_ICASE)
10272 	regmatch.rm_ic = TRUE;		/* 'wildignorecase' set */
10273     else
10274 	regmatch.rm_ic = p_fic;	/* ignore case when 'fileignorecase' is set */
10275     if (flags & (EW_NOERROR | EW_NOTWILD))
10276 	++emsg_silent;
10277     regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
10278     if (flags & (EW_NOERROR | EW_NOTWILD))
10279 	--emsg_silent;
10280     vim_free(pat);
10281 
10282     if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
10283     {
10284 	vim_free(buf);
10285 	return 0;
10286     }
10287 
10288     /* If "**" is by itself, this is the first time we encounter it and more
10289      * is following then find matches without any directory. */
10290     if (!didstar && stardepth < 100 && starstar && e - s == 2
10291 							  && *path_end == '/')
10292     {
10293 	STRCPY(s, path_end + 1);
10294 	++stardepth;
10295 	(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
10296 	--stardepth;
10297     }
10298 
10299     /* open the directory for scanning */
10300     *s = NUL;
10301     dirp = opendir(*buf == NUL ? "." : (char *)buf);
10302 
10303     /* Find all matching entries */
10304     if (dirp != NULL)
10305     {
10306 	for (;;)
10307 	{
10308 	    dp = readdir(dirp);
10309 	    if (dp == NULL)
10310 		break;
10311 	    if ((dp->d_name[0] != '.' || starts_with_dot
10312 			|| ((flags & EW_DODOT)
10313 			    && dp->d_name[1] != NUL
10314 			    && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
10315 		 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
10316 					     (char_u *)dp->d_name, (colnr_T)0))
10317 		   || ((flags & EW_NOTWILD)
10318 		     && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
10319 	    {
10320 		STRCPY(s, dp->d_name);
10321 		len = STRLEN(buf);
10322 
10323 		if (starstar && stardepth < 100)
10324 		{
10325 		    /* For "**" in the pattern first go deeper in the tree to
10326 		     * find matches. */
10327 		    STRCPY(buf + len, "/**");
10328 		    STRCPY(buf + len + 3, path_end);
10329 		    ++stardepth;
10330 		    (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
10331 		    --stardepth;
10332 		}
10333 
10334 		STRCPY(buf + len, path_end);
10335 		if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
10336 		{
10337 		    /* need to expand another component of the path */
10338 		    /* remove backslashes for the remaining components only */
10339 		    (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
10340 		}
10341 		else
10342 		{
10343 		    stat_T  sb;
10344 
10345 		    /* no more wildcards, check if there is a match */
10346 		    /* remove backslashes for the remaining components only */
10347 		    if (*path_end != NUL)
10348 			backslash_halve(buf + len + 1);
10349 		    /* add existing file or symbolic link */
10350 		    if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
10351 						      : mch_getperm(buf) >= 0)
10352 		    {
10353 #ifdef MACOS_CONVERT
10354 			size_t precomp_len = STRLEN(buf)+1;
10355 			char_u *precomp_buf =
10356 			    mac_precompose_path(buf, precomp_len, &precomp_len);
10357 
10358 			if (precomp_buf)
10359 			{
10360 			    mch_memmove(buf, precomp_buf, precomp_len);
10361 			    vim_free(precomp_buf);
10362 			}
10363 #endif
10364 			addfile(gap, buf, flags);
10365 		    }
10366 		}
10367 	    }
10368 	}
10369 
10370 	closedir(dirp);
10371     }
10372 
10373     vim_free(buf);
10374     vim_regfree(regmatch.regprog);
10375 
10376     matches = gap->ga_len - start_len;
10377     if (matches > 0)
10378 	qsort(((char_u **)gap->ga_data) + start_len, matches,
10379 						   sizeof(char_u *), pstrcmp);
10380     return matches;
10381 }
10382 #endif
10383 
10384 #if defined(FEAT_SEARCHPATH)
10385 static int find_previous_pathsep(char_u *path, char_u **psep);
10386 static int is_unique(char_u *maybe_unique, garray_T *gap, int i);
10387 static void expand_path_option(char_u *curdir, garray_T	*gap);
10388 static char_u *get_path_cutoff(char_u *fname, garray_T *gap);
10389 static void uniquefy_paths(garray_T *gap, char_u *pattern);
10390 static int expand_in_path(garray_T *gap, char_u	*pattern, int flags);
10391 
10392 /*
10393  * Moves "*psep" back to the previous path separator in "path".
10394  * Returns FAIL is "*psep" ends up at the beginning of "path".
10395  */
10396     static int
10397 find_previous_pathsep(char_u *path, char_u **psep)
10398 {
10399     /* skip the current separator */
10400     if (*psep > path && vim_ispathsep(**psep))
10401 	--*psep;
10402 
10403     /* find the previous separator */
10404     while (*psep > path)
10405     {
10406 	if (vim_ispathsep(**psep))
10407 	    return OK;
10408 	MB_PTR_BACK(path, *psep);
10409     }
10410 
10411     return FAIL;
10412 }
10413 
10414 /*
10415  * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
10416  * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
10417  */
10418     static int
10419 is_unique(char_u *maybe_unique, garray_T *gap, int i)
10420 {
10421     int	    j;
10422     int	    candidate_len;
10423     int	    other_path_len;
10424     char_u  **other_paths = (char_u **)gap->ga_data;
10425     char_u  *rival;
10426 
10427     for (j = 0; j < gap->ga_len; j++)
10428     {
10429 	if (j == i)
10430 	    continue;  /* don't compare it with itself */
10431 
10432 	candidate_len = (int)STRLEN(maybe_unique);
10433 	other_path_len = (int)STRLEN(other_paths[j]);
10434 	if (other_path_len < candidate_len)
10435 	    continue;  /* it's different when it's shorter */
10436 
10437 	rival = other_paths[j] + other_path_len - candidate_len;
10438 	if (fnamecmp(maybe_unique, rival) == 0
10439 		&& (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
10440 	    return FALSE;  /* match */
10441     }
10442 
10443     return TRUE;  /* no match found */
10444 }
10445 
10446 /*
10447  * Split the 'path' option into an array of strings in garray_T.  Relative
10448  * paths are expanded to their equivalent fullpath.  This includes the "."
10449  * (relative to current buffer directory) and empty path (relative to current
10450  * directory) notations.
10451  *
10452  * TODO: handle upward search (;) and path limiter (**N) notations by
10453  * expanding each into their equivalent path(s).
10454  */
10455     static void
10456 expand_path_option(char_u *curdir, garray_T *gap)
10457 {
10458     char_u	*path_option = *curbuf->b_p_path == NUL
10459 						  ? p_path : curbuf->b_p_path;
10460     char_u	*buf;
10461     char_u	*p;
10462     int		len;
10463 
10464     if ((buf = alloc((int)MAXPATHL)) == NULL)
10465 	return;
10466 
10467     while (*path_option != NUL)
10468     {
10469 	copy_option_part(&path_option, buf, MAXPATHL, " ,");
10470 
10471 	if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
10472 	{
10473 	    /* Relative to current buffer:
10474 	     * "/path/file" + "." -> "/path/"
10475 	     * "/path/file"  + "./subdir" -> "/path/subdir" */
10476 	    if (curbuf->b_ffname == NULL)
10477 		continue;
10478 	    p = gettail(curbuf->b_ffname);
10479 	    len = (int)(p - curbuf->b_ffname);
10480 	    if (len + (int)STRLEN(buf) >= MAXPATHL)
10481 		continue;
10482 	    if (buf[1] == NUL)
10483 		buf[len] = NUL;
10484 	    else
10485 		STRMOVE(buf + len, buf + 2);
10486 	    mch_memmove(buf, curbuf->b_ffname, len);
10487 	    simplify_filename(buf);
10488 	}
10489 	else if (buf[0] == NUL)
10490 	    /* relative to current directory */
10491 	    STRCPY(buf, curdir);
10492 	else if (path_with_url(buf))
10493 	    /* URL can't be used here */
10494 	    continue;
10495 	else if (!mch_isFullName(buf))
10496 	{
10497 	    /* Expand relative path to their full path equivalent */
10498 	    len = (int)STRLEN(curdir);
10499 	    if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
10500 		continue;
10501 	    STRMOVE(buf + len + 1, buf);
10502 	    STRCPY(buf, curdir);
10503 	    buf[len] = PATHSEP;
10504 	    simplify_filename(buf);
10505 	}
10506 
10507 	if (ga_grow(gap, 1) == FAIL)
10508 	    break;
10509 
10510 # if defined(MSWIN)
10511 	/* Avoid the path ending in a backslash, it fails when a comma is
10512 	 * appended. */
10513 	len = (int)STRLEN(buf);
10514 	if (buf[len - 1] == '\\')
10515 	    buf[len - 1] = '/';
10516 # endif
10517 
10518 	p = vim_strsave(buf);
10519 	if (p == NULL)
10520 	    break;
10521 	((char_u **)gap->ga_data)[gap->ga_len++] = p;
10522     }
10523 
10524     vim_free(buf);
10525 }
10526 
10527 /*
10528  * Returns a pointer to the file or directory name in "fname" that matches the
10529  * longest path in "ga"p, or NULL if there is no match. For example:
10530  *
10531  *    path: /foo/bar/baz
10532  *   fname: /foo/bar/baz/quux.txt
10533  * returns:		 ^this
10534  */
10535     static char_u *
10536 get_path_cutoff(char_u *fname, garray_T *gap)
10537 {
10538     int	    i;
10539     int	    maxlen = 0;
10540     char_u  **path_part = (char_u **)gap->ga_data;
10541     char_u  *cutoff = NULL;
10542 
10543     for (i = 0; i < gap->ga_len; i++)
10544     {
10545 	int j = 0;
10546 
10547 	while ((fname[j] == path_part[i][j]
10548 # if defined(MSWIN)
10549 		|| (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10550 #endif
10551 			     ) && fname[j] != NUL && path_part[i][j] != NUL)
10552 	    j++;
10553 	if (j > maxlen)
10554 	{
10555 	    maxlen = j;
10556 	    cutoff = &fname[j];
10557 	}
10558     }
10559 
10560     /* skip to the file or directory name */
10561     if (cutoff != NULL)
10562 	while (vim_ispathsep(*cutoff))
10563 	    MB_PTR_ADV(cutoff);
10564 
10565     return cutoff;
10566 }
10567 
10568 /*
10569  * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10570  * that they are unique with respect to each other while conserving the part
10571  * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
10572  */
10573     static void
10574 uniquefy_paths(garray_T *gap, char_u *pattern)
10575 {
10576     int		i;
10577     int		len;
10578     char_u	**fnames = (char_u **)gap->ga_data;
10579     int		sort_again = FALSE;
10580     char_u	*pat;
10581     char_u      *file_pattern;
10582     char_u	*curdir;
10583     regmatch_T	regmatch;
10584     garray_T	path_ga;
10585     char_u	**in_curdir = NULL;
10586     char_u	*short_name;
10587 
10588     remove_duplicates(gap);
10589     ga_init2(&path_ga, (int)sizeof(char_u *), 1);
10590 
10591     /*
10592      * We need to prepend a '*' at the beginning of file_pattern so that the
10593      * regex matches anywhere in the path. FIXME: is this valid for all
10594      * possible patterns?
10595      */
10596     len = (int)STRLEN(pattern);
10597     file_pattern = alloc(len + 2);
10598     if (file_pattern == NULL)
10599 	return;
10600     file_pattern[0] = '*';
10601     file_pattern[1] = NUL;
10602     STRCAT(file_pattern, pattern);
10603     pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10604     vim_free(file_pattern);
10605     if (pat == NULL)
10606 	return;
10607 
10608     regmatch.rm_ic = TRUE;		/* always ignore case */
10609     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10610     vim_free(pat);
10611     if (regmatch.regprog == NULL)
10612 	return;
10613 
10614     if ((curdir = alloc((int)(MAXPATHL))) == NULL)
10615 	goto theend;
10616     mch_dirname(curdir, MAXPATHL);
10617     expand_path_option(curdir, &path_ga);
10618 
10619     in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
10620     if (in_curdir == NULL)
10621 	goto theend;
10622 
10623     for (i = 0; i < gap->ga_len && !got_int; i++)
10624     {
10625 	char_u	    *path = fnames[i];
10626 	int	    is_in_curdir;
10627 	char_u	    *dir_end = gettail_dir(path);
10628 	char_u	    *pathsep_p;
10629 	char_u	    *path_cutoff;
10630 
10631 	len = (int)STRLEN(path);
10632 	is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
10633 					     && curdir[dir_end - path] == NUL;
10634 	if (is_in_curdir)
10635 	    in_curdir[i] = vim_strsave(path);
10636 
10637 	/* Shorten the filename while maintaining its uniqueness */
10638 	path_cutoff = get_path_cutoff(path, &path_ga);
10639 
10640 	/* Don't assume all files can be reached without path when search
10641 	 * pattern starts with star star slash, so only remove path_cutoff
10642 	 * when possible. */
10643 	if (pattern[0] == '*' && pattern[1] == '*'
10644 		&& vim_ispathsep_nocolon(pattern[2])
10645 		&& path_cutoff != NULL
10646 		&& vim_regexec(&regmatch, path_cutoff, (colnr_T)0)
10647 		&& is_unique(path_cutoff, gap, i))
10648 	{
10649 	    sort_again = TRUE;
10650 	    mch_memmove(path, path_cutoff, STRLEN(path_cutoff) + 1);
10651 	}
10652 	else
10653 	{
10654 	    /* Here all files can be reached without path, so get shortest
10655 	     * unique path.  We start at the end of the path. */
10656 	    pathsep_p = path + len - 1;
10657 
10658 	    while (find_previous_pathsep(path, &pathsep_p))
10659 		if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10660 			&& is_unique(pathsep_p + 1, gap, i)
10661 			&& path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10662 		{
10663 		    sort_again = TRUE;
10664 		    mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10665 		    break;
10666 		}
10667 	}
10668 
10669 	if (mch_isFullName(path))
10670 	{
10671 	    /*
10672 	     * Last resort: shorten relative to curdir if possible.
10673 	     * 'possible' means:
10674 	     * 1. It is under the current directory.
10675 	     * 2. The result is actually shorter than the original.
10676 	     *
10677 	     *	    Before		  curdir	After
10678 	     *	    /foo/bar/file.txt	  /foo/bar	./file.txt
10679 	     *	    c:\foo\bar\file.txt   c:\foo\bar	.\file.txt
10680 	     *	    /file.txt		  /		/file.txt
10681 	     *	    c:\file.txt		  c:\		.\file.txt
10682 	     */
10683 	    short_name = shorten_fname(path, curdir);
10684 	    if (short_name != NULL && short_name > path + 1
10685 #if defined(MSWIN)
10686 		    /* On windows,
10687 		     *	    shorten_fname("c:\a\a.txt", "c:\a\b")
10688 		     * returns "\a\a.txt", which is not really the short
10689 		     * name, hence: */
10690 		    && !vim_ispathsep(*short_name)
10691 #endif
10692 		)
10693 	    {
10694 		STRCPY(path, ".");
10695 		add_pathsep(path);
10696 		STRMOVE(path + STRLEN(path), short_name);
10697 	    }
10698 	}
10699 	ui_breakcheck();
10700     }
10701 
10702     /* Shorten filenames in /in/current/directory/{filename} */
10703     for (i = 0; i < gap->ga_len && !got_int; i++)
10704     {
10705 	char_u *rel_path;
10706 	char_u *path = in_curdir[i];
10707 
10708 	if (path == NULL)
10709 	    continue;
10710 
10711 	/* If the {filename} is not unique, change it to ./{filename}.
10712 	 * Else reduce it to {filename} */
10713 	short_name = shorten_fname(path, curdir);
10714 	if (short_name == NULL)
10715 	    short_name = path;
10716 	if (is_unique(short_name, gap, i))
10717 	{
10718 	    STRCPY(fnames[i], short_name);
10719 	    continue;
10720 	}
10721 
10722 	rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10723 	if (rel_path == NULL)
10724 	    goto theend;
10725 	STRCPY(rel_path, ".");
10726 	add_pathsep(rel_path);
10727 	STRCAT(rel_path, short_name);
10728 
10729 	vim_free(fnames[i]);
10730 	fnames[i] = rel_path;
10731 	sort_again = TRUE;
10732 	ui_breakcheck();
10733     }
10734 
10735 theend:
10736     vim_free(curdir);
10737     if (in_curdir != NULL)
10738     {
10739 	for (i = 0; i < gap->ga_len; i++)
10740 	    vim_free(in_curdir[i]);
10741 	vim_free(in_curdir);
10742     }
10743     ga_clear_strings(&path_ga);
10744     vim_regfree(regmatch.regprog);
10745 
10746     if (sort_again)
10747 	remove_duplicates(gap);
10748 }
10749 
10750 /*
10751  * Calls globpath() with 'path' values for the given pattern and stores the
10752  * result in "gap".
10753  * Returns the total number of matches.
10754  */
10755     static int
10756 expand_in_path(
10757     garray_T	*gap,
10758     char_u	*pattern,
10759     int		flags)		/* EW_* flags */
10760 {
10761     char_u	*curdir;
10762     garray_T	path_ga;
10763     char_u	*paths = NULL;
10764 
10765     if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
10766 	return 0;
10767     mch_dirname(curdir, MAXPATHL);
10768 
10769     ga_init2(&path_ga, (int)sizeof(char_u *), 1);
10770     expand_path_option(curdir, &path_ga);
10771     vim_free(curdir);
10772     if (path_ga.ga_len == 0)
10773 	return 0;
10774 
10775     paths = ga_concat_strings(&path_ga, ",");
10776     ga_clear_strings(&path_ga);
10777     if (paths == NULL)
10778 	return 0;
10779 
10780     globpath(paths, pattern, gap, (flags & EW_ICASE) ? WILD_ICASE : 0);
10781     vim_free(paths);
10782 
10783     return gap->ga_len;
10784 }
10785 #endif
10786 
10787 #if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10788 /*
10789  * Sort "gap" and remove duplicate entries.  "gap" is expected to contain a
10790  * list of file names in allocated memory.
10791  */
10792     void
10793 remove_duplicates(garray_T *gap)
10794 {
10795     int	    i;
10796     int	    j;
10797     char_u  **fnames = (char_u **)gap->ga_data;
10798 
10799     sort_strings(fnames, gap->ga_len);
10800     for (i = gap->ga_len - 1; i > 0; --i)
10801 	if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10802 	{
10803 	    vim_free(fnames[i]);
10804 	    for (j = i + 1; j < gap->ga_len; ++j)
10805 		fnames[j - 1] = fnames[j];
10806 	    --gap->ga_len;
10807 	}
10808 }
10809 #endif
10810 
10811 static int has_env_var(char_u *p);
10812 
10813 /*
10814  * Return TRUE if "p" contains what looks like an environment variable.
10815  * Allowing for escaping.
10816  */
10817     static int
10818 has_env_var(char_u *p)
10819 {
10820     for ( ; *p; MB_PTR_ADV(p))
10821     {
10822 	if (*p == '\\' && p[1] != NUL)
10823 	    ++p;
10824 	else if (vim_strchr((char_u *)
10825 #if defined(MSWIN)
10826 				    "$%"
10827 #else
10828 				    "$"
10829 #endif
10830 					, *p) != NULL)
10831 	    return TRUE;
10832     }
10833     return FALSE;
10834 }
10835 
10836 #ifdef SPECIAL_WILDCHAR
10837 static int has_special_wildchar(char_u *p);
10838 
10839 /*
10840  * Return TRUE if "p" contains a special wildcard character, one that Vim
10841  * cannot expand, requires using a shell.
10842  */
10843     static int
10844 has_special_wildchar(char_u *p)
10845 {
10846     for ( ; *p; MB_PTR_ADV(p))
10847     {
10848 	/* Allow for escaping. */
10849 	if (*p == '\\' && p[1] != NUL)
10850 	    ++p;
10851 	else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
10852 	    return TRUE;
10853     }
10854     return FALSE;
10855 }
10856 #endif
10857 
10858 /*
10859  * Generic wildcard expansion code.
10860  *
10861  * Characters in "pat" that should not be expanded must be preceded with a
10862  * backslash. E.g., "/path\ with\ spaces/my\*star*"
10863  *
10864  * Return FAIL when no single file was found.  In this case "num_file" is not
10865  * set, and "file" may contain an error message.
10866  * Return OK when some files found.  "num_file" is set to the number of
10867  * matches, "file" to the array of matches.  Call FreeWild() later.
10868  */
10869     int
10870 gen_expand_wildcards(
10871     int		num_pat,	/* number of input patterns */
10872     char_u	**pat,		/* array of input patterns */
10873     int		*num_file,	/* resulting number of files */
10874     char_u	***file,	/* array of resulting files */
10875     int		flags)		/* EW_* flags */
10876 {
10877     int			i;
10878     garray_T		ga;
10879     char_u		*p;
10880     static int		recursive = FALSE;
10881     int			add_pat;
10882     int			retval = OK;
10883 #if defined(FEAT_SEARCHPATH)
10884     int			did_expand_in_path = FALSE;
10885 #endif
10886 
10887     /*
10888      * expand_env() is called to expand things like "~user".  If this fails,
10889      * it calls ExpandOne(), which brings us back here.  In this case, always
10890      * call the machine specific expansion function, if possible.  Otherwise,
10891      * return FAIL.
10892      */
10893     if (recursive)
10894 #ifdef SPECIAL_WILDCHAR
10895 	return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10896 #else
10897 	return FAIL;
10898 #endif
10899 
10900 #ifdef SPECIAL_WILDCHAR
10901     /*
10902      * If there are any special wildcard characters which we cannot handle
10903      * here, call machine specific function for all the expansion.  This
10904      * avoids starting the shell for each argument separately.
10905      * For `=expr` do use the internal function.
10906      */
10907     for (i = 0; i < num_pat; i++)
10908     {
10909 	if (has_special_wildchar(pat[i])
10910 # ifdef VIM_BACKTICK
10911 		&& !(vim_backtick(pat[i]) && pat[i][1] == '=')
10912 # endif
10913 	   )
10914 	    return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10915     }
10916 #endif
10917 
10918     recursive = TRUE;
10919 
10920     /*
10921      * The matching file names are stored in a growarray.  Init it empty.
10922      */
10923     ga_init2(&ga, (int)sizeof(char_u *), 30);
10924 
10925     for (i = 0; i < num_pat; ++i)
10926     {
10927 	add_pat = -1;
10928 	p = pat[i];
10929 
10930 #ifdef VIM_BACKTICK
10931 	if (vim_backtick(p))
10932 	{
10933 	    add_pat = expand_backtick(&ga, p, flags);
10934 	    if (add_pat == -1)
10935 		retval = FAIL;
10936 	}
10937 	else
10938 #endif
10939 	{
10940 	    /*
10941 	     * First expand environment variables, "~/" and "~user/".
10942 	     */
10943 	    if (has_env_var(p) || *p == '~')
10944 	    {
10945 		p = expand_env_save_opt(p, TRUE);
10946 		if (p == NULL)
10947 		    p = pat[i];
10948 #ifdef UNIX
10949 		/*
10950 		 * On Unix, if expand_env() can't expand an environment
10951 		 * variable, use the shell to do that.  Discard previously
10952 		 * found file names and start all over again.
10953 		 */
10954 		else if (has_env_var(p) || *p == '~')
10955 		{
10956 		    vim_free(p);
10957 		    ga_clear_strings(&ga);
10958 		    i = mch_expand_wildcards(num_pat, pat, num_file, file,
10959 							 flags|EW_KEEPDOLLAR);
10960 		    recursive = FALSE;
10961 		    return i;
10962 		}
10963 #endif
10964 	    }
10965 
10966 	    /*
10967 	     * If there are wildcards: Expand file names and add each match to
10968 	     * the list.  If there is no match, and EW_NOTFOUND is given, add
10969 	     * the pattern.
10970 	     * If there are no wildcards: Add the file name if it exists or
10971 	     * when EW_NOTFOUND is given.
10972 	     */
10973 	    if (mch_has_exp_wildcard(p))
10974 	    {
10975 #if defined(FEAT_SEARCHPATH)
10976 		if ((flags & EW_PATH)
10977 			&& !mch_isFullName(p)
10978 			&& !(p[0] == '.'
10979 			    && (vim_ispathsep(p[1])
10980 				|| (p[1] == '.' && vim_ispathsep(p[2]))))
10981 		   )
10982 		{
10983 		    /* :find completion where 'path' is used.
10984 		     * Recursiveness is OK here. */
10985 		    recursive = FALSE;
10986 		    add_pat = expand_in_path(&ga, p, flags);
10987 		    recursive = TRUE;
10988 		    did_expand_in_path = TRUE;
10989 		}
10990 		else
10991 #endif
10992 		    add_pat = mch_expandpath(&ga, p, flags);
10993 	    }
10994 	}
10995 
10996 	if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10997 	{
10998 	    char_u	*t = backslash_halve_save(p);
10999 
11000 #if defined(MACOS_CLASSIC)
11001 	    slash_to_colon(t);
11002 #endif
11003 	    /* When EW_NOTFOUND is used, always add files and dirs.  Makes
11004 	     * "vim c:/" work. */
11005 	    if (flags & EW_NOTFOUND)
11006 		addfile(&ga, t, flags | EW_DIR | EW_FILE);
11007 	    else
11008 		addfile(&ga, t, flags);
11009 	    vim_free(t);
11010 	}
11011 
11012 #if defined(FEAT_SEARCHPATH)
11013 	if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
11014 	    uniquefy_paths(&ga, p);
11015 #endif
11016 	if (p != pat[i])
11017 	    vim_free(p);
11018     }
11019 
11020     *num_file = ga.ga_len;
11021     *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
11022 
11023     recursive = FALSE;
11024 
11025     return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
11026 }
11027 
11028 # ifdef VIM_BACKTICK
11029 
11030 /*
11031  * Return TRUE if we can expand this backtick thing here.
11032  */
11033     static int
11034 vim_backtick(char_u *p)
11035 {
11036     return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
11037 }
11038 
11039 /*
11040  * Expand an item in `backticks` by executing it as a command.
11041  * Currently only works when pat[] starts and ends with a `.
11042  * Returns number of file names found, -1 if an error is encountered.
11043  */
11044     static int
11045 expand_backtick(
11046     garray_T	*gap,
11047     char_u	*pat,
11048     int		flags)	/* EW_* flags */
11049 {
11050     char_u	*p;
11051     char_u	*cmd;
11052     char_u	*buffer;
11053     int		cnt = 0;
11054     int		i;
11055 
11056     /* Create the command: lop off the backticks. */
11057     cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
11058     if (cmd == NULL)
11059 	return -1;
11060 
11061 #ifdef FEAT_EVAL
11062     if (*cmd == '=')	    /* `={expr}`: Expand expression */
11063 	buffer = eval_to_string(cmd + 1, &p, TRUE);
11064     else
11065 #endif
11066 	buffer = get_cmd_output(cmd, NULL,
11067 				(flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
11068     vim_free(cmd);
11069     if (buffer == NULL)
11070 	return -1;
11071 
11072     cmd = buffer;
11073     while (*cmd != NUL)
11074     {
11075 	cmd = skipwhite(cmd);		/* skip over white space */
11076 	p = cmd;
11077 	while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
11078 	    ++p;
11079 	/* add an entry if it is not empty */
11080 	if (p > cmd)
11081 	{
11082 	    i = *p;
11083 	    *p = NUL;
11084 	    addfile(gap, cmd, flags);
11085 	    *p = i;
11086 	    ++cnt;
11087 	}
11088 	cmd = p;
11089 	while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
11090 	    ++cmd;
11091     }
11092 
11093     vim_free(buffer);
11094     return cnt;
11095 }
11096 # endif /* VIM_BACKTICK */
11097 
11098 /*
11099  * Add a file to a file list.  Accepted flags:
11100  * EW_DIR	add directories
11101  * EW_FILE	add files
11102  * EW_EXEC	add executable files
11103  * EW_NOTFOUND	add even when it doesn't exist
11104  * EW_ADDSLASH	add slash after directory name
11105  * EW_ALLLINKS	add symlink also when the referred file does not exist
11106  */
11107     void
11108 addfile(
11109     garray_T	*gap,
11110     char_u	*f,	/* filename */
11111     int		flags)
11112 {
11113     char_u	*p;
11114     int		isdir;
11115     stat_T	sb;
11116 
11117     /* if the file/dir/link doesn't exist, may not add it */
11118     if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
11119 			? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
11120 	return;
11121 
11122 #ifdef FNAME_ILLEGAL
11123     /* if the file/dir contains illegal characters, don't add it */
11124     if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
11125 	return;
11126 #endif
11127 
11128     isdir = mch_isdir(f);
11129     if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
11130 	return;
11131 
11132     /* If the file isn't executable, may not add it.  Do accept directories.
11133      * When invoked from expand_shellcmd() do not use $PATH. */
11134     if (!isdir && (flags & EW_EXEC)
11135 			     && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
11136 	return;
11137 
11138     /* Make room for another item in the file list. */
11139     if (ga_grow(gap, 1) == FAIL)
11140 	return;
11141 
11142     p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
11143     if (p == NULL)
11144 	return;
11145 
11146     STRCPY(p, f);
11147 #ifdef BACKSLASH_IN_FILENAME
11148     slash_adjust(p);
11149 #endif
11150     /*
11151      * Append a slash or backslash after directory names if none is present.
11152      */
11153 #ifndef DONT_ADD_PATHSEP_TO_DIR
11154     if (isdir && (flags & EW_ADDSLASH))
11155 	add_pathsep(p);
11156 #endif
11157     ((char_u **)gap->ga_data)[gap->ga_len++] = p;
11158 }
11159 #endif /* !NO_EXPANDPATH */
11160 
11161 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
11162 
11163 #ifndef SEEK_SET
11164 # define SEEK_SET 0
11165 #endif
11166 #ifndef SEEK_END
11167 # define SEEK_END 2
11168 #endif
11169 
11170 /*
11171  * Get the stdout of an external command.
11172  * If "ret_len" is NULL replace NUL characters with NL.  When "ret_len" is not
11173  * NULL store the length there.
11174  * Returns an allocated string, or NULL for error.
11175  */
11176     char_u *
11177 get_cmd_output(
11178     char_u	*cmd,
11179     char_u	*infile,	/* optional input file name */
11180     int		flags,		/* can be SHELL_SILENT */
11181     int		*ret_len)
11182 {
11183     char_u	*tempname;
11184     char_u	*command;
11185     char_u	*buffer = NULL;
11186     int		len;
11187     int		i = 0;
11188     FILE	*fd;
11189 
11190     if (check_restricted() || check_secure())
11191 	return NULL;
11192 
11193     /* get a name for the temp file */
11194     if ((tempname = vim_tempname('o', FALSE)) == NULL)
11195     {
11196 	EMSG(_(e_notmp));
11197 	return NULL;
11198     }
11199 
11200     /* Add the redirection stuff */
11201     command = make_filter_cmd(cmd, infile, tempname);
11202     if (command == NULL)
11203 	goto done;
11204 
11205     /*
11206      * Call the shell to execute the command (errors are ignored).
11207      * Don't check timestamps here.
11208      */
11209     ++no_check_timestamps;
11210     call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
11211     --no_check_timestamps;
11212 
11213     vim_free(command);
11214 
11215     /*
11216      * read the names from the file into memory
11217      */
11218 # ifdef VMS
11219     /* created temporary file is not always readable as binary */
11220     fd = mch_fopen((char *)tempname, "r");
11221 # else
11222     fd = mch_fopen((char *)tempname, READBIN);
11223 # endif
11224 
11225     if (fd == NULL)
11226     {
11227 	EMSG2(_(e_notopen), tempname);
11228 	goto done;
11229     }
11230 
11231     fseek(fd, 0L, SEEK_END);
11232     len = ftell(fd);		    /* get size of temp file */
11233     fseek(fd, 0L, SEEK_SET);
11234 
11235     buffer = alloc(len + 1);
11236     if (buffer != NULL)
11237 	i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
11238     fclose(fd);
11239     mch_remove(tempname);
11240     if (buffer == NULL)
11241 	goto done;
11242 #ifdef VMS
11243     len = i;	/* VMS doesn't give us what we asked for... */
11244 #endif
11245     if (i != len)
11246     {
11247 	EMSG2(_(e_notread), tempname);
11248 	vim_free(buffer);
11249 	buffer = NULL;
11250     }
11251     else if (ret_len == NULL)
11252     {
11253 	/* Change NUL into SOH, otherwise the string is truncated. */
11254 	for (i = 0; i < len; ++i)
11255 	    if (buffer[i] == NUL)
11256 		buffer[i] = 1;
11257 
11258 	buffer[len] = NUL;	/* make sure the buffer is terminated */
11259     }
11260     else
11261 	*ret_len = len;
11262 
11263 done:
11264     vim_free(tempname);
11265     return buffer;
11266 }
11267 #endif
11268 
11269 /*
11270  * Free the list of files returned by expand_wildcards() or other expansion
11271  * functions.
11272  */
11273     void
11274 FreeWild(int count, char_u **files)
11275 {
11276     if (count <= 0 || files == NULL)
11277 	return;
11278     while (count--)
11279 	vim_free(files[count]);
11280     vim_free(files);
11281 }
11282 
11283 /*
11284  * Return TRUE when need to go to Insert mode because of 'insertmode'.
11285  * Don't do this when still processing a command or a mapping.
11286  * Don't do this when inside a ":normal" command.
11287  */
11288     int
11289 goto_im(void)
11290 {
11291     return (p_im && stuff_empty() && typebuf_typed());
11292 }
11293 
11294 /*
11295  * Returns the isolated name of the shell in allocated memory:
11296  * - Skip beyond any path.  E.g., "/usr/bin/csh -f" -> "csh -f".
11297  * - Remove any argument.  E.g., "csh -f" -> "csh".
11298  * But don't allow a space in the path, so that this works:
11299  *   "/usr/bin/csh --rcfile ~/.cshrc"
11300  * But don't do that for Windows, it's common to have a space in the path.
11301  */
11302     char_u *
11303 get_isolated_shell_name(void)
11304 {
11305     char_u *p;
11306 
11307 #ifdef WIN3264
11308     p = gettail(p_sh);
11309     p = vim_strnsave(p, (int)(skiptowhite(p) - p));
11310 #else
11311     p = skiptowhite(p_sh);
11312     if (*p == NUL)
11313     {
11314 	/* No white space, use the tail. */
11315 	p = vim_strsave(gettail(p_sh));
11316     }
11317     else
11318     {
11319 	char_u  *p1, *p2;
11320 
11321 	/* Find the last path separator before the space. */
11322 	p1 = p_sh;
11323 	for (p2 = p_sh; p2 < p; MB_PTR_ADV(p2))
11324 	    if (vim_ispathsep(*p2))
11325 		p1 = p2 + 1;
11326 	p = vim_strnsave(p1, (int)(p - p1));
11327     }
11328 #endif
11329     return p;
11330 }
11331