xref: /vim-8.2.3635/src/misc1.c (revision f0b03c4e)
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_MOUSEMOVE
3349 	|| c == K_MIDDLEMOUSE
3350 	|| c == K_MIDDLEDRAG
3351 	|| c == K_MIDDLERELEASE
3352 	|| c == K_RIGHTMOUSE
3353 	|| c == K_RIGHTDRAG
3354 	|| c == K_RIGHTRELEASE
3355 	|| c == K_MOUSEDOWN
3356 	|| c == K_MOUSEUP
3357 	|| c == K_MOUSELEFT
3358 	|| c == K_MOUSERIGHT
3359 	|| c == K_X1MOUSE
3360 	|| c == K_X1DRAG
3361 	|| c == K_X1RELEASE
3362 	|| c == K_X2MOUSE
3363 	|| c == K_X2DRAG
3364 	|| c == K_X2RELEASE;
3365 }
3366 #endif
3367 
3368 /*
3369  * Get a key stroke directly from the user.
3370  * Ignores mouse clicks and scrollbar events, except a click for the left
3371  * button (used at the more prompt).
3372  * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3373  * Disadvantage: typeahead is ignored.
3374  * Translates the interrupt character for unix to ESC.
3375  */
3376     int
3377 get_keystroke(void)
3378 {
3379     char_u	*buf = NULL;
3380     int		buflen = 150;
3381     int		maxlen;
3382     int		len = 0;
3383     int		n;
3384     int		save_mapped_ctrl_c = mapped_ctrl_c;
3385     int		waited = 0;
3386 
3387     mapped_ctrl_c = FALSE;	/* mappings are not used here */
3388     for (;;)
3389     {
3390 	cursor_on();
3391 	out_flush();
3392 
3393 	/* Leave some room for check_termcode() to insert a key code into (max
3394 	 * 5 chars plus NUL).  And fix_input_buffer() can triple the number of
3395 	 * bytes. */
3396 	maxlen = (buflen - 6 - len) / 3;
3397 	if (buf == NULL)
3398 	    buf = alloc(buflen);
3399 	else if (maxlen < 10)
3400 	{
3401 	    char_u  *t_buf = buf;
3402 
3403 	    /* Need some more space. This might happen when receiving a long
3404 	     * escape sequence. */
3405 	    buflen += 100;
3406 	    buf = vim_realloc(buf, buflen);
3407 	    if (buf == NULL)
3408 		vim_free(t_buf);
3409 	    maxlen = (buflen - 6 - len) / 3;
3410 	}
3411 	if (buf == NULL)
3412 	{
3413 	    do_outofmem_msg((long_u)buflen);
3414 	    return ESC;  /* panic! */
3415 	}
3416 
3417 	/* First time: blocking wait.  Second time: wait up to 100ms for a
3418 	 * terminal code to complete. */
3419 	n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
3420 	if (n > 0)
3421 	{
3422 	    /* Replace zero and CSI by a special key code. */
3423 	    n = fix_input_buffer(buf + len, n);
3424 	    len += n;
3425 	    waited = 0;
3426 	}
3427 	else if (len > 0)
3428 	    ++waited;	    /* keep track of the waiting time */
3429 
3430 	/* Incomplete termcode and not timed out yet: get more characters */
3431 	if ((n = check_termcode(1, buf, buflen, &len)) < 0
3432 	       && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
3433 	    continue;
3434 
3435 	if (n == KEYLEN_REMOVED)  /* key code removed */
3436 	{
3437 	    if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
3438 	    {
3439 		/* Redrawing was postponed, do it now. */
3440 		update_screen(0);
3441 		setcursor(); /* put cursor back where it belongs */
3442 	    }
3443 	    continue;
3444 	}
3445 	if (n > 0)		/* found a termcode: adjust length */
3446 	    len = n;
3447 	if (len == 0)		/* nothing typed yet */
3448 	    continue;
3449 
3450 	/* Handle modifier and/or special key code. */
3451 	n = buf[0];
3452 	if (n == K_SPECIAL)
3453 	{
3454 	    n = TO_SPECIAL(buf[1], buf[2]);
3455 	    if (buf[1] == KS_MODIFIER
3456 		    || n == K_IGNORE
3457 #ifdef FEAT_MOUSE
3458 		    || (is_mouse_key(n) && n != K_LEFTMOUSE)
3459 #endif
3460 #ifdef FEAT_GUI
3461 		    || n == K_VER_SCROLLBAR
3462 		    || n == K_HOR_SCROLLBAR
3463 #endif
3464 	       )
3465 	    {
3466 		if (buf[1] == KS_MODIFIER)
3467 		    mod_mask = buf[2];
3468 		len -= 3;
3469 		if (len > 0)
3470 		    mch_memmove(buf, buf + 3, (size_t)len);
3471 		continue;
3472 	    }
3473 	    break;
3474 	}
3475 #ifdef FEAT_MBYTE
3476 	if (has_mbyte)
3477 	{
3478 	    if (MB_BYTE2LEN(n) > len)
3479 		continue;	/* more bytes to get */
3480 	    buf[len >= buflen ? buflen - 1 : len] = NUL;
3481 	    n = (*mb_ptr2char)(buf);
3482 	}
3483 #endif
3484 #ifdef UNIX
3485 	if (n == intr_char)
3486 	    n = ESC;
3487 #endif
3488 	break;
3489     }
3490     vim_free(buf);
3491 
3492     mapped_ctrl_c = save_mapped_ctrl_c;
3493     return n;
3494 }
3495 
3496 /*
3497  * Get a number from the user.
3498  * When "mouse_used" is not NULL allow using the mouse.
3499  */
3500     int
3501 get_number(
3502     int	    colon,			/* allow colon to abort */
3503     int	    *mouse_used)
3504 {
3505     int	n = 0;
3506     int	c;
3507     int typed = 0;
3508 
3509     if (mouse_used != NULL)
3510 	*mouse_used = FALSE;
3511 
3512     /* When not printing messages, the user won't know what to type, return a
3513      * zero (as if CR was hit). */
3514     if (msg_silent != 0)
3515 	return 0;
3516 
3517 #ifdef USE_ON_FLY_SCROLL
3518     dont_scroll = TRUE;		/* disallow scrolling here */
3519 #endif
3520     ++no_mapping;
3521     ++allow_keys;		/* no mapping here, but recognize keys */
3522     for (;;)
3523     {
3524 	windgoto(msg_row, msg_col);
3525 	c = safe_vgetc();
3526 	if (VIM_ISDIGIT(c))
3527 	{
3528 	    n = n * 10 + c - '0';
3529 	    msg_putchar(c);
3530 	    ++typed;
3531 	}
3532 	else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3533 	{
3534 	    if (typed > 0)
3535 	    {
3536 		MSG_PUTS("\b \b");
3537 		--typed;
3538 	    }
3539 	    n /= 10;
3540 	}
3541 #ifdef FEAT_MOUSE
3542 	else if (mouse_used != NULL && c == K_LEFTMOUSE)
3543 	{
3544 	    *mouse_used = TRUE;
3545 	    n = mouse_row + 1;
3546 	    break;
3547 	}
3548 #endif
3549 	else if (n == 0 && c == ':' && colon)
3550 	{
3551 	    stuffcharReadbuff(':');
3552 	    if (!exmode_active)
3553 		cmdline_row = msg_row;
3554 	    skip_redraw = TRUE;	    /* skip redraw once */
3555 	    do_redraw = FALSE;
3556 	    break;
3557 	}
3558 	else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3559 	    break;
3560     }
3561     --no_mapping;
3562     --allow_keys;
3563     return n;
3564 }
3565 
3566 /*
3567  * Ask the user to enter a number.
3568  * When "mouse_used" is not NULL allow using the mouse and in that case return
3569  * the line number.
3570  */
3571     int
3572 prompt_for_number(int *mouse_used)
3573 {
3574     int		i;
3575     int		save_cmdline_row;
3576     int		save_State;
3577 
3578     /* When using ":silent" assume that <CR> was entered. */
3579     if (mouse_used != NULL)
3580 	MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
3581     else
3582 	MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
3583 
3584     /* Set the state such that text can be selected/copied/pasted and we still
3585      * get mouse events. */
3586     save_cmdline_row = cmdline_row;
3587     cmdline_row = 0;
3588     save_State = State;
3589     State = ASKMORE;	/* prevents a screen update when using a timer */
3590 
3591     i = get_number(TRUE, mouse_used);
3592     if (KeyTyped)
3593     {
3594 	/* don't call wait_return() now */
3595 	/* msg_putchar('\n'); */
3596 	cmdline_row = msg_row - 1;
3597 	need_wait_return = FALSE;
3598 	msg_didany = FALSE;
3599 	msg_didout = FALSE;
3600     }
3601     else
3602 	cmdline_row = save_cmdline_row;
3603     State = save_State;
3604 
3605     return i;
3606 }
3607 
3608     void
3609 msgmore(long n)
3610 {
3611     long pn;
3612 
3613     if (global_busy	    /* no messages now, wait until global is finished */
3614 	    || !messaging())  /* 'lazyredraw' set, don't do messages now */
3615 	return;
3616 
3617     /* We don't want to overwrite another important message, but do overwrite
3618      * a previous "more lines" or "fewer lines" message, so that "5dd" and
3619      * then "put" reports the last action. */
3620     if (keep_msg != NULL && !keep_msg_more)
3621 	return;
3622 
3623     if (n > 0)
3624 	pn = n;
3625     else
3626 	pn = -n;
3627 
3628     if (pn > p_report)
3629     {
3630 	if (pn == 1)
3631 	{
3632 	    if (n > 0)
3633 		vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3634 							     MSG_BUF_LEN - 1);
3635 	    else
3636 		vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3637 							     MSG_BUF_LEN - 1);
3638 	}
3639 	else
3640 	{
3641 	    if (n > 0)
3642 		vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3643 						     _("%ld more lines"), pn);
3644 	    else
3645 		vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3646 						    _("%ld fewer lines"), pn);
3647 	}
3648 	if (got_int)
3649 	    vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
3650 	if (msg(msg_buf))
3651 	{
3652 	    set_keep_msg(msg_buf, 0);
3653 	    keep_msg_more = TRUE;
3654 	}
3655     }
3656 }
3657 
3658 /*
3659  * flush map and typeahead buffers and give a warning for an error
3660  */
3661     void
3662 beep_flush(void)
3663 {
3664     if (emsg_silent == 0)
3665     {
3666 	flush_buffers(FALSE);
3667 	vim_beep(BO_ERROR);
3668     }
3669 }
3670 
3671 /*
3672  * Give a warning for an error.
3673  */
3674     void
3675 vim_beep(
3676     unsigned val) /* one of the BO_ values, e.g., BO_OPER */
3677 {
3678     if (emsg_silent == 0)
3679     {
3680 	if (!((bo_flags & val) || (bo_flags & BO_ALL)))
3681 	{
3682 #ifdef ELAPSED_FUNC
3683 	    static int		did_init = FALSE;
3684 	    static ELAPSED_TYPE	start_tv;
3685 
3686 	    /* Only beep once per half a second, otherwise a sequence of beeps
3687 	     * would freeze Vim. */
3688 	    if (!did_init || ELAPSED_FUNC(start_tv) > 500)
3689 	    {
3690 		did_init = TRUE;
3691 		ELAPSED_INIT(start_tv);
3692 #endif
3693 		if (p_vb
3694 #ifdef FEAT_GUI
3695 			/* While the GUI is starting up the termcap is set for
3696 			 * the GUI but the output still goes to a terminal. */
3697 			&& !(gui.in_use && gui.starting)
3698 #endif
3699 			)
3700 		    out_str_cf(T_VB);
3701 		else
3702 		    out_char(BELL);
3703 #ifdef ELAPSED_FUNC
3704 	    }
3705 #endif
3706 	}
3707 
3708 	/* When 'verbose' is set and we are sourcing a script or executing a
3709 	 * function give the user a hint where the beep comes from. */
3710 	if (vim_strchr(p_debug, 'e') != NULL)
3711 	{
3712 	    msg_source(HL_ATTR(HLF_W));
3713 	    msg_attr((char_u *)_("Beep!"), HL_ATTR(HLF_W));
3714 	}
3715     }
3716 }
3717 
3718 /*
3719  * To get the "real" home directory:
3720  * - get value of $HOME
3721  * For Unix:
3722  *  - go to that directory
3723  *  - do mch_dirname() to get the real name of that directory.
3724  *  This also works with mounts and links.
3725  *  Don't do this for MS-DOS, it will change the "current dir" for a drive.
3726  */
3727 static char_u	*homedir = NULL;
3728 
3729     void
3730 init_homedir(void)
3731 {
3732     char_u  *var;
3733 
3734     /* In case we are called a second time (when 'encoding' changes). */
3735     vim_free(homedir);
3736     homedir = NULL;
3737 
3738 #ifdef VMS
3739     var = mch_getenv((char_u *)"SYS$LOGIN");
3740 #else
3741     var = mch_getenv((char_u *)"HOME");
3742 #endif
3743 
3744 #ifdef WIN3264
3745     /*
3746      * Typically, $HOME is not defined on Windows, unless the user has
3747      * specifically defined it for Vim's sake.  However, on Windows NT
3748      * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3749      * each user.  Try constructing $HOME from these.
3750      */
3751     if (var == NULL || *var == NUL)
3752     {
3753 	char_u *homedrive, *homepath;
3754 
3755 	homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3756 	homepath = mch_getenv((char_u *)"HOMEPATH");
3757 	if (homepath == NULL || *homepath == NUL)
3758 	    homepath = (char_u *)"\\";
3759 	if (homedrive != NULL
3760 			   && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3761 	{
3762 	    sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3763 	    if (NameBuff[0] != NUL)
3764 		var = NameBuff;
3765 	}
3766     }
3767 
3768     if (var == NULL)
3769 	var = mch_getenv((char_u *)"USERPROFILE");
3770 
3771     /*
3772      * Weird but true: $HOME may contain an indirect reference to another
3773      * variable, esp. "%USERPROFILE%".  Happens when $USERPROFILE isn't set
3774      * when $HOME is being set.
3775      */
3776     if (var != NULL && *var == '%')
3777     {
3778 	char_u	*p;
3779 	char_u	*exp;
3780 
3781 	p = vim_strchr(var + 1, '%');
3782 	if (p != NULL)
3783 	{
3784 	    vim_strncpy(NameBuff, var + 1, p - (var + 1));
3785 	    exp = mch_getenv(NameBuff);
3786 	    if (exp != NULL && *exp != NUL
3787 					&& STRLEN(exp) + STRLEN(p) < MAXPATHL)
3788 	    {
3789 		vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
3790 		var = NameBuff;
3791 	    }
3792 	}
3793     }
3794 
3795     if (var != NULL && *var == NUL)	/* empty is same as not set */
3796 	var = NULL;
3797 
3798 # ifdef FEAT_MBYTE
3799     if (enc_utf8 && var != NULL)
3800     {
3801 	int	len;
3802 	char_u  *pp = NULL;
3803 
3804 	/* Convert from active codepage to UTF-8.  Other conversions are
3805 	 * not done, because they would fail for non-ASCII characters. */
3806 	acp_to_enc(var, (int)STRLEN(var), &pp, &len);
3807 	if (pp != NULL)
3808 	{
3809 	    homedir = pp;
3810 	    return;
3811 	}
3812     }
3813 # endif
3814 
3815     /*
3816      * Default home dir is C:/
3817      * Best assumption we can make in such a situation.
3818      */
3819     if (var == NULL)
3820 	var = (char_u *)"C:/";
3821 #endif
3822 
3823     if (var != NULL)
3824     {
3825 #ifdef UNIX
3826 	/*
3827 	 * Change to the directory and get the actual path.  This resolves
3828 	 * links.  Don't do it when we can't return.
3829 	 */
3830 	if (mch_dirname(NameBuff, MAXPATHL) == OK
3831 					  && mch_chdir((char *)NameBuff) == 0)
3832 	{
3833 	    if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3834 		var = IObuff;
3835 	    if (mch_chdir((char *)NameBuff) != 0)
3836 		EMSG(_(e_prev_dir));
3837 	}
3838 #endif
3839 	homedir = vim_strsave(var);
3840     }
3841 }
3842 
3843 #if defined(EXITFREE) || defined(PROTO)
3844     void
3845 free_homedir(void)
3846 {
3847     vim_free(homedir);
3848 }
3849 
3850 # ifdef FEAT_CMDL_COMPL
3851     void
3852 free_users(void)
3853 {
3854     ga_clear_strings(&ga_users);
3855 }
3856 # endif
3857 #endif
3858 
3859 /*
3860  * Call expand_env() and store the result in an allocated string.
3861  * This is not very memory efficient, this expects the result to be freed
3862  * again soon.
3863  */
3864     char_u *
3865 expand_env_save(char_u *src)
3866 {
3867     return expand_env_save_opt(src, FALSE);
3868 }
3869 
3870 /*
3871  * Idem, but when "one" is TRUE handle the string as one file name, only
3872  * expand "~" at the start.
3873  */
3874     char_u *
3875 expand_env_save_opt(char_u *src, int one)
3876 {
3877     char_u	*p;
3878 
3879     p = alloc(MAXPATHL);
3880     if (p != NULL)
3881 	expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3882     return p;
3883 }
3884 
3885 /*
3886  * Expand environment variable with path name.
3887  * "~/" is also expanded, using $HOME.	For Unix "~user/" is expanded.
3888  * Skips over "\ ", "\~" and "\$" (not for Win32 though).
3889  * If anything fails no expansion is done and dst equals src.
3890  */
3891     void
3892 expand_env(
3893     char_u	*src,		/* input string e.g. "$HOME/vim.hlp" */
3894     char_u	*dst,		/* where to put the result */
3895     int		dstlen)		/* maximum length of the result */
3896 {
3897     expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
3898 }
3899 
3900     void
3901 expand_env_esc(
3902     char_u	*srcp,		/* input string e.g. "$HOME/vim.hlp" */
3903     char_u	*dst,		/* where to put the result */
3904     int		dstlen,		/* maximum length of the result */
3905     int		esc,		/* escape spaces in expanded variables */
3906     int		one,		/* "srcp" is one file name */
3907     char_u	*startstr)	/* start again after this (can be NULL) */
3908 {
3909     char_u	*src;
3910     char_u	*tail;
3911     int		c;
3912     char_u	*var;
3913     int		copy_char;
3914     int		mustfree;	/* var was allocated, need to free it later */
3915     int		at_start = TRUE; /* at start of a name */
3916     int		startstr_len = 0;
3917 
3918     if (startstr != NULL)
3919 	startstr_len = (int)STRLEN(startstr);
3920 
3921     src = skipwhite(srcp);
3922     --dstlen;		    /* leave one char space for "\," */
3923     while (*src && dstlen > 0)
3924     {
3925 #ifdef FEAT_EVAL
3926 	/* Skip over `=expr`. */
3927 	if (src[0] == '`' && src[1] == '=')
3928 	{
3929 	    size_t len;
3930 
3931 	    var = src;
3932 	    src += 2;
3933 	    (void)skip_expr(&src);
3934 	    if (*src == '`')
3935 		++src;
3936 	    len = src - var;
3937 	    if (len > (size_t)dstlen)
3938 		len = dstlen;
3939 	    vim_strncpy(dst, var, len);
3940 	    dst += len;
3941 	    dstlen -= (int)len;
3942 	    continue;
3943 	}
3944 #endif
3945 	copy_char = TRUE;
3946 	if ((*src == '$'
3947 #ifdef VMS
3948 		    && at_start
3949 #endif
3950 	   )
3951 #if defined(MSWIN)
3952 		|| *src == '%'
3953 #endif
3954 		|| (*src == '~' && at_start))
3955 	{
3956 	    mustfree = FALSE;
3957 
3958 	    /*
3959 	     * The variable name is copied into dst temporarily, because it may
3960 	     * be a string in read-only memory and a NUL needs to be appended.
3961 	     */
3962 	    if (*src != '~')				/* environment var */
3963 	    {
3964 		tail = src + 1;
3965 		var = dst;
3966 		c = dstlen - 1;
3967 
3968 #ifdef UNIX
3969 		/* Unix has ${var-name} type environment vars */
3970 		if (*tail == '{' && !vim_isIDc('{'))
3971 		{
3972 		    tail++;	/* ignore '{' */
3973 		    while (c-- > 0 && *tail && *tail != '}')
3974 			*var++ = *tail++;
3975 		}
3976 		else
3977 #endif
3978 		{
3979 		    while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3980 #if defined(MSWIN)
3981 			    || (*src == '%' && *tail != '%')
3982 #endif
3983 			    ))
3984 		    {
3985 			*var++ = *tail++;
3986 		    }
3987 		}
3988 
3989 #if defined(MSWIN) || defined(UNIX)
3990 # ifdef UNIX
3991 		if (src[1] == '{' && *tail != '}')
3992 # else
3993 		if (*src == '%' && *tail != '%')
3994 # endif
3995 		    var = NULL;
3996 		else
3997 		{
3998 # ifdef UNIX
3999 		    if (src[1] == '{')
4000 # else
4001 		    if (*src == '%')
4002 #endif
4003 			++tail;
4004 #endif
4005 		    *var = NUL;
4006 		    var = vim_getenv(dst, &mustfree);
4007 #if defined(MSWIN) || defined(UNIX)
4008 		}
4009 #endif
4010 	    }
4011 							/* home directory */
4012 	    else if (  src[1] == NUL
4013 		    || vim_ispathsep(src[1])
4014 		    || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
4015 	    {
4016 		var = homedir;
4017 		tail = src + 1;
4018 	    }
4019 	    else					/* user directory */
4020 	    {
4021 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
4022 		/*
4023 		 * Copy ~user to dst[], so we can put a NUL after it.
4024 		 */
4025 		tail = src;
4026 		var = dst;
4027 		c = dstlen - 1;
4028 		while (	   c-- > 0
4029 			&& *tail
4030 			&& vim_isfilec(*tail)
4031 			&& !vim_ispathsep(*tail))
4032 		    *var++ = *tail++;
4033 		*var = NUL;
4034 # ifdef UNIX
4035 		/*
4036 		 * If the system supports getpwnam(), use it.
4037 		 * Otherwise, or if getpwnam() fails, the shell is used to
4038 		 * expand ~user.  This is slower and may fail if the shell
4039 		 * does not support ~user (old versions of /bin/sh).
4040 		 */
4041 #  if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
4042 		{
4043 		    /* Note: memory allocated by getpwnam() is never freed.
4044 		     * Calling endpwent() apparently doesn't help. */
4045 		    struct passwd *pw = (*dst == NUL)
4046 					? NULL : getpwnam((char *)dst + 1);
4047 
4048 		    var = (pw == NULL) ? NULL : (char_u *)pw->pw_dir;
4049 		}
4050 		if (var == NULL)
4051 #  endif
4052 		{
4053 		    expand_T	xpc;
4054 
4055 		    ExpandInit(&xpc);
4056 		    xpc.xp_context = EXPAND_FILES;
4057 		    var = ExpandOne(&xpc, dst, NULL,
4058 				WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
4059 		    mustfree = TRUE;
4060 		}
4061 
4062 # else	/* !UNIX, thus VMS */
4063 		/*
4064 		 * USER_HOME is a comma-separated list of
4065 		 * directories to search for the user account in.
4066 		 */
4067 		{
4068 		    char_u	test[MAXPATHL], paths[MAXPATHL];
4069 		    char_u	*path, *next_path, *ptr;
4070 		    stat_T	st;
4071 
4072 		    STRCPY(paths, USER_HOME);
4073 		    next_path = paths;
4074 		    while (*next_path)
4075 		    {
4076 			for (path = next_path; *next_path && *next_path != ',';
4077 				next_path++);
4078 			if (*next_path)
4079 			    *next_path++ = NUL;
4080 			STRCPY(test, path);
4081 			STRCAT(test, "/");
4082 			STRCAT(test, dst + 1);
4083 			if (mch_stat(test, &st) == 0)
4084 			{
4085 			    var = alloc(STRLEN(test) + 1);
4086 			    STRCPY(var, test);
4087 			    mustfree = TRUE;
4088 			    break;
4089 			}
4090 		    }
4091 		}
4092 # endif /* UNIX */
4093 #else
4094 		/* cannot expand user's home directory, so don't try */
4095 		var = NULL;
4096 		tail = (char_u *)"";	/* for gcc */
4097 #endif /* UNIX || VMS */
4098 	    }
4099 
4100 #ifdef BACKSLASH_IN_FILENAME
4101 	    /* If 'shellslash' is set change backslashes to forward slashes.
4102 	     * Can't use slash_adjust(), p_ssl may be set temporarily. */
4103 	    if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4104 	    {
4105 		char_u	*p = vim_strsave(var);
4106 
4107 		if (p != NULL)
4108 		{
4109 		    if (mustfree)
4110 			vim_free(var);
4111 		    var = p;
4112 		    mustfree = TRUE;
4113 		    forward_slash(var);
4114 		}
4115 	    }
4116 #endif
4117 
4118 	    /* If "var" contains white space, escape it with a backslash.
4119 	     * Required for ":e ~/tt" when $HOME includes a space. */
4120 	    if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4121 	    {
4122 		char_u	*p = vim_strsave_escaped(var, (char_u *)" \t");
4123 
4124 		if (p != NULL)
4125 		{
4126 		    if (mustfree)
4127 			vim_free(var);
4128 		    var = p;
4129 		    mustfree = TRUE;
4130 		}
4131 	    }
4132 
4133 	    if (var != NULL && *var != NUL
4134 		    && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4135 	    {
4136 		STRCPY(dst, var);
4137 		dstlen -= (int)STRLEN(var);
4138 		c = (int)STRLEN(var);
4139 		/* if var[] ends in a path separator and tail[] starts
4140 		 * with it, skip a character */
4141 		if (*var != NUL && after_pathsep(dst, dst + c)
4142 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4143 			&& dst[-1] != ':'
4144 #endif
4145 			&& vim_ispathsep(*tail))
4146 		    ++tail;
4147 		dst += c;
4148 		src = tail;
4149 		copy_char = FALSE;
4150 	    }
4151 	    if (mustfree)
4152 		vim_free(var);
4153 	}
4154 
4155 	if (copy_char)	    /* copy at least one char */
4156 	{
4157 	    /*
4158 	     * Recognize the start of a new name, for '~'.
4159 	     * Don't do this when "one" is TRUE, to avoid expanding "~" in
4160 	     * ":edit foo ~ foo".
4161 	     */
4162 	    at_start = FALSE;
4163 	    if (src[0] == '\\' && src[1] != NUL)
4164 	    {
4165 		*dst++ = *src++;
4166 		--dstlen;
4167 	    }
4168 	    else if ((src[0] == ' ' || src[0] == ',') && !one)
4169 		at_start = TRUE;
4170 	    if (dstlen > 0)
4171 	    {
4172 		*dst++ = *src++;
4173 		--dstlen;
4174 
4175 		if (startstr != NULL && src - startstr_len >= srcp
4176 			&& STRNCMP(src - startstr_len, startstr,
4177 							    startstr_len) == 0)
4178 		    at_start = TRUE;
4179 	    }
4180 	}
4181 
4182     }
4183     *dst = NUL;
4184 }
4185 
4186 /*
4187  * Vim's version of getenv().
4188  * Special handling of $HOME, $VIM and $VIMRUNTIME.
4189  * Also does ACP to 'enc' conversion for Win32.
4190  * "mustfree" is set to TRUE when returned is allocated, it must be
4191  * initialized to FALSE by the caller.
4192  */
4193     char_u *
4194 vim_getenv(char_u *name, int *mustfree)
4195 {
4196     char_u	*p;
4197     char_u	*pend;
4198     int		vimruntime;
4199 
4200 #if defined(MSWIN)
4201     /* use "C:/" when $HOME is not set */
4202     if (STRCMP(name, "HOME") == 0)
4203 	return homedir;
4204 #endif
4205 
4206     p = mch_getenv(name);
4207     if (p != NULL && *p == NUL)	    /* empty is the same as not set */
4208 	p = NULL;
4209 
4210     if (p != NULL)
4211     {
4212 #if defined(FEAT_MBYTE) && defined(WIN3264)
4213 	if (enc_utf8)
4214 	{
4215 	    int	    len;
4216 	    char_u  *pp = NULL;
4217 
4218 	    /* Convert from active codepage to UTF-8.  Other conversions are
4219 	     * not done, because they would fail for non-ASCII characters. */
4220 	    acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4221 	    if (pp != NULL)
4222 	    {
4223 		p = pp;
4224 		*mustfree = TRUE;
4225 	    }
4226 	}
4227 #endif
4228 	return p;
4229     }
4230 
4231     vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4232     if (!vimruntime && STRCMP(name, "VIM") != 0)
4233 	return NULL;
4234 
4235     /*
4236      * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4237      * Don't do this when default_vimruntime_dir is non-empty.
4238      */
4239     if (vimruntime
4240 #ifdef HAVE_PATHDEF
4241 	    && *default_vimruntime_dir == NUL
4242 #endif
4243        )
4244     {
4245 	p = mch_getenv((char_u *)"VIM");
4246 	if (p != NULL && *p == NUL)	    /* empty is the same as not set */
4247 	    p = NULL;
4248 	if (p != NULL)
4249 	{
4250 	    p = vim_version_dir(p);
4251 	    if (p != NULL)
4252 		*mustfree = TRUE;
4253 	    else
4254 		p = mch_getenv((char_u *)"VIM");
4255 
4256 #if defined(FEAT_MBYTE) && defined(WIN3264)
4257 	    if (enc_utf8)
4258 	    {
4259 		int	len;
4260 		char_u  *pp = NULL;
4261 
4262 		/* Convert from active codepage to UTF-8.  Other conversions
4263 		 * are not done, because they would fail for non-ASCII
4264 		 * characters. */
4265 		acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4266 		if (pp != NULL)
4267 		{
4268 		    if (*mustfree)
4269 			vim_free(p);
4270 		    p = pp;
4271 		    *mustfree = TRUE;
4272 		}
4273 	    }
4274 #endif
4275 	}
4276     }
4277 
4278     /*
4279      * When expanding $VIM or $VIMRUNTIME fails, try using:
4280      * - the directory name from 'helpfile' (unless it contains '$')
4281      * - the executable name from argv[0]
4282      */
4283     if (p == NULL)
4284     {
4285 	if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4286 	    p = p_hf;
4287 #ifdef USE_EXE_NAME
4288 	/*
4289 	 * Use the name of the executable, obtained from argv[0].
4290 	 */
4291 	else
4292 	    p = exe_name;
4293 #endif
4294 	if (p != NULL)
4295 	{
4296 	    /* remove the file name */
4297 	    pend = gettail(p);
4298 
4299 	    /* remove "doc/" from 'helpfile', if present */
4300 	    if (p == p_hf)
4301 		pend = remove_tail(p, pend, (char_u *)"doc");
4302 
4303 #ifdef USE_EXE_NAME
4304 # ifdef MACOS_X
4305 	    /* remove "MacOS" from exe_name and add "Resources/vim" */
4306 	    if (p == exe_name)
4307 	    {
4308 		char_u	*pend1;
4309 		char_u	*pnew;
4310 
4311 		pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4312 		if (pend1 != pend)
4313 		{
4314 		    pnew = alloc((unsigned)(pend1 - p) + 15);
4315 		    if (pnew != NULL)
4316 		    {
4317 			STRNCPY(pnew, p, (pend1 - p));
4318 			STRCPY(pnew + (pend1 - p), "Resources/vim");
4319 			p = pnew;
4320 			pend = p + STRLEN(p);
4321 		    }
4322 		}
4323 	    }
4324 # endif
4325 	    /* remove "src/" from exe_name, if present */
4326 	    if (p == exe_name)
4327 		pend = remove_tail(p, pend, (char_u *)"src");
4328 #endif
4329 
4330 	    /* for $VIM, remove "runtime/" or "vim54/", if present */
4331 	    if (!vimruntime)
4332 	    {
4333 		pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4334 		pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4335 	    }
4336 
4337 	    /* remove trailing path separator */
4338 	    if (pend > p && after_pathsep(p, pend))
4339 		--pend;
4340 
4341 #ifdef MACOS_X
4342 	    if (p == exe_name || p == p_hf)
4343 #endif
4344 		/* check that the result is a directory name */
4345 		p = vim_strnsave(p, (int)(pend - p));
4346 
4347 	    if (p != NULL && !mch_isdir(p))
4348 	    {
4349 		vim_free(p);
4350 		p = NULL;
4351 	    }
4352 	    else
4353 	    {
4354 #ifdef USE_EXE_NAME
4355 		/* may add "/vim54" or "/runtime" if it exists */
4356 		if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4357 		{
4358 		    vim_free(p);
4359 		    p = pend;
4360 		}
4361 #endif
4362 		*mustfree = TRUE;
4363 	    }
4364 	}
4365     }
4366 
4367 #ifdef HAVE_PATHDEF
4368     /* When there is a pathdef.c file we can use default_vim_dir and
4369      * default_vimruntime_dir */
4370     if (p == NULL)
4371     {
4372 	/* Only use default_vimruntime_dir when it is not empty */
4373 	if (vimruntime && *default_vimruntime_dir != NUL)
4374 	{
4375 	    p = default_vimruntime_dir;
4376 	    *mustfree = FALSE;
4377 	}
4378 	else if (*default_vim_dir != NUL)
4379 	{
4380 	    if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4381 		*mustfree = TRUE;
4382 	    else
4383 	    {
4384 		p = default_vim_dir;
4385 		*mustfree = FALSE;
4386 	    }
4387 	}
4388     }
4389 #endif
4390 
4391     /*
4392      * Set the environment variable, so that the new value can be found fast
4393      * next time, and others can also use it (e.g. Perl).
4394      */
4395     if (p != NULL)
4396     {
4397 	if (vimruntime)
4398 	{
4399 	    vim_setenv((char_u *)"VIMRUNTIME", p);
4400 	    didset_vimruntime = TRUE;
4401 	}
4402 	else
4403 	{
4404 	    vim_setenv((char_u *)"VIM", p);
4405 	    didset_vim = TRUE;
4406 	}
4407     }
4408     return p;
4409 }
4410 
4411 /*
4412  * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4413  * Return NULL if not, return its name in allocated memory otherwise.
4414  */
4415     static char_u *
4416 vim_version_dir(char_u *vimdir)
4417 {
4418     char_u	*p;
4419 
4420     if (vimdir == NULL || *vimdir == NUL)
4421 	return NULL;
4422     p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4423     if (p != NULL && mch_isdir(p))
4424 	return p;
4425     vim_free(p);
4426     p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4427     if (p != NULL && mch_isdir(p))
4428 	return p;
4429     vim_free(p);
4430     return NULL;
4431 }
4432 
4433 /*
4434  * If the string between "p" and "pend" ends in "name/", return "pend" minus
4435  * the length of "name/".  Otherwise return "pend".
4436  */
4437     static char_u *
4438 remove_tail(char_u *p, char_u *pend, char_u *name)
4439 {
4440     int		len = (int)STRLEN(name) + 1;
4441     char_u	*newend = pend - len;
4442 
4443     if (newend >= p
4444 	    && fnamencmp(newend, name, len - 1) == 0
4445 	    && (newend == p || after_pathsep(p, newend)))
4446 	return newend;
4447     return pend;
4448 }
4449 
4450 /*
4451  * Our portable version of setenv.
4452  */
4453     void
4454 vim_setenv(char_u *name, char_u *val)
4455 {
4456 #ifdef HAVE_SETENV
4457     mch_setenv((char *)name, (char *)val, 1);
4458 #else
4459     char_u	*envbuf;
4460 
4461     /*
4462      * Putenv does not copy the string, it has to remain
4463      * valid.  The allocated memory will never be freed.
4464      */
4465     envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4466     if (envbuf != NULL)
4467     {
4468 	sprintf((char *)envbuf, "%s=%s", name, val);
4469 	putenv((char *)envbuf);
4470     }
4471 #endif
4472 #ifdef FEAT_GETTEXT
4473     /*
4474      * When setting $VIMRUNTIME adjust the directory to find message
4475      * translations to $VIMRUNTIME/lang.
4476      */
4477     if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4478     {
4479 	char_u	*buf = concat_str(val, (char_u *)"/lang");
4480 
4481 	if (buf != NULL)
4482 	{
4483 	    bindtextdomain(VIMPACKAGE, (char *)buf);
4484 	    vim_free(buf);
4485 	}
4486     }
4487 #endif
4488 }
4489 
4490 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4491 /*
4492  * Function given to ExpandGeneric() to obtain an environment variable name.
4493  */
4494     char_u *
4495 get_env_name(
4496     expand_T	*xp UNUSED,
4497     int		idx)
4498 {
4499 # if defined(AMIGA)
4500     /*
4501      * No environ[] on the Amiga.
4502      */
4503     return NULL;
4504 # else
4505 # ifndef __WIN32__
4506     /* Borland C++ 5.2 has this in a header file. */
4507     extern char		**environ;
4508 # endif
4509 # define ENVNAMELEN 100
4510     static char_u	name[ENVNAMELEN];
4511     char_u		*str;
4512     int			n;
4513 
4514     str = (char_u *)environ[idx];
4515     if (str == NULL)
4516 	return NULL;
4517 
4518     for (n = 0; n < ENVNAMELEN - 1; ++n)
4519     {
4520 	if (str[n] == '=' || str[n] == NUL)
4521 	    break;
4522 	name[n] = str[n];
4523     }
4524     name[n] = NUL;
4525     return name;
4526 # endif
4527 }
4528 
4529 /*
4530  * Find all user names for user completion.
4531  * Done only once and then cached.
4532  */
4533     static void
4534 init_users(void)
4535 {
4536     static int	lazy_init_done = FALSE;
4537 
4538     if (lazy_init_done)
4539 	return;
4540 
4541     lazy_init_done = TRUE;
4542     ga_init2(&ga_users, sizeof(char_u *), 20);
4543 
4544 # if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
4545     {
4546 	char_u*		user;
4547 	struct passwd*	pw;
4548 
4549 	setpwent();
4550 	while ((pw = getpwent()) != NULL)
4551 	    /* pw->pw_name shouldn't be NULL but just in case... */
4552 	    if (pw->pw_name != NULL)
4553 	    {
4554 		if (ga_grow(&ga_users, 1) == FAIL)
4555 		    break;
4556 		user = vim_strsave((char_u*)pw->pw_name);
4557 		if (user == NULL)
4558 		    break;
4559 		((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user;
4560 	    }
4561 	endpwent();
4562     }
4563 # endif
4564 }
4565 
4566 /*
4567  * Function given to ExpandGeneric() to obtain an user names.
4568  */
4569     char_u*
4570 get_users(expand_T *xp UNUSED, int idx)
4571 {
4572     init_users();
4573     if (idx < ga_users.ga_len)
4574 	return ((char_u **)ga_users.ga_data)[idx];
4575     return NULL;
4576 }
4577 
4578 /*
4579  * Check whether name matches a user name. Return:
4580  * 0 if name does not match any user name.
4581  * 1 if name partially matches the beginning of a user name.
4582  * 2 is name fully matches a user name.
4583  */
4584 int match_user(char_u* name)
4585 {
4586     int i;
4587     int n = (int)STRLEN(name);
4588     int result = 0;
4589 
4590     init_users();
4591     for (i = 0; i < ga_users.ga_len; i++)
4592     {
4593 	if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
4594 	    return 2; /* full match */
4595 	if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
4596 	    result = 1; /* partial match */
4597     }
4598     return result;
4599 }
4600 #endif
4601 
4602 /*
4603  * Replace home directory by "~" in each space or comma separated file name in
4604  * 'src'.
4605  * If anything fails (except when out of space) dst equals src.
4606  */
4607     void
4608 home_replace(
4609     buf_T	*buf,	/* when not NULL, check for help files */
4610     char_u	*src,	/* input file name */
4611     char_u	*dst,	/* where to put the result */
4612     int		dstlen,	/* maximum length of the result */
4613     int		one)	/* if TRUE, only replace one file name, include
4614 			   spaces and commas in the file name. */
4615 {
4616     size_t	dirlen = 0, envlen = 0;
4617     size_t	len;
4618     char_u	*homedir_env, *homedir_env_orig;
4619     char_u	*p;
4620 
4621     if (src == NULL)
4622     {
4623 	*dst = NUL;
4624 	return;
4625     }
4626 
4627     /*
4628      * If the file is a help file, remove the path completely.
4629      */
4630     if (buf != NULL && buf->b_help)
4631     {
4632 	vim_snprintf((char *)dst, dstlen, "%s", gettail(src));
4633 	return;
4634     }
4635 
4636     /*
4637      * We check both the value of the $HOME environment variable and the
4638      * "real" home directory.
4639      */
4640     if (homedir != NULL)
4641 	dirlen = STRLEN(homedir);
4642 
4643 #ifdef VMS
4644     homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4645 #else
4646     homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4647 #endif
4648 #ifdef WIN3264
4649     if (homedir_env == NULL)
4650 	homedir_env_orig = homedir_env = mch_getenv((char_u *)"USERPROFILE");
4651 #endif
4652     /* Empty is the same as not set. */
4653     if (homedir_env != NULL && *homedir_env == NUL)
4654 	homedir_env = NULL;
4655 
4656 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL)
4657     if (homedir_env != NULL && vim_strchr(homedir_env, '~') != NULL)
4658     {
4659 	int	usedlen = 0;
4660 	int	flen;
4661 	char_u	*fbuf = NULL;
4662 
4663 	flen = (int)STRLEN(homedir_env);
4664 	(void)modify_fname((char_u *)":p", &usedlen,
4665 						  &homedir_env, &fbuf, &flen);
4666 	flen = (int)STRLEN(homedir_env);
4667 	if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4668 	    /* Remove the trailing / that is added to a directory. */
4669 	    homedir_env[flen - 1] = NUL;
4670     }
4671 #endif
4672 
4673     if (homedir_env != NULL)
4674 	envlen = STRLEN(homedir_env);
4675 
4676     if (!one)
4677 	src = skipwhite(src);
4678     while (*src && dstlen > 0)
4679     {
4680 	/*
4681 	 * Here we are at the beginning of a file name.
4682 	 * First, check to see if the beginning of the file name matches
4683 	 * $HOME or the "real" home directory. Check that there is a '/'
4684 	 * after the match (so that if e.g. the file is "/home/pieter/bla",
4685 	 * and the home directory is "/home/piet", the file does not end up
4686 	 * as "~er/bla" (which would seem to indicate the file "bla" in user
4687 	 * er's home directory)).
4688 	 */
4689 	p = homedir;
4690 	len = dirlen;
4691 	for (;;)
4692 	{
4693 	    if (   len
4694 		&& fnamencmp(src, p, len) == 0
4695 		&& (vim_ispathsep(src[len])
4696 		    || (!one && (src[len] == ',' || src[len] == ' '))
4697 		    || src[len] == NUL))
4698 	    {
4699 		src += len;
4700 		if (--dstlen > 0)
4701 		    *dst++ = '~';
4702 
4703 		/*
4704 		 * If it's just the home directory, add  "/".
4705 		 */
4706 		if (!vim_ispathsep(src[0]) && --dstlen > 0)
4707 		    *dst++ = '/';
4708 		break;
4709 	    }
4710 	    if (p == homedir_env)
4711 		break;
4712 	    p = homedir_env;
4713 	    len = envlen;
4714 	}
4715 
4716 	/* if (!one) skip to separator: space or comma */
4717 	while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4718 	    *dst++ = *src++;
4719 	/* skip separator */
4720 	while ((*src == ' ' || *src == ',') && --dstlen > 0)
4721 	    *dst++ = *src++;
4722     }
4723     /* if (dstlen == 0) out of space, what to do??? */
4724 
4725     *dst = NUL;
4726 
4727     if (homedir_env != homedir_env_orig)
4728 	vim_free(homedir_env);
4729 }
4730 
4731 /*
4732  * Like home_replace, store the replaced string in allocated memory.
4733  * When something fails, NULL is returned.
4734  */
4735     char_u  *
4736 home_replace_save(
4737     buf_T	*buf,	/* when not NULL, check for help files */
4738     char_u	*src)	/* input file name */
4739 {
4740     char_u	*dst;
4741     unsigned	len;
4742 
4743     len = 3;			/* space for "~/" and trailing NUL */
4744     if (src != NULL)		/* just in case */
4745 	len += (unsigned)STRLEN(src);
4746     dst = alloc(len);
4747     if (dst != NULL)
4748 	home_replace(buf, src, dst, len, TRUE);
4749     return dst;
4750 }
4751 
4752 /*
4753  * Compare two file names and return:
4754  * FPC_SAME   if they both exist and are the same file.
4755  * FPC_SAMEX  if they both don't exist and have the same file name.
4756  * FPC_DIFF   if they both exist and are different files.
4757  * FPC_NOTX   if they both don't exist.
4758  * FPC_DIFFX  if one of them doesn't exist.
4759  * For the first name environment variables are expanded
4760  */
4761     int
4762 fullpathcmp(
4763     char_u *s1,
4764     char_u *s2,
4765     int	    checkname)		/* when both don't exist, check file names */
4766 {
4767 #ifdef UNIX
4768     char_u	    exp1[MAXPATHL];
4769     char_u	    full1[MAXPATHL];
4770     char_u	    full2[MAXPATHL];
4771     stat_T	    st1, st2;
4772     int		    r1, r2;
4773 
4774     expand_env(s1, exp1, MAXPATHL);
4775     r1 = mch_stat((char *)exp1, &st1);
4776     r2 = mch_stat((char *)s2, &st2);
4777     if (r1 != 0 && r2 != 0)
4778     {
4779 	/* if mch_stat() doesn't work, may compare the names */
4780 	if (checkname)
4781 	{
4782 	    if (fnamecmp(exp1, s2) == 0)
4783 		return FPC_SAMEX;
4784 	    r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4785 	    r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4786 	    if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4787 		return FPC_SAMEX;
4788 	}
4789 	return FPC_NOTX;
4790     }
4791     if (r1 != 0 || r2 != 0)
4792 	return FPC_DIFFX;
4793     if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4794 	return FPC_SAME;
4795     return FPC_DIFF;
4796 #else
4797     char_u  *exp1;		/* expanded s1 */
4798     char_u  *full1;		/* full path of s1 */
4799     char_u  *full2;		/* full path of s2 */
4800     int	    retval = FPC_DIFF;
4801     int	    r1, r2;
4802 
4803     /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4804     if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4805     {
4806 	full1 = exp1 + MAXPATHL;
4807 	full2 = full1 + MAXPATHL;
4808 
4809 	expand_env(s1, exp1, MAXPATHL);
4810 	r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4811 	r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4812 
4813 	/* If vim_FullName() fails, the file probably doesn't exist. */
4814 	if (r1 != OK && r2 != OK)
4815 	{
4816 	    if (checkname && fnamecmp(exp1, s2) == 0)
4817 		retval = FPC_SAMEX;
4818 	    else
4819 		retval = FPC_NOTX;
4820 	}
4821 	else if (r1 != OK || r2 != OK)
4822 	    retval = FPC_DIFFX;
4823 	else if (fnamecmp(full1, full2))
4824 	    retval = FPC_DIFF;
4825 	else
4826 	    retval = FPC_SAME;
4827 	vim_free(exp1);
4828     }
4829     return retval;
4830 #endif
4831 }
4832 
4833 /*
4834  * Get the tail of a path: the file name.
4835  * When the path ends in a path separator the tail is the NUL after it.
4836  * Fail safe: never returns NULL.
4837  */
4838     char_u *
4839 gettail(char_u *fname)
4840 {
4841     char_u  *p1, *p2;
4842 
4843     if (fname == NULL)
4844 	return (char_u *)"";
4845     for (p1 = p2 = get_past_head(fname); *p2; )	/* find last part of path */
4846     {
4847 	if (vim_ispathsep_nocolon(*p2))
4848 	    p1 = p2 + 1;
4849 	MB_PTR_ADV(p2);
4850     }
4851     return p1;
4852 }
4853 
4854 #if defined(FEAT_SEARCHPATH)
4855 static char_u *gettail_dir(char_u *fname);
4856 
4857 /*
4858  * Return the end of the directory name, on the first path
4859  * separator:
4860  * "/path/file", "/path/dir/", "/path//dir", "/file"
4861  *	 ^	       ^	     ^	      ^
4862  */
4863     static char_u *
4864 gettail_dir(char_u *fname)
4865 {
4866     char_u	*dir_end = fname;
4867     char_u	*next_dir_end = fname;
4868     int		look_for_sep = TRUE;
4869     char_u	*p;
4870 
4871     for (p = fname; *p != NUL; )
4872     {
4873 	if (vim_ispathsep(*p))
4874 	{
4875 	    if (look_for_sep)
4876 	    {
4877 		next_dir_end = p;
4878 		look_for_sep = FALSE;
4879 	    }
4880 	}
4881 	else
4882 	{
4883 	    if (!look_for_sep)
4884 		dir_end = next_dir_end;
4885 	    look_for_sep = TRUE;
4886 	}
4887 	MB_PTR_ADV(p);
4888     }
4889     return dir_end;
4890 }
4891 #endif
4892 
4893 /*
4894  * Get pointer to tail of "fname", including path separators.  Putting a NUL
4895  * here leaves the directory name.  Takes care of "c:/" and "//".
4896  * Always returns a valid pointer.
4897  */
4898     char_u *
4899 gettail_sep(char_u *fname)
4900 {
4901     char_u	*p;
4902     char_u	*t;
4903 
4904     p = get_past_head(fname);	/* don't remove the '/' from "c:/file" */
4905     t = gettail(fname);
4906     while (t > p && after_pathsep(fname, t))
4907 	--t;
4908 #ifdef VMS
4909     /* path separator is part of the path */
4910     ++t;
4911 #endif
4912     return t;
4913 }
4914 
4915 /*
4916  * get the next path component (just after the next path separator).
4917  */
4918     char_u *
4919 getnextcomp(char_u *fname)
4920 {
4921     while (*fname && !vim_ispathsep(*fname))
4922 	MB_PTR_ADV(fname);
4923     if (*fname)
4924 	++fname;
4925     return fname;
4926 }
4927 
4928 /*
4929  * Get a pointer to one character past the head of a path name.
4930  * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4931  * If there is no head, path is returned.
4932  */
4933     char_u *
4934 get_past_head(char_u *path)
4935 {
4936     char_u  *retval;
4937 
4938 #if defined(MSWIN)
4939     /* may skip "c:" */
4940     if (isalpha(path[0]) && path[1] == ':')
4941 	retval = path + 2;
4942     else
4943 	retval = path;
4944 #else
4945 # if defined(AMIGA)
4946     /* may skip "label:" */
4947     retval = vim_strchr(path, ':');
4948     if (retval == NULL)
4949 	retval = path;
4950 # else	/* Unix */
4951     retval = path;
4952 # endif
4953 #endif
4954 
4955     while (vim_ispathsep(*retval))
4956 	++retval;
4957 
4958     return retval;
4959 }
4960 
4961 /*
4962  * Return TRUE if 'c' is a path separator.
4963  * Note that for MS-Windows this includes the colon.
4964  */
4965     int
4966 vim_ispathsep(int c)
4967 {
4968 #ifdef UNIX
4969     return (c == '/');	    /* UNIX has ':' inside file names */
4970 #else
4971 # ifdef BACKSLASH_IN_FILENAME
4972     return (c == ':' || c == '/' || c == '\\');
4973 # else
4974 #  ifdef VMS
4975     /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4976     return (c == ':' || c == '[' || c == ']' || c == '/'
4977 	    || c == '<' || c == '>' || c == '"' );
4978 #  else
4979     return (c == ':' || c == '/');
4980 #  endif /* VMS */
4981 # endif
4982 #endif
4983 }
4984 
4985 /*
4986  * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
4987  */
4988     int
4989 vim_ispathsep_nocolon(int c)
4990 {
4991     return vim_ispathsep(c)
4992 #ifdef BACKSLASH_IN_FILENAME
4993 	&& c != ':'
4994 #endif
4995 	;
4996 }
4997 
4998 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
4999 /*
5000  * return TRUE if 'c' is a path list separator.
5001  */
5002     int
5003 vim_ispathlistsep(int c)
5004 {
5005 #ifdef UNIX
5006     return (c == ':');
5007 #else
5008     return (c == ';');	/* might not be right for every system... */
5009 #endif
5010 }
5011 #endif
5012 
5013 /*
5014  * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
5015  * It's done in-place.
5016  */
5017     void
5018 shorten_dir(char_u *str)
5019 {
5020     char_u	*tail, *s, *d;
5021     int		skip = FALSE;
5022 
5023     tail = gettail(str);
5024     d = str;
5025     for (s = str; ; ++s)
5026     {
5027 	if (s >= tail)		    /* copy the whole tail */
5028 	{
5029 	    *d++ = *s;
5030 	    if (*s == NUL)
5031 		break;
5032 	}
5033 	else if (vim_ispathsep(*s))	    /* copy '/' and next char */
5034 	{
5035 	    *d++ = *s;
5036 	    skip = FALSE;
5037 	}
5038 	else if (!skip)
5039 	{
5040 	    *d++ = *s;		    /* copy next char */
5041 	    if (*s != '~' && *s != '.') /* and leading "~" and "." */
5042 		skip = TRUE;
5043 # ifdef FEAT_MBYTE
5044 	    if (has_mbyte)
5045 	    {
5046 		int l = mb_ptr2len(s);
5047 
5048 		while (--l > 0)
5049 		    *d++ = *++s;
5050 	    }
5051 # endif
5052 	}
5053     }
5054 }
5055 
5056 /*
5057  * Return TRUE if the directory of "fname" exists, FALSE otherwise.
5058  * Also returns TRUE if there is no directory name.
5059  * "fname" must be writable!.
5060  */
5061     int
5062 dir_of_file_exists(char_u *fname)
5063 {
5064     char_u	*p;
5065     int		c;
5066     int		retval;
5067 
5068     p = gettail_sep(fname);
5069     if (p == fname)
5070 	return TRUE;
5071     c = *p;
5072     *p = NUL;
5073     retval = mch_isdir(fname);
5074     *p = c;
5075     return retval;
5076 }
5077 
5078 /*
5079  * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
5080  * and deal with 'fileignorecase'.
5081  */
5082     int
5083 vim_fnamecmp(char_u *x, char_u *y)
5084 {
5085 #ifdef BACKSLASH_IN_FILENAME
5086     return vim_fnamencmp(x, y, MAXPATHL);
5087 #else
5088     if (p_fic)
5089 	return MB_STRICMP(x, y);
5090     return STRCMP(x, y);
5091 #endif
5092 }
5093 
5094     int
5095 vim_fnamencmp(char_u *x, char_u *y, size_t len)
5096 {
5097 #ifdef BACKSLASH_IN_FILENAME
5098     char_u	*px = x;
5099     char_u	*py = y;
5100     int		cx = NUL;
5101     int		cy = NUL;
5102 
5103     while (len > 0)
5104     {
5105 	cx = PTR2CHAR(px);
5106 	cy = PTR2CHAR(py);
5107 	if (cx == NUL || cy == NUL
5108 	    || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
5109 		&& !(cx == '/' && cy == '\\')
5110 		&& !(cx == '\\' && cy == '/')))
5111 	    break;
5112 	len -= MB_PTR2LEN(px);
5113 	px += MB_PTR2LEN(px);
5114 	py += MB_PTR2LEN(py);
5115     }
5116     if (len == 0)
5117 	return 0;
5118     return (cx - cy);
5119 #else
5120     if (p_fic)
5121 	return MB_STRNICMP(x, y, len);
5122     return STRNCMP(x, y, len);
5123 #endif
5124 }
5125 
5126 /*
5127  * Concatenate file names fname1 and fname2 into allocated memory.
5128  * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
5129  */
5130     char_u  *
5131 concat_fnames(char_u *fname1, char_u *fname2, int sep)
5132 {
5133     char_u  *dest;
5134 
5135     dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
5136     if (dest != NULL)
5137     {
5138 	STRCPY(dest, fname1);
5139 	if (sep)
5140 	    add_pathsep(dest);
5141 	STRCAT(dest, fname2);
5142     }
5143     return dest;
5144 }
5145 
5146 /*
5147  * Concatenate two strings and return the result in allocated memory.
5148  * Returns NULL when out of memory.
5149  */
5150     char_u  *
5151 concat_str(char_u *str1, char_u *str2)
5152 {
5153     char_u  *dest;
5154     size_t  l = STRLEN(str1);
5155 
5156     dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5157     if (dest != NULL)
5158     {
5159 	STRCPY(dest, str1);
5160 	STRCPY(dest + l, str2);
5161     }
5162     return dest;
5163 }
5164 
5165 /*
5166  * Add a path separator to a file name, unless it already ends in a path
5167  * separator.
5168  */
5169     void
5170 add_pathsep(char_u *p)
5171 {
5172     if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
5173 	STRCAT(p, PATHSEPSTR);
5174 }
5175 
5176 /*
5177  * FullName_save - Make an allocated copy of a full file name.
5178  * Returns NULL when out of memory.
5179  */
5180     char_u  *
5181 FullName_save(
5182     char_u	*fname,
5183     int		force)		/* force expansion, even when it already looks
5184 				 * like a full path name */
5185 {
5186     char_u	*buf;
5187     char_u	*new_fname = NULL;
5188 
5189     if (fname == NULL)
5190 	return NULL;
5191 
5192     buf = alloc((unsigned)MAXPATHL);
5193     if (buf != NULL)
5194     {
5195 	if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5196 	    new_fname = vim_strsave(buf);
5197 	else
5198 	    new_fname = vim_strsave(fname);
5199 	vim_free(buf);
5200     }
5201     return new_fname;
5202 }
5203 
5204 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5205 
5206 static char_u	*skip_string(char_u *p);
5207 static pos_T *ind_find_start_comment(void);
5208 static pos_T *ind_find_start_CORS(linenr_T *is_raw);
5209 static pos_T *find_start_rawstring(int ind_maxcomment);
5210 
5211 /*
5212  * Find the start of a comment, not knowing if we are in a comment right now.
5213  * Search starts at w_cursor.lnum and goes backwards.
5214  * Return NULL when not inside a comment.
5215  */
5216     static pos_T *
5217 ind_find_start_comment(void)	    /* XXX */
5218 {
5219     return find_start_comment(curbuf->b_ind_maxcomment);
5220 }
5221 
5222     pos_T *
5223 find_start_comment(int ind_maxcomment)	/* XXX */
5224 {
5225     pos_T	*pos;
5226     char_u	*line;
5227     char_u	*p;
5228     int		cur_maxcomment = ind_maxcomment;
5229 
5230     for (;;)
5231     {
5232 	pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5233 	if (pos == NULL)
5234 	    break;
5235 
5236 	/*
5237 	 * Check if the comment start we found is inside a string.
5238 	 * If it is then restrict the search to below this line and try again.
5239 	 */
5240 	line = ml_get(pos->lnum);
5241 	for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
5242 	    p = skip_string(p);
5243 	if ((colnr_T)(p - line) <= pos->col)
5244 	    break;
5245 	cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5246 	if (cur_maxcomment <= 0)
5247 	{
5248 	    pos = NULL;
5249 	    break;
5250 	}
5251     }
5252     return pos;
5253 }
5254 
5255 /*
5256  * Find the start of a comment or raw string, not knowing if we are in a
5257  * comment or raw string right now.
5258  * Search starts at w_cursor.lnum and goes backwards.
5259  * If is_raw is given and returns start of raw_string, sets it to true.
5260  * Return NULL when not inside a comment or raw string.
5261  * "CORS" -> Comment Or Raw String
5262  */
5263     static pos_T *
5264 ind_find_start_CORS(linenr_T *is_raw)	    /* XXX */
5265 {
5266     static pos_T comment_pos_copy;
5267     pos_T	*comment_pos;
5268     pos_T	*rs_pos;
5269 
5270     comment_pos = find_start_comment(curbuf->b_ind_maxcomment);
5271     if (comment_pos != NULL)
5272     {
5273 	/* Need to make a copy of the static pos in findmatchlimit(),
5274 	 * calling find_start_rawstring() may change it. */
5275 	comment_pos_copy = *comment_pos;
5276 	comment_pos = &comment_pos_copy;
5277     }
5278     rs_pos = find_start_rawstring(curbuf->b_ind_maxcomment);
5279 
5280     /* If comment_pos is before rs_pos the raw string is inside the comment.
5281      * If rs_pos is before comment_pos the comment is inside the raw string. */
5282     if (comment_pos == NULL || (rs_pos != NULL
5283 					     && LT_POS(*rs_pos, *comment_pos)))
5284     {
5285 	if (is_raw != NULL && rs_pos != NULL)
5286 	    *is_raw = rs_pos->lnum;
5287 	return rs_pos;
5288     }
5289     return comment_pos;
5290 }
5291 
5292 /*
5293  * Find the start of a raw string, not knowing if we are in one right now.
5294  * Search starts at w_cursor.lnum and goes backwards.
5295  * Return NULL when not inside a raw string.
5296  */
5297     static pos_T *
5298 find_start_rawstring(int ind_maxcomment)	/* XXX */
5299 {
5300     pos_T	*pos;
5301     char_u	*line;
5302     char_u	*p;
5303     int		cur_maxcomment = ind_maxcomment;
5304 
5305     for (;;)
5306     {
5307 	pos = findmatchlimit(NULL, 'R', FM_BACKWARD, cur_maxcomment);
5308 	if (pos == NULL)
5309 	    break;
5310 
5311 	/*
5312 	 * Check if the raw string start we found is inside a string.
5313 	 * If it is then restrict the search to below this line and try again.
5314 	 */
5315 	line = ml_get(pos->lnum);
5316 	for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
5317 	    p = skip_string(p);
5318 	if ((colnr_T)(p - line) <= pos->col)
5319 	    break;
5320 	cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5321 	if (cur_maxcomment <= 0)
5322 	{
5323 	    pos = NULL;
5324 	    break;
5325 	}
5326     }
5327     return pos;
5328 }
5329 
5330 /*
5331  * Skip to the end of a "string" and a 'c' character.
5332  * If there is no string or character, return argument unmodified.
5333  */
5334     static char_u *
5335 skip_string(char_u *p)
5336 {
5337     int	    i;
5338 
5339     /*
5340      * We loop, because strings may be concatenated: "date""time".
5341      */
5342     for ( ; ; ++p)
5343     {
5344 	if (p[0] == '\'')		    /* 'c' or '\n' or '\000' */
5345 	{
5346 	    if (!p[1])			    /* ' at end of line */
5347 		break;
5348 	    i = 2;
5349 	    if (p[1] == '\\')		    /* '\n' or '\000' */
5350 	    {
5351 		++i;
5352 		while (vim_isdigit(p[i - 1]))   /* '\000' */
5353 		    ++i;
5354 	    }
5355 	    if (p[i] == '\'')		    /* check for trailing ' */
5356 	    {
5357 		p += i;
5358 		continue;
5359 	    }
5360 	}
5361 	else if (p[0] == '"')		    /* start of string */
5362 	{
5363 	    for (++p; p[0]; ++p)
5364 	    {
5365 		if (p[0] == '\\' && p[1] != NUL)
5366 		    ++p;
5367 		else if (p[0] == '"')	    /* end of string */
5368 		    break;
5369 	    }
5370 	    if (p[0] == '"')
5371 		continue; /* continue for another string */
5372 	}
5373 	else if (p[0] == 'R' && p[1] == '"')
5374 	{
5375 	    /* Raw string: R"[delim](...)[delim]" */
5376 	    char_u *delim = p + 2;
5377 	    char_u *paren = vim_strchr(delim, '(');
5378 
5379 	    if (paren != NULL)
5380 	    {
5381 		size_t delim_len = paren - delim;
5382 
5383 		for (p += 3; *p; ++p)
5384 		    if (p[0] == ')' && STRNCMP(p + 1, delim, delim_len) == 0
5385 			    && p[delim_len + 1] == '"')
5386 		    {
5387 			p += delim_len + 1;
5388 			break;
5389 		    }
5390 		if (p[0] == '"')
5391 		    continue; /* continue for another string */
5392 	    }
5393 	}
5394 	break;				    /* no string found */
5395     }
5396     if (!*p)
5397 	--p;				    /* backup from NUL */
5398     return p;
5399 }
5400 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
5401 
5402 #if defined(FEAT_CINDENT) || defined(PROTO)
5403 
5404 /*
5405  * Do C or expression indenting on the current line.
5406  */
5407     void
5408 do_c_expr_indent(void)
5409 {
5410 # ifdef FEAT_EVAL
5411     if (*curbuf->b_p_inde != NUL)
5412 	fixthisline(get_expr_indent);
5413     else
5414 # endif
5415 	fixthisline(get_c_indent);
5416 }
5417 
5418 /* Find result cache for cpp_baseclass */
5419 typedef struct {
5420     int	    found;
5421     lpos_T  lpos;
5422 } cpp_baseclass_cache_T;
5423 
5424 /*
5425  * Functions for C-indenting.
5426  * Most of this originally comes from Eric Fischer.
5427  */
5428 /*
5429  * Below "XXX" means that this function may unlock the current line.
5430  */
5431 
5432 static char_u	*cin_skipcomment(char_u *);
5433 static int	cin_nocode(char_u *);
5434 static pos_T	*find_line_comment(void);
5435 static int	cin_has_js_key(char_u *text);
5436 static int	cin_islabel_skip(char_u **);
5437 static int	cin_isdefault(char_u *);
5438 static char_u	*after_label(char_u *l);
5439 static int	get_indent_nolabel(linenr_T lnum);
5440 static int	skip_label(linenr_T, char_u **pp);
5441 static int	cin_first_id_amount(void);
5442 static int	cin_get_equal_amount(linenr_T lnum);
5443 static int	cin_ispreproc(char_u *);
5444 static int	cin_iscomment(char_u *);
5445 static int	cin_islinecomment(char_u *);
5446 static int	cin_isterminated(char_u *, int, int);
5447 static int	cin_isinit(void);
5448 static int	cin_isfuncdecl(char_u **, linenr_T, linenr_T);
5449 static int	cin_isif(char_u *);
5450 static int	cin_iselse(char_u *);
5451 static int	cin_isdo(char_u *);
5452 static int	cin_iswhileofdo(char_u *, linenr_T);
5453 static int	cin_is_if_for_while_before_offset(char_u *line, int *poffset);
5454 static int	cin_iswhileofdo_end(int terminated);
5455 static int	cin_isbreak(char_u *);
5456 static int	cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached);
5457 static int	get_baseclass_amount(int col);
5458 static int	cin_ends_in(char_u *, char_u *, char_u *);
5459 static int	cin_starts_with(char_u *s, char *word);
5460 static int	cin_skip2pos(pos_T *trypos);
5461 static pos_T	*find_start_brace(void);
5462 static pos_T	*find_match_paren(int);
5463 static pos_T	*find_match_char(int c, int ind_maxparen);
5464 static int	corr_ind_maxparen(pos_T *startpos);
5465 static int	find_last_paren(char_u *l, int start, int end);
5466 static int	find_match(int lookfor, linenr_T ourscope);
5467 static int	cin_is_cpp_namespace(char_u *);
5468 
5469 /*
5470  * Skip over white space and C comments within the line.
5471  * Also skip over Perl/shell comments if desired.
5472  */
5473     static char_u *
5474 cin_skipcomment(char_u *s)
5475 {
5476     while (*s)
5477     {
5478 	char_u *prev_s = s;
5479 
5480 	s = skipwhite(s);
5481 
5482 	/* Perl/shell # comment comment continues until eol.  Require a space
5483 	 * before # to avoid recognizing $#array. */
5484 	if (curbuf->b_ind_hash_comment != 0 && s != prev_s && *s == '#')
5485 	{
5486 	    s += STRLEN(s);
5487 	    break;
5488 	}
5489 	if (*s != '/')
5490 	    break;
5491 	++s;
5492 	if (*s == '/')		/* slash-slash comment continues till eol */
5493 	{
5494 	    s += STRLEN(s);
5495 	    break;
5496 	}
5497 	if (*s != '*')
5498 	    break;
5499 	for (++s; *s; ++s)	/* skip slash-star comment */
5500 	    if (s[0] == '*' && s[1] == '/')
5501 	    {
5502 		s += 2;
5503 		break;
5504 	    }
5505     }
5506     return s;
5507 }
5508 
5509 /*
5510  * Return TRUE if there is no code at *s.  White space and comments are
5511  * not considered code.
5512  */
5513     static int
5514 cin_nocode(char_u *s)
5515 {
5516     return *cin_skipcomment(s) == NUL;
5517 }
5518 
5519 /*
5520  * Check previous lines for a "//" line comment, skipping over blank lines.
5521  */
5522     static pos_T *
5523 find_line_comment(void) /* XXX */
5524 {
5525     static pos_T pos;
5526     char_u	 *line;
5527     char_u	 *p;
5528 
5529     pos = curwin->w_cursor;
5530     while (--pos.lnum > 0)
5531     {
5532 	line = ml_get(pos.lnum);
5533 	p = skipwhite(line);
5534 	if (cin_islinecomment(p))
5535 	{
5536 	    pos.col = (int)(p - line);
5537 	    return &pos;
5538 	}
5539 	if (*p != NUL)
5540 	    break;
5541     }
5542     return NULL;
5543 }
5544 
5545 /*
5546  * Return TRUE if "text" starts with "key:".
5547  */
5548     static int
5549 cin_has_js_key(char_u *text)
5550 {
5551     char_u *s = skipwhite(text);
5552     int	    quote = -1;
5553 
5554     if (*s == '\'' || *s == '"')
5555     {
5556 	/* can be 'key': or "key": */
5557 	quote = *s;
5558 	++s;
5559     }
5560     if (!vim_isIDc(*s))	    /* need at least one ID character */
5561 	return FALSE;
5562 
5563     while (vim_isIDc(*s))
5564 	++s;
5565     if (*s == quote)
5566 	++s;
5567 
5568     s = cin_skipcomment(s);
5569 
5570     /* "::" is not a label, it's C++ */
5571     return (*s == ':' && s[1] != ':');
5572 }
5573 
5574 /*
5575  * Check if string matches "label:"; move to character after ':' if true.
5576  * "*s" must point to the start of the label, if there is one.
5577  */
5578     static int
5579 cin_islabel_skip(char_u **s)
5580 {
5581     if (!vim_isIDc(**s))	    /* need at least one ID character */
5582 	return FALSE;
5583 
5584     while (vim_isIDc(**s))
5585 	(*s)++;
5586 
5587     *s = cin_skipcomment(*s);
5588 
5589     /* "::" is not a label, it's C++ */
5590     return (**s == ':' && *++*s != ':');
5591 }
5592 
5593 /*
5594  * Recognize a label: "label:".
5595  * Note: curwin->w_cursor must be where we are looking for the label.
5596  */
5597     int
5598 cin_islabel(void)		/* XXX */
5599 {
5600     char_u	*s;
5601 
5602     s = cin_skipcomment(ml_get_curline());
5603 
5604     /*
5605      * Exclude "default" from labels, since it should be indented
5606      * like a switch label.  Same for C++ scope declarations.
5607      */
5608     if (cin_isdefault(s))
5609 	return FALSE;
5610     if (cin_isscopedecl(s))
5611 	return FALSE;
5612 
5613     if (cin_islabel_skip(&s))
5614     {
5615 	/*
5616 	 * Only accept a label if the previous line is terminated or is a case
5617 	 * label.
5618 	 */
5619 	pos_T	cursor_save;
5620 	pos_T	*trypos;
5621 	char_u	*line;
5622 
5623 	cursor_save = curwin->w_cursor;
5624 	while (curwin->w_cursor.lnum > 1)
5625 	{
5626 	    --curwin->w_cursor.lnum;
5627 
5628 	    /*
5629 	     * If we're in a comment or raw string now, skip to the start of
5630 	     * it.
5631 	     */
5632 	    curwin->w_cursor.col = 0;
5633 	    if ((trypos = ind_find_start_CORS(NULL)) != NULL) /* XXX */
5634 		curwin->w_cursor = *trypos;
5635 
5636 	    line = ml_get_curline();
5637 	    if (cin_ispreproc(line))	/* ignore #defines, #if, etc. */
5638 		continue;
5639 	    if (*(line = cin_skipcomment(line)) == NUL)
5640 		continue;
5641 
5642 	    curwin->w_cursor = cursor_save;
5643 	    if (cin_isterminated(line, TRUE, FALSE)
5644 		    || cin_isscopedecl(line)
5645 		    || cin_iscase(line, TRUE)
5646 		    || (cin_islabel_skip(&line) && cin_nocode(line)))
5647 		return TRUE;
5648 	    return FALSE;
5649 	}
5650 	curwin->w_cursor = cursor_save;
5651 	return TRUE;		/* label at start of file??? */
5652     }
5653     return FALSE;
5654 }
5655 
5656 /*
5657  * Recognize structure initialization and enumerations:
5658  * "[typedef] [static|public|protected|private] enum"
5659  * "[typedef] [static|public|protected|private] = {"
5660  */
5661     static int
5662 cin_isinit(void)
5663 {
5664     char_u	*s;
5665     static char *skip[] = {"static", "public", "protected", "private"};
5666 
5667     s = cin_skipcomment(ml_get_curline());
5668 
5669     if (cin_starts_with(s, "typedef"))
5670 	s = cin_skipcomment(s + 7);
5671 
5672     for (;;)
5673     {
5674 	int i, l;
5675 
5676 	for (i = 0; i < (int)(sizeof(skip) / sizeof(char *)); ++i)
5677 	{
5678 	    l = (int)strlen(skip[i]);
5679 	    if (cin_starts_with(s, skip[i]))
5680 	    {
5681 		s = cin_skipcomment(s + l);
5682 		l = 0;
5683 		break;
5684 	    }
5685 	}
5686 	if (l != 0)
5687 	    break;
5688     }
5689 
5690     if (cin_starts_with(s, "enum"))
5691 	return TRUE;
5692 
5693     if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5694 	return TRUE;
5695 
5696     return FALSE;
5697 }
5698 
5699 /*
5700  * Recognize a switch label: "case .*:" or "default:".
5701  */
5702      int
5703 cin_iscase(
5704     char_u *s,
5705     int strict) /* Allow relaxed check of case statement for JS */
5706 {
5707     s = cin_skipcomment(s);
5708     if (cin_starts_with(s, "case"))
5709     {
5710 	for (s += 4; *s; ++s)
5711 	{
5712 	    s = cin_skipcomment(s);
5713 	    if (*s == ':')
5714 	    {
5715 		if (s[1] == ':')	/* skip over "::" for C++ */
5716 		    ++s;
5717 		else
5718 		    return TRUE;
5719 	    }
5720 	    if (*s == '\'' && s[1] && s[2] == '\'')
5721 		s += 2;			/* skip over ':' */
5722 	    else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5723 		return FALSE;		/* stop at comment */
5724 	    else if (*s == '"')
5725 	    {
5726 		/* JS etc. */
5727 		if (strict)
5728 		    return FALSE;		/* stop at string */
5729 		else
5730 		    return TRUE;
5731 	    }
5732 	}
5733 	return FALSE;
5734     }
5735 
5736     if (cin_isdefault(s))
5737 	return TRUE;
5738     return FALSE;
5739 }
5740 
5741 /*
5742  * Recognize a "default" switch label.
5743  */
5744     static int
5745 cin_isdefault(char_u *s)
5746 {
5747     return (STRNCMP(s, "default", 7) == 0
5748 	    && *(s = cin_skipcomment(s + 7)) == ':'
5749 	    && s[1] != ':');
5750 }
5751 
5752 /*
5753  * Recognize a "public/private/protected" scope declaration label.
5754  */
5755     int
5756 cin_isscopedecl(char_u *s)
5757 {
5758     int		i;
5759 
5760     s = cin_skipcomment(s);
5761     if (STRNCMP(s, "public", 6) == 0)
5762 	i = 6;
5763     else if (STRNCMP(s, "protected", 9) == 0)
5764 	i = 9;
5765     else if (STRNCMP(s, "private", 7) == 0)
5766 	i = 7;
5767     else
5768 	return FALSE;
5769     return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5770 }
5771 
5772 /* Maximum number of lines to search back for a "namespace" line. */
5773 #define FIND_NAMESPACE_LIM 20
5774 
5775 /*
5776  * Recognize a "namespace" scope declaration.
5777  */
5778     static int
5779 cin_is_cpp_namespace(char_u *s)
5780 {
5781     char_u	*p;
5782     int		has_name = FALSE;
5783     int		has_name_start = FALSE;
5784 
5785     s = cin_skipcomment(s);
5786     if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5787     {
5788 	p = cin_skipcomment(skipwhite(s + 9));
5789 	while (*p != NUL)
5790 	{
5791 	    if (VIM_ISWHITE(*p))
5792 	    {
5793 		has_name = TRUE; /* found end of a name */
5794 		p = cin_skipcomment(skipwhite(p));
5795 	    }
5796 	    else if (*p == '{')
5797 	    {
5798 		break;
5799 	    }
5800 	    else if (vim_iswordc(*p))
5801 	    {
5802 		has_name_start = TRUE;
5803 		if (has_name)
5804 		    return FALSE; /* word character after skipping past name */
5805 		++p;
5806 	    }
5807 	    else if (p[0] == ':' && p[1] == ':' && vim_iswordc(p[2]))
5808 	    {
5809 		if (!has_name_start || has_name)
5810 		    return FALSE;
5811 		/* C++ 17 nested namespace */
5812 		p += 3;
5813 	    }
5814 	    else
5815 	    {
5816 		return FALSE;
5817 	    }
5818 	}
5819 	return TRUE;
5820     }
5821     return FALSE;
5822 }
5823 
5824 /*
5825  * Recognize a `extern "C"` or `extern "C++"` linkage specifications.
5826  */
5827     static int
5828 cin_is_cpp_extern_c(char_u *s)
5829 {
5830     char_u	*p;
5831     int		has_string_literal = FALSE;
5832 
5833     s = cin_skipcomment(s);
5834     if (STRNCMP(s, "extern", 6) == 0 && (s[6] == NUL || !vim_iswordc(s[6])))
5835     {
5836 	p = cin_skipcomment(skipwhite(s + 6));
5837 	while (*p != NUL)
5838 	{
5839 	    if (VIM_ISWHITE(*p))
5840 	    {
5841 		p = cin_skipcomment(skipwhite(p));
5842 	    }
5843 	    else if (*p == '{')
5844 	    {
5845 		break;
5846 	    }
5847 	    else if (p[0] == '"' && p[1] == 'C' && p[2] == '"')
5848 	    {
5849 		if (has_string_literal)
5850 		    return FALSE;
5851 		has_string_literal = TRUE;
5852 		p += 3;
5853 	    }
5854 	    else if (p[0] == '"' && p[1] == 'C' && p[2] == '+' && p[3] == '+'
5855 		    && p[4] == '"')
5856 	    {
5857 		if (has_string_literal)
5858 		    return FALSE;
5859 		has_string_literal = TRUE;
5860 		p += 5;
5861 	    }
5862 	    else
5863 	    {
5864 		return FALSE;
5865 	    }
5866 	}
5867 	return has_string_literal ? TRUE : FALSE;
5868     }
5869     return FALSE;
5870 }
5871 
5872 /*
5873  * Return a pointer to the first non-empty non-comment character after a ':'.
5874  * Return NULL if not found.
5875  *	  case 234:    a = b;
5876  *		       ^
5877  */
5878     static char_u *
5879 after_label(char_u *l)
5880 {
5881     for ( ; *l; ++l)
5882     {
5883 	if (*l == ':')
5884 	{
5885 	    if (l[1] == ':')	    /* skip over "::" for C++ */
5886 		++l;
5887 	    else if (!cin_iscase(l + 1, FALSE))
5888 		break;
5889 	}
5890 	else if (*l == '\'' && l[1] && l[2] == '\'')
5891 	    l += 2;		    /* skip over 'x' */
5892     }
5893     if (*l == NUL)
5894 	return NULL;
5895     l = cin_skipcomment(l + 1);
5896     if (*l == NUL)
5897 	return NULL;
5898     return l;
5899 }
5900 
5901 /*
5902  * Get indent of line "lnum", skipping a label.
5903  * Return 0 if there is nothing after the label.
5904  */
5905     static int
5906 get_indent_nolabel (linenr_T lnum)	/* XXX */
5907 {
5908     char_u	*l;
5909     pos_T	fp;
5910     colnr_T	col;
5911     char_u	*p;
5912 
5913     l = ml_get(lnum);
5914     p = after_label(l);
5915     if (p == NULL)
5916 	return 0;
5917 
5918     fp.col = (colnr_T)(p - l);
5919     fp.lnum = lnum;
5920     getvcol(curwin, &fp, &col, NULL, NULL);
5921     return (int)col;
5922 }
5923 
5924 /*
5925  * Find indent for line "lnum", ignoring any case or jump label.
5926  * Also return a pointer to the text (after the label) in "pp".
5927  *   label:	if (asdf && asdfasdf)
5928  *		^
5929  */
5930     static int
5931 skip_label(linenr_T lnum, char_u **pp)
5932 {
5933     char_u	*l;
5934     int		amount;
5935     pos_T	cursor_save;
5936 
5937     cursor_save = curwin->w_cursor;
5938     curwin->w_cursor.lnum = lnum;
5939     l = ml_get_curline();
5940 				    /* XXX */
5941     if (cin_iscase(l, FALSE) || cin_isscopedecl(l) || cin_islabel())
5942     {
5943 	amount = get_indent_nolabel(lnum);
5944 	l = after_label(ml_get_curline());
5945 	if (l == NULL)		/* just in case */
5946 	    l = ml_get_curline();
5947     }
5948     else
5949     {
5950 	amount = get_indent();
5951 	l = ml_get_curline();
5952     }
5953     *pp = l;
5954 
5955     curwin->w_cursor = cursor_save;
5956     return amount;
5957 }
5958 
5959 /*
5960  * Return the indent of the first variable name after a type in a declaration.
5961  *  int	    a,			indent of "a"
5962  *  static struct foo    b,	indent of "b"
5963  *  enum bla    c,		indent of "c"
5964  * Returns zero when it doesn't look like a declaration.
5965  */
5966     static int
5967 cin_first_id_amount(void)
5968 {
5969     char_u	*line, *p, *s;
5970     int		len;
5971     pos_T	fp;
5972     colnr_T	col;
5973 
5974     line = ml_get_curline();
5975     p = skipwhite(line);
5976     len = (int)(skiptowhite(p) - p);
5977     if (len == 6 && STRNCMP(p, "static", 6) == 0)
5978     {
5979 	p = skipwhite(p + 6);
5980 	len = (int)(skiptowhite(p) - p);
5981     }
5982     if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5983 	p = skipwhite(p + 6);
5984     else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5985 	p = skipwhite(p + 4);
5986     else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5987 	    || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5988     {
5989 	s = skipwhite(p + len);
5990 	if ((STRNCMP(s, "int", 3) == 0 && VIM_ISWHITE(s[3]))
5991 		|| (STRNCMP(s, "long", 4) == 0 && VIM_ISWHITE(s[4]))
5992 		|| (STRNCMP(s, "short", 5) == 0 && VIM_ISWHITE(s[5]))
5993 		|| (STRNCMP(s, "char", 4) == 0 && VIM_ISWHITE(s[4])))
5994 	    p = s;
5995     }
5996     for (len = 0; vim_isIDc(p[len]); ++len)
5997 	;
5998     if (len == 0 || !VIM_ISWHITE(p[len]) || cin_nocode(p))
5999 	return 0;
6000 
6001     p = skipwhite(p + len);
6002     fp.lnum = curwin->w_cursor.lnum;
6003     fp.col = (colnr_T)(p - line);
6004     getvcol(curwin, &fp, &col, NULL, NULL);
6005     return (int)col;
6006 }
6007 
6008 /*
6009  * Return the indent of the first non-blank after an equal sign.
6010  *       char *foo = "here";
6011  * Return zero if no (useful) equal sign found.
6012  * Return -1 if the line above "lnum" ends in a backslash.
6013  *      foo = "asdf\
6014  *	       asdf\
6015  *	       here";
6016  */
6017     static int
6018 cin_get_equal_amount(linenr_T lnum)
6019 {
6020     char_u	*line;
6021     char_u	*s;
6022     colnr_T	col;
6023     pos_T	fp;
6024 
6025     if (lnum > 1)
6026     {
6027 	line = ml_get(lnum - 1);
6028 	if (*line != NUL && line[STRLEN(line) - 1] == '\\')
6029 	    return -1;
6030     }
6031 
6032     line = s = ml_get(lnum);
6033     while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
6034     {
6035 	if (cin_iscomment(s))	/* ignore comments */
6036 	    s = cin_skipcomment(s);
6037 	else
6038 	    ++s;
6039     }
6040     if (*s != '=')
6041 	return 0;
6042 
6043     s = skipwhite(s + 1);
6044     if (cin_nocode(s))
6045 	return 0;
6046 
6047     if (*s == '"')	/* nice alignment for continued strings */
6048 	++s;
6049 
6050     fp.lnum = lnum;
6051     fp.col = (colnr_T)(s - line);
6052     getvcol(curwin, &fp, &col, NULL, NULL);
6053     return (int)col;
6054 }
6055 
6056 /*
6057  * Recognize a preprocessor statement: Any line that starts with '#'.
6058  */
6059     static int
6060 cin_ispreproc(char_u *s)
6061 {
6062     if (*skipwhite(s) == '#')
6063 	return TRUE;
6064     return FALSE;
6065 }
6066 
6067 /*
6068  * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
6069  * continuation line of a preprocessor statement.  Decrease "*lnump" to the
6070  * start and return the line in "*pp".
6071  * Put the amount of indent in "*amount".
6072  */
6073     static int
6074 cin_ispreproc_cont(char_u **pp, linenr_T *lnump, int *amount)
6075 {
6076     char_u	*line = *pp;
6077     linenr_T	lnum = *lnump;
6078     int		retval = FALSE;
6079     int		candidate_amount = *amount;
6080 
6081     if (*line != NUL && line[STRLEN(line) - 1] == '\\')
6082 	candidate_amount = get_indent_lnum(lnum);
6083 
6084     for (;;)
6085     {
6086 	if (cin_ispreproc(line))
6087 	{
6088 	    retval = TRUE;
6089 	    *lnump = lnum;
6090 	    break;
6091 	}
6092 	if (lnum == 1)
6093 	    break;
6094 	line = ml_get(--lnum);
6095 	if (*line == NUL || line[STRLEN(line) - 1] != '\\')
6096 	    break;
6097     }
6098 
6099     if (lnum != *lnump)
6100 	*pp = ml_get(*lnump);
6101     if (retval)
6102 	*amount = candidate_amount;
6103     return retval;
6104 }
6105 
6106 /*
6107  * Recognize the start of a C or C++ comment.
6108  */
6109     static int
6110 cin_iscomment(char_u *p)
6111 {
6112     return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
6113 }
6114 
6115 /*
6116  * Recognize the start of a "//" comment.
6117  */
6118     static int
6119 cin_islinecomment(char_u *p)
6120 {
6121     return (p[0] == '/' && p[1] == '/');
6122 }
6123 
6124 /*
6125  * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
6126  * '}'.
6127  * Don't consider "} else" a terminated line.
6128  * If a line begins with an "else", only consider it terminated if no unmatched
6129  * opening braces follow (handle "else { foo();" correctly).
6130  * Return the character terminating the line (ending char's have precedence if
6131  * both apply in order to determine initializations).
6132  */
6133     static int
6134 cin_isterminated(
6135     char_u	*s,
6136     int		incl_open,	/* include '{' at the end as terminator */
6137     int		incl_comma)	/* recognize a trailing comma */
6138 {
6139     char_u	found_start = 0;
6140     unsigned	n_open = 0;
6141     int		is_else = FALSE;
6142 
6143     s = cin_skipcomment(s);
6144 
6145     if (*s == '{' || (*s == '}' && !cin_iselse(s)))
6146 	found_start = *s;
6147 
6148     if (!found_start)
6149 	is_else = cin_iselse(s);
6150 
6151     while (*s)
6152     {
6153 	/* skip over comments, "" strings and 'c'haracters */
6154 	s = skip_string(cin_skipcomment(s));
6155 	if (*s == '}' && n_open > 0)
6156 	    --n_open;
6157 	if ((!is_else || n_open == 0)
6158 		&& (*s == ';' || *s == '}' || (incl_comma && *s == ','))
6159 		&& cin_nocode(s + 1))
6160 	    return *s;
6161 	else if (*s == '{')
6162 	{
6163 	    if (incl_open && cin_nocode(s + 1))
6164 		return *s;
6165 	    else
6166 		++n_open;
6167 	}
6168 
6169 	if (*s)
6170 	    s++;
6171     }
6172     return found_start;
6173 }
6174 
6175 /*
6176  * Recognize the basic picture of a function declaration -- it needs to
6177  * have an open paren somewhere and a close paren at the end of the line and
6178  * no semicolons anywhere.
6179  * When a line ends in a comma we continue looking in the next line.
6180  * "sp" points to a string with the line.  When looking at other lines it must
6181  * be restored to the line.  When it's NULL fetch lines here.
6182  * "first_lnum" is where we start looking.
6183  * "min_lnum" is the line before which we will not be looking.
6184  */
6185     static int
6186 cin_isfuncdecl(
6187     char_u	**sp,
6188     linenr_T	first_lnum,
6189     linenr_T	min_lnum)
6190 {
6191     char_u	*s;
6192     linenr_T	lnum = first_lnum;
6193     linenr_T	save_lnum = curwin->w_cursor.lnum;
6194     int		retval = FALSE;
6195     pos_T	*trypos;
6196     int		just_started = TRUE;
6197 
6198     if (sp == NULL)
6199 	s = ml_get(lnum);
6200     else
6201 	s = *sp;
6202 
6203     curwin->w_cursor.lnum = lnum;
6204     if (find_last_paren(s, '(', ')')
6205 	&& (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
6206     {
6207 	lnum = trypos->lnum;
6208 	if (lnum < min_lnum)
6209 	{
6210 	    curwin->w_cursor.lnum = save_lnum;
6211 	    return FALSE;
6212 	}
6213 
6214 	s = ml_get(lnum);
6215     }
6216     curwin->w_cursor.lnum = save_lnum;
6217 
6218     /* Ignore line starting with #. */
6219     if (cin_ispreproc(s))
6220 	return FALSE;
6221 
6222     while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
6223     {
6224 	if (cin_iscomment(s))	/* ignore comments */
6225 	    s = cin_skipcomment(s);
6226 	else if (*s == ':')
6227 	{
6228 	    if (*(s + 1) == ':')
6229 		s += 2;
6230 	    else
6231 		/* To avoid a mistake in the following situation:
6232 		 * A::A(int a, int b)
6233 		 *     : a(0)  // <--not a function decl
6234 		 *     , b(0)
6235 		 * {...
6236 		 */
6237 		return FALSE;
6238 	}
6239 	else
6240 	    ++s;
6241     }
6242     if (*s != '(')
6243 	return FALSE;		/* ';', ' or "  before any () or no '(' */
6244 
6245     while (*s && *s != ';' && *s != '\'' && *s != '"')
6246     {
6247 	if (*s == ')' && cin_nocode(s + 1))
6248 	{
6249 	    /* ')' at the end: may have found a match
6250 	     * Check for he previous line not to end in a backslash:
6251 	     *       #if defined(x) && \
6252 	     *		 defined(y)
6253 	     */
6254 	    lnum = first_lnum - 1;
6255 	    s = ml_get(lnum);
6256 	    if (*s == NUL || s[STRLEN(s) - 1] != '\\')
6257 		retval = TRUE;
6258 	    goto done;
6259 	}
6260 	if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
6261 	{
6262 	    int comma = (*s == ',');
6263 
6264 	    /* ',' at the end: continue looking in the next line.
6265 	     * At the end: check for ',' in the next line, for this style:
6266 	     * func(arg1
6267 	     *       , arg2) */
6268 	    for (;;)
6269 	    {
6270 		if (lnum >= curbuf->b_ml.ml_line_count)
6271 		    break;
6272 		s = ml_get(++lnum);
6273 		if (!cin_ispreproc(s))
6274 		    break;
6275 	    }
6276 	    if (lnum >= curbuf->b_ml.ml_line_count)
6277 		break;
6278 	    /* Require a comma at end of the line or a comma or ')' at the
6279 	     * start of next line. */
6280 	    s = skipwhite(s);
6281 	    if (!just_started && (!comma && *s != ',' && *s != ')'))
6282 		break;
6283 	    just_started = FALSE;
6284 	}
6285 	else if (cin_iscomment(s))	/* ignore comments */
6286 	    s = cin_skipcomment(s);
6287 	else
6288 	{
6289 	    ++s;
6290 	    just_started = FALSE;
6291 	}
6292     }
6293 
6294 done:
6295     if (lnum != first_lnum && sp != NULL)
6296 	*sp = ml_get(first_lnum);
6297 
6298     return retval;
6299 }
6300 
6301     static int
6302 cin_isif(char_u *p)
6303 {
6304  return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
6305 }
6306 
6307     static int
6308 cin_iselse(
6309     char_u  *p)
6310 {
6311     if (*p == '}')	    /* accept "} else" */
6312 	p = cin_skipcomment(p + 1);
6313     return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
6314 }
6315 
6316     static int
6317 cin_isdo(char_u *p)
6318 {
6319     return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
6320 }
6321 
6322 /*
6323  * Check if this is a "while" that should have a matching "do".
6324  * We only accept a "while (condition) ;", with only white space between the
6325  * ')' and ';'. The condition may be spread over several lines.
6326  */
6327     static int
6328 cin_iswhileofdo (char_u *p, linenr_T lnum)	/* XXX */
6329 {
6330     pos_T	cursor_save;
6331     pos_T	*trypos;
6332     int		retval = FALSE;
6333 
6334     p = cin_skipcomment(p);
6335     if (*p == '}')		/* accept "} while (cond);" */
6336 	p = cin_skipcomment(p + 1);
6337     if (cin_starts_with(p, "while"))
6338     {
6339 	cursor_save = curwin->w_cursor;
6340 	curwin->w_cursor.lnum = lnum;
6341 	curwin->w_cursor.col = 0;
6342 	p = ml_get_curline();
6343 	while (*p && *p != 'w')	/* skip any '}', until the 'w' of the "while" */
6344 	{
6345 	    ++p;
6346 	    ++curwin->w_cursor.col;
6347 	}
6348 	if ((trypos = findmatchlimit(NULL, 0, 0,
6349 					      curbuf->b_ind_maxparen)) != NULL
6350 		&& *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
6351 	    retval = TRUE;
6352 	curwin->w_cursor = cursor_save;
6353     }
6354     return retval;
6355 }
6356 
6357 /*
6358  * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
6359  * Return 0 if there is none.
6360  * Otherwise return !0 and update "*poffset" to point to the place where the
6361  * string was found.
6362  */
6363     static int
6364 cin_is_if_for_while_before_offset(char_u *line, int *poffset)
6365 {
6366     int offset = *poffset;
6367 
6368     if (offset-- < 2)
6369 	return 0;
6370     while (offset > 2 && VIM_ISWHITE(line[offset]))
6371 	--offset;
6372 
6373     offset -= 1;
6374     if (!STRNCMP(line + offset, "if", 2))
6375 	goto probablyFound;
6376 
6377     if (offset >= 1)
6378     {
6379 	offset -= 1;
6380 	if (!STRNCMP(line + offset, "for", 3))
6381 	    goto probablyFound;
6382 
6383 	if (offset >= 2)
6384 	{
6385 	    offset -= 2;
6386 	    if (!STRNCMP(line + offset, "while", 5))
6387 		goto probablyFound;
6388 	}
6389     }
6390     return 0;
6391 
6392 probablyFound:
6393     if (!offset || !vim_isIDc(line[offset - 1]))
6394     {
6395 	*poffset = offset;
6396 	return 1;
6397     }
6398     return 0;
6399 }
6400 
6401 /*
6402  * Return TRUE if we are at the end of a do-while.
6403  *    do
6404  *       nothing;
6405  *    while (foo
6406  *	       && bar);  <-- here
6407  * Adjust the cursor to the line with "while".
6408  */
6409     static int
6410 cin_iswhileofdo_end(int terminated)
6411 {
6412     char_u	*line;
6413     char_u	*p;
6414     char_u	*s;
6415     pos_T	*trypos;
6416     int		i;
6417 
6418     if (terminated != ';')	/* there must be a ';' at the end */
6419 	return FALSE;
6420 
6421     p = line = ml_get_curline();
6422     while (*p != NUL)
6423     {
6424 	p = cin_skipcomment(p);
6425 	if (*p == ')')
6426 	{
6427 	    s = skipwhite(p + 1);
6428 	    if (*s == ';' && cin_nocode(s + 1))
6429 	    {
6430 		/* Found ");" at end of the line, now check there is "while"
6431 		 * before the matching '('.  XXX */
6432 		i = (int)(p - line);
6433 		curwin->w_cursor.col = i;
6434 		trypos = find_match_paren(curbuf->b_ind_maxparen);
6435 		if (trypos != NULL)
6436 		{
6437 		    s = cin_skipcomment(ml_get(trypos->lnum));
6438 		    if (*s == '}')		/* accept "} while (cond);" */
6439 			s = cin_skipcomment(s + 1);
6440 		    if (cin_starts_with(s, "while"))
6441 		    {
6442 			curwin->w_cursor.lnum = trypos->lnum;
6443 			return TRUE;
6444 		    }
6445 		}
6446 
6447 		/* Searching may have made "line" invalid, get it again. */
6448 		line = ml_get_curline();
6449 		p = line + i;
6450 	    }
6451 	}
6452 	if (*p != NUL)
6453 	    ++p;
6454     }
6455     return FALSE;
6456 }
6457 
6458     static int
6459 cin_isbreak(char_u *p)
6460 {
6461     return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6462 }
6463 
6464 /*
6465  * Find the position of a C++ base-class declaration or
6466  * constructor-initialization. eg:
6467  *
6468  * class MyClass :
6469  *	baseClass		<-- here
6470  * class MyClass : public baseClass,
6471  *	anotherBaseClass	<-- here (should probably lineup ??)
6472  * MyClass::MyClass(...) :
6473  *	baseClass(...)		<-- here (constructor-initialization)
6474  *
6475  * This is a lot of guessing.  Watch out for "cond ? func() : foo".
6476  */
6477     static int
6478 cin_is_cpp_baseclass(
6479     cpp_baseclass_cache_T *cached) /* input and output */
6480 {
6481     lpos_T	*pos = &cached->lpos;	    /* find position */
6482     char_u	*s;
6483     int		class_or_struct, lookfor_ctor_init, cpp_base_class;
6484     linenr_T	lnum = curwin->w_cursor.lnum;
6485     char_u	*line = ml_get_curline();
6486 
6487     if (pos->lnum <= lnum)
6488 	return cached->found;	/* Use the cached result */
6489 
6490     pos->col = 0;
6491 
6492     s = skipwhite(line);
6493     if (*s == '#')		/* skip #define FOO x ? (x) : x */
6494 	return FALSE;
6495     s = cin_skipcomment(s);
6496     if (*s == NUL)
6497 	return FALSE;
6498 
6499     cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6500 
6501     /* Search for a line starting with '#', empty, ending in ';' or containing
6502      * '{' or '}' and start below it.  This handles the following situations:
6503      *	a = cond ?
6504      *	      func() :
6505      *		   asdf;
6506      *	func::foo()
6507      *	      : something
6508      *	{}
6509      *	Foo::Foo (int one, int two)
6510      *		: something(4),
6511      *		somethingelse(3)
6512      *	{}
6513      */
6514     while (lnum > 1)
6515     {
6516 	line = ml_get(lnum - 1);
6517 	s = skipwhite(line);
6518 	if (*s == '#' || *s == NUL)
6519 	    break;
6520 	while (*s != NUL)
6521 	{
6522 	    s = cin_skipcomment(s);
6523 	    if (*s == '{' || *s == '}'
6524 		    || (*s == ';' && cin_nocode(s + 1)))
6525 		break;
6526 	    if (*s != NUL)
6527 		++s;
6528 	}
6529 	if (*s != NUL)
6530 	    break;
6531 	--lnum;
6532     }
6533 
6534     pos->lnum = lnum;
6535     line = ml_get(lnum);
6536     s = line;
6537     for (;;)
6538     {
6539 	if (*s == NUL)
6540 	{
6541 	    if (lnum == curwin->w_cursor.lnum)
6542 		break;
6543 	    /* Continue in the cursor line. */
6544 	    line = ml_get(++lnum);
6545 	    s = line;
6546 	}
6547 	if (s == line)
6548 	{
6549 	    /* don't recognize "case (foo):" as a baseclass */
6550 	    if (cin_iscase(s, FALSE))
6551 		break;
6552 	    s = cin_skipcomment(line);
6553 	    if (*s == NUL)
6554 		continue;
6555 	}
6556 
6557 	if (s[0] == '"' || (s[0] == 'R' && s[1] == '"'))
6558 	    s = skip_string(s) + 1;
6559 	else if (s[0] == ':')
6560 	{
6561 	    if (s[1] == ':')
6562 	    {
6563 		/* skip double colon. It can't be a constructor
6564 		 * initialization any more */
6565 		lookfor_ctor_init = FALSE;
6566 		s = cin_skipcomment(s + 2);
6567 	    }
6568 	    else if (lookfor_ctor_init || class_or_struct)
6569 	    {
6570 		/* we have something found, that looks like the start of
6571 		 * cpp-base-class-declaration or constructor-initialization */
6572 		cpp_base_class = TRUE;
6573 		lookfor_ctor_init = class_or_struct = FALSE;
6574 		pos->col = 0;
6575 		s = cin_skipcomment(s + 1);
6576 	    }
6577 	    else
6578 		s = cin_skipcomment(s + 1);
6579 	}
6580 	else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6581 		|| (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6582 	{
6583 	    class_or_struct = TRUE;
6584 	    lookfor_ctor_init = FALSE;
6585 
6586 	    if (*s == 'c')
6587 		s = cin_skipcomment(s + 5);
6588 	    else
6589 		s = cin_skipcomment(s + 6);
6590 	}
6591 	else
6592 	{
6593 	    if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6594 	    {
6595 		cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6596 	    }
6597 	    else if (s[0] == ')')
6598 	    {
6599 		/* Constructor-initialization is assumed if we come across
6600 		 * something like "):" */
6601 		class_or_struct = FALSE;
6602 		lookfor_ctor_init = TRUE;
6603 	    }
6604 	    else if (s[0] == '?')
6605 	    {
6606 		/* Avoid seeing '() :' after '?' as constructor init. */
6607 		return FALSE;
6608 	    }
6609 	    else if (!vim_isIDc(s[0]))
6610 	    {
6611 		/* if it is not an identifier, we are wrong */
6612 		class_or_struct = FALSE;
6613 		lookfor_ctor_init = FALSE;
6614 	    }
6615 	    else if (pos->col == 0)
6616 	    {
6617 		/* it can't be a constructor-initialization any more */
6618 		lookfor_ctor_init = FALSE;
6619 
6620 		/* the first statement starts here: lineup with this one... */
6621 		if (cpp_base_class)
6622 		    pos->col = (colnr_T)(s - line);
6623 	    }
6624 
6625 	    /* When the line ends in a comma don't align with it. */
6626 	    if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6627 		pos->col = 0;
6628 
6629 	    s = cin_skipcomment(s + 1);
6630 	}
6631     }
6632 
6633     cached->found = cpp_base_class;
6634     if (cpp_base_class)
6635 	pos->lnum = lnum;
6636     return cpp_base_class;
6637 }
6638 
6639     static int
6640 get_baseclass_amount(int col)
6641 {
6642     int		amount;
6643     colnr_T	vcol;
6644     pos_T	*trypos;
6645 
6646     if (col == 0)
6647     {
6648 	amount = get_indent();
6649 	if (find_last_paren(ml_get_curline(), '(', ')')
6650 		&& (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
6651 	    amount = get_indent_lnum(trypos->lnum); /* XXX */
6652 	if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6653 	    amount += curbuf->b_ind_cpp_baseclass;
6654     }
6655     else
6656     {
6657 	curwin->w_cursor.col = col;
6658 	getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6659 	amount = (int)vcol;
6660     }
6661     if (amount < curbuf->b_ind_cpp_baseclass)
6662 	amount = curbuf->b_ind_cpp_baseclass;
6663     return amount;
6664 }
6665 
6666 /*
6667  * Return TRUE if string "s" ends with the string "find", possibly followed by
6668  * white space and comments.  Skip strings and comments.
6669  * Ignore "ignore" after "find" if it's not NULL.
6670  */
6671     static int
6672 cin_ends_in(char_u *s, char_u *find, char_u *ignore)
6673 {
6674     char_u	*p = s;
6675     char_u	*r;
6676     int		len = (int)STRLEN(find);
6677 
6678     while (*p != NUL)
6679     {
6680 	p = cin_skipcomment(p);
6681 	if (STRNCMP(p, find, len) == 0)
6682 	{
6683 	    r = skipwhite(p + len);
6684 	    if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6685 		r = skipwhite(r + STRLEN(ignore));
6686 	    if (cin_nocode(r))
6687 		return TRUE;
6688 	}
6689 	if (*p != NUL)
6690 	    ++p;
6691     }
6692     return FALSE;
6693 }
6694 
6695 /*
6696  * Return TRUE when "s" starts with "word" and then a non-ID character.
6697  */
6698     static int
6699 cin_starts_with(char_u *s, char *word)
6700 {
6701     int l = (int)STRLEN(word);
6702 
6703     return (STRNCMP(s, word, l) == 0 && !vim_isIDc(s[l]));
6704 }
6705 
6706 /*
6707  * Skip strings, chars and comments until at or past "trypos".
6708  * Return the column found.
6709  */
6710     static int
6711 cin_skip2pos(pos_T *trypos)
6712 {
6713     char_u	*line;
6714     char_u	*p;
6715     char_u	*new_p;
6716 
6717     p = line = ml_get(trypos->lnum);
6718     while (*p && (colnr_T)(p - line) < trypos->col)
6719     {
6720 	if (cin_iscomment(p))
6721 	    p = cin_skipcomment(p);
6722 	else
6723 	{
6724 	    new_p = skip_string(p);
6725 	    if (new_p == p)
6726 		++p;
6727 	    else
6728 		p = new_p;
6729 	}
6730     }
6731     return (int)(p - line);
6732 }
6733 
6734 /*
6735  * Find the '{' at the start of the block we are in.
6736  * Return NULL if no match found.
6737  * Ignore a '{' that is in a comment, makes indenting the next three lines
6738  * work. */
6739 /* foo()    */
6740 /* {	    */
6741 /* }	    */
6742 
6743     static pos_T *
6744 find_start_brace(void)	    /* XXX */
6745 {
6746     pos_T	cursor_save;
6747     pos_T	*trypos;
6748     pos_T	*pos;
6749     static pos_T	pos_copy;
6750 
6751     cursor_save = curwin->w_cursor;
6752     while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6753     {
6754 	pos_copy = *trypos;	/* copy pos_T, next findmatch will change it */
6755 	trypos = &pos_copy;
6756 	curwin->w_cursor = *trypos;
6757 	pos = NULL;
6758 	/* ignore the { if it's in a // or / *  * / comment */
6759 	if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6760 		       && (pos = ind_find_start_CORS(NULL)) == NULL) /* XXX */
6761 	    break;
6762 	if (pos != NULL)
6763 	    curwin->w_cursor.lnum = pos->lnum;
6764     }
6765     curwin->w_cursor = cursor_save;
6766     return trypos;
6767 }
6768 
6769 /*
6770  * Find the matching '(', ignoring it if it is in a comment.
6771  * Return NULL if no match found.
6772  */
6773     static pos_T *
6774 find_match_paren(int ind_maxparen)	/* XXX */
6775 {
6776     return find_match_char('(', ind_maxparen);
6777 }
6778 
6779     static pos_T *
6780 find_match_char (int c, int ind_maxparen)	/* XXX */
6781 {
6782     pos_T	cursor_save;
6783     pos_T	*trypos;
6784     static pos_T pos_copy;
6785     int		ind_maxp_wk;
6786 
6787     cursor_save = curwin->w_cursor;
6788     ind_maxp_wk = ind_maxparen;
6789 retry:
6790     if ((trypos = findmatchlimit(NULL, c, 0, ind_maxp_wk)) != NULL)
6791     {
6792 	/* check if the ( is in a // comment */
6793 	if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6794 	{
6795 	    ind_maxp_wk = ind_maxparen - (int)(cursor_save.lnum - trypos->lnum);
6796 	    if (ind_maxp_wk > 0)
6797 	    {
6798 		curwin->w_cursor = *trypos;
6799 		curwin->w_cursor.col = 0;	/* XXX */
6800 		goto retry;
6801 	    }
6802 	    trypos = NULL;
6803 	}
6804 	else
6805 	{
6806 	    pos_T	*trypos_wk;
6807 
6808 	    pos_copy = *trypos;	    /* copy trypos, findmatch will change it */
6809 	    trypos = &pos_copy;
6810 	    curwin->w_cursor = *trypos;
6811 	    if ((trypos_wk = ind_find_start_CORS(NULL)) != NULL) /* XXX */
6812 	    {
6813 		ind_maxp_wk = ind_maxparen - (int)(cursor_save.lnum
6814 			- trypos_wk->lnum);
6815 		if (ind_maxp_wk > 0)
6816 		{
6817 		    curwin->w_cursor = *trypos_wk;
6818 		    goto retry;
6819 		}
6820 		trypos = NULL;
6821 	    }
6822 	}
6823     }
6824     curwin->w_cursor = cursor_save;
6825     return trypos;
6826 }
6827 
6828 /*
6829  * Find the matching '(', ignoring it if it is in a comment or before an
6830  * unmatched {.
6831  * Return NULL if no match found.
6832  */
6833     static pos_T *
6834 find_match_paren_after_brace (int ind_maxparen)	    /* XXX */
6835 {
6836     pos_T	*trypos = find_match_paren(ind_maxparen);
6837 
6838     if (trypos != NULL)
6839     {
6840 	pos_T	*tryposBrace = find_start_brace();
6841 
6842 	/* If both an unmatched '(' and '{' is found.  Ignore the '('
6843 	 * position if the '{' is further down. */
6844 	if (tryposBrace != NULL
6845 		&& (trypos->lnum != tryposBrace->lnum
6846 		    ? trypos->lnum < tryposBrace->lnum
6847 		    : trypos->col < tryposBrace->col))
6848 	    trypos = NULL;
6849     }
6850     return trypos;
6851 }
6852 
6853 /*
6854  * Return ind_maxparen corrected for the difference in line number between the
6855  * cursor position and "startpos".  This makes sure that searching for a
6856  * matching paren above the cursor line doesn't find a match because of
6857  * looking a few lines further.
6858  */
6859     static int
6860 corr_ind_maxparen(pos_T *startpos)
6861 {
6862     long	n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6863 
6864     if (n > 0 && n < curbuf->b_ind_maxparen / 2)
6865 	return curbuf->b_ind_maxparen - (int)n;
6866     return curbuf->b_ind_maxparen;
6867 }
6868 
6869 /*
6870  * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
6871  * line "l".  "l" must point to the start of the line.
6872  */
6873     static int
6874 find_last_paren(char_u *l, int start, int end)
6875 {
6876     int		i;
6877     int		retval = FALSE;
6878     int		open_count = 0;
6879 
6880     curwin->w_cursor.col = 0;		    /* default is start of line */
6881 
6882     for (i = 0; l[i] != NUL; i++)
6883     {
6884 	i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6885 	i = (int)(skip_string(l + i) - l);    /* ignore parens in quotes */
6886 	if (l[i] == start)
6887 	    ++open_count;
6888 	else if (l[i] == end)
6889 	{
6890 	    if (open_count > 0)
6891 		--open_count;
6892 	    else
6893 	    {
6894 		curwin->w_cursor.col = i;
6895 		retval = TRUE;
6896 	    }
6897 	}
6898     }
6899     return retval;
6900 }
6901 
6902 /*
6903  * Parse 'cinoptions' and set the values in "curbuf".
6904  * Must be called when 'cinoptions', 'shiftwidth' and/or 'tabstop' changes.
6905  */
6906     void
6907 parse_cino(buf_T *buf)
6908 {
6909     char_u	*p;
6910     char_u	*l;
6911     char_u	*digits;
6912     int		n;
6913     int		divider;
6914     int		fraction = 0;
6915     int		sw = (int)get_sw_value(buf);
6916 
6917     /*
6918      * Set the default values.
6919      */
6920     /* Spaces from a block's opening brace the prevailing indent for that
6921      * block should be. */
6922     buf->b_ind_level = sw;
6923 
6924     /* Spaces from the edge of the line an open brace that's at the end of a
6925      * line is imagined to be. */
6926     buf->b_ind_open_imag = 0;
6927 
6928     /* Spaces from the prevailing indent for a line that is not preceded by
6929      * an opening brace. */
6930     buf->b_ind_no_brace = 0;
6931 
6932     /* Column where the first { of a function should be located }. */
6933     buf->b_ind_first_open = 0;
6934 
6935     /* Spaces from the prevailing indent a leftmost open brace should be
6936      * located. */
6937     buf->b_ind_open_extra = 0;
6938 
6939     /* Spaces from the matching open brace (real location for one at the left
6940      * edge; imaginary location from one that ends a line) the matching close
6941      * brace should be located. */
6942     buf->b_ind_close_extra = 0;
6943 
6944     /* Spaces from the edge of the line an open brace sitting in the leftmost
6945      * column is imagined to be. */
6946     buf->b_ind_open_left_imag = 0;
6947 
6948     /* Spaces jump labels should be shifted to the left if N is non-negative,
6949      * otherwise the jump label will be put to column 1. */
6950     buf->b_ind_jump_label = -1;
6951 
6952     /* Spaces from the switch() indent a "case xx" label should be located. */
6953     buf->b_ind_case = sw;
6954 
6955     /* Spaces from the "case xx:" code after a switch() should be located. */
6956     buf->b_ind_case_code = sw;
6957 
6958     /* Lineup break at end of case in switch() with case label. */
6959     buf->b_ind_case_break = 0;
6960 
6961     /* Spaces from the class declaration indent a scope declaration label
6962      * should be located. */
6963     buf->b_ind_scopedecl = sw;
6964 
6965     /* Spaces from the scope declaration label code should be located. */
6966     buf->b_ind_scopedecl_code = sw;
6967 
6968     /* Amount K&R-style parameters should be indented. */
6969     buf->b_ind_param = sw;
6970 
6971     /* Amount a function type spec should be indented. */
6972     buf->b_ind_func_type = sw;
6973 
6974     /* Amount a cpp base class declaration or constructor initialization
6975      * should be indented. */
6976     buf->b_ind_cpp_baseclass = sw;
6977 
6978     /* additional spaces beyond the prevailing indent a continuation line
6979      * should be located. */
6980     buf->b_ind_continuation = sw;
6981 
6982     /* Spaces from the indent of the line with an unclosed parentheses. */
6983     buf->b_ind_unclosed = sw * 2;
6984 
6985     /* Spaces from the indent of the line with an unclosed parentheses, which
6986      * itself is also unclosed. */
6987     buf->b_ind_unclosed2 = sw;
6988 
6989     /* Suppress ignoring spaces from the indent of a line starting with an
6990      * unclosed parentheses. */
6991     buf->b_ind_unclosed_noignore = 0;
6992 
6993     /* If the opening paren is the last nonwhite character on the line, and
6994      * b_ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6995      * context (for very long lines). */
6996     buf->b_ind_unclosed_wrapped = 0;
6997 
6998     /* Suppress ignoring white space when lining up with the character after
6999      * an unclosed parentheses. */
7000     buf->b_ind_unclosed_whiteok = 0;
7001 
7002     /* Indent a closing parentheses under the line start of the matching
7003      * opening parentheses. */
7004     buf->b_ind_matching_paren = 0;
7005 
7006     /* Indent a closing parentheses under the previous line. */
7007     buf->b_ind_paren_prev = 0;
7008 
7009     /* Extra indent for comments. */
7010     buf->b_ind_comment = 0;
7011 
7012     /* Spaces from the comment opener when there is nothing after it. */
7013     buf->b_ind_in_comment = 3;
7014 
7015     /* Boolean: if non-zero, use b_ind_in_comment even if there is something
7016      * after the comment opener. */
7017     buf->b_ind_in_comment2 = 0;
7018 
7019     /* Max lines to search for an open paren. */
7020     buf->b_ind_maxparen = 20;
7021 
7022     /* Max lines to search for an open comment. */
7023     buf->b_ind_maxcomment = 70;
7024 
7025     /* Handle braces for java code. */
7026     buf->b_ind_java = 0;
7027 
7028     /* Not to confuse JS object properties with labels. */
7029     buf->b_ind_js = 0;
7030 
7031     /* Handle blocked cases correctly. */
7032     buf->b_ind_keep_case_label = 0;
7033 
7034     /* Handle C++ namespace. */
7035     buf->b_ind_cpp_namespace = 0;
7036 
7037     /* Handle continuation lines containing conditions of if(), for() and
7038      * while(). */
7039     buf->b_ind_if_for_while = 0;
7040 
7041     /* indentation for # comments */
7042     buf->b_ind_hash_comment = 0;
7043 
7044     /* Handle C++ extern "C" or "C++" */
7045     buf->b_ind_cpp_extern_c = 0;
7046 
7047     for (p = buf->b_p_cino; *p; )
7048     {
7049 	l = p++;
7050 	if (*p == '-')
7051 	    ++p;
7052 	digits = p;	    /* remember where the digits start */
7053 	n = getdigits(&p);
7054 	divider = 0;
7055 	if (*p == '.')	    /* ".5s" means a fraction */
7056 	{
7057 	    fraction = atol((char *)++p);
7058 	    while (VIM_ISDIGIT(*p))
7059 	    {
7060 		++p;
7061 		if (divider)
7062 		    divider *= 10;
7063 		else
7064 		    divider = 10;
7065 	    }
7066 	}
7067 	if (*p == 's')	    /* "2s" means two times 'shiftwidth' */
7068 	{
7069 	    if (p == digits)
7070 		n = sw;	/* just "s" is one 'shiftwidth' */
7071 	    else
7072 	    {
7073 		n *= sw;
7074 		if (divider)
7075 		    n += (sw * fraction + divider / 2) / divider;
7076 	    }
7077 	    ++p;
7078 	}
7079 	if (l[1] == '-')
7080 	    n = -n;
7081 
7082 	/* When adding an entry here, also update the default 'cinoptions' in
7083 	 * doc/indent.txt, and add explanation for it! */
7084 	switch (*l)
7085 	{
7086 	    case '>': buf->b_ind_level = n; break;
7087 	    case 'e': buf->b_ind_open_imag = n; break;
7088 	    case 'n': buf->b_ind_no_brace = n; break;
7089 	    case 'f': buf->b_ind_first_open = n; break;
7090 	    case '{': buf->b_ind_open_extra = n; break;
7091 	    case '}': buf->b_ind_close_extra = n; break;
7092 	    case '^': buf->b_ind_open_left_imag = n; break;
7093 	    case 'L': buf->b_ind_jump_label = n; break;
7094 	    case ':': buf->b_ind_case = n; break;
7095 	    case '=': buf->b_ind_case_code = n; break;
7096 	    case 'b': buf->b_ind_case_break = n; break;
7097 	    case 'p': buf->b_ind_param = n; break;
7098 	    case 't': buf->b_ind_func_type = n; break;
7099 	    case '/': buf->b_ind_comment = n; break;
7100 	    case 'c': buf->b_ind_in_comment = n; break;
7101 	    case 'C': buf->b_ind_in_comment2 = n; break;
7102 	    case 'i': buf->b_ind_cpp_baseclass = n; break;
7103 	    case '+': buf->b_ind_continuation = n; break;
7104 	    case '(': buf->b_ind_unclosed = n; break;
7105 	    case 'u': buf->b_ind_unclosed2 = n; break;
7106 	    case 'U': buf->b_ind_unclosed_noignore = n; break;
7107 	    case 'W': buf->b_ind_unclosed_wrapped = n; break;
7108 	    case 'w': buf->b_ind_unclosed_whiteok = n; break;
7109 	    case 'm': buf->b_ind_matching_paren = n; break;
7110 	    case 'M': buf->b_ind_paren_prev = n; break;
7111 	    case ')': buf->b_ind_maxparen = n; break;
7112 	    case '*': buf->b_ind_maxcomment = n; break;
7113 	    case 'g': buf->b_ind_scopedecl = n; break;
7114 	    case 'h': buf->b_ind_scopedecl_code = n; break;
7115 	    case 'j': buf->b_ind_java = n; break;
7116 	    case 'J': buf->b_ind_js = n; break;
7117 	    case 'l': buf->b_ind_keep_case_label = n; break;
7118 	    case '#': buf->b_ind_hash_comment = n; break;
7119 	    case 'N': buf->b_ind_cpp_namespace = n; break;
7120 	    case 'k': buf->b_ind_if_for_while = n; break;
7121 	    case 'E': buf->b_ind_cpp_extern_c = n; break;
7122 	}
7123 	if (*p == ',')
7124 	    ++p;
7125     }
7126 }
7127 
7128 /*
7129  * Return the desired indent for C code.
7130  * Return -1 if the indent should be left alone (inside a raw string).
7131  */
7132     int
7133 get_c_indent(void)
7134 {
7135     pos_T	cur_curpos;
7136     int		amount;
7137     int		scope_amount;
7138     int		cur_amount = MAXCOL;
7139     colnr_T	col;
7140     char_u	*theline;
7141     char_u	*linecopy;
7142     pos_T	*trypos;
7143     pos_T	*comment_pos;
7144     pos_T	*tryposBrace = NULL;
7145     pos_T	tryposCopy;
7146     pos_T	our_paren_pos;
7147     char_u	*start;
7148     int		start_brace;
7149 #define BRACE_IN_COL0		1	    /* '{' is in column 0 */
7150 #define BRACE_AT_START		2	    /* '{' is at start of line */
7151 #define BRACE_AT_END		3	    /* '{' is at end of line */
7152     linenr_T	ourscope;
7153     char_u	*l;
7154     char_u	*look;
7155     char_u	terminated;
7156     int		lookfor;
7157 #define LOOKFOR_INITIAL		0
7158 #define LOOKFOR_IF		1
7159 #define LOOKFOR_DO		2
7160 #define LOOKFOR_CASE		3
7161 #define LOOKFOR_ANY		4
7162 #define LOOKFOR_TERM		5
7163 #define LOOKFOR_UNTERM		6
7164 #define LOOKFOR_SCOPEDECL	7
7165 #define LOOKFOR_NOBREAK		8
7166 #define LOOKFOR_CPP_BASECLASS	9
7167 #define LOOKFOR_ENUM_OR_INIT	10
7168 #define LOOKFOR_JS_KEY		11
7169 #define LOOKFOR_COMMA		12
7170 
7171     int		whilelevel;
7172     linenr_T	lnum;
7173     int		n;
7174     int		iscase;
7175     int		lookfor_break;
7176     int		lookfor_cpp_namespace = FALSE;
7177     int		cont_amount = 0;    /* amount for continuation line */
7178     int		original_line_islabel;
7179     int		added_to_amount = 0;
7180     int		js_cur_has_key = 0;
7181     linenr_T	raw_string_start = 0;
7182     cpp_baseclass_cache_T cache_cpp_baseclass = { FALSE, { MAXLNUM, 0 } };
7183 
7184     /* make a copy, value is changed below */
7185     int		ind_continuation = curbuf->b_ind_continuation;
7186 
7187     /* remember where the cursor was when we started */
7188     cur_curpos = curwin->w_cursor;
7189 
7190     /* if we are at line 1 zero indent is fine, right? */
7191     if (cur_curpos.lnum == 1)
7192 	return 0;
7193 
7194     /* Get a copy of the current contents of the line.
7195      * This is required, because only the most recent line obtained with
7196      * ml_get is valid! */
7197     linecopy = vim_strsave(ml_get(cur_curpos.lnum));
7198     if (linecopy == NULL)
7199 	return 0;
7200 
7201     /*
7202      * In insert mode and the cursor is on a ')' truncate the line at the
7203      * cursor position.  We don't want to line up with the matching '(' when
7204      * inserting new stuff.
7205      * For unknown reasons the cursor might be past the end of the line, thus
7206      * check for that.
7207      */
7208     if ((State & INSERT)
7209 	    && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
7210 	    && linecopy[curwin->w_cursor.col] == ')')
7211 	linecopy[curwin->w_cursor.col] = NUL;
7212 
7213     theline = skipwhite(linecopy);
7214 
7215     /* move the cursor to the start of the line */
7216 
7217     curwin->w_cursor.col = 0;
7218 
7219     original_line_islabel = cin_islabel();  /* XXX */
7220 
7221     /*
7222      * If we are inside a raw string don't change the indent.
7223      * Ignore a raw string inside a comment.
7224      */
7225     comment_pos = ind_find_start_comment();
7226     if (comment_pos != NULL)
7227     {
7228 	/* findmatchlimit() static pos is overwritten, make a copy */
7229 	tryposCopy = *comment_pos;
7230 	comment_pos = &tryposCopy;
7231     }
7232     trypos = find_start_rawstring(curbuf->b_ind_maxcomment);
7233     if (trypos != NULL && (comment_pos == NULL
7234 					     || LT_POS(*trypos, *comment_pos)))
7235     {
7236 	amount = -1;
7237 	goto laterend;
7238     }
7239 
7240     /*
7241      * #defines and so on always go at the left when included in 'cinkeys'.
7242      */
7243     if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
7244     {
7245 	amount = curbuf->b_ind_hash_comment;
7246 	goto theend;
7247     }
7248 
7249     /*
7250      * Is it a non-case label?	Then that goes at the left margin too unless:
7251      *  - JS flag is set.
7252      *  - 'L' item has a positive value.
7253      */
7254     if (original_line_islabel && !curbuf->b_ind_js
7255 					      && curbuf->b_ind_jump_label < 0)
7256     {
7257 	amount = 0;
7258 	goto theend;
7259     }
7260 
7261     /*
7262      * If we're inside a "//" comment and there is a "//" comment in a
7263      * previous line, lineup with that one.
7264      */
7265     if (cin_islinecomment(theline)
7266 	    && (trypos = find_line_comment()) != NULL) /* XXX */
7267     {
7268 	/* find how indented the line beginning the comment is */
7269 	getvcol(curwin, trypos, &col, NULL, NULL);
7270 	amount = col;
7271 	goto theend;
7272     }
7273 
7274     /*
7275      * If we're inside a comment and not looking at the start of the
7276      * comment, try using the 'comments' option.
7277      */
7278     if (!cin_iscomment(theline) && comment_pos != NULL) /* XXX */
7279     {
7280 	int	lead_start_len = 2;
7281 	int	lead_middle_len = 1;
7282 	char_u	lead_start[COM_MAX_LEN];	/* start-comment string */
7283 	char_u	lead_middle[COM_MAX_LEN];	/* middle-comment string */
7284 	char_u	lead_end[COM_MAX_LEN];		/* end-comment string */
7285 	char_u	*p;
7286 	int	start_align = 0;
7287 	int	start_off = 0;
7288 	int	done = FALSE;
7289 
7290 	/* find how indented the line beginning the comment is */
7291 	getvcol(curwin, comment_pos, &col, NULL, NULL);
7292 	amount = col;
7293 	*lead_start = NUL;
7294 	*lead_middle = NUL;
7295 
7296 	p = curbuf->b_p_com;
7297 	while (*p != NUL)
7298 	{
7299 	    int	align = 0;
7300 	    int	off = 0;
7301 	    int what = 0;
7302 
7303 	    while (*p != NUL && *p != ':')
7304 	    {
7305 		if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
7306 		    what = *p++;
7307 		else if (*p == COM_LEFT || *p == COM_RIGHT)
7308 		    align = *p++;
7309 		else if (VIM_ISDIGIT(*p) || *p == '-')
7310 		    off = getdigits(&p);
7311 		else
7312 		    ++p;
7313 	    }
7314 
7315 	    if (*p == ':')
7316 		++p;
7317 	    (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
7318 	    if (what == COM_START)
7319 	    {
7320 		STRCPY(lead_start, lead_end);
7321 		lead_start_len = (int)STRLEN(lead_start);
7322 		start_off = off;
7323 		start_align = align;
7324 	    }
7325 	    else if (what == COM_MIDDLE)
7326 	    {
7327 		STRCPY(lead_middle, lead_end);
7328 		lead_middle_len = (int)STRLEN(lead_middle);
7329 	    }
7330 	    else if (what == COM_END)
7331 	    {
7332 		/* If our line starts with the middle comment string, line it
7333 		 * up with the comment opener per the 'comments' option. */
7334 		if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
7335 			&& STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
7336 		{
7337 		    done = TRUE;
7338 		    if (curwin->w_cursor.lnum > 1)
7339 		    {
7340 			/* If the start comment string matches in the previous
7341 			 * line, use the indent of that line plus offset.  If
7342 			 * the middle comment string matches in the previous
7343 			 * line, use the indent of that line.  XXX */
7344 			look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
7345 			if (STRNCMP(look, lead_start, lead_start_len) == 0)
7346 			    amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7347 			else if (STRNCMP(look, lead_middle,
7348 							lead_middle_len) == 0)
7349 			{
7350 			    amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7351 			    break;
7352 			}
7353 			/* If the start comment string doesn't match with the
7354 			 * start of the comment, skip this entry. XXX */
7355 			else if (STRNCMP(ml_get(comment_pos->lnum) + comment_pos->col,
7356 					     lead_start, lead_start_len) != 0)
7357 			    continue;
7358 		    }
7359 		    if (start_off != 0)
7360 			amount += start_off;
7361 		    else if (start_align == COM_RIGHT)
7362 			amount += vim_strsize(lead_start)
7363 						   - vim_strsize(lead_middle);
7364 		    break;
7365 		}
7366 
7367 		/* If our line starts with the end comment string, line it up
7368 		 * with the middle comment */
7369 		if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
7370 			&& STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
7371 		{
7372 		    amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7373 								     /* XXX */
7374 		    if (off != 0)
7375 			amount += off;
7376 		    else if (align == COM_RIGHT)
7377 			amount += vim_strsize(lead_start)
7378 						   - vim_strsize(lead_middle);
7379 		    done = TRUE;
7380 		    break;
7381 		}
7382 	    }
7383 	}
7384 
7385 	/* If our line starts with an asterisk, line up with the
7386 	 * asterisk in the comment opener; otherwise, line up
7387 	 * with the first character of the comment text.
7388 	 */
7389 	if (done)
7390 	    ;
7391 	else if (theline[0] == '*')
7392 	    amount += 1;
7393 	else
7394 	{
7395 	    /*
7396 	     * If we are more than one line away from the comment opener, take
7397 	     * the indent of the previous non-empty line.  If 'cino' has "CO"
7398 	     * and we are just below the comment opener and there are any
7399 	     * white characters after it line up with the text after it;
7400 	     * otherwise, add the amount specified by "c" in 'cino'
7401 	     */
7402 	    amount = -1;
7403 	    for (lnum = cur_curpos.lnum - 1; lnum > comment_pos->lnum; --lnum)
7404 	    {
7405 		if (linewhite(lnum))		    /* skip blank lines */
7406 		    continue;
7407 		amount = get_indent_lnum(lnum);	    /* XXX */
7408 		break;
7409 	    }
7410 	    if (amount == -1)			    /* use the comment opener */
7411 	    {
7412 		if (!curbuf->b_ind_in_comment2)
7413 		{
7414 		    start = ml_get(comment_pos->lnum);
7415 		    look = start + comment_pos->col + 2; /* skip / and * */
7416 		    if (*look != NUL)		    /* if something after it */
7417 			comment_pos->col = (colnr_T)(skipwhite(look) - start);
7418 		}
7419 		getvcol(curwin, comment_pos, &col, NULL, NULL);
7420 		amount = col;
7421 		if (curbuf->b_ind_in_comment2 || *look == NUL)
7422 		    amount += curbuf->b_ind_in_comment;
7423 	    }
7424 	}
7425 	goto theend;
7426     }
7427 
7428     /*
7429      * Are we looking at a ']' that has a match?
7430      */
7431     if (*skipwhite(theline) == ']'
7432 	    && (trypos = find_match_char('[', curbuf->b_ind_maxparen)) != NULL)
7433     {
7434 	/* align with the line containing the '['. */
7435 	amount = get_indent_lnum(trypos->lnum);
7436 	goto theend;
7437     }
7438 
7439     /*
7440      * Are we inside parentheses or braces?
7441      */						    /* XXX */
7442     if (((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL
7443 		&& curbuf->b_ind_java == 0)
7444 	    || (tryposBrace = find_start_brace()) != NULL
7445 	    || trypos != NULL)
7446     {
7447       if (trypos != NULL && tryposBrace != NULL)
7448       {
7449 	  /* Both an unmatched '(' and '{' is found.  Use the one which is
7450 	   * closer to the current cursor position, set the other to NULL. */
7451 	  if (trypos->lnum != tryposBrace->lnum
7452 		  ? trypos->lnum < tryposBrace->lnum
7453 		  : trypos->col < tryposBrace->col)
7454 	      trypos = NULL;
7455 	  else
7456 	      tryposBrace = NULL;
7457       }
7458 
7459       if (trypos != NULL)
7460       {
7461 	/*
7462 	 * If the matching paren is more than one line away, use the indent of
7463 	 * a previous non-empty line that matches the same paren.
7464 	 */
7465 	if (theline[0] == ')' && curbuf->b_ind_paren_prev)
7466 	{
7467 	    /* Line up with the start of the matching paren line. */
7468 	    amount = get_indent_lnum(curwin->w_cursor.lnum - 1);  /* XXX */
7469 	}
7470 	else
7471 	{
7472 	    amount = -1;
7473 	    our_paren_pos = *trypos;
7474 	    for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
7475 	    {
7476 		l = skipwhite(ml_get(lnum));
7477 		if (cin_nocode(l))		/* skip comment lines */
7478 		    continue;
7479 		if (cin_ispreproc_cont(&l, &lnum, &amount))
7480 		    continue;			/* ignore #define, #if, etc. */
7481 		curwin->w_cursor.lnum = lnum;
7482 
7483 		/* Skip a comment or raw string. XXX */
7484 		if ((trypos = ind_find_start_CORS(NULL)) != NULL)
7485 		{
7486 		    lnum = trypos->lnum + 1;
7487 		    continue;
7488 		}
7489 
7490 		/* XXX */
7491 		if ((trypos = find_match_paren(
7492 			corr_ind_maxparen(&cur_curpos))) != NULL
7493 			&& trypos->lnum == our_paren_pos.lnum
7494 			&& trypos->col == our_paren_pos.col)
7495 		{
7496 			amount = get_indent_lnum(lnum);	/* XXX */
7497 
7498 			if (theline[0] == ')')
7499 			{
7500 			    if (our_paren_pos.lnum != lnum
7501 						       && cur_amount > amount)
7502 				cur_amount = amount;
7503 			    amount = -1;
7504 			}
7505 		    break;
7506 		}
7507 	    }
7508 	}
7509 
7510 	/*
7511 	 * Line up with line where the matching paren is. XXX
7512 	 * If the line starts with a '(' or the indent for unclosed
7513 	 * parentheses is zero, line up with the unclosed parentheses.
7514 	 */
7515 	if (amount == -1)
7516 	{
7517 	    int	    ignore_paren_col = 0;
7518 	    int	    is_if_for_while = 0;
7519 
7520 	    if (curbuf->b_ind_if_for_while)
7521 	    {
7522 		/* Look for the outermost opening parenthesis on this line
7523 		 * and check whether it belongs to an "if", "for" or "while". */
7524 
7525 		pos_T	    cursor_save = curwin->w_cursor;
7526 		pos_T	    outermost;
7527 		char_u	    *line;
7528 
7529 		trypos = &our_paren_pos;
7530 		do {
7531 		    outermost = *trypos;
7532 		    curwin->w_cursor.lnum = outermost.lnum;
7533 		    curwin->w_cursor.col = outermost.col;
7534 
7535 		    trypos = find_match_paren(curbuf->b_ind_maxparen);
7536 		} while (trypos && trypos->lnum == outermost.lnum);
7537 
7538 		curwin->w_cursor = cursor_save;
7539 
7540 		line = ml_get(outermost.lnum);
7541 
7542 		is_if_for_while =
7543 		    cin_is_if_for_while_before_offset(line, &outermost.col);
7544 	    }
7545 
7546 	    amount = skip_label(our_paren_pos.lnum, &look);
7547 	    look = skipwhite(look);
7548 	    if (*look == '(')
7549 	    {
7550 		linenr_T    save_lnum = curwin->w_cursor.lnum;
7551 		char_u	    *line;
7552 		int	    look_col;
7553 
7554 		/* Ignore a '(' in front of the line that has a match before
7555 		 * our matching '('. */
7556 		curwin->w_cursor.lnum = our_paren_pos.lnum;
7557 		line = ml_get_curline();
7558 		look_col = (int)(look - line);
7559 		curwin->w_cursor.col = look_col + 1;
7560 		if ((trypos = findmatchlimit(NULL, ')', 0,
7561 						      curbuf->b_ind_maxparen))
7562 								      != NULL
7563 			  && trypos->lnum == our_paren_pos.lnum
7564 			  && trypos->col < our_paren_pos.col)
7565 		    ignore_paren_col = trypos->col + 1;
7566 
7567 		curwin->w_cursor.lnum = save_lnum;
7568 		look = ml_get(our_paren_pos.lnum) + look_col;
7569 	    }
7570 	    if (theline[0] == ')' || (curbuf->b_ind_unclosed == 0
7571 						      && is_if_for_while == 0)
7572 		    || (!curbuf->b_ind_unclosed_noignore && *look == '('
7573 						    && ignore_paren_col == 0))
7574 	    {
7575 		/*
7576 		 * If we're looking at a close paren, line up right there;
7577 		 * otherwise, line up with the next (non-white) character.
7578 		 * When b_ind_unclosed_wrapped is set and the matching paren is
7579 		 * the last nonwhite character of the line, use either the
7580 		 * indent of the current line or the indentation of the next
7581 		 * outer paren and add b_ind_unclosed_wrapped (for very long
7582 		 * lines).
7583 		 */
7584 		if (theline[0] != ')')
7585 		{
7586 		    cur_amount = MAXCOL;
7587 		    l = ml_get(our_paren_pos.lnum);
7588 		    if (curbuf->b_ind_unclosed_wrapped
7589 				       && cin_ends_in(l, (char_u *)"(", NULL))
7590 		    {
7591 			/* look for opening unmatched paren, indent one level
7592 			 * for each additional level */
7593 			n = 1;
7594 			for (col = 0; col < our_paren_pos.col; ++col)
7595 			{
7596 			    switch (l[col])
7597 			    {
7598 				case '(':
7599 				case '{': ++n;
7600 					  break;
7601 
7602 				case ')':
7603 				case '}': if (n > 1)
7604 					      --n;
7605 					  break;
7606 			    }
7607 			}
7608 
7609 			our_paren_pos.col = 0;
7610 			amount += n * curbuf->b_ind_unclosed_wrapped;
7611 		    }
7612 		    else if (curbuf->b_ind_unclosed_whiteok)
7613 			our_paren_pos.col++;
7614 		    else
7615 		    {
7616 			col = our_paren_pos.col + 1;
7617 			while (VIM_ISWHITE(l[col]))
7618 			    col++;
7619 			if (l[col] != NUL)	/* In case of trailing space */
7620 			    our_paren_pos.col = col;
7621 			else
7622 			    our_paren_pos.col++;
7623 		    }
7624 		}
7625 
7626 		/*
7627 		 * Find how indented the paren is, or the character after it
7628 		 * if we did the above "if".
7629 		 */
7630 		if (our_paren_pos.col > 0)
7631 		{
7632 		    getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7633 		    if (cur_amount > (int)col)
7634 			cur_amount = col;
7635 		}
7636 	    }
7637 
7638 	    if (theline[0] == ')' && curbuf->b_ind_matching_paren)
7639 	    {
7640 		/* Line up with the start of the matching paren line. */
7641 	    }
7642 	    else if ((curbuf->b_ind_unclosed == 0 && is_if_for_while == 0)
7643 		     || (!curbuf->b_ind_unclosed_noignore
7644 				    && *look == '(' && ignore_paren_col == 0))
7645 	    {
7646 		if (cur_amount != MAXCOL)
7647 		    amount = cur_amount;
7648 	    }
7649 	    else
7650 	    {
7651 		/* Add b_ind_unclosed2 for each '(' before our matching one,
7652 		 * but ignore (void) before the line (ignore_paren_col). */
7653 		col = our_paren_pos.col;
7654 		while ((int)our_paren_pos.col > ignore_paren_col)
7655 		{
7656 		    --our_paren_pos.col;
7657 		    switch (*ml_get_pos(&our_paren_pos))
7658 		    {
7659 			case '(': amount += curbuf->b_ind_unclosed2;
7660 				  col = our_paren_pos.col;
7661 				  break;
7662 			case ')': amount -= curbuf->b_ind_unclosed2;
7663 				  col = MAXCOL;
7664 				  break;
7665 		    }
7666 		}
7667 
7668 		/* Use b_ind_unclosed once, when the first '(' is not inside
7669 		 * braces */
7670 		if (col == MAXCOL)
7671 		    amount += curbuf->b_ind_unclosed;
7672 		else
7673 		{
7674 		    curwin->w_cursor.lnum = our_paren_pos.lnum;
7675 		    curwin->w_cursor.col = col;
7676 		    if (find_match_paren_after_brace(curbuf->b_ind_maxparen)
7677 								      != NULL)
7678 			amount += curbuf->b_ind_unclosed2;
7679 		    else
7680 		    {
7681 			if (is_if_for_while)
7682 			    amount += curbuf->b_ind_if_for_while;
7683 			else
7684 			    amount += curbuf->b_ind_unclosed;
7685 		    }
7686 		}
7687 		/*
7688 		 * For a line starting with ')' use the minimum of the two
7689 		 * positions, to avoid giving it more indent than the previous
7690 		 * lines:
7691 		 *  func_long_name(		    if (x
7692 		 *	arg				    && yy
7693 		 *	)	  ^ not here	       )    ^ not here
7694 		 */
7695 		if (cur_amount < amount)
7696 		    amount = cur_amount;
7697 	    }
7698 	}
7699 
7700 	/* add extra indent for a comment */
7701 	if (cin_iscomment(theline))
7702 	    amount += curbuf->b_ind_comment;
7703       }
7704       else
7705       {
7706 	/*
7707 	 * We are inside braces, there is a { before this line at the position
7708 	 * stored in tryposBrace.
7709 	 * Make a copy of tryposBrace, it may point to pos_copy inside
7710 	 * find_start_brace(), which may be changed somewhere.
7711 	 */
7712 	tryposCopy = *tryposBrace;
7713 	tryposBrace = &tryposCopy;
7714 	trypos = tryposBrace;
7715 	ourscope = trypos->lnum;
7716 	start = ml_get(ourscope);
7717 
7718 	/*
7719 	 * Now figure out how indented the line is in general.
7720 	 * If the brace was at the start of the line, we use that;
7721 	 * otherwise, check out the indentation of the line as
7722 	 * a whole and then add the "imaginary indent" to that.
7723 	 */
7724 	look = skipwhite(start);
7725 	if (*look == '{')
7726 	{
7727 	    getvcol(curwin, trypos, &col, NULL, NULL);
7728 	    amount = col;
7729 	    if (*start == '{')
7730 		start_brace = BRACE_IN_COL0;
7731 	    else
7732 		start_brace = BRACE_AT_START;
7733 	}
7734 	else
7735 	{
7736 	    /* That opening brace might have been on a continuation
7737 	     * line.  if so, find the start of the line. */
7738 	    curwin->w_cursor.lnum = ourscope;
7739 
7740 	    /* Position the cursor over the rightmost paren, so that
7741 	     * matching it will take us back to the start of the line. */
7742 	    lnum = ourscope;
7743 	    if (find_last_paren(start, '(', ')')
7744 			&& (trypos = find_match_paren(curbuf->b_ind_maxparen))
7745 								      != NULL)
7746 		lnum = trypos->lnum;
7747 
7748 	    /* It could have been something like
7749 	     *	   case 1: if (asdf &&
7750 	     *			ldfd) {
7751 	     *		    }
7752 	     */
7753 	    if ((curbuf->b_ind_js || curbuf->b_ind_keep_case_label)
7754 			   && cin_iscase(skipwhite(ml_get_curline()), FALSE))
7755 		amount = get_indent();
7756 	    else if (curbuf->b_ind_js)
7757 		amount = get_indent_lnum(lnum);
7758 	    else
7759 		amount = skip_label(lnum, &l);
7760 
7761 	    start_brace = BRACE_AT_END;
7762 	}
7763 
7764 	/* For Javascript check if the line starts with "key:". */
7765 	if (curbuf->b_ind_js)
7766 	    js_cur_has_key = cin_has_js_key(theline);
7767 
7768 	/*
7769 	 * If we're looking at a closing brace, that's where
7770 	 * we want to be.  otherwise, add the amount of room
7771 	 * that an indent is supposed to be.
7772 	 */
7773 	if (theline[0] == '}')
7774 	{
7775 	    /*
7776 	     * they may want closing braces to line up with something
7777 	     * other than the open brace.  indulge them, if so.
7778 	     */
7779 	    amount += curbuf->b_ind_close_extra;
7780 	}
7781 	else
7782 	{
7783 	    /*
7784 	     * If we're looking at an "else", try to find an "if"
7785 	     * to match it with.
7786 	     * If we're looking at a "while", try to find a "do"
7787 	     * to match it with.
7788 	     */
7789 	    lookfor = LOOKFOR_INITIAL;
7790 	    if (cin_iselse(theline))
7791 		lookfor = LOOKFOR_IF;
7792 	    else if (cin_iswhileofdo(theline, cur_curpos.lnum)) /* XXX */
7793 		lookfor = LOOKFOR_DO;
7794 	    if (lookfor != LOOKFOR_INITIAL)
7795 	    {
7796 		curwin->w_cursor.lnum = cur_curpos.lnum;
7797 		if (find_match(lookfor, ourscope) == OK)
7798 		{
7799 		    amount = get_indent();	/* XXX */
7800 		    goto theend;
7801 		}
7802 	    }
7803 
7804 	    /*
7805 	     * We get here if we are not on an "while-of-do" or "else" (or
7806 	     * failed to find a matching "if").
7807 	     * Search backwards for something to line up with.
7808 	     * First set amount for when we don't find anything.
7809 	     */
7810 
7811 	    /*
7812 	     * if the '{' is  _really_ at the left margin, use the imaginary
7813 	     * location of a left-margin brace.  Otherwise, correct the
7814 	     * location for b_ind_open_extra.
7815 	     */
7816 
7817 	    if (start_brace == BRACE_IN_COL0)	    /* '{' is in column 0 */
7818 	    {
7819 		amount = curbuf->b_ind_open_left_imag;
7820 		lookfor_cpp_namespace = TRUE;
7821 	    }
7822 	    else if (start_brace == BRACE_AT_START &&
7823 		    lookfor_cpp_namespace)	  /* '{' is at start */
7824 	    {
7825 
7826 		lookfor_cpp_namespace = TRUE;
7827 	    }
7828 	    else
7829 	    {
7830 		if (start_brace == BRACE_AT_END)    /* '{' is at end of line */
7831 		{
7832 		    amount += curbuf->b_ind_open_imag;
7833 
7834 		    l = skipwhite(ml_get_curline());
7835 		    if (cin_is_cpp_namespace(l))
7836 			amount += curbuf->b_ind_cpp_namespace;
7837 		    else if (cin_is_cpp_extern_c(l))
7838 			amount += curbuf->b_ind_cpp_extern_c;
7839 		}
7840 		else
7841 		{
7842 		    /* Compensate for adding b_ind_open_extra later. */
7843 		    amount -= curbuf->b_ind_open_extra;
7844 		    if (amount < 0)
7845 			amount = 0;
7846 		}
7847 	    }
7848 
7849 	    lookfor_break = FALSE;
7850 
7851 	    if (cin_iscase(theline, FALSE))	/* it's a switch() label */
7852 	    {
7853 		lookfor = LOOKFOR_CASE;	/* find a previous switch() label */
7854 		amount += curbuf->b_ind_case;
7855 	    }
7856 	    else if (cin_isscopedecl(theline))	/* private:, ... */
7857 	    {
7858 		lookfor = LOOKFOR_SCOPEDECL;	/* class decl is this block */
7859 		amount += curbuf->b_ind_scopedecl;
7860 	    }
7861 	    else
7862 	    {
7863 		if (curbuf->b_ind_case_break && cin_isbreak(theline))
7864 		    /* break; ... */
7865 		    lookfor_break = TRUE;
7866 
7867 		lookfor = LOOKFOR_INITIAL;
7868 		/* b_ind_level from start of block */
7869 		amount += curbuf->b_ind_level;
7870 	    }
7871 	    scope_amount = amount;
7872 	    whilelevel = 0;
7873 
7874 	    /*
7875 	     * Search backwards.  If we find something we recognize, line up
7876 	     * with that.
7877 	     *
7878 	     * If we're looking at an open brace, indent
7879 	     * the usual amount relative to the conditional
7880 	     * that opens the block.
7881 	     */
7882 	    curwin->w_cursor = cur_curpos;
7883 	    for (;;)
7884 	    {
7885 		curwin->w_cursor.lnum--;
7886 		curwin->w_cursor.col = 0;
7887 
7888 		/*
7889 		 * If we went all the way back to the start of our scope, line
7890 		 * up with it.
7891 		 */
7892 		if (curwin->w_cursor.lnum <= ourscope)
7893 		{
7894 		    /* We reached end of scope:
7895 		     * If looking for a enum or structure initialization
7896 		     * go further back:
7897 		     * If it is an initializer (enum xxx or xxx =), then
7898 		     * don't add ind_continuation, otherwise it is a variable
7899 		     * declaration:
7900 		     * int x,
7901 		     *     here; <-- add ind_continuation
7902 		     */
7903 		    if (lookfor == LOOKFOR_ENUM_OR_INIT)
7904 		    {
7905 			if (curwin->w_cursor.lnum == 0
7906 				|| curwin->w_cursor.lnum
7907 					  < ourscope - curbuf->b_ind_maxparen)
7908 			{
7909 			    /* nothing found (abuse curbuf->b_ind_maxparen as
7910 			     * limit) assume terminated line (i.e. a variable
7911 			     * initialization) */
7912 			    if (cont_amount > 0)
7913 				amount = cont_amount;
7914 			    else if (!curbuf->b_ind_js)
7915 				amount += ind_continuation;
7916 			    break;
7917 			}
7918 
7919 			l = ml_get_curline();
7920 
7921 			/*
7922 			 * If we're in a comment or raw string now, skip to
7923 			 * the start of it.
7924 			 */
7925 			trypos = ind_find_start_CORS(NULL);
7926 			if (trypos != NULL)
7927 			{
7928 			    curwin->w_cursor.lnum = trypos->lnum + 1;
7929 			    curwin->w_cursor.col = 0;
7930 			    continue;
7931 			}
7932 
7933 			/*
7934 			 * Skip preprocessor directives and blank lines.
7935 			 */
7936 			if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum,
7937 								    &amount))
7938 			    continue;
7939 
7940 			if (cin_nocode(l))
7941 			    continue;
7942 
7943 			terminated = cin_isterminated(l, FALSE, TRUE);
7944 
7945 			/*
7946 			 * If we are at top level and the line looks like a
7947 			 * function declaration, we are done
7948 			 * (it's a variable declaration).
7949 			 */
7950 			if (start_brace != BRACE_IN_COL0
7951 			     || !cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0))
7952 			{
7953 			    /* if the line is terminated with another ','
7954 			     * it is a continued variable initialization.
7955 			     * don't add extra indent.
7956 			     * TODO: does not work, if  a function
7957 			     * declaration is split over multiple lines:
7958 			     * cin_isfuncdecl returns FALSE then.
7959 			     */
7960 			    if (terminated == ',')
7961 				break;
7962 
7963 			    /* if it es a enum declaration or an assignment,
7964 			     * we are done.
7965 			     */
7966 			    if (terminated != ';' && cin_isinit())
7967 				break;
7968 
7969 			    /* nothing useful found */
7970 			    if (terminated == 0 || terminated == '{')
7971 				continue;
7972 			}
7973 
7974 			if (terminated != ';')
7975 			{
7976 			    /* Skip parens and braces. Position the cursor
7977 			     * over the rightmost paren, so that matching it
7978 			     * will take us back to the start of the line.
7979 			     */					/* XXX */
7980 			    trypos = NULL;
7981 			    if (find_last_paren(l, '(', ')'))
7982 				trypos = find_match_paren(
7983 						      curbuf->b_ind_maxparen);
7984 
7985 			    if (trypos == NULL && find_last_paren(l, '{', '}'))
7986 				trypos = find_start_brace();
7987 
7988 			    if (trypos != NULL)
7989 			    {
7990 				curwin->w_cursor.lnum = trypos->lnum + 1;
7991 				curwin->w_cursor.col = 0;
7992 				continue;
7993 			    }
7994 			}
7995 
7996 			/* it's a variable declaration, add indentation
7997 			 * like in
7998 			 * int a,
7999 			 *    b;
8000 			 */
8001 			if (cont_amount > 0)
8002 			    amount = cont_amount;
8003 			else
8004 			    amount += ind_continuation;
8005 		    }
8006 		    else if (lookfor == LOOKFOR_UNTERM)
8007 		    {
8008 			if (cont_amount > 0)
8009 			    amount = cont_amount;
8010 			else
8011 			    amount += ind_continuation;
8012 		    }
8013 		    else
8014 		    {
8015 			if (lookfor != LOOKFOR_TERM
8016 					&& lookfor != LOOKFOR_CPP_BASECLASS
8017 					&& lookfor != LOOKFOR_COMMA)
8018 			{
8019 			    amount = scope_amount;
8020 			    if (theline[0] == '{')
8021 			    {
8022 				amount += curbuf->b_ind_open_extra;
8023 				added_to_amount = curbuf->b_ind_open_extra;
8024 			    }
8025 			}
8026 
8027 			if (lookfor_cpp_namespace)
8028 			{
8029 			    /*
8030 			     * Looking for C++ namespace, need to look further
8031 			     * back.
8032 			     */
8033 			    if (curwin->w_cursor.lnum == ourscope)
8034 				continue;
8035 
8036 			    if (curwin->w_cursor.lnum == 0
8037 				    || curwin->w_cursor.lnum
8038 					      < ourscope - FIND_NAMESPACE_LIM)
8039 				break;
8040 
8041 			    l = ml_get_curline();
8042 
8043 			    /* If we're in a comment or raw string now, skip
8044 			     * to the start of it. */
8045 			    trypos = ind_find_start_CORS(NULL);
8046 			    if (trypos != NULL)
8047 			    {
8048 				curwin->w_cursor.lnum = trypos->lnum + 1;
8049 				curwin->w_cursor.col = 0;
8050 				continue;
8051 			    }
8052 
8053 			    /* Skip preprocessor directives and blank lines. */
8054 			    if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum,
8055 								    &amount))
8056 				continue;
8057 
8058 			    /* Finally the actual check for "namespace". */
8059 			    if (cin_is_cpp_namespace(l))
8060 			    {
8061 				amount += curbuf->b_ind_cpp_namespace
8062 							    - added_to_amount;
8063 				break;
8064 			    }
8065 			    else if (cin_is_cpp_extern_c(l))
8066 			    {
8067 				amount += curbuf->b_ind_cpp_extern_c
8068 							    - added_to_amount;
8069 				break;
8070 			    }
8071 
8072 			    if (cin_nocode(l))
8073 				continue;
8074 			}
8075 		    }
8076 		    break;
8077 		}
8078 
8079 		/*
8080 		 * If we're in a comment or raw string now, skip to the start
8081 		 * of it.
8082 		 */					    /* XXX */
8083 		if ((trypos = ind_find_start_CORS(&raw_string_start)) != NULL)
8084 		{
8085 		    curwin->w_cursor.lnum = trypos->lnum + 1;
8086 		    curwin->w_cursor.col = 0;
8087 		    continue;
8088 		}
8089 
8090 		l = ml_get_curline();
8091 
8092 		/*
8093 		 * If this is a switch() label, may line up relative to that.
8094 		 * If this is a C++ scope declaration, do the same.
8095 		 */
8096 		iscase = cin_iscase(l, FALSE);
8097 		if (iscase || cin_isscopedecl(l))
8098 		{
8099 		    /* we are only looking for cpp base class
8100 		     * declaration/initialization any longer */
8101 		    if (lookfor == LOOKFOR_CPP_BASECLASS)
8102 			break;
8103 
8104 		    /* When looking for a "do" we are not interested in
8105 		     * labels. */
8106 		    if (whilelevel > 0)
8107 			continue;
8108 
8109 		    /*
8110 		     *	case xx:
8111 		     *	    c = 99 +	    <- this indent plus continuation
8112 		     *->	   here;
8113 		     */
8114 		    if (lookfor == LOOKFOR_UNTERM
8115 					   || lookfor == LOOKFOR_ENUM_OR_INIT)
8116 		    {
8117 			if (cont_amount > 0)
8118 			    amount = cont_amount;
8119 			else
8120 			    amount += ind_continuation;
8121 			break;
8122 		    }
8123 
8124 		    /*
8125 		     *	case xx:	<- line up with this case
8126 		     *	    x = 333;
8127 		     *	case yy:
8128 		     */
8129 		    if (       (iscase && lookfor == LOOKFOR_CASE)
8130 			    || (iscase && lookfor_break)
8131 			    || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
8132 		    {
8133 			/*
8134 			 * Check that this case label is not for another
8135 			 * switch()
8136 			 */				    /* XXX */
8137 			if ((trypos = find_start_brace()) == NULL
8138 						  || trypos->lnum == ourscope)
8139 			{
8140 			    amount = get_indent();	/* XXX */
8141 			    break;
8142 			}
8143 			continue;
8144 		    }
8145 
8146 		    n = get_indent_nolabel(curwin->w_cursor.lnum);  /* XXX */
8147 
8148 		    /*
8149 		     *	 case xx: if (cond)	    <- line up with this if
8150 		     *		      y = y + 1;
8151 		     * ->	  s = 99;
8152 		     *
8153 		     *	 case xx:
8154 		     *	     if (cond)		<- line up with this line
8155 		     *		 y = y + 1;
8156 		     * ->    s = 99;
8157 		     */
8158 		    if (lookfor == LOOKFOR_TERM)
8159 		    {
8160 			if (n)
8161 			    amount = n;
8162 
8163 			if (!lookfor_break)
8164 			    break;
8165 		    }
8166 
8167 		    /*
8168 		     *	 case xx: x = x + 1;	    <- line up with this x
8169 		     * ->	  y = y + 1;
8170 		     *
8171 		     *	 case xx: if (cond)	    <- line up with this if
8172 		     * ->	       y = y + 1;
8173 		     */
8174 		    if (n)
8175 		    {
8176 			amount = n;
8177 			l = after_label(ml_get_curline());
8178 			if (l != NULL && cin_is_cinword(l))
8179 			{
8180 			    if (theline[0] == '{')
8181 				amount += curbuf->b_ind_open_extra;
8182 			    else
8183 				amount += curbuf->b_ind_level
8184 						     + curbuf->b_ind_no_brace;
8185 			}
8186 			break;
8187 		    }
8188 
8189 		    /*
8190 		     * Try to get the indent of a statement before the switch
8191 		     * label.  If nothing is found, line up relative to the
8192 		     * switch label.
8193 		     *	    break;		<- may line up with this line
8194 		     *	 case xx:
8195 		     * ->   y = 1;
8196 		     */
8197 		    scope_amount = get_indent() + (iscase    /* XXX */
8198 					? curbuf->b_ind_case_code
8199 					: curbuf->b_ind_scopedecl_code);
8200 		    lookfor = curbuf->b_ind_case_break
8201 					      ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
8202 		    continue;
8203 		}
8204 
8205 		/*
8206 		 * Looking for a switch() label or C++ scope declaration,
8207 		 * ignore other lines, skip {}-blocks.
8208 		 */
8209 		if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
8210 		{
8211 		    if (find_last_paren(l, '{', '}')
8212 				     && (trypos = find_start_brace()) != NULL)
8213 		    {
8214 			curwin->w_cursor.lnum = trypos->lnum + 1;
8215 			curwin->w_cursor.col = 0;
8216 		    }
8217 		    continue;
8218 		}
8219 
8220 		/*
8221 		 * Ignore jump labels with nothing after them.
8222 		 */
8223 		if (!curbuf->b_ind_js && cin_islabel())
8224 		{
8225 		    l = after_label(ml_get_curline());
8226 		    if (l == NULL || cin_nocode(l))
8227 			continue;
8228 		}
8229 
8230 		/*
8231 		 * Ignore #defines, #if, etc.
8232 		 * Ignore comment and empty lines.
8233 		 * (need to get the line again, cin_islabel() may have
8234 		 * unlocked it)
8235 		 */
8236 		l = ml_get_curline();
8237 		if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount)
8238 							     || cin_nocode(l))
8239 		    continue;
8240 
8241 		/*
8242 		 * Are we at the start of a cpp base class declaration or
8243 		 * constructor initialization?
8244 		 */						    /* XXX */
8245 		n = FALSE;
8246 		if (lookfor != LOOKFOR_TERM && curbuf->b_ind_cpp_baseclass > 0)
8247 		{
8248 		    n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
8249 		    l = ml_get_curline();
8250 		}
8251 		if (n)
8252 		{
8253 		    if (lookfor == LOOKFOR_UNTERM)
8254 		    {
8255 			if (cont_amount > 0)
8256 			    amount = cont_amount;
8257 			else
8258 			    amount += ind_continuation;
8259 		    }
8260 		    else if (theline[0] == '{')
8261 		    {
8262 			/* Need to find start of the declaration. */
8263 			lookfor = LOOKFOR_UNTERM;
8264 			ind_continuation = 0;
8265 			continue;
8266 		    }
8267 		    else
8268 								     /* XXX */
8269 			amount = get_baseclass_amount(
8270 						cache_cpp_baseclass.lpos.col);
8271 		    break;
8272 		}
8273 		else if (lookfor == LOOKFOR_CPP_BASECLASS)
8274 		{
8275 		    /* only look, whether there is a cpp base class
8276 		     * declaration or initialization before the opening brace.
8277 		     */
8278 		    if (cin_isterminated(l, TRUE, FALSE))
8279 			break;
8280 		    else
8281 			continue;
8282 		}
8283 
8284 		/*
8285 		 * What happens next depends on the line being terminated.
8286 		 * If terminated with a ',' only consider it terminating if
8287 		 * there is another unterminated statement behind, eg:
8288 		 *   123,
8289 		 *   sizeof
8290 		 *	  here
8291 		 * Otherwise check whether it is a enumeration or structure
8292 		 * initialisation (not indented) or a variable declaration
8293 		 * (indented).
8294 		 */
8295 		terminated = cin_isterminated(l, FALSE, TRUE);
8296 
8297 		if (js_cur_has_key)
8298 		{
8299 		    js_cur_has_key = 0; /* only check the first line */
8300 		    if (curbuf->b_ind_js && terminated == ',')
8301 		    {
8302 			/* For Javascript we might be inside an object:
8303 			 *   key: something,  <- align with this
8304 			 *   key: something
8305 			 * or:
8306 			 *   key: something +  <- align with this
8307 			 *       something,
8308 			 *   key: something
8309 			 */
8310 			lookfor = LOOKFOR_JS_KEY;
8311 		    }
8312 		}
8313 		if (lookfor == LOOKFOR_JS_KEY && cin_has_js_key(l))
8314 		{
8315 		    amount = get_indent();
8316 		    break;
8317 		}
8318 		if (lookfor == LOOKFOR_COMMA)
8319 		{
8320 		    if (tryposBrace != NULL && tryposBrace->lnum
8321 						    >= curwin->w_cursor.lnum)
8322 			break;
8323 		    if (terminated == ',')
8324 			/* line below current line is the one that starts a
8325 			 * (possibly broken) line ending in a comma. */
8326 			break;
8327 		    else
8328 		    {
8329 			amount = get_indent();
8330 			if (curwin->w_cursor.lnum - 1 == ourscope)
8331 			    /* line above is start of the scope, thus current
8332 			     * line is the one that stars a (possibly broken)
8333 			     * line ending in a comma. */
8334 			    break;
8335 		    }
8336 		}
8337 
8338 		if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
8339 							&& terminated == ','))
8340 		{
8341 		    if (lookfor != LOOKFOR_ENUM_OR_INIT &&
8342 			    (*skipwhite(l) == '[' || l[STRLEN(l) - 1] == '['))
8343 			amount += ind_continuation;
8344 		    /*
8345 		     * if we're in the middle of a paren thing,
8346 		     * go back to the line that starts it so
8347 		     * we can get the right prevailing indent
8348 		     *	   if ( foo &&
8349 		     *		    bar )
8350 		     */
8351 		    /*
8352 		     * Position the cursor over the rightmost paren, so that
8353 		     * matching it will take us back to the start of the line.
8354 		     * Ignore a match before the start of the block.
8355 		     */
8356 		    (void)find_last_paren(l, '(', ')');
8357 		    trypos = find_match_paren(corr_ind_maxparen(&cur_curpos));
8358 		    if (trypos != NULL && (trypos->lnum < tryposBrace->lnum
8359 				|| (trypos->lnum == tryposBrace->lnum
8360 				    && trypos->col < tryposBrace->col)))
8361 			trypos = NULL;
8362 
8363 		    /*
8364 		     * If we are looking for ',', we also look for matching
8365 		     * braces.
8366 		     */
8367 		    if (trypos == NULL && terminated == ','
8368 					      && find_last_paren(l, '{', '}'))
8369 			trypos = find_start_brace();
8370 
8371 		    if (trypos != NULL)
8372 		    {
8373 			/*
8374 			 * Check if we are on a case label now.  This is
8375 			 * handled above.
8376 			 *     case xx:  if ( asdf &&
8377 			 *			asdf)
8378 			 */
8379 			curwin->w_cursor = *trypos;
8380 			l = ml_get_curline();
8381 			if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
8382 			{
8383 			    ++curwin->w_cursor.lnum;
8384 			    curwin->w_cursor.col = 0;
8385 			    continue;
8386 			}
8387 		    }
8388 
8389 		    /*
8390 		     * Skip over continuation lines to find the one to get the
8391 		     * indent from
8392 		     * char *usethis = "bla\
8393 		     *		 bla",
8394 		     *      here;
8395 		     */
8396 		    if (terminated == ',')
8397 		    {
8398 			while (curwin->w_cursor.lnum > 1)
8399 			{
8400 			    l = ml_get(curwin->w_cursor.lnum - 1);
8401 			    if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8402 				break;
8403 			    --curwin->w_cursor.lnum;
8404 			    curwin->w_cursor.col = 0;
8405 			}
8406 		    }
8407 
8408 		    /*
8409 		     * Get indent and pointer to text for current line,
8410 		     * ignoring any jump label.	    XXX
8411 		     */
8412 		    if (curbuf->b_ind_js)
8413 			cur_amount = get_indent();
8414 		    else
8415 			cur_amount = skip_label(curwin->w_cursor.lnum, &l);
8416 		    /*
8417 		     * If this is just above the line we are indenting, and it
8418 		     * starts with a '{', line it up with this line.
8419 		     *		while (not)
8420 		     * ->	{
8421 		     *		}
8422 		     */
8423 		    if (terminated != ',' && lookfor != LOOKFOR_TERM
8424 							 && theline[0] == '{')
8425 		    {
8426 			amount = cur_amount;
8427 			/*
8428 			 * Only add b_ind_open_extra when the current line
8429 			 * doesn't start with a '{', which must have a match
8430 			 * in the same line (scope is the same).  Probably:
8431 			 *	{ 1, 2 },
8432 			 * ->	{ 3, 4 }
8433 			 */
8434 			if (*skipwhite(l) != '{')
8435 			    amount += curbuf->b_ind_open_extra;
8436 
8437 			if (curbuf->b_ind_cpp_baseclass && !curbuf->b_ind_js)
8438 			{
8439 			    /* have to look back, whether it is a cpp base
8440 			     * class declaration or initialization */
8441 			    lookfor = LOOKFOR_CPP_BASECLASS;
8442 			    continue;
8443 			}
8444 			break;
8445 		    }
8446 
8447 		    /*
8448 		     * Check if we are after an "if", "while", etc.
8449 		     * Also allow "   } else".
8450 		     */
8451 		    if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
8452 		    {
8453 			/*
8454 			 * Found an unterminated line after an if (), line up
8455 			 * with the last one.
8456 			 *   if (cond)
8457 			 *	    100 +
8458 			 * ->		here;
8459 			 */
8460 			if (lookfor == LOOKFOR_UNTERM
8461 					   || lookfor == LOOKFOR_ENUM_OR_INIT)
8462 			{
8463 			    if (cont_amount > 0)
8464 				amount = cont_amount;
8465 			    else
8466 				amount += ind_continuation;
8467 			    break;
8468 			}
8469 
8470 			/*
8471 			 * If this is just above the line we are indenting, we
8472 			 * are finished.
8473 			 *	    while (not)
8474 			 * ->		here;
8475 			 * Otherwise this indent can be used when the line
8476 			 * before this is terminated.
8477 			 *	yyy;
8478 			 *	if (stat)
8479 			 *	    while (not)
8480 			 *		xxx;
8481 			 * ->	here;
8482 			 */
8483 			amount = cur_amount;
8484 			if (theline[0] == '{')
8485 			    amount += curbuf->b_ind_open_extra;
8486 			if (lookfor != LOOKFOR_TERM)
8487 			{
8488 			    amount += curbuf->b_ind_level
8489 						     + curbuf->b_ind_no_brace;
8490 			    break;
8491 			}
8492 
8493 			/*
8494 			 * Special trick: when expecting the while () after a
8495 			 * do, line up with the while()
8496 			 *     do
8497 			 *	    x = 1;
8498 			 * ->  here
8499 			 */
8500 			l = skipwhite(ml_get_curline());
8501 			if (cin_isdo(l))
8502 			{
8503 			    if (whilelevel == 0)
8504 				break;
8505 			    --whilelevel;
8506 			}
8507 
8508 			/*
8509 			 * When searching for a terminated line, don't use the
8510 			 * one between the "if" and the matching "else".
8511 			 * Need to use the scope of this "else".  XXX
8512 			 * If whilelevel != 0 continue looking for a "do {".
8513 			 */
8514 			if (cin_iselse(l) && whilelevel == 0)
8515 			{
8516 			    /* If we're looking at "} else", let's make sure we
8517 			     * find the opening brace of the enclosing scope,
8518 			     * not the one from "if () {". */
8519 			    if (*l == '}')
8520 				curwin->w_cursor.col =
8521 					  (colnr_T)(l - ml_get_curline()) + 1;
8522 
8523 			    if ((trypos = find_start_brace()) == NULL
8524 				       || find_match(LOOKFOR_IF, trypos->lnum)
8525 								      == FAIL)
8526 				break;
8527 			}
8528 		    }
8529 
8530 		    /*
8531 		     * If we're below an unterminated line that is not an
8532 		     * "if" or something, we may line up with this line or
8533 		     * add something for a continuation line, depending on
8534 		     * the line before this one.
8535 		     */
8536 		    else
8537 		    {
8538 			/*
8539 			 * Found two unterminated lines on a row, line up with
8540 			 * the last one.
8541 			 *   c = 99 +
8542 			 *	    100 +
8543 			 * ->	    here;
8544 			 */
8545 			if (lookfor == LOOKFOR_UNTERM)
8546 			{
8547 			    /* When line ends in a comma add extra indent */
8548 			    if (terminated == ',')
8549 				amount += ind_continuation;
8550 			    break;
8551 			}
8552 
8553 			if (lookfor == LOOKFOR_ENUM_OR_INIT)
8554 			{
8555 			    /* Found two lines ending in ',', lineup with the
8556 			     * lowest one, but check for cpp base class
8557 			     * declaration/initialization, if it is an
8558 			     * opening brace or we are looking just for
8559 			     * enumerations/initializations. */
8560 			    if (terminated == ',')
8561 			    {
8562 				if (curbuf->b_ind_cpp_baseclass == 0)
8563 				    break;
8564 
8565 				lookfor = LOOKFOR_CPP_BASECLASS;
8566 				continue;
8567 			    }
8568 
8569 			    /* Ignore unterminated lines in between, but
8570 			     * reduce indent. */
8571 			    if (amount > cur_amount)
8572 				amount = cur_amount;
8573 			}
8574 			else
8575 			{
8576 			    /*
8577 			     * Found first unterminated line on a row, may
8578 			     * line up with this line, remember its indent
8579 			     *	    100 +
8580 			     * ->	    here;
8581 			     */
8582 			    l = ml_get_curline();
8583 			    amount = cur_amount;
8584 
8585 			    n = (int)STRLEN(l);
8586 			    if (terminated == ',' && (*skipwhite(l) == ']'
8587 					|| (n >=2 && l[n - 2] == ']')))
8588 				break;
8589 
8590 			    /*
8591 			     * If previous line ends in ',', check whether we
8592 			     * are in an initialization or enum
8593 			     * struct xxx =
8594 			     * {
8595 			     *      sizeof a,
8596 			     *      124 };
8597 			     * or a normal possible continuation line.
8598 			     * but only, of no other statement has been found
8599 			     * yet.
8600 			     */
8601 			    if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8602 			    {
8603 				if (curbuf->b_ind_js)
8604 				{
8605 				    /* Search for a line ending in a comma
8606 				     * and line up with the line below it
8607 				     * (could be the current line).
8608 				     * some = [
8609 				     *     1,     <- line up here
8610 				     *     2,
8611 				     * some = [
8612 				     *     3 +    <- line up here
8613 				     *       4 *
8614 				     *        5,
8615 				     *     6,
8616 				     */
8617 				    if (cin_iscomment(skipwhite(l)))
8618 					break;
8619 				    lookfor = LOOKFOR_COMMA;
8620 				    trypos = find_match_char('[',
8621 						      curbuf->b_ind_maxparen);
8622 				    if (trypos != NULL)
8623 				    {
8624 					if (trypos->lnum
8625 						 == curwin->w_cursor.lnum - 1)
8626 					{
8627 					    /* Current line is first inside
8628 					     * [], line up with it. */
8629 					    break;
8630 					}
8631 					ourscope = trypos->lnum;
8632 				    }
8633 				}
8634 				else
8635 				{
8636 				    lookfor = LOOKFOR_ENUM_OR_INIT;
8637 				    cont_amount = cin_first_id_amount();
8638 				}
8639 			    }
8640 			    else
8641 			    {
8642 				if (lookfor == LOOKFOR_INITIAL
8643 					&& *l != NUL
8644 					&& l[STRLEN(l) - 1] == '\\')
8645 								/* XXX */
8646 				    cont_amount = cin_get_equal_amount(
8647 						       curwin->w_cursor.lnum);
8648 				if (lookfor != LOOKFOR_TERM
8649 						&& lookfor != LOOKFOR_JS_KEY
8650 						&& lookfor != LOOKFOR_COMMA
8651 						&& raw_string_start != curwin->w_cursor.lnum)
8652 				    lookfor = LOOKFOR_UNTERM;
8653 			    }
8654 			}
8655 		    }
8656 		}
8657 
8658 		/*
8659 		 * Check if we are after a while (cond);
8660 		 * If so: Ignore until the matching "do".
8661 		 */
8662 		else if (cin_iswhileofdo_end(terminated)) /* XXX */
8663 		{
8664 		    /*
8665 		     * Found an unterminated line after a while ();, line up
8666 		     * with the last one.
8667 		     *	    while (cond);
8668 		     *	    100 +		<- line up with this one
8669 		     * ->	    here;
8670 		     */
8671 		    if (lookfor == LOOKFOR_UNTERM
8672 					   || lookfor == LOOKFOR_ENUM_OR_INIT)
8673 		    {
8674 			if (cont_amount > 0)
8675 			    amount = cont_amount;
8676 			else
8677 			    amount += ind_continuation;
8678 			break;
8679 		    }
8680 
8681 		    if (whilelevel == 0)
8682 		    {
8683 			lookfor = LOOKFOR_TERM;
8684 			amount = get_indent();	    /* XXX */
8685 			if (theline[0] == '{')
8686 			    amount += curbuf->b_ind_open_extra;
8687 		    }
8688 		    ++whilelevel;
8689 		}
8690 
8691 		/*
8692 		 * We are after a "normal" statement.
8693 		 * If we had another statement we can stop now and use the
8694 		 * indent of that other statement.
8695 		 * Otherwise the indent of the current statement may be used,
8696 		 * search backwards for the next "normal" statement.
8697 		 */
8698 		else
8699 		{
8700 		    /*
8701 		     * Skip single break line, if before a switch label. It
8702 		     * may be lined up with the case label.
8703 		     */
8704 		    if (lookfor == LOOKFOR_NOBREAK
8705 				  && cin_isbreak(skipwhite(ml_get_curline())))
8706 		    {
8707 			lookfor = LOOKFOR_ANY;
8708 			continue;
8709 		    }
8710 
8711 		    /*
8712 		     * Handle "do {" line.
8713 		     */
8714 		    if (whilelevel > 0)
8715 		    {
8716 			l = cin_skipcomment(ml_get_curline());
8717 			if (cin_isdo(l))
8718 			{
8719 			    amount = get_indent();	/* XXX */
8720 			    --whilelevel;
8721 			    continue;
8722 			}
8723 		    }
8724 
8725 		    /*
8726 		     * Found a terminated line above an unterminated line. Add
8727 		     * the amount for a continuation line.
8728 		     *	 x = 1;
8729 		     *	 y = foo +
8730 		     * ->	here;
8731 		     * or
8732 		     *	 int x = 1;
8733 		     *	 int foo,
8734 		     * ->	here;
8735 		     */
8736 		    if (lookfor == LOOKFOR_UNTERM
8737 					   || lookfor == LOOKFOR_ENUM_OR_INIT)
8738 		    {
8739 			if (cont_amount > 0)
8740 			    amount = cont_amount;
8741 			else
8742 			    amount += ind_continuation;
8743 			break;
8744 		    }
8745 
8746 		    /*
8747 		     * Found a terminated line above a terminated line or "if"
8748 		     * etc. line. Use the amount of the line below us.
8749 		     *	 x = 1;				x = 1;
8750 		     *	 if (asdf)		    y = 2;
8751 		     *	     while (asdf)	  ->here;
8752 		     *		here;
8753 		     * ->foo;
8754 		     */
8755 		    if (lookfor == LOOKFOR_TERM)
8756 		    {
8757 			if (!lookfor_break && whilelevel == 0)
8758 			    break;
8759 		    }
8760 
8761 		    /*
8762 		     * First line above the one we're indenting is terminated.
8763 		     * To know what needs to be done look further backward for
8764 		     * a terminated line.
8765 		     */
8766 		    else
8767 		    {
8768 			/*
8769 			 * position the cursor over the rightmost paren, so
8770 			 * that matching it will take us back to the start of
8771 			 * the line.  Helps for:
8772 			 *     func(asdr,
8773 			 *	      asdfasdf);
8774 			 *     here;
8775 			 */
8776 term_again:
8777 			l = ml_get_curline();
8778 			if (find_last_paren(l, '(', ')')
8779 				&& (trypos = find_match_paren(
8780 					   curbuf->b_ind_maxparen)) != NULL)
8781 			{
8782 			    /*
8783 			     * Check if we are on a case label now.  This is
8784 			     * handled above.
8785 			     *	   case xx:  if ( asdf &&
8786 			     *			    asdf)
8787 			     */
8788 			    curwin->w_cursor = *trypos;
8789 			    l = ml_get_curline();
8790 			    if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
8791 			    {
8792 				++curwin->w_cursor.lnum;
8793 				curwin->w_cursor.col = 0;
8794 				continue;
8795 			    }
8796 			}
8797 
8798 			/* When aligning with the case statement, don't align
8799 			 * with a statement after it.
8800 			 *  case 1: {   <-- don't use this { position
8801 			 *	stat;
8802 			 *  }
8803 			 *  case 2:
8804 			 *	stat;
8805 			 * }
8806 			 */
8807 			iscase = (curbuf->b_ind_keep_case_label
8808 						     && cin_iscase(l, FALSE));
8809 
8810 			/*
8811 			 * Get indent and pointer to text for current line,
8812 			 * ignoring any jump label.
8813 			 */
8814 			amount = skip_label(curwin->w_cursor.lnum, &l);
8815 
8816 			if (theline[0] == '{')
8817 			    amount += curbuf->b_ind_open_extra;
8818 			/* See remark above: "Only add b_ind_open_extra.." */
8819 			l = skipwhite(l);
8820 			if (*l == '{')
8821 			    amount -= curbuf->b_ind_open_extra;
8822 			lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8823 
8824 			/*
8825 			 * When a terminated line starts with "else" skip to
8826 			 * the matching "if":
8827 			 *       else 3;
8828 			 *	     indent this;
8829 			 * Need to use the scope of this "else".  XXX
8830 			 * If whilelevel != 0 continue looking for a "do {".
8831 			 */
8832 			if (lookfor == LOOKFOR_TERM
8833 				&& *l != '}'
8834 				&& cin_iselse(l)
8835 				&& whilelevel == 0)
8836 			{
8837 			    if ((trypos = find_start_brace()) == NULL
8838 				       || find_match(LOOKFOR_IF, trypos->lnum)
8839 								      == FAIL)
8840 				break;
8841 			    continue;
8842 			}
8843 
8844 			/*
8845 			 * If we're at the end of a block, skip to the start of
8846 			 * that block.
8847 			 */
8848 			l = ml_get_curline();
8849 			if (find_last_paren(l, '{', '}') /* XXX */
8850 				     && (trypos = find_start_brace()) != NULL)
8851 			{
8852 			    curwin->w_cursor = *trypos;
8853 			    /* if not "else {" check for terminated again */
8854 			    /* but skip block for "} else {" */
8855 			    l = cin_skipcomment(ml_get_curline());
8856 			    if (*l == '}' || !cin_iselse(l))
8857 				goto term_again;
8858 			    ++curwin->w_cursor.lnum;
8859 			    curwin->w_cursor.col = 0;
8860 			}
8861 		    }
8862 		}
8863 	    }
8864 	}
8865       }
8866 
8867       /* add extra indent for a comment */
8868       if (cin_iscomment(theline))
8869 	  amount += curbuf->b_ind_comment;
8870 
8871       /* subtract extra left-shift for jump labels */
8872       if (curbuf->b_ind_jump_label > 0 && original_line_islabel)
8873 	  amount -= curbuf->b_ind_jump_label;
8874 
8875       goto theend;
8876     }
8877 
8878     /*
8879      * ok -- we're not inside any sort of structure at all!
8880      *
8881      * This means we're at the top level, and everything should
8882      * basically just match where the previous line is, except
8883      * for the lines immediately following a function declaration,
8884      * which are K&R-style parameters and need to be indented.
8885      *
8886      * if our line starts with an open brace, forget about any
8887      * prevailing indent and make sure it looks like the start
8888      * of a function
8889      */
8890 
8891     if (theline[0] == '{')
8892     {
8893 	amount = curbuf->b_ind_first_open;
8894 	goto theend;
8895     }
8896 
8897     /*
8898      * If the NEXT line is a function declaration, the current
8899      * line needs to be indented as a function type spec.
8900      * Don't do this if the current line looks like a comment or if the
8901      * current line is terminated, ie. ends in ';', or if the current line
8902      * contains { or }: "void f() {\n if (1)"
8903      */
8904     if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8905 	    && !cin_nocode(theline)
8906 	    && vim_strchr(theline, '{') == NULL
8907 	    && vim_strchr(theline, '}') == NULL
8908 	    && !cin_ends_in(theline, (char_u *)":", NULL)
8909 	    && !cin_ends_in(theline, (char_u *)",", NULL)
8910 	    && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8911 			      cur_curpos.lnum + 1)
8912 	    && !cin_isterminated(theline, FALSE, TRUE))
8913     {
8914 	amount = curbuf->b_ind_func_type;
8915 	goto theend;
8916     }
8917 
8918     /* search backwards until we find something we recognize */
8919     amount = 0;
8920     curwin->w_cursor = cur_curpos;
8921     while (curwin->w_cursor.lnum > 1)
8922     {
8923 	curwin->w_cursor.lnum--;
8924 	curwin->w_cursor.col = 0;
8925 
8926 	l = ml_get_curline();
8927 
8928 	/*
8929 	 * If we're in a comment or raw string now, skip to the start
8930 	 * of it.
8931 	 */						/* XXX */
8932 	if ((trypos = ind_find_start_CORS(NULL)) != NULL)
8933 	{
8934 	    curwin->w_cursor.lnum = trypos->lnum + 1;
8935 	    curwin->w_cursor.col = 0;
8936 	    continue;
8937 	}
8938 
8939 	/*
8940 	 * Are we at the start of a cpp base class declaration or
8941 	 * constructor initialization?
8942 	 */						    /* XXX */
8943 	n = FALSE;
8944 	if (curbuf->b_ind_cpp_baseclass != 0 && theline[0] != '{')
8945 	{
8946 	    n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
8947 	    l = ml_get_curline();
8948 	}
8949 	if (n)
8950 	{
8951 							     /* XXX */
8952 	    amount = get_baseclass_amount(cache_cpp_baseclass.lpos.col);
8953 	    break;
8954 	}
8955 
8956 	/*
8957 	 * Skip preprocessor directives and blank lines.
8958 	 */
8959 	if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount))
8960 	    continue;
8961 
8962 	if (cin_nocode(l))
8963 	    continue;
8964 
8965 	/*
8966 	 * If the previous line ends in ',', use one level of
8967 	 * indentation:
8968 	 * int foo,
8969 	 *     bar;
8970 	 * do this before checking for '}' in case of eg.
8971 	 * enum foobar
8972 	 * {
8973 	 *   ...
8974 	 * } foo,
8975 	 *   bar;
8976 	 */
8977 	n = 0;
8978 	if (cin_ends_in(l, (char_u *)",", NULL)
8979 		     || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8980 	{
8981 	    /* take us back to opening paren */
8982 	    if (find_last_paren(l, '(', ')')
8983 		    && (trypos = find_match_paren(
8984 				     curbuf->b_ind_maxparen)) != NULL)
8985 		curwin->w_cursor = *trypos;
8986 
8987 	    /* For a line ending in ',' that is a continuation line go
8988 	     * back to the first line with a backslash:
8989 	     * char *foo = "bla\
8990 	     *		 bla",
8991 	     *      here;
8992 	     */
8993 	    while (n == 0 && curwin->w_cursor.lnum > 1)
8994 	    {
8995 		l = ml_get(curwin->w_cursor.lnum - 1);
8996 		if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8997 		    break;
8998 		--curwin->w_cursor.lnum;
8999 		curwin->w_cursor.col = 0;
9000 	    }
9001 
9002 	    amount = get_indent();	    /* XXX */
9003 
9004 	    if (amount == 0)
9005 		amount = cin_first_id_amount();
9006 	    if (amount == 0)
9007 		amount = ind_continuation;
9008 	    break;
9009 	}
9010 
9011 	/*
9012 	 * If the line looks like a function declaration, and we're
9013 	 * not in a comment, put it the left margin.
9014 	 */
9015 	if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0))  /* XXX */
9016 	    break;
9017 	l = ml_get_curline();
9018 
9019 	/*
9020 	 * Finding the closing '}' of a previous function.  Put
9021 	 * current line at the left margin.  For when 'cino' has "fs".
9022 	 */
9023 	if (*skipwhite(l) == '}')
9024 	    break;
9025 
9026 	/*			    (matching {)
9027 	 * If the previous line ends on '};' (maybe followed by
9028 	 * comments) align at column 0.  For example:
9029 	 * char *string_array[] = { "foo",
9030 	 *     / * x * / "b};ar" }; / * foobar * /
9031 	 */
9032 	if (cin_ends_in(l, (char_u *)"};", NULL))
9033 	    break;
9034 
9035 	/*
9036 	 * If the previous line ends on '[' we are probably in an
9037 	 * array constant:
9038 	 * something = [
9039 	 *     234,  <- extra indent
9040 	 */
9041 	if (cin_ends_in(l, (char_u *)"[", NULL))
9042 	{
9043 	    amount = get_indent() + ind_continuation;
9044 	    break;
9045 	}
9046 
9047 	/*
9048 	 * Find a line only has a semicolon that belongs to a previous
9049 	 * line ending in '}', e.g. before an #endif.  Don't increase
9050 	 * indent then.
9051 	 */
9052 	if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
9053 	{
9054 	    pos_T curpos_save = curwin->w_cursor;
9055 
9056 	    while (curwin->w_cursor.lnum > 1)
9057 	    {
9058 		look = ml_get(--curwin->w_cursor.lnum);
9059 		if (!(cin_nocode(look) || cin_ispreproc_cont(
9060 				      &look, &curwin->w_cursor.lnum, &amount)))
9061 		    break;
9062 	    }
9063 	    if (curwin->w_cursor.lnum > 0
9064 			    && cin_ends_in(look, (char_u *)"}", NULL))
9065 		break;
9066 
9067 	    curwin->w_cursor = curpos_save;
9068 	}
9069 
9070 	/*
9071 	 * If the PREVIOUS line is a function declaration, the current
9072 	 * line (and the ones that follow) needs to be indented as
9073 	 * parameters.
9074 	 */
9075 	if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0))
9076 	{
9077 	    amount = curbuf->b_ind_param;
9078 	    break;
9079 	}
9080 
9081 	/*
9082 	 * If the previous line ends in ';' and the line before the
9083 	 * previous line ends in ',' or '\', ident to column zero:
9084 	 * int foo,
9085 	 *     bar;
9086 	 * indent_to_0 here;
9087 	 */
9088 	if (cin_ends_in(l, (char_u *)";", NULL))
9089 	{
9090 	    l = ml_get(curwin->w_cursor.lnum - 1);
9091 	    if (cin_ends_in(l, (char_u *)",", NULL)
9092 		    || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
9093 		break;
9094 	    l = ml_get_curline();
9095 	}
9096 
9097 	/*
9098 	 * Doesn't look like anything interesting -- so just
9099 	 * use the indent of this line.
9100 	 *
9101 	 * Position the cursor over the rightmost paren, so that
9102 	 * matching it will take us back to the start of the line.
9103 	 */
9104 	find_last_paren(l, '(', ')');
9105 
9106 	if ((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
9107 	    curwin->w_cursor = *trypos;
9108 	amount = get_indent();	    /* XXX */
9109 	break;
9110     }
9111 
9112     /* add extra indent for a comment */
9113     if (cin_iscomment(theline))
9114 	amount += curbuf->b_ind_comment;
9115 
9116     /* add extra indent if the previous line ended in a backslash:
9117      *	      "asdfasdf\
9118      *		  here";
9119      *	    char *foo = "asdf\
9120      *			 here";
9121      */
9122     if (cur_curpos.lnum > 1)
9123     {
9124 	l = ml_get(cur_curpos.lnum - 1);
9125 	if (*l != NUL && l[STRLEN(l) - 1] == '\\')
9126 	{
9127 	    cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
9128 	    if (cur_amount > 0)
9129 		amount = cur_amount;
9130 	    else if (cur_amount == 0)
9131 		amount += ind_continuation;
9132 	}
9133     }
9134 
9135 theend:
9136     if (amount < 0)
9137 	amount = 0;
9138 
9139 laterend:
9140     /* put the cursor back where it belongs */
9141     curwin->w_cursor = cur_curpos;
9142 
9143     vim_free(linecopy);
9144 
9145     return amount;
9146 }
9147 
9148     static int
9149 find_match(int lookfor, linenr_T ourscope)
9150 {
9151     char_u	*look;
9152     pos_T	*theirscope;
9153     char_u	*mightbeif;
9154     int		elselevel;
9155     int		whilelevel;
9156 
9157     if (lookfor == LOOKFOR_IF)
9158     {
9159 	elselevel = 1;
9160 	whilelevel = 0;
9161     }
9162     else
9163     {
9164 	elselevel = 0;
9165 	whilelevel = 1;
9166     }
9167 
9168     curwin->w_cursor.col = 0;
9169 
9170     while (curwin->w_cursor.lnum > ourscope + 1)
9171     {
9172 	curwin->w_cursor.lnum--;
9173 	curwin->w_cursor.col = 0;
9174 
9175 	look = cin_skipcomment(ml_get_curline());
9176 	if (cin_iselse(look)
9177 		|| cin_isif(look)
9178 		|| cin_isdo(look)			    /* XXX */
9179 		|| cin_iswhileofdo(look, curwin->w_cursor.lnum))
9180 	{
9181 	    /*
9182 	     * if we've gone outside the braces entirely,
9183 	     * we must be out of scope...
9184 	     */
9185 	    theirscope = find_start_brace();  /* XXX */
9186 	    if (theirscope == NULL)
9187 		break;
9188 
9189 	    /*
9190 	     * and if the brace enclosing this is further
9191 	     * back than the one enclosing the else, we're
9192 	     * out of luck too.
9193 	     */
9194 	    if (theirscope->lnum < ourscope)
9195 		break;
9196 
9197 	    /*
9198 	     * and if they're enclosed in a *deeper* brace,
9199 	     * then we can ignore it because it's in a
9200 	     * different scope...
9201 	     */
9202 	    if (theirscope->lnum > ourscope)
9203 		continue;
9204 
9205 	    /*
9206 	     * if it was an "else" (that's not an "else if")
9207 	     * then we need to go back to another if, so
9208 	     * increment elselevel
9209 	     */
9210 	    look = cin_skipcomment(ml_get_curline());
9211 	    if (cin_iselse(look))
9212 	    {
9213 		mightbeif = cin_skipcomment(look + 4);
9214 		if (!cin_isif(mightbeif))
9215 		    ++elselevel;
9216 		continue;
9217 	    }
9218 
9219 	    /*
9220 	     * if it was a "while" then we need to go back to
9221 	     * another "do", so increment whilelevel.  XXX
9222 	     */
9223 	    if (cin_iswhileofdo(look, curwin->w_cursor.lnum))
9224 	    {
9225 		++whilelevel;
9226 		continue;
9227 	    }
9228 
9229 	    /* If it's an "if" decrement elselevel */
9230 	    look = cin_skipcomment(ml_get_curline());
9231 	    if (cin_isif(look))
9232 	    {
9233 		elselevel--;
9234 		/*
9235 		 * When looking for an "if" ignore "while"s that
9236 		 * get in the way.
9237 		 */
9238 		if (elselevel == 0 && lookfor == LOOKFOR_IF)
9239 		    whilelevel = 0;
9240 	    }
9241 
9242 	    /* If it's a "do" decrement whilelevel */
9243 	    if (cin_isdo(look))
9244 		whilelevel--;
9245 
9246 	    /*
9247 	     * if we've used up all the elses, then
9248 	     * this must be the if that we want!
9249 	     * match the indent level of that if.
9250 	     */
9251 	    if (elselevel <= 0 && whilelevel <= 0)
9252 	    {
9253 		return OK;
9254 	    }
9255 	}
9256     }
9257     return FAIL;
9258 }
9259 
9260 # if defined(FEAT_EVAL) || defined(PROTO)
9261 /*
9262  * Get indent level from 'indentexpr'.
9263  */
9264     int
9265 get_expr_indent(void)
9266 {
9267     int		indent = -1;
9268     char_u	*inde_copy;
9269     pos_T	save_pos;
9270     colnr_T	save_curswant;
9271     int		save_set_curswant;
9272     int		save_State;
9273     int		use_sandbox = was_set_insecurely((char_u *)"indentexpr",
9274 								   OPT_LOCAL);
9275 
9276     /* Save and restore cursor position and curswant, in case it was changed
9277      * via :normal commands */
9278     save_pos = curwin->w_cursor;
9279     save_curswant = curwin->w_curswant;
9280     save_set_curswant = curwin->w_set_curswant;
9281     set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
9282     if (use_sandbox)
9283 	++sandbox;
9284     ++textlock;
9285 
9286     /* Need to make a copy, the 'indentexpr' option could be changed while
9287      * evaluating it. */
9288     inde_copy = vim_strsave(curbuf->b_p_inde);
9289     if (inde_copy != NULL)
9290     {
9291 	indent = (int)eval_to_number(inde_copy);
9292 	vim_free(inde_copy);
9293     }
9294 
9295     if (use_sandbox)
9296 	--sandbox;
9297     --textlock;
9298 
9299     /* Restore the cursor position so that 'indentexpr' doesn't need to.
9300      * Pretend to be in Insert mode, allow cursor past end of line for "o"
9301      * command. */
9302     save_State = State;
9303     State = INSERT;
9304     curwin->w_cursor = save_pos;
9305     curwin->w_curswant = save_curswant;
9306     curwin->w_set_curswant = save_set_curswant;
9307     check_cursor();
9308     State = save_State;
9309 
9310     /* If there is an error, just keep the current indent. */
9311     if (indent < 0)
9312 	indent = get_indent();
9313 
9314     return indent;
9315 }
9316 # endif
9317 
9318 #endif /* FEAT_CINDENT */
9319 
9320 #if defined(FEAT_LISP) || defined(PROTO)
9321 
9322 static int lisp_match(char_u *p);
9323 
9324     static int
9325 lisp_match(char_u *p)
9326 {
9327     char_u	buf[LSIZE];
9328     int		len;
9329     char_u	*word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords;
9330 
9331     while (*word != NUL)
9332     {
9333 	(void)copy_option_part(&word, buf, LSIZE, ",");
9334 	len = (int)STRLEN(buf);
9335 	if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
9336 	    return TRUE;
9337     }
9338     return FALSE;
9339 }
9340 
9341 /*
9342  * When 'p' is present in 'cpoptions, a Vi compatible method is used.
9343  * The incompatible newer method is quite a bit better at indenting
9344  * code in lisp-like languages than the traditional one; it's still
9345  * mostly heuristics however -- Dirk van Deun, [email protected]
9346  *
9347  * TODO:
9348  * Findmatch() should be adapted for lisp, also to make showmatch
9349  * work correctly: now (v5.3) it seems all C/C++ oriented:
9350  * - it does not recognize the #\( and #\) notations as character literals
9351  * - it doesn't know about comments starting with a semicolon
9352  * - it incorrectly interprets '(' as a character literal
9353  * All this messes up get_lisp_indent in some rare cases.
9354  * Update from Sergey Khorev:
9355  * I tried to fix the first two issues.
9356  */
9357     int
9358 get_lisp_indent(void)
9359 {
9360     pos_T	*pos, realpos, paren;
9361     int		amount;
9362     char_u	*that;
9363     colnr_T	col;
9364     colnr_T	firsttry;
9365     int		parencount, quotecount;
9366     int		vi_lisp;
9367 
9368     /* Set vi_lisp to use the vi-compatible method */
9369     vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
9370 
9371     realpos = curwin->w_cursor;
9372     curwin->w_cursor.col = 0;
9373 
9374     if ((pos = findmatch(NULL, '(')) == NULL)
9375 	pos = findmatch(NULL, '[');
9376     else
9377     {
9378 	paren = *pos;
9379 	pos = findmatch(NULL, '[');
9380 	if (pos == NULL || LT_POSP(pos, &paren))
9381 	    pos = &paren;
9382     }
9383     if (pos != NULL)
9384     {
9385 	/* Extra trick: Take the indent of the first previous non-white
9386 	 * line that is at the same () level. */
9387 	amount = -1;
9388 	parencount = 0;
9389 
9390 	while (--curwin->w_cursor.lnum >= pos->lnum)
9391 	{
9392 	    if (linewhite(curwin->w_cursor.lnum))
9393 		continue;
9394 	    for (that = ml_get_curline(); *that != NUL; ++that)
9395 	    {
9396 		if (*that == ';')
9397 		{
9398 		    while (*(that + 1) != NUL)
9399 			++that;
9400 		    continue;
9401 		}
9402 		if (*that == '\\')
9403 		{
9404 		    if (*(that + 1) != NUL)
9405 			++that;
9406 		    continue;
9407 		}
9408 		if (*that == '"' && *(that + 1) != NUL)
9409 		{
9410 		    while (*++that && *that != '"')
9411 		    {
9412 			/* skipping escaped characters in the string */
9413 			if (*that == '\\')
9414 			{
9415 			    if (*++that == NUL)
9416 				break;
9417 			    if (that[1] == NUL)
9418 			    {
9419 				++that;
9420 				break;
9421 			    }
9422 			}
9423 		    }
9424 		}
9425 		if (*that == '(' || *that == '[')
9426 		    ++parencount;
9427 		else if (*that == ')' || *that == ']')
9428 		    --parencount;
9429 	    }
9430 	    if (parencount == 0)
9431 	    {
9432 		amount = get_indent();
9433 		break;
9434 	    }
9435 	}
9436 
9437 	if (amount == -1)
9438 	{
9439 	    curwin->w_cursor.lnum = pos->lnum;
9440 	    curwin->w_cursor.col = pos->col;
9441 	    col = pos->col;
9442 
9443 	    that = ml_get_curline();
9444 
9445 	    if (vi_lisp && get_indent() == 0)
9446 		amount = 2;
9447 	    else
9448 	    {
9449 		char_u *line = that;
9450 
9451 		amount = 0;
9452 		while (*that && col)
9453 		{
9454 		    amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);
9455 		    col--;
9456 		}
9457 
9458 		/*
9459 		 * Some keywords require "body" indenting rules (the
9460 		 * non-standard-lisp ones are Scheme special forms):
9461 		 *
9462 		 * (let ((a 1))    instead    (let ((a 1))
9463 		 *   (...))	      of	   (...))
9464 		 */
9465 
9466 		if (!vi_lisp && (*that == '(' || *that == '[')
9467 						      && lisp_match(that + 1))
9468 		    amount += 2;
9469 		else
9470 		{
9471 		    that++;
9472 		    amount++;
9473 		    firsttry = amount;
9474 
9475 		    while (VIM_ISWHITE(*that))
9476 		    {
9477 			amount += lbr_chartabsize(line, that, (colnr_T)amount);
9478 			++that;
9479 		    }
9480 
9481 		    if (*that && *that != ';') /* not a comment line */
9482 		    {
9483 			/* test *that != '(' to accommodate first let/do
9484 			 * argument if it is more than one line */
9485 			if (!vi_lisp && *that != '(' && *that != '[')
9486 			    firsttry++;
9487 
9488 			parencount = 0;
9489 			quotecount = 0;
9490 
9491 			if (vi_lisp
9492 				|| (*that != '"'
9493 				    && *that != '\''
9494 				    && *that != '#'
9495 				    && (*that < '0' || *that > '9')))
9496 			{
9497 			    while (*that
9498 				    && (!VIM_ISWHITE(*that)
9499 					|| quotecount
9500 					|| parencount)
9501 				    && (!((*that == '(' || *that == '[')
9502 					    && !quotecount
9503 					    && !parencount
9504 					    && vi_lisp)))
9505 			    {
9506 				if (*that == '"')
9507 				    quotecount = !quotecount;
9508 				if ((*that == '(' || *that == '[')
9509 							       && !quotecount)
9510 				    ++parencount;
9511 				if ((*that == ')' || *that == ']')
9512 							       && !quotecount)
9513 				    --parencount;
9514 				if (*that == '\\' && *(that+1) != NUL)
9515 				    amount += lbr_chartabsize_adv(
9516 						line, &that, (colnr_T)amount);
9517 				amount += lbr_chartabsize_adv(
9518 						line, &that, (colnr_T)amount);
9519 			    }
9520 			}
9521 			while (VIM_ISWHITE(*that))
9522 			{
9523 			    amount += lbr_chartabsize(
9524 						 line, that, (colnr_T)amount);
9525 			    that++;
9526 			}
9527 			if (!*that || *that == ';')
9528 			    amount = firsttry;
9529 		    }
9530 		}
9531 	    }
9532 	}
9533     }
9534     else
9535 	amount = 0;	/* no matching '(' or '[' found, use zero indent */
9536 
9537     curwin->w_cursor = realpos;
9538 
9539     return amount;
9540 }
9541 #endif /* FEAT_LISP */
9542 
9543     void
9544 prepare_to_exit(void)
9545 {
9546 #if defined(SIGHUP) && defined(SIG_IGN)
9547     /* Ignore SIGHUP, because a dropped connection causes a read error, which
9548      * makes Vim exit and then handling SIGHUP causes various reentrance
9549      * problems. */
9550     signal(SIGHUP, SIG_IGN);
9551 #endif
9552 
9553 #ifdef FEAT_GUI
9554     if (gui.in_use)
9555     {
9556 	gui.dying = TRUE;
9557 	out_trash();	/* trash any pending output */
9558     }
9559     else
9560 #endif
9561     {
9562 	windgoto((int)Rows - 1, 0);
9563 
9564 	/*
9565 	 * Switch terminal mode back now, so messages end up on the "normal"
9566 	 * screen (if there are two screens).
9567 	 */
9568 	settmode(TMODE_COOK);
9569 	stoptermcap();
9570 	out_flush();
9571     }
9572 }
9573 
9574 /*
9575  * Preserve files and exit.
9576  * When called IObuff must contain a message.
9577  * NOTE: This may be called from deathtrap() in a signal handler, avoid unsafe
9578  * functions, such as allocating memory.
9579  */
9580     void
9581 preserve_exit(void)
9582 {
9583     buf_T	*buf;
9584 
9585     prepare_to_exit();
9586 
9587     /* Setting this will prevent free() calls.  That avoids calling free()
9588      * recursively when free() was invoked with a bad pointer. */
9589     really_exiting = TRUE;
9590 
9591     out_str(IObuff);
9592     screen_start();		    /* don't know where cursor is now */
9593     out_flush();
9594 
9595     ml_close_notmod();		    /* close all not-modified buffers */
9596 
9597     FOR_ALL_BUFFERS(buf)
9598     {
9599 	if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9600 	{
9601 	    OUT_STR("Vim: preserving files...\n");
9602 	    screen_start();	    /* don't know where cursor is now */
9603 	    out_flush();
9604 	    ml_sync_all(FALSE, FALSE);	/* preserve all swap files */
9605 	    break;
9606 	}
9607     }
9608 
9609     ml_close_all(FALSE);	    /* close all memfiles, without deleting */
9610 
9611     OUT_STR("Vim: Finished.\n");
9612 
9613     getout(1);
9614 }
9615 
9616 /*
9617  * return TRUE if "fname" exists.
9618  */
9619     int
9620 vim_fexists(char_u *fname)
9621 {
9622     stat_T st;
9623 
9624     if (mch_stat((char *)fname, &st))
9625 	return FALSE;
9626     return TRUE;
9627 }
9628 
9629 /*
9630  * Check for CTRL-C pressed, but only once in a while.
9631  * Should be used instead of ui_breakcheck() for functions that check for
9632  * each line in the file.  Calling ui_breakcheck() each time takes too much
9633  * time, because it can be a system call.
9634  */
9635 
9636 #ifndef BREAKCHECK_SKIP
9637 # ifdef FEAT_GUI		    /* assume the GUI only runs on fast computers */
9638 #  define BREAKCHECK_SKIP 200
9639 # else
9640 #  define BREAKCHECK_SKIP 32
9641 # endif
9642 #endif
9643 
9644 static int	breakcheck_count = 0;
9645 
9646     void
9647 line_breakcheck(void)
9648 {
9649     if (++breakcheck_count >= BREAKCHECK_SKIP)
9650     {
9651 	breakcheck_count = 0;
9652 	ui_breakcheck();
9653     }
9654 }
9655 
9656 /*
9657  * Like line_breakcheck() but check 10 times less often.
9658  */
9659     void
9660 fast_breakcheck(void)
9661 {
9662     if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9663     {
9664 	breakcheck_count = 0;
9665 	ui_breakcheck();
9666     }
9667 }
9668 
9669 /*
9670  * Invoke expand_wildcards() for one pattern.
9671  * Expand items like "%:h" before the expansion.
9672  * Returns OK or FAIL.
9673  */
9674     int
9675 expand_wildcards_eval(
9676     char_u	 **pat,		/* pointer to input pattern */
9677     int		  *num_file,	/* resulting number of files */
9678     char_u	***file,	/* array of resulting files */
9679     int		   flags)	/* EW_DIR, etc. */
9680 {
9681     int		ret = FAIL;
9682     char_u	*eval_pat = NULL;
9683     char_u	*exp_pat = *pat;
9684     char_u      *ignored_msg;
9685     int		usedlen;
9686 
9687     if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9688     {
9689 	++emsg_off;
9690 	eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9691 						    NULL, &ignored_msg, NULL);
9692 	--emsg_off;
9693 	if (eval_pat != NULL)
9694 	    exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9695     }
9696 
9697     if (exp_pat != NULL)
9698 	ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9699 
9700     if (eval_pat != NULL)
9701     {
9702 	vim_free(exp_pat);
9703 	vim_free(eval_pat);
9704     }
9705 
9706     return ret;
9707 }
9708 
9709 /*
9710  * Expand wildcards.  Calls gen_expand_wildcards() and removes files matching
9711  * 'wildignore'.
9712  * Returns OK or FAIL.  When FAIL then "num_files" won't be set.
9713  */
9714     int
9715 expand_wildcards(
9716     int		   num_pat,	/* number of input patterns */
9717     char_u	 **pat,		/* array of input patterns */
9718     int		  *num_files,	/* resulting number of files */
9719     char_u	***files,	/* array of resulting files */
9720     int		   flags)	/* EW_DIR, etc. */
9721 {
9722     int		retval;
9723     int		i, j;
9724     char_u	*p;
9725     int		non_suf_match;	/* number without matching suffix */
9726 
9727     retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
9728 
9729     /* When keeping all matches, return here */
9730     if ((flags & EW_KEEPALL) || retval == FAIL)
9731 	return retval;
9732 
9733 #ifdef FEAT_WILDIGN
9734     /*
9735      * Remove names that match 'wildignore'.
9736      */
9737     if (*p_wig)
9738     {
9739 	char_u	*ffname;
9740 
9741 	/* check all files in (*files)[] */
9742 	for (i = 0; i < *num_files; ++i)
9743 	{
9744 	    ffname = FullName_save((*files)[i], FALSE);
9745 	    if (ffname == NULL)		/* out of memory */
9746 		break;
9747 # ifdef VMS
9748 	    vms_remove_version(ffname);
9749 # endif
9750 	    if (match_file_list(p_wig, (*files)[i], ffname))
9751 	    {
9752 		/* remove this matching file from the list */
9753 		vim_free((*files)[i]);
9754 		for (j = i; j + 1 < *num_files; ++j)
9755 		    (*files)[j] = (*files)[j + 1];
9756 		--*num_files;
9757 		--i;
9758 	    }
9759 	    vim_free(ffname);
9760 	}
9761 
9762 	/* If the number of matches is now zero, we fail. */
9763 	if (*num_files == 0)
9764 	{
9765 	    vim_free(*files);
9766 	    *files = NULL;
9767 	    return FAIL;
9768 	}
9769     }
9770 #endif
9771 
9772     /*
9773      * Move the names where 'suffixes' match to the end.
9774      */
9775     if (*num_files > 1)
9776     {
9777 	non_suf_match = 0;
9778 	for (i = 0; i < *num_files; ++i)
9779 	{
9780 	    if (!match_suffix((*files)[i]))
9781 	    {
9782 		/*
9783 		 * Move the name without matching suffix to the front
9784 		 * of the list.
9785 		 */
9786 		p = (*files)[i];
9787 		for (j = i; j > non_suf_match; --j)
9788 		    (*files)[j] = (*files)[j - 1];
9789 		(*files)[non_suf_match++] = p;
9790 	    }
9791 	}
9792     }
9793 
9794     return retval;
9795 }
9796 
9797 /*
9798  * Return TRUE if "fname" matches with an entry in 'suffixes'.
9799  */
9800     int
9801 match_suffix(char_u *fname)
9802 {
9803     int		fnamelen, setsuflen;
9804     char_u	*setsuf;
9805 #define MAXSUFLEN 30	    /* maximum length of a file suffix */
9806     char_u	suf_buf[MAXSUFLEN];
9807 
9808     fnamelen = (int)STRLEN(fname);
9809     setsuflen = 0;
9810     for (setsuf = p_su; *setsuf; )
9811     {
9812 	setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
9813 	if (setsuflen == 0)
9814 	{
9815 	    char_u *tail = gettail(fname);
9816 
9817 	    /* empty entry: match name without a '.' */
9818 	    if (vim_strchr(tail, '.') == NULL)
9819 	    {
9820 		setsuflen = 1;
9821 		break;
9822 	    }
9823 	}
9824 	else
9825 	{
9826 	    if (fnamelen >= setsuflen
9827 		    && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9828 						  (size_t)setsuflen) == 0)
9829 		break;
9830 	    setsuflen = 0;
9831 	}
9832     }
9833     return (setsuflen != 0);
9834 }
9835 
9836 #if !defined(NO_EXPANDPATH) || defined(PROTO)
9837 
9838 # ifdef VIM_BACKTICK
9839 static int vim_backtick(char_u *p);
9840 static int expand_backtick(garray_T *gap, char_u *pat, int flags);
9841 # endif
9842 
9843 # if defined(WIN3264)
9844 /*
9845  * File name expansion code for MS-DOS, Win16 and Win32.  It's here because
9846  * it's shared between these systems.
9847  */
9848 # if defined(PROTO)
9849 #  define _cdecl
9850 # else
9851 #  ifdef __BORLANDC__
9852 #   define _cdecl _RTLENTRYF
9853 #  endif
9854 # endif
9855 
9856 /*
9857  * comparison function for qsort in dos_expandpath()
9858  */
9859     static int _cdecl
9860 pstrcmp(const void *a, const void *b)
9861 {
9862     return (pathcmp(*(char **)a, *(char **)b, -1));
9863 }
9864 
9865 /*
9866  * Recursively expand one path component into all matching files and/or
9867  * directories.  Adds matches to "gap".  Handles "*", "?", "[a-z]", "**", etc.
9868  * Return the number of matches found.
9869  * "path" has backslashes before chars that are not to be expanded, starting
9870  * at "path[wildoff]".
9871  * Return the number of matches found.
9872  * NOTE: much of this is identical to unix_expandpath(), keep in sync!
9873  */
9874     static int
9875 dos_expandpath(
9876     garray_T	*gap,
9877     char_u	*path,
9878     int		wildoff,
9879     int		flags,		/* EW_* flags */
9880     int		didstar)	/* expanded "**" once already */
9881 {
9882     char_u	*buf;
9883     char_u	*path_end;
9884     char_u	*p, *s, *e;
9885     int		start_len = gap->ga_len;
9886     char_u	*pat;
9887     regmatch_T	regmatch;
9888     int		starts_with_dot;
9889     int		matches;
9890     int		len;
9891     int		starstar = FALSE;
9892     static int	stardepth = 0;	    /* depth for "**" expansion */
9893     WIN32_FIND_DATA	fb;
9894     HANDLE		hFind = (HANDLE)0;
9895 # ifdef FEAT_MBYTE
9896     WIN32_FIND_DATAW    wfb;
9897     WCHAR		*wn = NULL;	/* UCS-2 name, NULL when not used. */
9898 # endif
9899     char_u		*matchname;
9900     int			ok;
9901 
9902     /* Expanding "**" may take a long time, check for CTRL-C. */
9903     if (stardepth > 0)
9904     {
9905 	ui_breakcheck();
9906 	if (got_int)
9907 	    return 0;
9908     }
9909 
9910     /* Make room for file name.  When doing encoding conversion the actual
9911      * length may be quite a bit longer, thus use the maximum possible length. */
9912     buf = alloc((int)MAXPATHL);
9913     if (buf == NULL)
9914 	return 0;
9915 
9916     /*
9917      * Find the first part in the path name that contains a wildcard or a ~1.
9918      * Copy it into buf, including the preceding characters.
9919      */
9920     p = buf;
9921     s = buf;
9922     e = NULL;
9923     path_end = path;
9924     while (*path_end != NUL)
9925     {
9926 	/* May ignore a wildcard that has a backslash before it; it will
9927 	 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9928 	if (path_end >= path + wildoff && rem_backslash(path_end))
9929 	    *p++ = *path_end++;
9930 	else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9931 	{
9932 	    if (e != NULL)
9933 		break;
9934 	    s = p + 1;
9935 	}
9936 	else if (path_end >= path + wildoff
9937 			 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9938 	    e = p;
9939 # ifdef FEAT_MBYTE
9940 	if (has_mbyte)
9941 	{
9942 	    len = (*mb_ptr2len)(path_end);
9943 	    STRNCPY(p, path_end, len);
9944 	    p += len;
9945 	    path_end += len;
9946 	}
9947 	else
9948 # endif
9949 	    *p++ = *path_end++;
9950     }
9951     e = p;
9952     *e = NUL;
9953 
9954     /* now we have one wildcard component between s and e */
9955     /* Remove backslashes between "wildoff" and the start of the wildcard
9956      * component. */
9957     for (p = buf + wildoff; p < s; ++p)
9958 	if (rem_backslash(p))
9959 	{
9960 	    STRMOVE(p, p + 1);
9961 	    --e;
9962 	    --s;
9963 	}
9964 
9965     /* Check for "**" between "s" and "e". */
9966     for (p = s; p < e; ++p)
9967 	if (p[0] == '*' && p[1] == '*')
9968 	    starstar = TRUE;
9969 
9970     starts_with_dot = *s == '.';
9971     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9972     if (pat == NULL)
9973     {
9974 	vim_free(buf);
9975 	return 0;
9976     }
9977 
9978     /* compile the regexp into a program */
9979     if (flags & (EW_NOERROR | EW_NOTWILD))
9980 	++emsg_silent;
9981     regmatch.rm_ic = TRUE;		/* Always ignore case */
9982     regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9983     if (flags & (EW_NOERROR | EW_NOTWILD))
9984 	--emsg_silent;
9985     vim_free(pat);
9986 
9987     if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
9988     {
9989 	vim_free(buf);
9990 	return 0;
9991     }
9992 
9993     /* remember the pattern or file name being looked for */
9994     matchname = vim_strsave(s);
9995 
9996     /* If "**" is by itself, this is the first time we encounter it and more
9997      * is following then find matches without any directory. */
9998     if (!didstar && stardepth < 100 && starstar && e - s == 2
9999 							  && *path_end == '/')
10000     {
10001 	STRCPY(s, path_end + 1);
10002 	++stardepth;
10003 	(void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
10004 	--stardepth;
10005     }
10006 
10007     /* Scan all files in the directory with "dir/ *.*" */
10008     STRCPY(s, "*.*");
10009 # ifdef FEAT_MBYTE
10010     if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
10011     {
10012 	/* The active codepage differs from 'encoding'.  Attempt using the
10013 	 * wide function.  If it fails because it is not implemented fall back
10014 	 * to the non-wide version (for Windows 98) */
10015 	wn = enc_to_utf16(buf, NULL);
10016 	if (wn != NULL)
10017 	{
10018 	    hFind = FindFirstFileW(wn, &wfb);
10019 	    if (hFind == INVALID_HANDLE_VALUE
10020 			      && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
10021 	    {
10022 		vim_free(wn);
10023 		wn = NULL;
10024 	    }
10025 	}
10026     }
10027 
10028     if (wn == NULL)
10029 # endif
10030 	hFind = FindFirstFile((LPCSTR)buf, &fb);
10031     ok = (hFind != INVALID_HANDLE_VALUE);
10032 
10033     while (ok)
10034     {
10035 # ifdef FEAT_MBYTE
10036 	if (wn != NULL)
10037 	    p = utf16_to_enc(wfb.cFileName, NULL);   /* p is allocated here */
10038 	else
10039 # endif
10040 	    p = (char_u *)fb.cFileName;
10041 	/* Ignore entries starting with a dot, unless when asked for.  Accept
10042 	 * all entries found with "matchname". */
10043 	if ((p[0] != '.' || starts_with_dot
10044 			 || ((flags & EW_DODOT)
10045 			     && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
10046 		&& (matchname == NULL
10047 		  || (regmatch.regprog != NULL
10048 				     && vim_regexec(&regmatch, p, (colnr_T)0))
10049 		  || ((flags & EW_NOTWILD)
10050 		     && fnamencmp(path + (s - buf), p, e - s) == 0)))
10051 	{
10052 	    STRCPY(s, p);
10053 	    len = (int)STRLEN(buf);
10054 
10055 	    if (starstar && stardepth < 100)
10056 	    {
10057 		/* For "**" in the pattern first go deeper in the tree to
10058 		 * find matches. */
10059 		STRCPY(buf + len, "/**");
10060 		STRCPY(buf + len + 3, path_end);
10061 		++stardepth;
10062 		(void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
10063 		--stardepth;
10064 	    }
10065 
10066 	    STRCPY(buf + len, path_end);
10067 	    if (mch_has_exp_wildcard(path_end))
10068 	    {
10069 		/* need to expand another component of the path */
10070 		/* remove backslashes for the remaining components only */
10071 		(void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
10072 	    }
10073 	    else
10074 	    {
10075 		/* no more wildcards, check if there is a match */
10076 		/* remove backslashes for the remaining components only */
10077 		if (*path_end != 0)
10078 		    backslash_halve(buf + len + 1);
10079 		if (mch_getperm(buf) >= 0)	/* add existing file */
10080 		    addfile(gap, buf, flags);
10081 	    }
10082 	}
10083 
10084 # ifdef FEAT_MBYTE
10085 	if (wn != NULL)
10086 	{
10087 	    vim_free(p);
10088 	    ok = FindNextFileW(hFind, &wfb);
10089 	}
10090 	else
10091 # endif
10092 	    ok = FindNextFile(hFind, &fb);
10093 
10094 	/* If no more matches and no match was used, try expanding the name
10095 	 * itself.  Finds the long name of a short filename. */
10096 	if (!ok && matchname != NULL && gap->ga_len == start_len)
10097 	{
10098 	    STRCPY(s, matchname);
10099 	    FindClose(hFind);
10100 # ifdef FEAT_MBYTE
10101 	    if (wn != NULL)
10102 	    {
10103 		vim_free(wn);
10104 		wn = enc_to_utf16(buf, NULL);
10105 		if (wn != NULL)
10106 		    hFind = FindFirstFileW(wn, &wfb);
10107 	    }
10108 	    if (wn == NULL)
10109 # endif
10110 		hFind = FindFirstFile((LPCSTR)buf, &fb);
10111 	    ok = (hFind != INVALID_HANDLE_VALUE);
10112 	    vim_free(matchname);
10113 	    matchname = NULL;
10114 	}
10115     }
10116 
10117     FindClose(hFind);
10118 # ifdef FEAT_MBYTE
10119     vim_free(wn);
10120 # endif
10121     vim_free(buf);
10122     vim_regfree(regmatch.regprog);
10123     vim_free(matchname);
10124 
10125     matches = gap->ga_len - start_len;
10126     if (matches > 0)
10127 	qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
10128 						   sizeof(char_u *), pstrcmp);
10129     return matches;
10130 }
10131 
10132     int
10133 mch_expandpath(
10134     garray_T	*gap,
10135     char_u	*path,
10136     int		flags)		/* EW_* flags */
10137 {
10138     return dos_expandpath(gap, path, 0, flags, FALSE);
10139 }
10140 # endif /* WIN3264 */
10141 
10142 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
10143 	|| defined(PROTO)
10144 /*
10145  * Unix style wildcard expansion code.
10146  * It's here because it's used both for Unix and Mac.
10147  */
10148 static int	pstrcmp(const void *, const void *);
10149 
10150     static int
10151 pstrcmp(const void *a, const void *b)
10152 {
10153     return (pathcmp(*(char **)a, *(char **)b, -1));
10154 }
10155 
10156 /*
10157  * Recursively expand one path component into all matching files and/or
10158  * directories.  Adds matches to "gap".  Handles "*", "?", "[a-z]", "**", etc.
10159  * "path" has backslashes before chars that are not to be expanded, starting
10160  * at "path + wildoff".
10161  * Return the number of matches found.
10162  * NOTE: much of this is identical to dos_expandpath(), keep in sync!
10163  */
10164     int
10165 unix_expandpath(
10166     garray_T	*gap,
10167     char_u	*path,
10168     int		wildoff,
10169     int		flags,		/* EW_* flags */
10170     int		didstar)	/* expanded "**" once already */
10171 {
10172     char_u	*buf;
10173     char_u	*path_end;
10174     char_u	*p, *s, *e;
10175     int		start_len = gap->ga_len;
10176     char_u	*pat;
10177     regmatch_T	regmatch;
10178     int		starts_with_dot;
10179     int		matches;
10180     int		len;
10181     int		starstar = FALSE;
10182     static int	stardepth = 0;	    /* depth for "**" expansion */
10183 
10184     DIR		*dirp;
10185     struct dirent *dp;
10186 
10187     /* Expanding "**" may take a long time, check for CTRL-C. */
10188     if (stardepth > 0)
10189     {
10190 	ui_breakcheck();
10191 	if (got_int)
10192 	    return 0;
10193     }
10194 
10195     /* make room for file name */
10196     buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
10197     if (buf == NULL)
10198 	return 0;
10199 
10200     /*
10201      * Find the first part in the path name that contains a wildcard.
10202      * When EW_ICASE is set every letter is considered to be a wildcard.
10203      * Copy it into "buf", including the preceding characters.
10204      */
10205     p = buf;
10206     s = buf;
10207     e = NULL;
10208     path_end = path;
10209     while (*path_end != NUL)
10210     {
10211 	/* May ignore a wildcard that has a backslash before it; it will
10212 	 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
10213 	if (path_end >= path + wildoff && rem_backslash(path_end))
10214 	    *p++ = *path_end++;
10215 	else if (*path_end == '/')
10216 	{
10217 	    if (e != NULL)
10218 		break;
10219 	    s = p + 1;
10220 	}
10221 	else if (path_end >= path + wildoff
10222 			 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
10223 			     || (!p_fic && (flags & EW_ICASE)
10224 					     && isalpha(PTR2CHAR(path_end)))))
10225 	    e = p;
10226 #ifdef FEAT_MBYTE
10227 	if (has_mbyte)
10228 	{
10229 	    len = (*mb_ptr2len)(path_end);
10230 	    STRNCPY(p, path_end, len);
10231 	    p += len;
10232 	    path_end += len;
10233 	}
10234 	else
10235 #endif
10236 	    *p++ = *path_end++;
10237     }
10238     e = p;
10239     *e = NUL;
10240 
10241     /* Now we have one wildcard component between "s" and "e". */
10242     /* Remove backslashes between "wildoff" and the start of the wildcard
10243      * component. */
10244     for (p = buf + wildoff; p < s; ++p)
10245 	if (rem_backslash(p))
10246 	{
10247 	    STRMOVE(p, p + 1);
10248 	    --e;
10249 	    --s;
10250 	}
10251 
10252     /* Check for "**" between "s" and "e". */
10253     for (p = s; p < e; ++p)
10254 	if (p[0] == '*' && p[1] == '*')
10255 	    starstar = TRUE;
10256 
10257     /* convert the file pattern to a regexp pattern */
10258     starts_with_dot = *s == '.';
10259     pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
10260     if (pat == NULL)
10261     {
10262 	vim_free(buf);
10263 	return 0;
10264     }
10265 
10266     /* compile the regexp into a program */
10267     if (flags & EW_ICASE)
10268 	regmatch.rm_ic = TRUE;		/* 'wildignorecase' set */
10269     else
10270 	regmatch.rm_ic = p_fic;	/* ignore case when 'fileignorecase' is set */
10271     if (flags & (EW_NOERROR | EW_NOTWILD))
10272 	++emsg_silent;
10273     regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
10274     if (flags & (EW_NOERROR | EW_NOTWILD))
10275 	--emsg_silent;
10276     vim_free(pat);
10277 
10278     if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
10279     {
10280 	vim_free(buf);
10281 	return 0;
10282     }
10283 
10284     /* If "**" is by itself, this is the first time we encounter it and more
10285      * is following then find matches without any directory. */
10286     if (!didstar && stardepth < 100 && starstar && e - s == 2
10287 							  && *path_end == '/')
10288     {
10289 	STRCPY(s, path_end + 1);
10290 	++stardepth;
10291 	(void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
10292 	--stardepth;
10293     }
10294 
10295     /* open the directory for scanning */
10296     *s = NUL;
10297     dirp = opendir(*buf == NUL ? "." : (char *)buf);
10298 
10299     /* Find all matching entries */
10300     if (dirp != NULL)
10301     {
10302 	for (;;)
10303 	{
10304 	    dp = readdir(dirp);
10305 	    if (dp == NULL)
10306 		break;
10307 	    if ((dp->d_name[0] != '.' || starts_with_dot
10308 			|| ((flags & EW_DODOT)
10309 			    && dp->d_name[1] != NUL
10310 			    && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
10311 		 && ((regmatch.regprog != NULL && vim_regexec(&regmatch,
10312 					     (char_u *)dp->d_name, (colnr_T)0))
10313 		   || ((flags & EW_NOTWILD)
10314 		     && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
10315 	    {
10316 		STRCPY(s, dp->d_name);
10317 		len = STRLEN(buf);
10318 
10319 		if (starstar && stardepth < 100)
10320 		{
10321 		    /* For "**" in the pattern first go deeper in the tree to
10322 		     * find matches. */
10323 		    STRCPY(buf + len, "/**");
10324 		    STRCPY(buf + len + 3, path_end);
10325 		    ++stardepth;
10326 		    (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
10327 		    --stardepth;
10328 		}
10329 
10330 		STRCPY(buf + len, path_end);
10331 		if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
10332 		{
10333 		    /* need to expand another component of the path */
10334 		    /* remove backslashes for the remaining components only */
10335 		    (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
10336 		}
10337 		else
10338 		{
10339 		    stat_T  sb;
10340 
10341 		    /* no more wildcards, check if there is a match */
10342 		    /* remove backslashes for the remaining components only */
10343 		    if (*path_end != NUL)
10344 			backslash_halve(buf + len + 1);
10345 		    /* add existing file or symbolic link */
10346 		    if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
10347 						      : mch_getperm(buf) >= 0)
10348 		    {
10349 #ifdef MACOS_CONVERT
10350 			size_t precomp_len = STRLEN(buf)+1;
10351 			char_u *precomp_buf =
10352 			    mac_precompose_path(buf, precomp_len, &precomp_len);
10353 
10354 			if (precomp_buf)
10355 			{
10356 			    mch_memmove(buf, precomp_buf, precomp_len);
10357 			    vim_free(precomp_buf);
10358 			}
10359 #endif
10360 			addfile(gap, buf, flags);
10361 		    }
10362 		}
10363 	    }
10364 	}
10365 
10366 	closedir(dirp);
10367     }
10368 
10369     vim_free(buf);
10370     vim_regfree(regmatch.regprog);
10371 
10372     matches = gap->ga_len - start_len;
10373     if (matches > 0)
10374 	qsort(((char_u **)gap->ga_data) + start_len, matches,
10375 						   sizeof(char_u *), pstrcmp);
10376     return matches;
10377 }
10378 #endif
10379 
10380 #if defined(FEAT_SEARCHPATH)
10381 static int find_previous_pathsep(char_u *path, char_u **psep);
10382 static int is_unique(char_u *maybe_unique, garray_T *gap, int i);
10383 static void expand_path_option(char_u *curdir, garray_T	*gap);
10384 static char_u *get_path_cutoff(char_u *fname, garray_T *gap);
10385 static void uniquefy_paths(garray_T *gap, char_u *pattern);
10386 static int expand_in_path(garray_T *gap, char_u	*pattern, int flags);
10387 
10388 /*
10389  * Moves "*psep" back to the previous path separator in "path".
10390  * Returns FAIL is "*psep" ends up at the beginning of "path".
10391  */
10392     static int
10393 find_previous_pathsep(char_u *path, char_u **psep)
10394 {
10395     /* skip the current separator */
10396     if (*psep > path && vim_ispathsep(**psep))
10397 	--*psep;
10398 
10399     /* find the previous separator */
10400     while (*psep > path)
10401     {
10402 	if (vim_ispathsep(**psep))
10403 	    return OK;
10404 	MB_PTR_BACK(path, *psep);
10405     }
10406 
10407     return FAIL;
10408 }
10409 
10410 /*
10411  * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
10412  * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
10413  */
10414     static int
10415 is_unique(char_u *maybe_unique, garray_T *gap, int i)
10416 {
10417     int	    j;
10418     int	    candidate_len;
10419     int	    other_path_len;
10420     char_u  **other_paths = (char_u **)gap->ga_data;
10421     char_u  *rival;
10422 
10423     for (j = 0; j < gap->ga_len; j++)
10424     {
10425 	if (j == i)
10426 	    continue;  /* don't compare it with itself */
10427 
10428 	candidate_len = (int)STRLEN(maybe_unique);
10429 	other_path_len = (int)STRLEN(other_paths[j]);
10430 	if (other_path_len < candidate_len)
10431 	    continue;  /* it's different when it's shorter */
10432 
10433 	rival = other_paths[j] + other_path_len - candidate_len;
10434 	if (fnamecmp(maybe_unique, rival) == 0
10435 		&& (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
10436 	    return FALSE;  /* match */
10437     }
10438 
10439     return TRUE;  /* no match found */
10440 }
10441 
10442 /*
10443  * Split the 'path' option into an array of strings in garray_T.  Relative
10444  * paths are expanded to their equivalent fullpath.  This includes the "."
10445  * (relative to current buffer directory) and empty path (relative to current
10446  * directory) notations.
10447  *
10448  * TODO: handle upward search (;) and path limiter (**N) notations by
10449  * expanding each into their equivalent path(s).
10450  */
10451     static void
10452 expand_path_option(char_u *curdir, garray_T *gap)
10453 {
10454     char_u	*path_option = *curbuf->b_p_path == NUL
10455 						  ? p_path : curbuf->b_p_path;
10456     char_u	*buf;
10457     char_u	*p;
10458     int		len;
10459 
10460     if ((buf = alloc((int)MAXPATHL)) == NULL)
10461 	return;
10462 
10463     while (*path_option != NUL)
10464     {
10465 	copy_option_part(&path_option, buf, MAXPATHL, " ,");
10466 
10467 	if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
10468 	{
10469 	    /* Relative to current buffer:
10470 	     * "/path/file" + "." -> "/path/"
10471 	     * "/path/file"  + "./subdir" -> "/path/subdir" */
10472 	    if (curbuf->b_ffname == NULL)
10473 		continue;
10474 	    p = gettail(curbuf->b_ffname);
10475 	    len = (int)(p - curbuf->b_ffname);
10476 	    if (len + (int)STRLEN(buf) >= MAXPATHL)
10477 		continue;
10478 	    if (buf[1] == NUL)
10479 		buf[len] = NUL;
10480 	    else
10481 		STRMOVE(buf + len, buf + 2);
10482 	    mch_memmove(buf, curbuf->b_ffname, len);
10483 	    simplify_filename(buf);
10484 	}
10485 	else if (buf[0] == NUL)
10486 	    /* relative to current directory */
10487 	    STRCPY(buf, curdir);
10488 	else if (path_with_url(buf))
10489 	    /* URL can't be used here */
10490 	    continue;
10491 	else if (!mch_isFullName(buf))
10492 	{
10493 	    /* Expand relative path to their full path equivalent */
10494 	    len = (int)STRLEN(curdir);
10495 	    if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
10496 		continue;
10497 	    STRMOVE(buf + len + 1, buf);
10498 	    STRCPY(buf, curdir);
10499 	    buf[len] = PATHSEP;
10500 	    simplify_filename(buf);
10501 	}
10502 
10503 	if (ga_grow(gap, 1) == FAIL)
10504 	    break;
10505 
10506 # if defined(MSWIN)
10507 	/* Avoid the path ending in a backslash, it fails when a comma is
10508 	 * appended. */
10509 	len = (int)STRLEN(buf);
10510 	if (buf[len - 1] == '\\')
10511 	    buf[len - 1] = '/';
10512 # endif
10513 
10514 	p = vim_strsave(buf);
10515 	if (p == NULL)
10516 	    break;
10517 	((char_u **)gap->ga_data)[gap->ga_len++] = p;
10518     }
10519 
10520     vim_free(buf);
10521 }
10522 
10523 /*
10524  * Returns a pointer to the file or directory name in "fname" that matches the
10525  * longest path in "ga"p, or NULL if there is no match. For example:
10526  *
10527  *    path: /foo/bar/baz
10528  *   fname: /foo/bar/baz/quux.txt
10529  * returns:		 ^this
10530  */
10531     static char_u *
10532 get_path_cutoff(char_u *fname, garray_T *gap)
10533 {
10534     int	    i;
10535     int	    maxlen = 0;
10536     char_u  **path_part = (char_u **)gap->ga_data;
10537     char_u  *cutoff = NULL;
10538 
10539     for (i = 0; i < gap->ga_len; i++)
10540     {
10541 	int j = 0;
10542 
10543 	while ((fname[j] == path_part[i][j]
10544 # if defined(MSWIN)
10545 		|| (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10546 #endif
10547 			     ) && fname[j] != NUL && path_part[i][j] != NUL)
10548 	    j++;
10549 	if (j > maxlen)
10550 	{
10551 	    maxlen = j;
10552 	    cutoff = &fname[j];
10553 	}
10554     }
10555 
10556     /* skip to the file or directory name */
10557     if (cutoff != NULL)
10558 	while (vim_ispathsep(*cutoff))
10559 	    MB_PTR_ADV(cutoff);
10560 
10561     return cutoff;
10562 }
10563 
10564 /*
10565  * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10566  * that they are unique with respect to each other while conserving the part
10567  * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
10568  */
10569     static void
10570 uniquefy_paths(garray_T *gap, char_u *pattern)
10571 {
10572     int		i;
10573     int		len;
10574     char_u	**fnames = (char_u **)gap->ga_data;
10575     int		sort_again = FALSE;
10576     char_u	*pat;
10577     char_u      *file_pattern;
10578     char_u	*curdir;
10579     regmatch_T	regmatch;
10580     garray_T	path_ga;
10581     char_u	**in_curdir = NULL;
10582     char_u	*short_name;
10583 
10584     remove_duplicates(gap);
10585     ga_init2(&path_ga, (int)sizeof(char_u *), 1);
10586 
10587     /*
10588      * We need to prepend a '*' at the beginning of file_pattern so that the
10589      * regex matches anywhere in the path. FIXME: is this valid for all
10590      * possible patterns?
10591      */
10592     len = (int)STRLEN(pattern);
10593     file_pattern = alloc(len + 2);
10594     if (file_pattern == NULL)
10595 	return;
10596     file_pattern[0] = '*';
10597     file_pattern[1] = NUL;
10598     STRCAT(file_pattern, pattern);
10599     pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10600     vim_free(file_pattern);
10601     if (pat == NULL)
10602 	return;
10603 
10604     regmatch.rm_ic = TRUE;		/* always ignore case */
10605     regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10606     vim_free(pat);
10607     if (regmatch.regprog == NULL)
10608 	return;
10609 
10610     if ((curdir = alloc((int)(MAXPATHL))) == NULL)
10611 	goto theend;
10612     mch_dirname(curdir, MAXPATHL);
10613     expand_path_option(curdir, &path_ga);
10614 
10615     in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
10616     if (in_curdir == NULL)
10617 	goto theend;
10618 
10619     for (i = 0; i < gap->ga_len && !got_int; i++)
10620     {
10621 	char_u	    *path = fnames[i];
10622 	int	    is_in_curdir;
10623 	char_u	    *dir_end = gettail_dir(path);
10624 	char_u	    *pathsep_p;
10625 	char_u	    *path_cutoff;
10626 
10627 	len = (int)STRLEN(path);
10628 	is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
10629 					     && curdir[dir_end - path] == NUL;
10630 	if (is_in_curdir)
10631 	    in_curdir[i] = vim_strsave(path);
10632 
10633 	/* Shorten the filename while maintaining its uniqueness */
10634 	path_cutoff = get_path_cutoff(path, &path_ga);
10635 
10636 	/* Don't assume all files can be reached without path when search
10637 	 * pattern starts with star star slash, so only remove path_cutoff
10638 	 * when possible. */
10639 	if (pattern[0] == '*' && pattern[1] == '*'
10640 		&& vim_ispathsep_nocolon(pattern[2])
10641 		&& path_cutoff != NULL
10642 		&& vim_regexec(&regmatch, path_cutoff, (colnr_T)0)
10643 		&& is_unique(path_cutoff, gap, i))
10644 	{
10645 	    sort_again = TRUE;
10646 	    mch_memmove(path, path_cutoff, STRLEN(path_cutoff) + 1);
10647 	}
10648 	else
10649 	{
10650 	    /* Here all files can be reached without path, so get shortest
10651 	     * unique path.  We start at the end of the path. */
10652 	    pathsep_p = path + len - 1;
10653 
10654 	    while (find_previous_pathsep(path, &pathsep_p))
10655 		if (vim_regexec(&regmatch, pathsep_p + 1, (colnr_T)0)
10656 			&& is_unique(pathsep_p + 1, gap, i)
10657 			&& path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10658 		{
10659 		    sort_again = TRUE;
10660 		    mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10661 		    break;
10662 		}
10663 	}
10664 
10665 	if (mch_isFullName(path))
10666 	{
10667 	    /*
10668 	     * Last resort: shorten relative to curdir if possible.
10669 	     * 'possible' means:
10670 	     * 1. It is under the current directory.
10671 	     * 2. The result is actually shorter than the original.
10672 	     *
10673 	     *	    Before		  curdir	After
10674 	     *	    /foo/bar/file.txt	  /foo/bar	./file.txt
10675 	     *	    c:\foo\bar\file.txt   c:\foo\bar	.\file.txt
10676 	     *	    /file.txt		  /		/file.txt
10677 	     *	    c:\file.txt		  c:\		.\file.txt
10678 	     */
10679 	    short_name = shorten_fname(path, curdir);
10680 	    if (short_name != NULL && short_name > path + 1
10681 #if defined(MSWIN)
10682 		    /* On windows,
10683 		     *	    shorten_fname("c:\a\a.txt", "c:\a\b")
10684 		     * returns "\a\a.txt", which is not really the short
10685 		     * name, hence: */
10686 		    && !vim_ispathsep(*short_name)
10687 #endif
10688 		)
10689 	    {
10690 		STRCPY(path, ".");
10691 		add_pathsep(path);
10692 		STRMOVE(path + STRLEN(path), short_name);
10693 	    }
10694 	}
10695 	ui_breakcheck();
10696     }
10697 
10698     /* Shorten filenames in /in/current/directory/{filename} */
10699     for (i = 0; i < gap->ga_len && !got_int; i++)
10700     {
10701 	char_u *rel_path;
10702 	char_u *path = in_curdir[i];
10703 
10704 	if (path == NULL)
10705 	    continue;
10706 
10707 	/* If the {filename} is not unique, change it to ./{filename}.
10708 	 * Else reduce it to {filename} */
10709 	short_name = shorten_fname(path, curdir);
10710 	if (short_name == NULL)
10711 	    short_name = path;
10712 	if (is_unique(short_name, gap, i))
10713 	{
10714 	    STRCPY(fnames[i], short_name);
10715 	    continue;
10716 	}
10717 
10718 	rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10719 	if (rel_path == NULL)
10720 	    goto theend;
10721 	STRCPY(rel_path, ".");
10722 	add_pathsep(rel_path);
10723 	STRCAT(rel_path, short_name);
10724 
10725 	vim_free(fnames[i]);
10726 	fnames[i] = rel_path;
10727 	sort_again = TRUE;
10728 	ui_breakcheck();
10729     }
10730 
10731 theend:
10732     vim_free(curdir);
10733     if (in_curdir != NULL)
10734     {
10735 	for (i = 0; i < gap->ga_len; i++)
10736 	    vim_free(in_curdir[i]);
10737 	vim_free(in_curdir);
10738     }
10739     ga_clear_strings(&path_ga);
10740     vim_regfree(regmatch.regprog);
10741 
10742     if (sort_again)
10743 	remove_duplicates(gap);
10744 }
10745 
10746 /*
10747  * Calls globpath() with 'path' values for the given pattern and stores the
10748  * result in "gap".
10749  * Returns the total number of matches.
10750  */
10751     static int
10752 expand_in_path(
10753     garray_T	*gap,
10754     char_u	*pattern,
10755     int		flags)		/* EW_* flags */
10756 {
10757     char_u	*curdir;
10758     garray_T	path_ga;
10759     char_u	*paths = NULL;
10760 
10761     if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
10762 	return 0;
10763     mch_dirname(curdir, MAXPATHL);
10764 
10765     ga_init2(&path_ga, (int)sizeof(char_u *), 1);
10766     expand_path_option(curdir, &path_ga);
10767     vim_free(curdir);
10768     if (path_ga.ga_len == 0)
10769 	return 0;
10770 
10771     paths = ga_concat_strings(&path_ga, ",");
10772     ga_clear_strings(&path_ga);
10773     if (paths == NULL)
10774 	return 0;
10775 
10776     globpath(paths, pattern, gap, (flags & EW_ICASE) ? WILD_ICASE : 0);
10777     vim_free(paths);
10778 
10779     return gap->ga_len;
10780 }
10781 #endif
10782 
10783 #if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10784 /*
10785  * Sort "gap" and remove duplicate entries.  "gap" is expected to contain a
10786  * list of file names in allocated memory.
10787  */
10788     void
10789 remove_duplicates(garray_T *gap)
10790 {
10791     int	    i;
10792     int	    j;
10793     char_u  **fnames = (char_u **)gap->ga_data;
10794 
10795     sort_strings(fnames, gap->ga_len);
10796     for (i = gap->ga_len - 1; i > 0; --i)
10797 	if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10798 	{
10799 	    vim_free(fnames[i]);
10800 	    for (j = i + 1; j < gap->ga_len; ++j)
10801 		fnames[j - 1] = fnames[j];
10802 	    --gap->ga_len;
10803 	}
10804 }
10805 #endif
10806 
10807 static int has_env_var(char_u *p);
10808 
10809 /*
10810  * Return TRUE if "p" contains what looks like an environment variable.
10811  * Allowing for escaping.
10812  */
10813     static int
10814 has_env_var(char_u *p)
10815 {
10816     for ( ; *p; MB_PTR_ADV(p))
10817     {
10818 	if (*p == '\\' && p[1] != NUL)
10819 	    ++p;
10820 	else if (vim_strchr((char_u *)
10821 #if defined(MSWIN)
10822 				    "$%"
10823 #else
10824 				    "$"
10825 #endif
10826 					, *p) != NULL)
10827 	    return TRUE;
10828     }
10829     return FALSE;
10830 }
10831 
10832 #ifdef SPECIAL_WILDCHAR
10833 static int has_special_wildchar(char_u *p);
10834 
10835 /*
10836  * Return TRUE if "p" contains a special wildcard character, one that Vim
10837  * cannot expand, requires using a shell.
10838  */
10839     static int
10840 has_special_wildchar(char_u *p)
10841 {
10842     for ( ; *p; MB_PTR_ADV(p))
10843     {
10844 	/* Allow for escaping. */
10845 	if (*p == '\\' && p[1] != NUL)
10846 	    ++p;
10847 	else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
10848 	    return TRUE;
10849     }
10850     return FALSE;
10851 }
10852 #endif
10853 
10854 /*
10855  * Generic wildcard expansion code.
10856  *
10857  * Characters in "pat" that should not be expanded must be preceded with a
10858  * backslash. E.g., "/path\ with\ spaces/my\*star*"
10859  *
10860  * Return FAIL when no single file was found.  In this case "num_file" is not
10861  * set, and "file" may contain an error message.
10862  * Return OK when some files found.  "num_file" is set to the number of
10863  * matches, "file" to the array of matches.  Call FreeWild() later.
10864  */
10865     int
10866 gen_expand_wildcards(
10867     int		num_pat,	/* number of input patterns */
10868     char_u	**pat,		/* array of input patterns */
10869     int		*num_file,	/* resulting number of files */
10870     char_u	***file,	/* array of resulting files */
10871     int		flags)		/* EW_* flags */
10872 {
10873     int			i;
10874     garray_T		ga;
10875     char_u		*p;
10876     static int		recursive = FALSE;
10877     int			add_pat;
10878     int			retval = OK;
10879 #if defined(FEAT_SEARCHPATH)
10880     int			did_expand_in_path = FALSE;
10881 #endif
10882 
10883     /*
10884      * expand_env() is called to expand things like "~user".  If this fails,
10885      * it calls ExpandOne(), which brings us back here.  In this case, always
10886      * call the machine specific expansion function, if possible.  Otherwise,
10887      * return FAIL.
10888      */
10889     if (recursive)
10890 #ifdef SPECIAL_WILDCHAR
10891 	return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10892 #else
10893 	return FAIL;
10894 #endif
10895 
10896 #ifdef SPECIAL_WILDCHAR
10897     /*
10898      * If there are any special wildcard characters which we cannot handle
10899      * here, call machine specific function for all the expansion.  This
10900      * avoids starting the shell for each argument separately.
10901      * For `=expr` do use the internal function.
10902      */
10903     for (i = 0; i < num_pat; i++)
10904     {
10905 	if (has_special_wildchar(pat[i])
10906 # ifdef VIM_BACKTICK
10907 		&& !(vim_backtick(pat[i]) && pat[i][1] == '=')
10908 # endif
10909 	   )
10910 	    return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10911     }
10912 #endif
10913 
10914     recursive = TRUE;
10915 
10916     /*
10917      * The matching file names are stored in a growarray.  Init it empty.
10918      */
10919     ga_init2(&ga, (int)sizeof(char_u *), 30);
10920 
10921     for (i = 0; i < num_pat; ++i)
10922     {
10923 	add_pat = -1;
10924 	p = pat[i];
10925 
10926 #ifdef VIM_BACKTICK
10927 	if (vim_backtick(p))
10928 	{
10929 	    add_pat = expand_backtick(&ga, p, flags);
10930 	    if (add_pat == -1)
10931 		retval = FAIL;
10932 	}
10933 	else
10934 #endif
10935 	{
10936 	    /*
10937 	     * First expand environment variables, "~/" and "~user/".
10938 	     */
10939 	    if (has_env_var(p) || *p == '~')
10940 	    {
10941 		p = expand_env_save_opt(p, TRUE);
10942 		if (p == NULL)
10943 		    p = pat[i];
10944 #ifdef UNIX
10945 		/*
10946 		 * On Unix, if expand_env() can't expand an environment
10947 		 * variable, use the shell to do that.  Discard previously
10948 		 * found file names and start all over again.
10949 		 */
10950 		else if (has_env_var(p) || *p == '~')
10951 		{
10952 		    vim_free(p);
10953 		    ga_clear_strings(&ga);
10954 		    i = mch_expand_wildcards(num_pat, pat, num_file, file,
10955 							 flags|EW_KEEPDOLLAR);
10956 		    recursive = FALSE;
10957 		    return i;
10958 		}
10959 #endif
10960 	    }
10961 
10962 	    /*
10963 	     * If there are wildcards: Expand file names and add each match to
10964 	     * the list.  If there is no match, and EW_NOTFOUND is given, add
10965 	     * the pattern.
10966 	     * If there are no wildcards: Add the file name if it exists or
10967 	     * when EW_NOTFOUND is given.
10968 	     */
10969 	    if (mch_has_exp_wildcard(p))
10970 	    {
10971 #if defined(FEAT_SEARCHPATH)
10972 		if ((flags & EW_PATH)
10973 			&& !mch_isFullName(p)
10974 			&& !(p[0] == '.'
10975 			    && (vim_ispathsep(p[1])
10976 				|| (p[1] == '.' && vim_ispathsep(p[2]))))
10977 		   )
10978 		{
10979 		    /* :find completion where 'path' is used.
10980 		     * Recursiveness is OK here. */
10981 		    recursive = FALSE;
10982 		    add_pat = expand_in_path(&ga, p, flags);
10983 		    recursive = TRUE;
10984 		    did_expand_in_path = TRUE;
10985 		}
10986 		else
10987 #endif
10988 		    add_pat = mch_expandpath(&ga, p, flags);
10989 	    }
10990 	}
10991 
10992 	if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10993 	{
10994 	    char_u	*t = backslash_halve_save(p);
10995 
10996 	    /* When EW_NOTFOUND is used, always add files and dirs.  Makes
10997 	     * "vim c:/" work. */
10998 	    if (flags & EW_NOTFOUND)
10999 		addfile(&ga, t, flags | EW_DIR | EW_FILE);
11000 	    else
11001 		addfile(&ga, t, flags);
11002 	    vim_free(t);
11003 	}
11004 
11005 #if defined(FEAT_SEARCHPATH)
11006 	if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
11007 	    uniquefy_paths(&ga, p);
11008 #endif
11009 	if (p != pat[i])
11010 	    vim_free(p);
11011     }
11012 
11013     *num_file = ga.ga_len;
11014     *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
11015 
11016     recursive = FALSE;
11017 
11018     return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
11019 }
11020 
11021 # ifdef VIM_BACKTICK
11022 
11023 /*
11024  * Return TRUE if we can expand this backtick thing here.
11025  */
11026     static int
11027 vim_backtick(char_u *p)
11028 {
11029     return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
11030 }
11031 
11032 /*
11033  * Expand an item in `backticks` by executing it as a command.
11034  * Currently only works when pat[] starts and ends with a `.
11035  * Returns number of file names found, -1 if an error is encountered.
11036  */
11037     static int
11038 expand_backtick(
11039     garray_T	*gap,
11040     char_u	*pat,
11041     int		flags)	/* EW_* flags */
11042 {
11043     char_u	*p;
11044     char_u	*cmd;
11045     char_u	*buffer;
11046     int		cnt = 0;
11047     int		i;
11048 
11049     /* Create the command: lop off the backticks. */
11050     cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
11051     if (cmd == NULL)
11052 	return -1;
11053 
11054 #ifdef FEAT_EVAL
11055     if (*cmd == '=')	    /* `={expr}`: Expand expression */
11056 	buffer = eval_to_string(cmd + 1, &p, TRUE);
11057     else
11058 #endif
11059 	buffer = get_cmd_output(cmd, NULL,
11060 				(flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
11061     vim_free(cmd);
11062     if (buffer == NULL)
11063 	return -1;
11064 
11065     cmd = buffer;
11066     while (*cmd != NUL)
11067     {
11068 	cmd = skipwhite(cmd);		/* skip over white space */
11069 	p = cmd;
11070 	while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
11071 	    ++p;
11072 	/* add an entry if it is not empty */
11073 	if (p > cmd)
11074 	{
11075 	    i = *p;
11076 	    *p = NUL;
11077 	    addfile(gap, cmd, flags);
11078 	    *p = i;
11079 	    ++cnt;
11080 	}
11081 	cmd = p;
11082 	while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
11083 	    ++cmd;
11084     }
11085 
11086     vim_free(buffer);
11087     return cnt;
11088 }
11089 # endif /* VIM_BACKTICK */
11090 
11091 /*
11092  * Add a file to a file list.  Accepted flags:
11093  * EW_DIR	add directories
11094  * EW_FILE	add files
11095  * EW_EXEC	add executable files
11096  * EW_NOTFOUND	add even when it doesn't exist
11097  * EW_ADDSLASH	add slash after directory name
11098  * EW_ALLLINKS	add symlink also when the referred file does not exist
11099  */
11100     void
11101 addfile(
11102     garray_T	*gap,
11103     char_u	*f,	/* filename */
11104     int		flags)
11105 {
11106     char_u	*p;
11107     int		isdir;
11108     stat_T	sb;
11109 
11110     /* if the file/dir/link doesn't exist, may not add it */
11111     if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
11112 			? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
11113 	return;
11114 
11115 #ifdef FNAME_ILLEGAL
11116     /* if the file/dir contains illegal characters, don't add it */
11117     if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
11118 	return;
11119 #endif
11120 
11121     isdir = mch_isdir(f);
11122     if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
11123 	return;
11124 
11125     /* If the file isn't executable, may not add it.  Do accept directories.
11126      * When invoked from expand_shellcmd() do not use $PATH. */
11127     if (!isdir && (flags & EW_EXEC)
11128 			     && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
11129 	return;
11130 
11131     /* Make room for another item in the file list. */
11132     if (ga_grow(gap, 1) == FAIL)
11133 	return;
11134 
11135     p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
11136     if (p == NULL)
11137 	return;
11138 
11139     STRCPY(p, f);
11140 #ifdef BACKSLASH_IN_FILENAME
11141     slash_adjust(p);
11142 #endif
11143     /*
11144      * Append a slash or backslash after directory names if none is present.
11145      */
11146 #ifndef DONT_ADD_PATHSEP_TO_DIR
11147     if (isdir && (flags & EW_ADDSLASH))
11148 	add_pathsep(p);
11149 #endif
11150     ((char_u **)gap->ga_data)[gap->ga_len++] = p;
11151 }
11152 #endif /* !NO_EXPANDPATH */
11153 
11154 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
11155 
11156 #ifndef SEEK_SET
11157 # define SEEK_SET 0
11158 #endif
11159 #ifndef SEEK_END
11160 # define SEEK_END 2
11161 #endif
11162 
11163 /*
11164  * Get the stdout of an external command.
11165  * If "ret_len" is NULL replace NUL characters with NL.  When "ret_len" is not
11166  * NULL store the length there.
11167  * Returns an allocated string, or NULL for error.
11168  */
11169     char_u *
11170 get_cmd_output(
11171     char_u	*cmd,
11172     char_u	*infile,	/* optional input file name */
11173     int		flags,		/* can be SHELL_SILENT */
11174     int		*ret_len)
11175 {
11176     char_u	*tempname;
11177     char_u	*command;
11178     char_u	*buffer = NULL;
11179     int		len;
11180     int		i = 0;
11181     FILE	*fd;
11182 
11183     if (check_restricted() || check_secure())
11184 	return NULL;
11185 
11186     /* get a name for the temp file */
11187     if ((tempname = vim_tempname('o', FALSE)) == NULL)
11188     {
11189 	EMSG(_(e_notmp));
11190 	return NULL;
11191     }
11192 
11193     /* Add the redirection stuff */
11194     command = make_filter_cmd(cmd, infile, tempname);
11195     if (command == NULL)
11196 	goto done;
11197 
11198     /*
11199      * Call the shell to execute the command (errors are ignored).
11200      * Don't check timestamps here.
11201      */
11202     ++no_check_timestamps;
11203     call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
11204     --no_check_timestamps;
11205 
11206     vim_free(command);
11207 
11208     /*
11209      * read the names from the file into memory
11210      */
11211 # ifdef VMS
11212     /* created temporary file is not always readable as binary */
11213     fd = mch_fopen((char *)tempname, "r");
11214 # else
11215     fd = mch_fopen((char *)tempname, READBIN);
11216 # endif
11217 
11218     if (fd == NULL)
11219     {
11220 	EMSG2(_(e_notopen), tempname);
11221 	goto done;
11222     }
11223 
11224     fseek(fd, 0L, SEEK_END);
11225     len = ftell(fd);		    /* get size of temp file */
11226     fseek(fd, 0L, SEEK_SET);
11227 
11228     buffer = alloc(len + 1);
11229     if (buffer != NULL)
11230 	i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
11231     fclose(fd);
11232     mch_remove(tempname);
11233     if (buffer == NULL)
11234 	goto done;
11235 #ifdef VMS
11236     len = i;	/* VMS doesn't give us what we asked for... */
11237 #endif
11238     if (i != len)
11239     {
11240 	EMSG2(_(e_notread), tempname);
11241 	vim_free(buffer);
11242 	buffer = NULL;
11243     }
11244     else if (ret_len == NULL)
11245     {
11246 	/* Change NUL into SOH, otherwise the string is truncated. */
11247 	for (i = 0; i < len; ++i)
11248 	    if (buffer[i] == NUL)
11249 		buffer[i] = 1;
11250 
11251 	buffer[len] = NUL;	/* make sure the buffer is terminated */
11252     }
11253     else
11254 	*ret_len = len;
11255 
11256 done:
11257     vim_free(tempname);
11258     return buffer;
11259 }
11260 #endif
11261 
11262 /*
11263  * Free the list of files returned by expand_wildcards() or other expansion
11264  * functions.
11265  */
11266     void
11267 FreeWild(int count, char_u **files)
11268 {
11269     if (count <= 0 || files == NULL)
11270 	return;
11271     while (count--)
11272 	vim_free(files[count]);
11273     vim_free(files);
11274 }
11275 
11276 /*
11277  * Return TRUE when need to go to Insert mode because of 'insertmode'.
11278  * Don't do this when still processing a command or a mapping.
11279  * Don't do this when inside a ":normal" command.
11280  */
11281     int
11282 goto_im(void)
11283 {
11284     return (p_im && stuff_empty() && typebuf_typed());
11285 }
11286 
11287 /*
11288  * Returns the isolated name of the shell in allocated memory:
11289  * - Skip beyond any path.  E.g., "/usr/bin/csh -f" -> "csh -f".
11290  * - Remove any argument.  E.g., "csh -f" -> "csh".
11291  * But don't allow a space in the path, so that this works:
11292  *   "/usr/bin/csh --rcfile ~/.cshrc"
11293  * But don't do that for Windows, it's common to have a space in the path.
11294  */
11295     char_u *
11296 get_isolated_shell_name(void)
11297 {
11298     char_u *p;
11299 
11300 #ifdef WIN3264
11301     p = gettail(p_sh);
11302     p = vim_strnsave(p, (int)(skiptowhite(p) - p));
11303 #else
11304     p = skiptowhite(p_sh);
11305     if (*p == NUL)
11306     {
11307 	/* No white space, use the tail. */
11308 	p = vim_strsave(gettail(p_sh));
11309     }
11310     else
11311     {
11312 	char_u  *p1, *p2;
11313 
11314 	/* Find the last path separator before the space. */
11315 	p1 = p_sh;
11316 	for (p2 = p_sh; p2 < p; MB_PTR_ADV(p2))
11317 	    if (vim_ispathsep(*p2))
11318 		p1 = p2 + 1;
11319 	p = vim_strnsave(p1, (int)(p - p1));
11320     }
11321 #endif
11322     return p;
11323 }
11324