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