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