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