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