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