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