1 /* vi:set ts=8 sts=4 sw=4 noet:
3 * VIM - Vi IMproved by Bram Moolenaar
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.
11 * misc1.c: functions that didn't seem to fit elsewhere
17 static char_u *vim_version_dir(char_u *vimdir);
18 static char_u *remove_tail(char_u *p, char_u *pend, char_u *name);
19 #if defined(FEAT_CMDL_COMPL)
20 static void init_users(void);
22 static int copy_indent(int size, char_u *src);
24 /* All user names (for ~user completion as done by shell). */
25 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
26 static garray_T ga_users;
30 * Count the size (in window cells) of the indent in the current line.
35 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts, FALSE);
39 * Count the size (in window cells) of the indent in line "lnum".
42 get_indent_lnum(linenr_T lnum)
44 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts, FALSE);
47 #if defined(FEAT_FOLDING) || defined(PROTO)
49 * Count the size (in window cells) of the indent in line "lnum" of buffer
53 get_indent_buf(buf_T *buf, linenr_T lnum)
55 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts, FALSE);
60 * count the size (in window cells) of the indent in line "ptr", with
67 int list) /* if TRUE, count only screen size for tabs */
75 if (!list || lcs_tab1) /* count a tab for what it is worth */
76 count += ts - (count % ts);
78 /* In list mode, when tab is not set, count screen char width
79 * for Tab, displays: ^I */
80 count += ptr2cells(ptr);
83 ++count; /* count a space for one */
91 * Set the indent of the current line.
92 * Leaves the cursor on the first non-blank in the line.
93 * Caller must take care of undo.
95 * SIN_CHANGED: call changed_bytes() if the line was changed.
96 * SIN_INSERT: insert the indent in front of the line.
97 * SIN_UNDO: save line for undo before changing it.
98 * Returns TRUE if the line was changed.
102 int size, /* measured in spaces */
110 int ind_len; /* measured in characters */
113 int ind_done = 0; /* measured in spaces */
116 int orig_char_len = -1; /* number of initial whitespace chars when
117 'et' and 'pi' are both set */
120 * First check if there is anything to do and compute the number of
121 * characters needed for the indent.
125 p = oldline = ml_get_curline();
127 /* Calculate the buffer size for the new indent, and check to see if it
128 * isn't already set */
130 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
131 * 'preserveindent' are set count the number of characters at the
132 * beginning of the line to be copied */
133 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
135 /* If 'preserveindent' is set then reuse as much as possible of
136 * the existing indent structure for the new indent */
137 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
141 /* count as many characters as we can use */
142 while (todo > 0 && VIM_ISWHITE(*p))
146 tab_pad = (int)curbuf->b_p_ts
147 - (ind_done % (int)curbuf->b_p_ts);
148 /* stop if this tab will overshoot the target */
164 /* Set initial number of whitespace chars to copy if we are
165 * preserving indent but expandtab is set */
167 orig_char_len = ind_len;
169 /* Fill to next tabstop with a tab, if possible */
170 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
171 if (todo >= tab_pad && orig_char_len == -1)
176 /* ind_done += tab_pad; */
180 /* count tabs required for indent */
181 while (todo >= (int)curbuf->b_p_ts)
187 todo -= (int)curbuf->b_p_ts;
189 /* ind_done += (int)curbuf->b_p_ts; */
192 /* count spaces required for indent */
204 /* Return if the indent is OK already. */
205 if (!doit && !VIM_ISWHITE(*p) && !(flags & SIN_INSERT))
208 /* Allocate memory for the new line. */
209 if (flags & SIN_INSERT)
213 line_len = (int)STRLEN(p) + 1;
215 /* If 'preserveindent' and 'expandtab' are both set keep the original
216 * characters and allocate accordingly. We will fill the rest with spaces
217 * after the if (!curbuf->b_p_et) below. */
218 if (orig_char_len != -1)
220 newline = alloc(orig_char_len + size - ind_done + line_len);
223 todo = size - ind_done;
224 ind_len = orig_char_len + todo; /* Set total length of indent in
225 * characters, which may have been
226 * undercounted until now */
229 while (orig_char_len > 0)
235 /* Skip over any additional white space (useful when newindent is less
237 while (VIM_ISWHITE(*p))
244 newline = alloc(ind_len + line_len);
250 /* Put the characters in the new line. */
251 /* if 'expandtab' isn't set: use TABs */
254 /* If 'preserveindent' is set then reuse as much as possible of
255 * the existing indent structure for the new indent */
256 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
261 while (todo > 0 && VIM_ISWHITE(*p))
265 tab_pad = (int)curbuf->b_p_ts
266 - (ind_done % (int)curbuf->b_p_ts);
267 /* stop if this tab will overshoot the target */
281 /* Fill to next tabstop with a tab, if possible */
282 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
292 while (todo >= (int)curbuf->b_p_ts)
295 todo -= (int)curbuf->b_p_ts;
303 mch_memmove(s, p, (size_t)line_len);
305 /* Replace the line (unless undo fails). */
306 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
308 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
309 if (flags & SIN_CHANGED)
310 changed_bytes(curwin->w_cursor.lnum, 0);
311 /* Correct saved cursor position if it is in this line. */
312 if (saved_cursor.lnum == curwin->w_cursor.lnum)
314 if (saved_cursor.col >= (colnr_T)(p - oldline))
315 /* cursor was after the indent, adjust for the number of
316 * bytes added/removed */
317 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
318 else if (saved_cursor.col >= (colnr_T)(s - newline))
319 /* cursor was in the indent, and is now after it, put it back
320 * at the start of the indent (replacing spaces with TAB) */
321 saved_cursor.col = (colnr_T)(s - newline);
328 curwin->w_cursor.col = ind_len;
333 * Copy the indent from ptr to the current line (and fill to size)
334 * Leaves the cursor on the first non-blank in the line.
335 * Returns TRUE if the line was changed.
338 copy_indent(int size, char_u *src)
350 /* Round 1: compute the number of characters needed for the indent
351 * Round 2: copy the characters. */
352 for (round = 1; round <= 2; ++round)
359 /* Count/copy the usable portion of the source line */
360 while (todo > 0 && VIM_ISWHITE(*s))
364 tab_pad = (int)curbuf->b_p_ts
365 - (ind_done % (int)curbuf->b_p_ts);
366 /* Stop if this tab will overshoot the target */
383 /* Fill to next tabstop with a tab, if possible */
384 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
385 if (todo >= tab_pad && !curbuf->b_p_et)
393 /* Add tabs required for indent */
394 while (todo >= (int)curbuf->b_p_ts && !curbuf->b_p_et)
396 todo -= (int)curbuf->b_p_ts;
402 /* Count/add spaces required for indent */
413 /* Allocate memory for the result: the copied indent, new indent
414 * and the rest of the line. */
415 line_len = (int)STRLEN(ml_get_curline()) + 1;
416 line = alloc(ind_len + line_len);
423 /* Append the original line */
424 mch_memmove(p, ml_get_curline(), (size_t)line_len);
426 /* Replace the line */
427 ml_replace(curwin->w_cursor.lnum, line, FALSE);
429 /* Put the cursor after the indent. */
430 curwin->w_cursor.col = ind_len;
435 * Return the indent of the current line after a number. Return -1 if no
436 * number was found. Used for 'n' in 'formatoptions': numbered list.
437 * Since a pattern is used it can actually handle more than numbers.
440 get_number_indent(linenr_T lnum)
446 int lead_len = 0; /* length of comment leader */
448 if (lnum > curbuf->b_ml.ml_line_count)
453 /* In format_lines() (i.e. not insert mode), fo+=q is needed too... */
454 if ((State & INSERT) || has_format_option(FO_Q_COMS))
455 lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
457 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
458 if (regmatch.regprog != NULL)
460 regmatch.rm_ic = FALSE;
462 /* vim_regexec() expects a pointer to a line. This lets us
463 * start matching for the flp beyond any comment leader... */
464 if (vim_regexec(®match, ml_get(lnum) + lead_len, (colnr_T)0))
467 pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
468 #ifdef FEAT_VIRTUALEDIT
472 vim_regfree(regmatch.regprog);
475 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
477 getvcol(curwin, &pos, &col, NULL, NULL);
481 #if defined(FEAT_LINEBREAK) || defined(PROTO)
483 * Return appropriate space number for breakindent, taking influencing
484 * parameters into account. Window must be specified, since it is not
485 * necessarily always the current one.
490 char_u *line) /* start of the line */
492 static int prev_indent = 0; /* cached indent value */
493 static long prev_ts = 0L; /* cached tabstop value */
494 static char_u *prev_line = NULL; /* cached pointer to line */
495 static varnumber_T prev_tick = 0; /* changedtick of cached value */
497 /* window width minus window margin space, i.e. what rests for text */
498 const int eff_wwidth = W_WIDTH(wp)
499 - ((wp->w_p_nu || wp->w_p_rnu)
500 && (vim_strchr(p_cpo, CPO_NUMCOL) == NULL)
501 ? number_width(wp) + 1 : 0);
503 /* used cached indent, unless pointer or 'tabstop' changed */
504 if (prev_line != line || prev_ts != wp->w_buffer->b_p_ts
505 || prev_tick != CHANGEDTICK(wp->w_buffer))
508 prev_ts = wp->w_buffer->b_p_ts;
509 prev_tick = CHANGEDTICK(wp->w_buffer);
510 prev_indent = get_indent_str(line,
511 (int)wp->w_buffer->b_p_ts, wp->w_p_list);
513 bri = prev_indent + wp->w_p_brishift;
515 /* indent minus the length of the showbreak string */
517 bri -= vim_strsize(p_sbr);
519 /* Add offset for number column, if 'n' is in 'cpoptions' */
520 bri += win_col_off2(wp);
522 /* never indent past left window margin */
525 /* always leave at least bri_min characters on the left,
526 * if text width is sufficient */
527 else if (bri > eff_wwidth - wp->w_p_brimin)
528 bri = (eff_wwidth - wp->w_p_brimin < 0)
529 ? 0 : eff_wwidth - wp->w_p_brimin;
536 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
538 static int cin_is_cinword(char_u *line);
541 * Return TRUE if the string "line" starts with a word from 'cinwords'.
544 cin_is_cinword(char_u *line)
552 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
553 cinw_buf = alloc((unsigned)cinw_len);
554 if (cinw_buf != NULL)
556 line = skipwhite(line);
557 for (cinw = curbuf->b_p_cinw; *cinw; )
559 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
560 if (STRNCMP(line, cinw_buf, len) == 0
561 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
574 * open_line: Add a new line below or above the current line.
576 * For VREPLACE mode, we only add a new line when we get to the end of the
577 * file, otherwise we just start replacing the next line.
579 * Caller must take care of undo. Since VREPLACE may affect any number of
580 * lines however, it may call u_save_cursor() again when starting to change a
582 * "flags": OPENLINE_DELSPACES delete spaces after cursor
583 * OPENLINE_DO_COM format comments
584 * OPENLINE_KEEPTRAIL keep trailing spaces
585 * OPENLINE_MARKFIX adjust mark positions after the line break
586 * OPENLINE_COM_LIST format comments with list or 2nd line indent
588 * "second_line_indent": indent for after ^^D in Insert mode or if flag
591 * Return TRUE for success, FALSE for failure
595 int dir, /* FORWARD or BACKWARD */
597 int second_line_indent)
599 char_u *saved_line; /* copy of the original line */
600 char_u *next_line = NULL; /* copy of the next line */
601 char_u *p_extra = NULL; /* what goes to next line */
602 int less_cols = 0; /* less columns for mark in new line */
603 int less_cols_off = 0; /* columns to skip for mark adjust */
604 pos_T old_cursor; /* old cursor position */
605 int newcol = 0; /* new cursor column */
606 int newindent = 0; /* auto-indent of the new line */
608 int trunc_line = FALSE; /* truncate current line afterwards */
609 int retval = FALSE; /* return value, default is FAIL */
611 int extra_len = 0; /* length of p_extra string */
612 int lead_len; /* length of comment leader */
613 char_u *lead_flags; /* position in 'comments' for comment leader */
614 char_u *leader = NULL; /* copy of comment leader */
616 char_u *allocated = NULL; /* allocated memory */
617 #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
618 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
621 int saved_char = NUL; /* init for GCC */
622 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
625 #ifdef FEAT_SMARTINDENT
626 int do_si = (!p_paste && curbuf->b_p_si
631 int no_si = FALSE; /* reset did_si afterwards */
632 int first_char = NUL; /* init for GCC */
634 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
637 int did_append; /* appended a new line */
638 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
641 * make a copy of the current line so we can mess with it
643 saved_line = vim_strsave(ml_get_curline());
644 if (saved_line == NULL) /* out of memory! */
648 if (State & VREPLACE_FLAG)
651 * With VREPLACE we make a copy of the next line, which we will be
652 * starting to replace. First make the new line empty and let vim play
653 * with the indenting and comment leader to its heart's content. Then
654 * we grab what it ended up putting on the new line, put back the
655 * original line, and call ins_char() to put each new character onto
656 * the line, replacing what was there before and pushing the right
657 * stuff onto the replace stack. -- webb.
659 if (curwin->w_cursor.lnum < orig_line_count)
660 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
662 next_line = vim_strsave((char_u *)"");
663 if (next_line == NULL) /* out of memory! */
667 * In VREPLACE mode, a NL replaces the rest of the line, and starts
668 * replacing the next line, so push all of the characters left on the
669 * line onto the replace stack. We'll push any other characters that
670 * might be replaced at the start of the next line (due to autoindent
673 replace_push(NUL); /* Call twice because BS over NL expects it */
675 p = saved_line + curwin->w_cursor.col;
680 p += replace_push_mb(p);
685 saved_line[curwin->w_cursor.col] = NUL;
691 && !(State & VREPLACE_FLAG)
695 p_extra = saved_line + curwin->w_cursor.col;
696 #ifdef FEAT_SMARTINDENT
697 if (do_si) /* need first char after new line break */
699 p = skipwhite(p_extra);
704 extra_len = (int)STRLEN(p_extra);
706 saved_char = *p_extra;
710 u_clearline(); /* cannot do "U" command when adding lines */
711 #ifdef FEAT_SMARTINDENT
717 * If we just did an auto-indent, then we didn't type anything on
718 * the prior line, and it should be truncated. Do this even if 'ai' is not
719 * set because automatically inserting a comment leader also sets did_ai.
721 if (dir == FORWARD && did_ai)
725 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
726 * indent to use for the new line.
729 #ifdef FEAT_SMARTINDENT
735 * count white space on current line
737 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts, FALSE);
738 if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
739 newindent = second_line_indent; /* for ^^D command in insert mode */
741 #ifdef FEAT_SMARTINDENT
743 * Do smart indenting.
744 * In insert/replace mode (only when dir == FORWARD)
745 * we may move some text to the next line. If it starts with '{'
746 * don't add an indent. Fixes inserting a NL before '{' in line
749 if (!trunc_line && do_si && *saved_line != NUL
750 && (p_extra == NULL || first_char != '{'))
755 old_cursor = curwin->w_cursor;
757 # ifdef FEAT_COMMENTS
758 if (flags & OPENLINE_DO_COM)
759 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
766 * Skip preprocessor directives, unless they are
767 * recognised as comments.
770 # ifdef FEAT_COMMENTS
775 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
776 ptr = ml_get(--curwin->w_cursor.lnum);
777 newindent = get_indent();
779 # ifdef FEAT_COMMENTS
780 if (flags & OPENLINE_DO_COM)
781 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
787 * This case gets the following right:
789 * * A comment (read '\' as '/').
792 * This should line up here;
795 if (p[0] == '/' && p[1] == '*')
801 if (p[0] == '/' && p[-1] == '*')
804 * End of C comment, indent should line up
805 * with the line containing the start of
808 curwin->w_cursor.col = (colnr_T)(p - ptr);
809 if ((pos = findmatch(NULL, NUL)) != NULL)
811 curwin->w_cursor.lnum = pos->lnum;
812 newindent = get_indent();
818 else /* Not a comment line */
821 /* Find last non-blank in line */
822 p = ptr + STRLEN(ptr) - 1;
823 while (p > ptr && VIM_ISWHITE(*p))
828 * find the character just before the '{' or ';'
830 if (last_char == '{' || last_char == ';')
834 while (p > ptr && VIM_ISWHITE(*p))
838 * Try to catch lines that are split over multiple
842 * Should line up here!
847 curwin->w_cursor.col = (colnr_T)(p - ptr);
848 if ((pos = findmatch(NULL, '(')) != NULL)
850 curwin->w_cursor.lnum = pos->lnum;
851 newindent = get_indent();
852 ptr = ml_get_curline();
856 * If last character is '{' do indent, without
857 * checking for "if" and the like.
859 if (last_char == '{')
861 did_si = TRUE; /* do indent */
862 no_si = TRUE; /* don't delete it when '{' typed */
865 * Look for "if" and the like, use 'cinwords'.
866 * Don't do this if the previous line ended in ';' or
869 else if (last_char != ';' && last_char != '}'
870 && cin_is_cinword(ptr))
874 else /* dir == BACKWARD */
877 * Skip preprocessor directives, unless they are
878 * recognised as comments.
881 # ifdef FEAT_COMMENTS
886 int was_backslashed = FALSE;
888 while ((ptr[0] == '#' || was_backslashed) &&
889 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
891 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
892 was_backslashed = TRUE;
894 was_backslashed = FALSE;
895 ptr = ml_get(++curwin->w_cursor.lnum);
898 newindent = 0; /* Got to end of file */
900 newindent = get_indent();
903 if (*p == '}') /* if line starts with '}': do indent */
905 else /* can delete indent when '{' typed */
908 curwin->w_cursor = old_cursor;
912 #endif /* FEAT_SMARTINDENT */
919 * Find out if the current line starts with a comment leader.
920 * This may then be inserted in front of the new line.
922 end_comment_pending = NUL;
923 if (flags & OPENLINE_DO_COM)
924 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, TRUE);
929 char_u *lead_repl = NULL; /* replaces comment leader */
930 int lead_repl_len = 0; /* length of *lead_repl */
931 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
932 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
933 char_u *comment_end = NULL; /* where lead_end has been found */
934 int extra_space = FALSE; /* append extra space */
936 int require_blank = FALSE; /* requires blank after middle */
940 * If the comment leader has the start, middle or end flag, it may not
941 * be used or may be replaced with the middle leader.
943 for (p = lead_flags; *p && *p != ':'; ++p)
947 require_blank = TRUE;
950 if (*p == COM_START || *p == COM_MIDDLE)
956 * Doing "O" on a start of comment does not insert leader.
964 /* find start of middle part */
965 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
966 require_blank = FALSE;
970 * Isolate the strings of the middle and end leader.
972 while (*p && p[-1] != ':') /* find end of middle flags */
975 require_blank = TRUE;
978 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
980 while (*p && p[-1] != ':') /* find end of end flags */
982 /* Check whether we allow automatic ending of comments */
983 if (*p == COM_AUTO_END)
984 end_comment_pending = -1; /* means we want to set it */
987 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
989 if (end_comment_pending == -1) /* we can set it now */
990 end_comment_pending = lead_end[n - 1];
993 * If the end of the comment is in the same line, don't use
994 * the comment leader.
998 for (p = saved_line + lead_len; *p; ++p)
999 if (STRNCMP(p, lead_end, n) == 0)
1008 * Doing "o" on a start of comment inserts the middle leader.
1012 if (current_flag == COM_START)
1014 lead_repl = lead_middle;
1015 lead_repl_len = (int)STRLEN(lead_middle);
1019 * If we have hit RETURN immediately after the start
1020 * comment leader, then put a space after the middle
1021 * comment leader on the next line.
1023 if (!VIM_ISWHITE(saved_line[lead_len - 1])
1024 && ((p_extra != NULL
1025 && (int)curwin->w_cursor.col == lead_len)
1027 && saved_line[lead_len] == NUL)
1036 * Doing "o" on the end of a comment does not insert leader.
1037 * Remember where the end is, might want to use it to find the
1038 * start (for C-comments).
1042 comment_end = skipwhite(saved_line);
1048 * Doing "O" on the end of a comment inserts the middle leader.
1049 * Find the string for the middle leader, searching backwards.
1051 while (p > curbuf->b_p_com && *p != ',')
1053 for (lead_repl = p; lead_repl > curbuf->b_p_com
1054 && lead_repl[-1] != ':'; --lead_repl)
1056 lead_repl_len = (int)(p - lead_repl);
1058 /* We can probably always add an extra space when doing "O" on
1059 * the comment-end */
1062 /* Check whether we allow automatic ending of comments */
1063 for (p2 = p; *p2 && *p2 != ':'; p2++)
1065 if (*p2 == COM_AUTO_END)
1066 end_comment_pending = -1; /* means we want to set it */
1068 if (end_comment_pending == -1)
1070 /* Find last character in end-comment string */
1071 while (*p2 && *p2 != ',')
1073 end_comment_pending = p2[-1];
1077 if (*p == COM_FIRST)
1080 * Comment leader for first line only: Don't repeat leader
1081 * when using "O", blank out leader when using "o".
1083 if (dir == BACKWARD)
1087 lead_repl = (char_u *)"";
1095 /* allocate buffer (may concatenate p_extra later) */
1096 leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
1097 + (second_line_indent > 0 ? second_line_indent : 0) + 1);
1098 allocated = leader; /* remember to free it later */
1104 vim_strncpy(leader, saved_line, lead_len);
1107 * Replace leader with lead_repl, right or left adjusted
1109 if (lead_repl != NULL)
1114 for (p = lead_flags; *p != NUL && *p != ':'; )
1116 if (*p == COM_RIGHT || *p == COM_LEFT)
1118 else if (VIM_ISDIGIT(*p) || *p == '-')
1119 off = getdigits(&p);
1123 if (c == COM_RIGHT) /* right adjusted leader */
1125 /* find last non-white in the leader to line up with */
1126 for (p = leader + lead_len - 1; p > leader
1127 && VIM_ISWHITE(*p); --p)
1132 /* Compute the length of the replaced characters in
1133 * screen characters, not bytes. */
1135 int repl_size = vim_strnsize(lead_repl,
1141 while (old_size < repl_size && p > leader)
1143 MB_PTR_BACK(leader, p);
1144 old_size += ptr2cells(p);
1146 l = lead_repl_len - (int)(endp - p);
1148 mch_memmove(endp + l, endp,
1149 (size_t)((leader + lead_len) - endp));
1153 if (p < leader + lead_repl_len)
1158 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1159 if (p + lead_repl_len > leader + lead_len)
1160 p[lead_repl_len] = NUL;
1162 /* blank-out any other chars from the old leader. */
1163 while (--p >= leader)
1166 int l = mb_head_off(leader, p);
1171 if (ptr2cells(p) > 1)
1176 mch_memmove(p + 1, p + l + 1,
1177 (size_t)((leader + lead_len) - (p + l + 1)));
1183 if (!VIM_ISWHITE(*p))
1187 else /* left adjusted leader */
1189 p = skipwhite(leader);
1191 /* Compute the length of the replaced characters in
1192 * screen characters, not bytes. Move the part that is
1193 * not to be overwritten. */
1195 int repl_size = vim_strnsize(lead_repl,
1200 for (i = 0; i < lead_len && p[i] != NUL; i += l)
1202 l = (*mb_ptr2len)(p + i);
1203 if (vim_strnsize(p, i + l) > repl_size)
1206 if (i != lead_repl_len)
1208 mch_memmove(p + lead_repl_len, p + i,
1209 (size_t)(lead_len - i - (p - leader)));
1210 lead_len += lead_repl_len - i;
1214 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1216 /* Replace any remaining non-white chars in the old
1217 * leader by spaces. Keep Tabs, the indent must
1218 * remain the same. */
1219 for (p += lead_repl_len; p < leader + lead_len; ++p)
1220 if (!VIM_ISWHITE(*p))
1222 /* Don't put a space before a TAB. */
1223 if (p + 1 < leader + lead_len && p[1] == TAB)
1226 mch_memmove(p, p + 1,
1227 (leader + lead_len) - p);
1232 int l = (*mb_ptr2len)(p);
1236 if (ptr2cells(p) > 1)
1238 /* Replace a double-wide char with
1243 mch_memmove(p + 1, p + l,
1244 (leader + lead_len) - p);
1254 /* Recompute the indent, it may have changed. */
1256 #ifdef FEAT_SMARTINDENT
1260 newindent = get_indent_str(leader, (int)curbuf->b_p_ts, FALSE);
1262 /* Add the indent offset */
1263 if (newindent + off < 0)
1271 /* Correct trailing spaces for the shift, so that
1272 * alignment remains equal. */
1273 while (off > 0 && lead_len > 0
1274 && leader[lead_len - 1] == ' ')
1276 /* Don't do it when there is a tab before the space */
1277 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1283 /* If the leader ends in white space, don't add an
1285 if (lead_len > 0 && VIM_ISWHITE(leader[lead_len - 1]))
1286 extra_space = FALSE;
1287 leader[lead_len] = NUL;
1292 leader[lead_len++] = ' ';
1293 leader[lead_len] = NUL;
1299 * if a new indent will be set below, remove the indent that
1300 * is in the comment leader
1303 #ifdef FEAT_SMARTINDENT
1308 while (lead_len && VIM_ISWHITE(*leader))
1317 #ifdef FEAT_SMARTINDENT
1318 did_si = can_si = FALSE;
1321 else if (comment_end != NULL)
1324 * We have finished a comment, so we don't use the leader.
1325 * If this was a C-comment and 'ai' or 'si' is set do a normal
1326 * indent to align with the line containing the start of the
1329 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1331 #ifdef FEAT_SMARTINDENT
1336 old_cursor = curwin->w_cursor;
1337 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1338 if ((pos = findmatch(NULL, NUL)) != NULL)
1340 curwin->w_cursor.lnum = pos->lnum;
1341 newindent = get_indent();
1343 curwin->w_cursor = old_cursor;
1349 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1350 if (p_extra != NULL)
1352 *p_extra = saved_char; /* restore char that NUL replaced */
1355 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1358 * When in REPLACE mode, put the deleted blanks on the replace stack,
1359 * preceded by a NUL, so they can be put back when a BS is entered.
1361 if (REPLACE_NORMAL(State))
1362 replace_push(NUL); /* end of extra blanks */
1363 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1365 while ((*p_extra == ' ' || *p_extra == '\t')
1368 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1372 if (REPLACE_NORMAL(State))
1373 replace_push(*p_extra);
1378 if (*p_extra != NUL)
1379 did_ai = FALSE; /* append some text, don't truncate now */
1381 /* columns for marks adjusted for removed columns */
1382 less_cols = (int)(p_extra - saved_line);
1385 if (p_extra == NULL)
1386 p_extra = (char_u *)""; /* append empty line */
1388 #ifdef FEAT_COMMENTS
1389 /* concatenate leader and p_extra, if there is a leader */
1392 if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
1395 int padding = second_line_indent
1396 - (newindent + (int)STRLEN(leader));
1398 /* Here whitespace is inserted after the comment char.
1399 * Below, set_indent(newindent, SIN_INSERT) will insert the
1400 * whitespace needed before the comment char. */
1401 for (i = 0; i < padding; i++)
1403 STRCAT(leader, " ");
1408 STRCAT(leader, p_extra);
1410 did_ai = TRUE; /* So truncating blanks works with comments */
1411 less_cols -= lead_len;
1414 end_comment_pending = NUL; /* turns out there was no leader */
1417 old_cursor = curwin->w_cursor;
1418 if (dir == BACKWARD)
1419 --curwin->w_cursor.lnum;
1420 #ifdef FEAT_VREPLACE
1421 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1424 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1427 /* Postpone calling changed_lines(), because it would mess up folding
1429 * Skip mark_adjust when adding a line after the last one, there can't
1430 * be marks there. But still needed in diff mode. */
1431 if (curwin->w_cursor.lnum + 1 < curbuf->b_ml.ml_line_count
1436 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1439 #ifdef FEAT_VREPLACE
1443 * In VREPLACE mode we are starting to replace the next line.
1445 curwin->w_cursor.lnum++;
1446 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1448 /* In case we NL to a new line, BS to the previous one, and NL
1449 * again, we don't want to save the new line for undo twice.
1451 (void)u_save_cursor(); /* errors are ignored! */
1454 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1455 changed_bytes(curwin->w_cursor.lnum, 0);
1456 curwin->w_cursor.lnum--;
1462 #ifdef FEAT_SMARTINDENT
1467 ++curwin->w_cursor.lnum;
1468 #ifdef FEAT_SMARTINDENT
1471 int sw = (int)get_sw_value(curbuf);
1474 newindent -= newindent % sw;
1478 /* Copy the indent */
1481 (void)copy_indent(newindent, saved_line);
1484 * Set the 'preserveindent' option so that any further screwing
1485 * with the line doesn't entirely destroy our efforts to preserve
1486 * it. It gets restored at the function end.
1488 curbuf->b_p_pi = TRUE;
1491 (void)set_indent(newindent, SIN_INSERT);
1492 less_cols -= curwin->w_cursor.col;
1494 ai_col = curwin->w_cursor.col;
1497 * In REPLACE mode, for each character in the new indent, there must
1498 * be a NUL on the replace stack, for when it is deleted with BS
1500 if (REPLACE_NORMAL(State))
1501 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1503 newcol += curwin->w_cursor.col;
1504 #ifdef FEAT_SMARTINDENT
1510 #ifdef FEAT_COMMENTS
1512 * In REPLACE mode, for each character in the extra leader, there must be
1513 * a NUL on the replace stack, for when it is deleted with BS.
1515 if (REPLACE_NORMAL(State))
1516 while (lead_len-- > 0)
1520 curwin->w_cursor = old_cursor;
1524 if (trunc_line || (State & INSERT))
1526 /* truncate current line at cursor */
1527 saved_line[curwin->w_cursor.col] = NUL;
1528 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1529 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1530 truncate_spaces(saved_line);
1531 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1535 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1536 curwin->w_cursor.lnum + 1, 1L);
1539 /* Move marks after the line break to the new line. */
1540 if (flags & OPENLINE_MARKFIX)
1541 mark_col_adjust(curwin->w_cursor.lnum,
1542 curwin->w_cursor.col + less_cols_off,
1543 1L, (long)-less_cols);
1546 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1550 * Put the cursor on the new line. Careful: the scrollup() above may
1551 * have moved w_cursor, we must use old_cursor.
1553 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1556 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1558 curwin->w_cursor.col = newcol;
1559 #ifdef FEAT_VIRTUALEDIT
1560 curwin->w_cursor.coladd = 0;
1563 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1565 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1566 * fixthisline() from doing it (via change_indent()) by telling it we're in
1567 * normal INSERT mode.
1569 if (State & VREPLACE_FLAG)
1571 vreplace_mode = State; /* So we know to put things right later */
1579 * May do lisp indenting.
1582 # ifdef FEAT_COMMENTS
1588 fixthisline(get_lisp_indent);
1589 p = ml_get_curline();
1590 ai_col = (colnr_T)(skipwhite(p) - p);
1595 * May do indenting after opening a new line.
1600 || *curbuf->b_p_inde != NUL
1603 && in_cinkeys(dir == FORWARD
1605 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1608 p = ml_get_curline();
1609 ai_col = (colnr_T)(skipwhite(p) - p);
1612 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1613 if (vreplace_mode != 0)
1614 State = vreplace_mode;
1617 #ifdef FEAT_VREPLACE
1619 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1620 * original line, and inserts the new stuff char by char, pushing old stuff
1621 * onto the replace stack (via ins_char()).
1623 if (State & VREPLACE_FLAG)
1625 /* Put new line in p_extra */
1626 p_extra = vim_strsave(ml_get_curline());
1627 if (p_extra == NULL)
1630 /* Put back original line */
1631 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1633 /* Insert new stuff into line again */
1634 curwin->w_cursor.col = 0;
1635 #ifdef FEAT_VIRTUALEDIT
1636 curwin->w_cursor.coladd = 0;
1638 ins_bytes(p_extra); /* will call changed_bytes() */
1644 retval = TRUE; /* success! */
1646 curbuf->b_p_pi = saved_pi;
1647 vim_free(saved_line);
1648 vim_free(next_line);
1649 vim_free(allocated);
1653 #if defined(FEAT_COMMENTS) || defined(PROTO)
1655 * get_leader_len() returns the length in bytes of the prefix of the given
1656 * string which introduces a comment. If this string is not a comment then
1658 * When "flags" is not NULL, it is set to point to the flags of the recognized
1660 * "backward" must be true for the "O" command.
1661 * If "include_space" is set, include trailing whitespace while calculating the
1673 int got_com = FALSE;
1675 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1676 char_u *string; /* pointer to comment string */
1678 int middle_match_len = 0;
1680 char_u *saved_flags = NULL;
1683 while (VIM_ISWHITE(line[i])) /* leading white space is ignored */
1687 * Repeat to match several nested comment strings.
1689 while (line[i] != NUL)
1692 * scan through the 'comments' option for a match
1695 for (list = curbuf->b_p_com; *list; )
1697 /* Get one option part into part_buf[]. Advance "list" to next
1698 * one. Put "string" at start of string. */
1699 if (!got_com && flags != NULL)
1700 *flags = list; /* remember where flags started */
1702 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1703 string = vim_strchr(part_buf, ':');
1704 if (string == NULL) /* missing ':', ignore this part */
1706 *string++ = NUL; /* isolate flags from string */
1708 /* If we found a middle match previously, use that match when this
1709 * is not a middle or end. */
1710 if (middle_match_len != 0
1711 && vim_strchr(part_buf, COM_MIDDLE) == NULL
1712 && vim_strchr(part_buf, COM_END) == NULL)
1715 /* When we already found a nested comment, only accept further
1716 * nested comments. */
1717 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1720 /* When 'O' flag present and using "O" command skip this one. */
1721 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1724 /* Line contents and string must match.
1725 * When string starts with white space, must have some white space
1726 * (but the amount does not need to match, there might be a mix of
1727 * TABs and spaces). */
1728 if (VIM_ISWHITE(string[0]))
1730 if (i == 0 || !VIM_ISWHITE(line[i - 1]))
1731 continue; /* missing white space */
1732 while (VIM_ISWHITE(string[0]))
1735 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1737 if (string[j] != NUL)
1738 continue; /* string doesn't match */
1740 /* When 'b' flag used, there must be white space or an
1741 * end-of-line after the string in the line. */
1742 if (vim_strchr(part_buf, COM_BLANK) != NULL
1743 && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
1746 /* We have found a match, stop searching unless this is a middle
1747 * comment. The middle comment can be a substring of the end
1748 * comment in which case it's better to return the length of the
1749 * end comment and its flags. Thus we keep searching with middle
1750 * and end matches and use an end match if it matches better. */
1751 if (vim_strchr(part_buf, COM_MIDDLE) != NULL)
1753 if (middle_match_len == 0)
1755 middle_match_len = j;
1756 saved_flags = prev_list;
1760 if (middle_match_len != 0 && j > middle_match_len)
1761 /* Use this match instead of the middle match, since it's a
1762 * longer thus better match. */
1763 middle_match_len = 0;
1765 if (middle_match_len == 0)
1771 if (middle_match_len != 0)
1773 /* Use the previously found middle match after failing to find a
1774 * match with an end. */
1775 if (!got_com && flags != NULL)
1776 *flags = saved_flags;
1777 i += middle_match_len;
1781 /* No match found, stop scanning. */
1787 /* Include any trailing white space. */
1788 while (VIM_ISWHITE(line[i]))
1794 /* If this comment doesn't nest, stop here. */
1796 if (vim_strchr(part_buf, COM_NEST) == NULL)
1803 * Return the offset at which the last comment in line starts. If there is no
1804 * comment in the whole line, -1 is returned.
1806 * When "flags" is not null, it is set to point to the flags describing the
1807 * recognized comment leader.
1810 get_last_leader_offset(char_u *line, char_u **flags)
1814 int lower_check_bound = 0;
1820 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1823 * Repeat to match several nested comment strings.
1825 i = (int)STRLEN(line);
1826 while (--i >= lower_check_bound)
1829 * scan through the 'comments' option for a match
1832 for (list = curbuf->b_p_com; *list; )
1834 char_u *flags_save = list;
1837 * Get one option part into part_buf[]. Advance list to next one.
1838 * put string at start of string.
1840 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1841 string = vim_strchr(part_buf, ':');
1842 if (string == NULL) /* If everything is fine, this cannot actually
1847 *string++ = NUL; /* Isolate flags from string. */
1848 com_leader = string;
1851 * Line contents and string must match.
1852 * When string starts with white space, must have some white space
1853 * (but the amount does not need to match, there might be a mix of
1856 if (VIM_ISWHITE(string[0]))
1858 if (i == 0 || !VIM_ISWHITE(line[i - 1]))
1860 while (VIM_ISWHITE(string[0]))
1863 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1865 if (string[j] != NUL)
1869 * When 'b' flag used, there must be white space or an
1870 * end-of-line after the string in the line.
1872 if (vim_strchr(part_buf, COM_BLANK) != NULL
1873 && !VIM_ISWHITE(line[i + j]) && line[i + j] != NUL)
1879 * We have found a match, stop searching.
1884 *flags = flags_save;
1885 com_flags = flags_save;
1892 char_u part_buf2[COM_MAX_LEN]; /* buffer for one option part */
1893 int len1, len2, off;
1897 * If this comment nests, continue searching.
1899 if (vim_strchr(part_buf, COM_NEST) != NULL)
1902 lower_check_bound = i;
1904 /* Let's verify whether the comment leader found is a substring
1905 * of other comment leaders. If it is, let's adjust the
1906 * lower_check_bound so that we make sure that we have determined
1907 * the comment leader correctly.
1910 while (VIM_ISWHITE(*com_leader))
1912 len1 = (int)STRLEN(com_leader);
1914 for (list = curbuf->b_p_com; *list; )
1916 char_u *flags_save = list;
1918 (void)copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
1919 if (flags_save == com_flags)
1921 string = vim_strchr(part_buf2, ':');
1923 while (VIM_ISWHITE(*string))
1925 len2 = (int)STRLEN(string);
1929 /* Now we have to verify whether string ends with a substring
1930 * beginning the com_leader. */
1931 for (off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;)
1934 if (!STRNCMP(string + off, com_leader, len2 - off))
1936 if (i - off < lower_check_bound)
1937 lower_check_bound = i - off;
1948 * Return the number of window lines occupied by buffer line "lnum".
1951 plines(linenr_T lnum)
1953 return plines_win(curwin, lnum, TRUE);
1960 int winheight) /* when TRUE limit to window height */
1962 #if defined(FEAT_DIFF) || defined(PROTO)
1963 /* Check for filler lines above this buffer line. When folded the result
1964 * is one line anyway. */
1965 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1969 plines_nofill(linenr_T lnum)
1971 return plines_win_nofill(curwin, lnum, TRUE);
1978 int winheight) /* when TRUE limit to window height */
1987 if (wp->w_width == 0)
1992 /* A folded lines is handled just like an empty line. */
1993 /* NOTE: Caller must handle lines that are MAYBE folded. */
1994 if (lineFolded(wp, lnum) == TRUE)
1998 lines = plines_win_nofold(wp, lnum);
1999 if (winheight > 0 && lines > wp->w_height)
2000 return (int)wp->w_height;
2005 * Return number of window lines physical line "lnum" will occupy in window
2006 * "wp". Does not care about folding, 'wrap' or 'diff'.
2009 plines_win_nofold(win_T *wp, linenr_T lnum)
2015 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2016 if (*s == NUL) /* empty line */
2018 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
2021 * If list mode is on, then the '$' at the end of the line may take up one
2024 if (wp->w_p_list && lcs_eol != NUL)
2028 * Add column offset for 'number', 'relativenumber' and 'foldcolumn'.
2030 width = W_WIDTH(wp) - win_col_off(wp);
2036 width += win_col_off2(wp);
2037 return (col + (width - 1)) / width + 1;
2041 * Like plines_win(), but only reports the number of physical screen lines
2042 * used from the start of the line to the given column number.
2045 plines_win_col(win_T *wp, linenr_T lnum, long column)
2054 /* Check for filler lines above this buffer line. When folded the result
2055 * is one line anyway. */
2056 lines = diff_check_fill(wp, lnum);
2063 if (wp->w_width == 0)
2067 line = s = ml_get_buf(wp->w_buffer, lnum, FALSE);
2070 while (*s != NUL && --column >= 0)
2072 col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL);
2077 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
2078 * INSERT mode, then col must be adjusted so that it represents the last
2079 * screen position of the TAB. This only fixes an error when the TAB wraps
2080 * from one screen line to the next (when 'columns' is not a multiple of
2083 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
2084 col += win_lbr_chartabsize(wp, line, s, (colnr_T)col, NULL) - 1;
2087 * Add column offset for 'number', 'relativenumber', 'foldcolumn', etc.
2089 width = W_WIDTH(wp) - win_col_off(wp);
2095 lines += (col - width) / (width + win_col_off2(wp)) + 1;
2100 plines_m_win(win_T *wp, linenr_T first, linenr_T last)
2104 while (first <= last)
2109 /* Check if there are any really folded lines, but also included lines
2110 * that are maybe folded. */
2111 x = foldedCount(wp, first, NULL);
2114 ++count; /* count 1 for "+-- folded" line */
2121 if (first == wp->w_topline)
2122 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
2125 count += plines_win(wp, first, TRUE);
2132 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2134 * Insert string "p" at the cursor position. Stops at a NUL byte.
2135 * Handles Replace mode and multi-byte characters.
2138 ins_bytes(char_u *p)
2140 ins_bytes_len(p, (int)STRLEN(p));
2144 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2145 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2147 * Insert string "p" with length "len" at the cursor position.
2148 * Handles Replace mode and multi-byte characters.
2151 ins_bytes_len(char_u *p, int len)
2158 for (i = 0; i < len; i += n)
2161 /* avoid reading past p[len] */
2162 n = utfc_ptr2len_len(p + i, len - i);
2164 n = (*mb_ptr2len)(p + i);
2165 ins_char_bytes(p + i, n);
2169 for (i = 0; i < len; ++i)
2175 * Insert or replace a single character at the cursor position.
2176 * When in REPLACE or VREPLACE mode, replace any existing character.
2177 * Caller must have prepared for undo.
2178 * For multi-byte characters we get the whole character, the caller must
2179 * convert bytes to a character.
2184 char_u buf[MB_MAXBYTES + 1];
2188 n = (*mb_char2bytes)(c, buf);
2190 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2191 * Happens for CTRL-Vu9900. */
2198 ins_char_bytes(buf, n);
2202 ins_char_bytes(char_u *buf, int charlen)
2205 int newlen; /* nr of bytes inserted */
2206 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2210 int linelen; /* length of old line including NUL */
2212 linenr_T lnum = curwin->w_cursor.lnum;
2215 #ifdef FEAT_VIRTUALEDIT
2216 /* Break tabs if needed. */
2217 if (virtual_active() && curwin->w_cursor.coladd > 0)
2218 coladvance_force(getviscol());
2221 col = curwin->w_cursor.col;
2222 oldp = ml_get(lnum);
2223 linelen = (int)STRLEN(oldp) + 1;
2225 /* The lengths default to the values for when not replacing. */
2229 if (State & REPLACE_FLAG)
2231 #ifdef FEAT_VREPLACE
2232 if (State & VREPLACE_FLAG)
2234 colnr_T new_vcol = 0; /* init for GCC */
2242 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2243 * Returns the old value of list, so when finished,
2244 * curwin->w_p_list should be set back to this.
2246 old_list = curwin->w_p_list;
2247 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2248 curwin->w_p_list = FALSE;
2251 * In virtual replace mode each character may replace one or more
2252 * characters (zero if it's a TAB). Count the number of bytes to
2253 * be deleted to make room for the new character, counting screen
2254 * cells. May result in adding spaces to fill a gap.
2256 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2261 new_vcol = vcol + chartabsize(buf, vcol);
2262 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2264 vcol += chartabsize(oldp + col + oldlen, vcol);
2265 /* Don't need to remove a TAB that takes us to the right
2267 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2270 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
2274 /* Deleted a bit too much, insert spaces. */
2275 if (vcol > new_vcol)
2276 newlen += vcol - new_vcol;
2278 curwin->w_p_list = old_list;
2282 if (oldp[col] != NUL)
2284 /* normal replace */
2286 oldlen = (*mb_ptr2len)(oldp + col);
2293 /* Push the replaced bytes onto the replace stack, so that they can be
2294 * put back when BS is used. The bytes of a multi-byte character are
2295 * done the other way around, so that the first byte is popped off
2296 * first (it tells the byte length of the character). */
2298 for (i = 0; i < oldlen; ++i)
2302 i += replace_push_mb(oldp + col + i) - 1;
2305 replace_push(oldp[col + i]);
2309 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2313 /* Copy bytes before the cursor. */
2315 mch_memmove(newp, oldp, (size_t)col);
2317 /* Copy bytes after the changed character(s). */
2319 mch_memmove(p + newlen, oldp + col + oldlen,
2320 (size_t)(linelen - col - oldlen));
2322 /* Insert or overwrite the new character. */
2324 mch_memmove(p, buf, charlen);
2331 /* Fill with spaces when necessary. */
2335 /* Replace the line in the buffer. */
2336 ml_replace(lnum, newp, FALSE);
2338 /* mark the buffer as changed and prepare for displaying */
2339 changed_bytes(lnum, col);
2342 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2343 * show the match for right parens and braces.
2345 if (p_sm && (State & INSERT)
2347 #ifdef FEAT_INS_EXPAND
2348 && !ins_compl_active()
2354 showmatch(mb_ptr2char(buf));
2360 #ifdef FEAT_RIGHTLEFT
2361 if (!p_ri || (State & REPLACE_FLAG))
2364 /* Normal insert: move cursor right */
2366 curwin->w_cursor.col += charlen;
2368 ++curwin->w_cursor.col;
2372 * TODO: should try to update w_row here, to avoid recomputing it later.
2377 * Insert a string at the cursor position.
2378 * Note: Does NOT handle Replace mode.
2379 * Caller must have prepared for undo.
2384 char_u *oldp, *newp;
2385 int newlen = (int)STRLEN(s);
2388 linenr_T lnum = curwin->w_cursor.lnum;
2390 #ifdef FEAT_VIRTUALEDIT
2391 if (virtual_active() && curwin->w_cursor.coladd > 0)
2392 coladvance_force(getviscol());
2395 col = curwin->w_cursor.col;
2396 oldp = ml_get(lnum);
2397 oldlen = (int)STRLEN(oldp);
2399 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2403 mch_memmove(newp, oldp, (size_t)col);
2404 mch_memmove(newp + col, s, (size_t)newlen);
2405 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2406 ml_replace(lnum, newp, FALSE);
2407 changed_bytes(lnum, col);
2408 curwin->w_cursor.col += newlen;
2412 * Delete one character under the cursor.
2413 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2414 * Caller must have prepared for undo.
2416 * return FAIL for failure, OK otherwise
2419 del_char(int fixpos)
2424 /* Make sure the cursor is at the start of a character. */
2426 if (*ml_get_cursor() == NUL)
2428 return del_chars(1L, fixpos);
2431 return del_bytes(1L, fixpos, TRUE);
2434 #if defined(FEAT_MBYTE) || defined(PROTO)
2436 * Like del_bytes(), but delete characters instead of bytes.
2439 del_chars(long count, int fixpos)
2446 p = ml_get_cursor();
2447 for (i = 0; i < count && *p != NUL; ++i)
2449 l = (*mb_ptr2len)(p);
2453 return del_bytes(bytes, fixpos, TRUE);
2458 * Delete "count" bytes under the cursor.
2459 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2460 * Caller must have prepared for undo.
2462 * return FAIL for failure, OK otherwise
2468 int use_delcombine UNUSED) /* 'delcombine' option applies */
2470 char_u *oldp, *newp;
2472 linenr_T lnum = curwin->w_cursor.lnum;
2473 colnr_T col = curwin->w_cursor.col;
2476 int fixpos = fixpos_arg;
2478 oldp = ml_get(lnum);
2479 oldlen = (int)STRLEN(oldp);
2482 * Can't do anything when the cursor is on the NUL after the line.
2488 /* If 'delcombine' is set and deleting (less than) one character, only
2489 * delete the last combining character. */
2490 if (p_deco && use_delcombine && enc_utf8
2491 && utfc_ptr2len(oldp + col) >= count)
2496 (void)utfc_ptr2char(oldp + col, cc);
2499 /* Find the last composing char, there can be several. */
2504 count = utf_ptr2len(oldp + n);
2506 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2513 * When count is too big, reduce it.
2515 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2519 * If we just took off the last character of a non-blank line, and
2520 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2521 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2523 if (col > 0 && fixpos && restart_edit == 0
2524 #ifdef FEAT_VIRTUALEDIT
2525 && (ve_flags & VE_ONEMORE) == 0
2529 --curwin->w_cursor.col;
2530 #ifdef FEAT_VIRTUALEDIT
2531 curwin->w_cursor.coladd = 0;
2535 curwin->w_cursor.col -=
2536 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2539 count = oldlen - col;
2544 * If the old line has been allocated the deletion can be done in the
2545 * existing line. Otherwise a new line has to be allocated
2546 * Can't do this when using Netbeans, because we would need to invoke
2547 * netbeans_removed(), which deallocates the line. Let ml_replace() take
2548 * care of notifying Netbeans.
2550 #ifdef FEAT_NETBEANS_INTG
2551 if (netbeans_active())
2552 was_alloced = FALSE;
2555 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
2557 newp = oldp; /* use same allocated memory */
2559 { /* need to allocate a new line */
2560 newp = alloc((unsigned)(oldlen + 1 - count));
2563 mch_memmove(newp, oldp, (size_t)col);
2565 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2567 ml_replace(lnum, newp, FALSE);
2569 /* mark the buffer as changed and prepare for displaying */
2570 changed_bytes(lnum, curwin->w_cursor.col);
2576 * Delete from cursor to end of line.
2577 * Caller must have prepared for undo.
2579 * return FAIL for failure, OK otherwise
2583 int fixpos) /* if TRUE fix the cursor position when done */
2586 linenr_T lnum = curwin->w_cursor.lnum;
2587 colnr_T col = curwin->w_cursor.col;
2590 newp = vim_strsave((char_u *)"");
2592 newp = vim_strnsave(ml_get(lnum), col);
2597 ml_replace(lnum, newp, FALSE);
2599 /* mark the buffer as changed and prepare for displaying */
2600 changed_bytes(lnum, curwin->w_cursor.col);
2603 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2605 if (fixpos && curwin->w_cursor.col > 0)
2606 --curwin->w_cursor.col;
2612 * Delete "nlines" lines at the cursor.
2613 * Saves the lines for undo first if "undo" is TRUE.
2617 long nlines, /* number of lines to delete */
2618 int undo) /* if TRUE, prepare for undo */
2621 linenr_T first = curwin->w_cursor.lnum;
2626 /* save the deleted lines for undo */
2627 if (undo && u_savedel(first, nlines) == FAIL)
2630 for (n = 0; n < nlines; )
2632 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2635 ml_delete(first, TRUE);
2638 /* If we delete the last line in the file, stop */
2639 if (first > curbuf->b_ml.ml_line_count)
2643 /* Correct the cursor position before calling deleted_lines_mark(), it may
2644 * trigger a callback to display the cursor. */
2645 curwin->w_cursor.col = 0;
2646 check_cursor_lnum();
2648 /* adjust marks, mark the buffer as changed and prepare for displaying */
2649 deleted_lines_mark(first, n);
2653 gchar_pos(pos_T *pos)
2655 char_u *ptr = ml_get_pos(pos);
2659 return (*mb_ptr2char)(ptr);
2669 return (*mb_ptr2char)(ml_get_cursor());
2671 return (int)*ml_get_cursor();
2675 * Write a character at the current cursor position.
2676 * It is directly written into the block.
2681 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2682 + curwin->w_cursor.col) = c;
2686 * When extra == 0: Return TRUE if the cursor is before or on the first
2687 * non-blank in the line.
2688 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2697 for (col = 0, ptr = ml_get_curline(); VIM_ISWHITE(*ptr); ++col)
2699 if (col >= curwin->w_cursor.col + extra)
2706 * Skip to next part of an option argument: Skip space and comma.
2709 skip_to_option_part(char_u *p)
2719 * Call this function when something in the current buffer is changed.
2721 * Most often called through changed_bytes() and changed_lines(), which also
2722 * mark the area of the display to be redrawn.
2724 * Careful: may trigger autocommands that reload the buffer.
2729 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2730 /* The text of the preediting area is inserted, but this doesn't
2731 * mean a change of the buffer yet. That is delayed until the
2732 * text is committed. (this means preedit becomes empty) */
2733 if (im_is_preediting() && !xim_changed_while_preediting)
2735 xim_changed_while_preediting = FALSE;
2738 if (!curbuf->b_changed)
2740 int save_msg_scroll = msg_scroll;
2742 /* Give a warning about changing a read-only file. This may also
2743 * check-out the file, thus change "curbuf"! */
2746 /* Create a swap file if that is wanted.
2747 * Don't do this for "nofile" and "nowrite" buffer types. */
2748 if (curbuf->b_may_swap
2749 #ifdef FEAT_QUICKFIX
2750 && !bt_dontwrite(curbuf)
2754 int save_need_wait_return = need_wait_return;
2756 need_wait_return = FALSE;
2757 ml_open_file(curbuf);
2759 /* The ml_open_file() can cause an ATTENTION message.
2760 * Wait two seconds, to make sure the user reads this unexpected
2761 * message. Since we could be anywhere, call wait_return() now,
2762 * and don't let the emsg() set msg_scroll. */
2763 if (need_wait_return && emsg_silent == 0)
2766 ui_delay(2000L, TRUE);
2768 msg_scroll = save_msg_scroll;
2771 need_wait_return = save_need_wait_return;
2775 ++CHANGEDTICK(curbuf);
2779 * Internal part of changed(), no user interaction.
2784 curbuf->b_changed = TRUE;
2785 ml_setflags(curbuf);
2787 check_status(curbuf);
2788 redraw_tabline = TRUE;
2791 need_maketitle = TRUE; /* set window title later */
2795 static void changedOneline(buf_T *buf, linenr_T lnum);
2796 static void changed_lines_buf(buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra);
2797 static void changed_common(linenr_T lnum, colnr_T col, linenr_T lnume, long xtra);
2800 * Changed bytes within a single line for the current buffer.
2801 * - marks the windows on this buffer to be redisplayed
2802 * - marks the buffer changed by calling changed()
2803 * - invalidates cached values
2804 * Careful: may trigger autocommands that reload the buffer.
2807 changed_bytes(linenr_T lnum, colnr_T col)
2809 changedOneline(curbuf, lnum);
2810 changed_common(lnum, col, lnum + 1, 0L);
2813 /* Diff highlighting in other diff windows may need to be updated too. */
2814 if (curwin->w_p_diff)
2820 if (wp->w_p_diff && wp != curwin)
2822 redraw_win_later(wp, VALID);
2823 wlnum = diff_lnum_win(lnum, wp);
2825 changedOneline(wp->w_buffer, wlnum);
2832 changedOneline(buf_T *buf, linenr_T lnum)
2836 /* find the maximum area that must be redisplayed */
2837 if (lnum < buf->b_mod_top)
2838 buf->b_mod_top = lnum;
2839 else if (lnum >= buf->b_mod_bot)
2840 buf->b_mod_bot = lnum + 1;
2844 /* set the area that must be redisplayed to one line */
2845 buf->b_mod_set = TRUE;
2846 buf->b_mod_top = lnum;
2847 buf->b_mod_bot = lnum + 1;
2848 buf->b_mod_xlines = 0;
2853 * Appended "count" lines below line "lnum" in the current buffer.
2854 * Must be called AFTER the change and after mark_adjust().
2855 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2858 appended_lines(linenr_T lnum, long count)
2860 changed_lines(lnum + 1, 0, lnum + 1, count);
2864 * Like appended_lines(), but adjust marks first.
2867 appended_lines_mark(linenr_T lnum, long count)
2869 /* Skip mark_adjust when adding a line after the last one, there can't
2870 * be marks there. But it's still needed in diff mode. */
2871 if (lnum + count < curbuf->b_ml.ml_line_count
2876 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2877 changed_lines(lnum + 1, 0, lnum + 1, count);
2881 * Deleted "count" lines at line "lnum" in the current buffer.
2882 * Must be called AFTER the change and after mark_adjust().
2883 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2886 deleted_lines(linenr_T lnum, long count)
2888 changed_lines(lnum, 0, lnum + count, -count);
2892 * Like deleted_lines(), but adjust marks first.
2893 * Make sure the cursor is on a valid line before calling, a GUI callback may
2894 * be triggered to display the cursor.
2897 deleted_lines_mark(linenr_T lnum, long count)
2899 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2900 changed_lines(lnum, 0, lnum + count, -count);
2904 * Changed lines for the current buffer.
2905 * Must be called AFTER the change and after mark_adjust().
2906 * - mark the buffer changed by calling changed()
2907 * - mark the windows on this buffer to be redisplayed
2908 * - invalidate cached values
2909 * "lnum" is the first line that needs displaying, "lnume" the first line
2910 * below the changed lines (BEFORE the change).
2911 * When only inserting lines, "lnum" and "lnume" are equal.
2912 * Takes care of calling changed() and updating b_mod_*.
2913 * Careful: may trigger autocommands that reload the buffer.
2917 linenr_T lnum, /* first line with change */
2918 colnr_T col, /* column in first line with change */
2919 linenr_T lnume, /* line below last changed line */
2920 long xtra) /* number of extra lines (negative when deleting) */
2922 changed_lines_buf(curbuf, lnum, lnume, xtra);
2925 if (xtra == 0 && curwin->w_p_diff)
2927 /* When the number of lines doesn't change then mark_adjust() isn't
2928 * called and other diff buffers still need to be marked for
2934 if (wp->w_p_diff && wp != curwin)
2936 redraw_win_later(wp, VALID);
2937 wlnum = diff_lnum_win(lnum, wp);
2939 changed_lines_buf(wp->w_buffer, wlnum,
2940 lnume - lnum + wlnum, 0L);
2945 changed_common(lnum, col, lnume, xtra);
2951 linenr_T lnum, /* first line with change */
2952 linenr_T lnume, /* line below last changed line */
2953 long xtra) /* number of extra lines (negative when deleting) */
2957 /* find the maximum area that must be redisplayed */
2958 if (lnum < buf->b_mod_top)
2959 buf->b_mod_top = lnum;
2960 if (lnum < buf->b_mod_bot)
2962 /* adjust old bot position for xtra lines */
2963 buf->b_mod_bot += xtra;
2964 if (buf->b_mod_bot < lnum)
2965 buf->b_mod_bot = lnum;
2967 if (lnume + xtra > buf->b_mod_bot)
2968 buf->b_mod_bot = lnume + xtra;
2969 buf->b_mod_xlines += xtra;
2973 /* set the area that must be redisplayed */
2974 buf->b_mod_set = TRUE;
2975 buf->b_mod_top = lnum;
2976 buf->b_mod_bot = lnume + xtra;
2977 buf->b_mod_xlines = xtra;
2982 * Common code for when a change is was made.
2983 * See changed_lines() for the arguments.
2984 * Careful: may trigger autocommands that reload the buffer.
2998 #ifdef FEAT_JUMPLIST
3004 /* mark the buffer as modified */
3007 /* set the '. mark */
3008 if (!cmdmod.keepjumps)
3010 curbuf->b_last_change.lnum = lnum;
3011 curbuf->b_last_change.col = col;
3013 #ifdef FEAT_JUMPLIST
3014 /* Create a new entry if a new undo-able change was started or we
3015 * don't have an entry yet. */
3016 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
3018 if (curbuf->b_changelistlen == 0)
3022 /* Don't create a new entry when the line number is the same
3023 * as the last one and the column is not too far away. Avoids
3024 * creating many entries for typing "xxxxx". */
3025 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
3026 if (p->lnum != lnum)
3030 cols = comp_textwidth(FALSE);
3033 add = (p->col + cols < col || col + cols < p->col);
3038 /* This is the first of a new sequence of undo-able changes
3039 * and it's at some distance of the last change. Use a new
3040 * position in the changelist. */
3041 curbuf->b_new_change = FALSE;
3043 if (curbuf->b_changelistlen == JUMPLISTSIZE)
3045 /* changelist is full: remove oldest entry */
3046 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
3047 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
3048 sizeof(pos_T) * (JUMPLISTSIZE - 1));
3049 FOR_ALL_TAB_WINDOWS(tp, wp)
3051 /* Correct position in changelist for other windows on
3053 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
3054 --wp->w_changelistidx;
3057 FOR_ALL_TAB_WINDOWS(tp, wp)
3059 /* For other windows, if the position in the changelist is
3060 * at the end it stays at the end. */
3061 if (wp->w_buffer == curbuf
3062 && wp->w_changelistidx == curbuf->b_changelistlen)
3063 ++wp->w_changelistidx;
3065 ++curbuf->b_changelistlen;
3068 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
3069 curbuf->b_last_change;
3070 /* The current window is always after the last change, so that "g,"
3071 * takes you back to it. */
3072 curwin->w_changelistidx = curbuf->b_changelistlen;
3076 FOR_ALL_TAB_WINDOWS(tp, wp)
3078 if (wp->w_buffer == curbuf)
3080 /* Mark this window to be redrawn later. */
3081 if (wp->w_redr_type < VALID)
3082 wp->w_redr_type = VALID;
3084 /* Check if a change in the buffer has invalidated the cached
3085 * values for the cursor. */
3088 * Update the folds for this window. Can't postpone this, because
3089 * a following operator might work on the whole fold: ">>dd".
3091 foldUpdate(wp, lnum, lnume + xtra - 1);
3093 /* The change may cause lines above or below the change to become
3094 * included in a fold. Set lnum/lnume to the first/last line that
3095 * might be displayed differently.
3096 * Set w_cline_folded here as an efficient way to update it when
3097 * inserting lines just above a closed fold. */
3098 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
3099 if (wp->w_cursor.lnum == lnum)
3100 wp->w_cline_folded = i;
3101 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
3102 if (wp->w_cursor.lnum == lnume)
3103 wp->w_cline_folded = i;
3105 /* If the changed line is in a range of previously folded lines,
3106 * compare with the first line in that range. */
3107 if (wp->w_cursor.lnum <= lnum)
3109 i = find_wl_entry(wp, lnum);
3110 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
3111 changed_line_abv_curs_win(wp);
3115 if (wp->w_cursor.lnum > lnum)
3116 changed_line_abv_curs_win(wp);
3117 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
3118 changed_cline_bef_curs_win(wp);
3119 if (wp->w_botline >= lnum)
3121 /* Assume that botline doesn't change (inserted lines make
3122 * other lines scroll down below botline). */
3123 approximate_botline_win(wp);
3126 /* Check if any w_lines[] entries have become invalid.
3127 * For entries below the change: Correct the lnums for
3128 * inserted/deleted lines. Makes it possible to stop displaying
3129 * after the change. */
3130 for (i = 0; i < wp->w_lines_valid; ++i)
3131 if (wp->w_lines[i].wl_valid)
3133 if (wp->w_lines[i].wl_lnum >= lnum)
3135 if (wp->w_lines[i].wl_lnum < lnume)
3137 /* line included in change */
3138 wp->w_lines[i].wl_valid = FALSE;
3142 /* line below change */
3143 wp->w_lines[i].wl_lnum += xtra;
3145 wp->w_lines[i].wl_lastlnum += xtra;
3150 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3152 /* change somewhere inside this range of folded lines,
3153 * may need to be redrawn */
3154 wp->w_lines[i].wl_valid = FALSE;
3160 /* Take care of side effects for setting w_topline when folds have
3161 * changed. Esp. when the buffer was changed in another window. */
3162 if (hasAnyFolding(wp))
3163 set_topline(wp, wp->w_topline);
3165 /* relative numbering may require updating more */
3167 redraw_win_later(wp, SOME_VALID);
3171 /* Call update_screen() later, which checks out what needs to be redrawn,
3172 * since it notices b_mod_set and then uses b_mod_*. */
3173 if (must_redraw < VALID)
3174 must_redraw = VALID;
3177 /* when the cursor line is changed always trigger CursorMoved */
3178 if (lnum <= curwin->w_cursor.lnum
3179 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
3180 last_cursormoved.lnum = 0;
3185 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3190 int ff) /* also reset 'fileformat' */
3192 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
3200 redraw_tabline = TRUE;
3203 need_maketitle = TRUE; /* set window title later */
3207 #ifdef FEAT_NETBEANS_INTG
3208 netbeans_unmodified(buf);
3212 #if defined(FEAT_WINDOWS) || defined(PROTO)
3214 * check_status: called when the status bars for the buffer 'buf'
3215 * need to be updated
3218 check_status(buf_T *buf)
3223 if (wp->w_buffer == buf && wp->w_status_height)
3225 wp->w_redr_status = TRUE;
3226 if (must_redraw < VALID)
3227 must_redraw = VALID;
3233 * If the file is readonly, give a warning message with the first change.
3234 * Don't do this for autocommands.
3235 * Don't use emsg(), because it flushes the macro buffer.
3236 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
3238 * Careful: may trigger autocommands that reload the buffer.
3242 int col) /* column for message; non-zero when in insert
3243 mode and 'showmode' is on */
3245 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3247 if (curbuf->b_did_warn == FALSE
3248 && curbufIsChanged() == 0
3256 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
3258 if (!curbuf->b_p_ro)
3262 * Do what msg() does, but with a column offset if the warning should
3263 * be after the mode message.
3266 if (msg_row == Rows - 1)
3268 msg_source(HL_ATTR(HLF_W));
3269 MSG_PUTS_ATTR(_(w_readonly), HL_ATTR(HLF_W) | MSG_HIST);
3271 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3275 if (msg_silent == 0 && !silent_mode
3277 && time_for_testing != 1
3282 ui_delay(1000L, TRUE); /* give the user time to think about it */
3284 curbuf->b_did_warn = TRUE;
3285 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3286 if (msg_row < Rows - 1)
3292 * Ask for a reply from the user, a 'y' or a 'n'.
3293 * No other characters are accepted, the message is repeated until a valid
3294 * reply is entered or CTRL-C is hit.
3295 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3296 * from any buffers but directly from the user.
3298 * return the 'y' or 'n'
3301 ask_yesno(char_u *str, int direct)
3304 int save_State = State;
3306 if (exiting) /* put terminal in raw mode for this question */
3307 settmode(TMODE_RAW);
3309 #ifdef USE_ON_FLY_SCROLL
3310 dont_scroll = TRUE; /* disallow scrolling here */
3312 State = CONFIRM; /* mouse behaves like with :confirm */
3314 setmouse(); /* disables mouse for xterm */
3317 ++allow_keys; /* no mapping here, but recognize keys */
3319 while (r != 'y' && r != 'n')
3321 /* same highlighting as for wait_return */
3322 smsg_attr(HL_ATTR(HLF_R), (char_u *)"%s (y/n)?", str);
3324 r = get_keystroke();
3327 if (r == Ctrl_C || r == ESC)
3329 msg_putchar(r); /* show what you typed */
3343 #if defined(FEAT_MOUSE) || defined(PROTO)
3345 * Return TRUE if "c" is a mouse key.
3350 return c == K_LEFTMOUSE
3351 || c == K_LEFTMOUSE_NM
3353 || c == K_LEFTRELEASE
3354 || c == K_LEFTRELEASE_NM
3355 || c == K_MIDDLEMOUSE
3356 || c == K_MIDDLEDRAG
3357 || c == K_MIDDLERELEASE
3358 || c == K_RIGHTMOUSE
3360 || c == K_RIGHTRELEASE
3364 || c == K_MOUSERIGHT
3370 || c == K_X2RELEASE;
3375 * Get a key stroke directly from the user.
3376 * Ignores mouse clicks and scrollbar events, except a click for the left
3377 * button (used at the more prompt).
3378 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3379 * Disadvantage: typeahead is ignored.
3380 * Translates the interrupt character for unix to ESC.
3390 int save_mapped_ctrl_c = mapped_ctrl_c;
3393 mapped_ctrl_c = FALSE; /* mappings are not used here */
3399 /* Leave some room for check_termcode() to insert a key code into (max
3400 * 5 chars plus NUL). And fix_input_buffer() can triple the number of
3402 maxlen = (buflen - 6 - len) / 3;
3404 buf = alloc(buflen);
3405 else if (maxlen < 10)
3407 char_u *t_buf = buf;
3409 /* Need some more space. This might happen when receiving a long
3410 * escape sequence. */
3412 buf = vim_realloc(buf, buflen);
3415 maxlen = (buflen - 6 - len) / 3;
3419 do_outofmem_msg((long_u)buflen);
3420 return ESC; /* panic! */
3423 /* First time: blocking wait. Second time: wait up to 100ms for a
3424 * terminal code to complete. */
3425 n = ui_inchar(buf + len, maxlen, len == 0 ? -1L : 100L, 0);
3428 /* Replace zero and CSI by a special key code. */
3429 n = fix_input_buffer(buf + len, n);
3434 ++waited; /* keep track of the waiting time */
3436 /* Incomplete termcode and not timed out yet: get more characters */
3437 if ((n = check_termcode(1, buf, buflen, &len)) < 0
3438 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
3441 if (n == KEYLEN_REMOVED) /* key code removed */
3443 if (must_redraw != 0 && !need_wait_return && (State & CMDLINE) == 0)
3445 /* Redrawing was postponed, do it now. */
3447 setcursor(); /* put cursor back where it belongs */
3451 if (n > 0) /* found a termcode: adjust length */
3453 if (len == 0) /* nothing typed yet */
3456 /* Handle modifier and/or special key code. */
3460 n = TO_SPECIAL(buf[1], buf[2]);
3461 if (buf[1] == KS_MODIFIER
3464 || (is_mouse_key(n) && n != K_LEFTMOUSE)
3467 || n == K_VER_SCROLLBAR
3468 || n == K_HOR_SCROLLBAR
3472 if (buf[1] == KS_MODIFIER)
3476 mch_memmove(buf, buf + 3, (size_t)len);
3484 if (MB_BYTE2LEN(n) > len)
3485 continue; /* more bytes to get */
3486 buf[len >= buflen ? buflen - 1 : len] = NUL;
3487 n = (*mb_ptr2char)(buf);
3498 mapped_ctrl_c = save_mapped_ctrl_c;
3503 * Get a number from the user.
3504 * When "mouse_used" is not NULL allow using the mouse.
3508 int colon, /* allow colon to abort */
3515 if (mouse_used != NULL)
3516 *mouse_used = FALSE;
3518 /* When not printing messages, the user won't know what to type, return a
3519 * zero (as if CR was hit). */
3520 if (msg_silent != 0)
3523 #ifdef USE_ON_FLY_SCROLL
3524 dont_scroll = TRUE; /* disallow scrolling here */
3527 ++allow_keys; /* no mapping here, but recognize keys */
3530 windgoto(msg_row, msg_col);
3534 n = n * 10 + c - '0';
3538 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3548 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3555 else if (n == 0 && c == ':' && colon)
3557 stuffcharReadbuff(':');
3559 cmdline_row = msg_row;
3560 skip_redraw = TRUE; /* skip redraw once */
3564 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3573 * Ask the user to enter a number.
3574 * When "mouse_used" is not NULL allow using the mouse and in that case return
3578 prompt_for_number(int *mouse_used)
3581 int save_cmdline_row;
3584 /* When using ":silent" assume that <CR> was entered. */
3585 if (mouse_used != NULL)
3586 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
3588 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
3590 /* Set the state such that text can be selected/copied/pasted and we still
3591 * get mouse events. */
3592 save_cmdline_row = cmdline_row;
3597 i = get_number(TRUE, mouse_used);
3600 /* don't call wait_return() now */
3601 /* msg_putchar('\n'); */
3602 cmdline_row = msg_row - 1;
3603 need_wait_return = FALSE;
3608 cmdline_row = save_cmdline_row;
3619 if (global_busy /* no messages now, wait until global is finished */
3620 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3623 /* We don't want to overwrite another important message, but do overwrite
3624 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3625 * then "put" reports the last action. */
3626 if (keep_msg != NULL && !keep_msg_more)
3639 vim_strncpy(msg_buf, (char_u *)_("1 more line"),
3642 vim_strncpy(msg_buf, (char_u *)_("1 line less"),
3648 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3649 _("%ld more lines"), pn);
3651 vim_snprintf((char *)msg_buf, MSG_BUF_LEN,
3652 _("%ld fewer lines"), pn);
3655 vim_strcat(msg_buf, (char_u *)_(" (Interrupted)"), MSG_BUF_LEN);
3658 set_keep_msg(msg_buf, 0);
3659 keep_msg_more = TRUE;
3665 * flush map and typeahead buffers and give a warning for an error
3670 if (emsg_silent == 0)
3672 flush_buffers(FALSE);
3678 * Give a warning for an error.
3682 unsigned val) /* one of the BO_ values, e.g., BO_OPER */
3684 if (emsg_silent == 0)
3686 if (!((bo_flags & val) || (bo_flags & BO_ALL)))
3690 /* While the GUI is starting up the termcap is set for the
3691 * GUI but the output still goes to a terminal. */
3692 && !(gui.in_use && gui.starting)
3700 /* When 'verbose' is set and we are sourcing a script or executing a
3701 * function give the user a hint where the beep comes from. */
3702 if (vim_strchr(p_debug, 'e') != NULL)
3704 msg_source(HL_ATTR(HLF_W));
3705 msg_attr((char_u *)_("Beep!"), HL_ATTR(HLF_W));
3711 * To get the "real" home directory:
3712 * - get value of $HOME
3714 * - go to that directory
3715 * - do mch_dirname() to get the real name of that directory.
3716 * This also works with mounts and links.
3717 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3719 static char_u *homedir = NULL;
3726 /* In case we are called a second time (when 'encoding' changes). */
3731 var = mch_getenv((char_u *)"SYS$LOGIN");
3733 var = mch_getenv((char_u *)"HOME");
3736 if (var != NULL && *var == NUL) /* empty is same as not set */
3741 * Weird but true: $HOME may contain an indirect reference to another
3742 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3743 * when $HOME is being set.
3745 if (var != NULL && *var == '%')
3750 p = vim_strchr(var + 1, '%');
3753 vim_strncpy(NameBuff, var + 1, p - (var + 1));
3754 exp = mch_getenv(NameBuff);
3755 if (exp != NULL && *exp != NUL
3756 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3758 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
3760 /* Also set $HOME, it's needed for _viminfo. */
3761 vim_setenv((char_u *)"HOME", NameBuff);
3767 * Typically, $HOME is not defined on Windows, unless the user has
3768 * specifically defined it for Vim's sake. However, on Windows NT
3769 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3770 * each user. Try constructing $HOME from these.
3774 char_u *homedrive, *homepath;
3776 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3777 homepath = mch_getenv((char_u *)"HOMEPATH");
3778 if (homepath == NULL || *homepath == NUL)
3779 homepath = (char_u *)"\\";
3780 if (homedrive != NULL
3781 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3783 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3784 if (NameBuff[0] != NUL)
3787 /* Also set $HOME, it's needed for _viminfo. */
3788 vim_setenv((char_u *)"HOME", NameBuff);
3793 # if defined(FEAT_MBYTE)
3794 if (enc_utf8 && var != NULL)
3799 /* Convert from active codepage to UTF-8. Other conversions are
3800 * not done, because they would fail for non-ASCII characters. */
3801 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
3813 * Default home dir is C:/
3814 * Best assumption we can make in such a situation.
3817 var = (char_u *)"C:/";
3823 * Change to the directory and get the actual path. This resolves
3824 * links. Don't do it when we can't return.
3826 if (mch_dirname(NameBuff, MAXPATHL) == OK
3827 && mch_chdir((char *)NameBuff) == 0)
3829 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3831 if (mch_chdir((char *)NameBuff) != 0)
3832 EMSG(_(e_prev_dir));
3835 homedir = vim_strsave(var);
3839 #if defined(EXITFREE) || defined(PROTO)
3846 # ifdef FEAT_CMDL_COMPL
3850 ga_clear_strings(&ga_users);
3856 * Call expand_env() and store the result in an allocated string.
3857 * This is not very memory efficient, this expects the result to be freed
3861 expand_env_save(char_u *src)
3863 return expand_env_save_opt(src, FALSE);
3867 * Idem, but when "one" is TRUE handle the string as one file name, only
3868 * expand "~" at the start.
3871 expand_env_save_opt(char_u *src, int one)
3875 p = alloc(MAXPATHL);
3877 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3882 * Expand environment variable with path name.
3883 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3884 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
3885 * If anything fails no expansion is done and dst equals src.
3889 char_u *src, /* input string e.g. "$HOME/vim.hlp" */
3890 char_u *dst, /* where to put the result */
3891 int dstlen) /* maximum length of the result */
3893 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
3898 char_u *srcp, /* input string e.g. "$HOME/vim.hlp" */
3899 char_u *dst, /* where to put the result */
3900 int dstlen, /* maximum length of the result */
3901 int esc, /* escape spaces in expanded variables */
3902 int one, /* "srcp" is one file name */
3903 char_u *startstr) /* start again after this (can be NULL) */
3910 int mustfree; /* var was allocated, need to free it later */
3911 int at_start = TRUE; /* at start of a name */
3912 int startstr_len = 0;
3914 if (startstr != NULL)
3915 startstr_len = (int)STRLEN(startstr);
3917 src = skipwhite(srcp);
3918 --dstlen; /* leave one char space for "\," */
3919 while (*src && dstlen > 0)
3922 /* Skip over `=expr`. */
3923 if (src[0] == '`' && src[1] == '=')
3929 (void)skip_expr(&src);
3933 if (len > (size_t)dstlen)
3935 vim_strncpy(dst, var, len);
3950 || (*src == '~' && at_start))
3955 * The variable name is copied into dst temporarily, because it may
3956 * be a string in read-only memory and a NUL needs to be appended.
3958 if (*src != '~') /* environment var */
3965 /* Unix has ${var-name} type environment vars */
3966 if (*tail == '{' && !vim_isIDc('{'))
3968 tail++; /* ignore '{' */
3969 while (c-- > 0 && *tail && *tail != '}')
3975 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3977 || (*src == '%' && *tail != '%')
3985 #if defined(MSWIN) || defined(UNIX)
3987 if (src[1] == '{' && *tail != '}')
3989 if (*src == '%' && *tail != '%')
4002 var = vim_getenv(dst, &mustfree);
4003 #if defined(MSWIN) || defined(UNIX)
4007 /* home directory */
4008 else if ( src[1] == NUL
4009 || vim_ispathsep(src[1])
4010 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
4015 else /* user directory */
4017 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
4019 * Copy ~user to dst[], so we can put a NUL after it.
4026 && vim_isfilec(*tail)
4027 && !vim_ispathsep(*tail))
4032 * If the system supports getpwnam(), use it.
4033 * Otherwise, or if getpwnam() fails, the shell is used to
4034 * expand ~user. This is slower and may fail if the shell
4035 * does not support ~user (old versions of /bin/sh).
4037 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
4039 /* Note: memory allocated by getpwnam() is never freed.
4040 * Calling endpwent() apparently doesn't help. */
4041 struct passwd *pw = (*dst == NUL)
4042 ? NULL : getpwnam((char *)dst + 1);
4044 var = (pw == NULL) ? NULL : (char_u *)pw->pw_dir;
4052 xpc.xp_context = EXPAND_FILES;
4053 var = ExpandOne(&xpc, dst, NULL,
4054 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
4058 # else /* !UNIX, thus VMS */
4060 * USER_HOME is a comma-separated list of
4061 * directories to search for the user account in.
4064 char_u test[MAXPATHL], paths[MAXPATHL];
4065 char_u *path, *next_path, *ptr;
4068 STRCPY(paths, USER_HOME);
4072 for (path = next_path; *next_path && *next_path != ',';
4078 STRCAT(test, dst + 1);
4079 if (mch_stat(test, &st) == 0)
4081 var = alloc(STRLEN(test) + 1);
4090 /* cannot expand user's home directory, so don't try */
4092 tail = (char_u *)""; /* for gcc */
4093 #endif /* UNIX || VMS */
4096 #ifdef BACKSLASH_IN_FILENAME
4097 /* If 'shellslash' is set change backslashes to forward slashes.
4098 * Can't use slash_adjust(), p_ssl may be set temporarily. */
4099 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
4101 char_u *p = vim_strsave(var);
4114 /* If "var" contains white space, escape it with a backslash.
4115 * Required for ":e ~/tt" when $HOME includes a space. */
4116 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
4118 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
4129 if (var != NULL && *var != NUL
4130 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
4133 dstlen -= (int)STRLEN(var);
4134 c = (int)STRLEN(var);
4135 /* if var[] ends in a path separator and tail[] starts
4136 * with it, skip a character */
4137 if (*var != NUL && after_pathsep(dst, dst + c)
4138 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
4141 && vim_ispathsep(*tail))
4151 if (copy_char) /* copy at least one char */
4154 * Recognize the start of a new name, for '~'.
4155 * Don't do this when "one" is TRUE, to avoid expanding "~" in
4156 * ":edit foo ~ foo".
4159 if (src[0] == '\\' && src[1] != NUL)
4164 else if ((src[0] == ' ' || src[0] == ',') && !one)
4169 if (startstr != NULL && src - startstr_len >= srcp
4170 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
4178 * Vim's version of getenv().
4179 * Special handling of $HOME, $VIM and $VIMRUNTIME.
4180 * Also does ACP to 'enc' conversion for Win32.
4181 * "mustfree" is set to TRUE when returned is allocated, it must be
4182 * initialized to FALSE by the caller.
4185 vim_getenv(char_u *name, int *mustfree)
4192 /* use "C:/" when $HOME is not set */
4193 if (STRCMP(name, "HOME") == 0)
4197 p = mch_getenv(name);
4198 if (p != NULL && *p == NUL) /* empty is the same as not set */
4203 #if defined(FEAT_MBYTE) && defined(WIN3264)
4209 /* Convert from active codepage to UTF-8. Other conversions are
4210 * not done, because they would fail for non-ASCII characters. */
4211 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4222 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4223 if (!vimruntime && STRCMP(name, "VIM") != 0)
4227 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4228 * Don't do this when default_vimruntime_dir is non-empty.
4232 && *default_vimruntime_dir == NUL
4236 p = mch_getenv((char_u *)"VIM");
4237 if (p != NULL && *p == NUL) /* empty is the same as not set */
4241 p = vim_version_dir(p);
4245 p = mch_getenv((char_u *)"VIM");
4247 #if defined(FEAT_MBYTE) && defined(WIN3264)
4253 /* Convert from active codepage to UTF-8. Other conversions
4254 * are not done, because they would fail for non-ASCII
4256 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4270 * When expanding $VIM or $VIMRUNTIME fails, try using:
4271 * - the directory name from 'helpfile' (unless it contains '$')
4272 * - the executable name from argv[0]
4276 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4280 * Use the name of the executable, obtained from argv[0].
4287 /* remove the file name */
4290 /* remove "doc/" from 'helpfile', if present */
4292 pend = remove_tail(p, pend, (char_u *)"doc");
4296 /* remove "MacOS" from exe_name and add "Resources/vim" */
4302 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4305 pnew = alloc((unsigned)(pend1 - p) + 15);
4308 STRNCPY(pnew, p, (pend1 - p));
4309 STRCPY(pnew + (pend1 - p), "Resources/vim");
4311 pend = p + STRLEN(p);
4316 /* remove "src/" from exe_name, if present */
4318 pend = remove_tail(p, pend, (char_u *)"src");
4321 /* for $VIM, remove "runtime/" or "vim54/", if present */
4324 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4325 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4328 /* remove trailing path separator */
4329 #ifndef MACOS_CLASSIC
4330 /* With MacOS path (with colons) the final colon is required */
4331 /* to avoid confusion between absolute and relative path */
4332 if (pend > p && after_pathsep(p, pend))
4337 if (p == exe_name || p == p_hf)
4339 /* check that the result is a directory name */
4340 p = vim_strnsave(p, (int)(pend - p));
4342 if (p != NULL && !mch_isdir(p))
4350 /* may add "/vim54" or "/runtime" if it exists */
4351 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4363 /* When there is a pathdef.c file we can use default_vim_dir and
4364 * default_vimruntime_dir */
4367 /* Only use default_vimruntime_dir when it is not empty */
4368 if (vimruntime && *default_vimruntime_dir != NUL)
4370 p = default_vimruntime_dir;
4373 else if (*default_vim_dir != NUL)
4375 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4379 p = default_vim_dir;
4387 * Set the environment variable, so that the new value can be found fast
4388 * next time, and others can also use it (e.g. Perl).
4394 vim_setenv((char_u *)"VIMRUNTIME", p);
4395 didset_vimruntime = TRUE;
4399 vim_setenv((char_u *)"VIM", p);
4407 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4408 * Return NULL if not, return its name in allocated memory otherwise.
4411 vim_version_dir(char_u *vimdir)
4415 if (vimdir == NULL || *vimdir == NUL)
4417 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4418 if (p != NULL && mch_isdir(p))
4421 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4422 if (p != NULL && mch_isdir(p))
4429 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4430 * the length of "name/". Otherwise return "pend".
4433 remove_tail(char_u *p, char_u *pend, char_u *name)
4435 int len = (int)STRLEN(name) + 1;
4436 char_u *newend = pend - len;
4439 && fnamencmp(newend, name, len - 1) == 0
4440 && (newend == p || after_pathsep(p, newend)))
4446 * Our portable version of setenv.
4449 vim_setenv(char_u *name, char_u *val)
4452 mch_setenv((char *)name, (char *)val, 1);
4457 * Putenv does not copy the string, it has to remain
4458 * valid. The allocated memory will never be freed.
4460 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4463 sprintf((char *)envbuf, "%s=%s", name, val);
4464 putenv((char *)envbuf);
4469 * When setting $VIMRUNTIME adjust the directory to find message
4470 * translations to $VIMRUNTIME/lang.
4472 if (*val != NUL && STRICMP(name, "VIMRUNTIME") == 0)
4474 char_u *buf = concat_str(val, (char_u *)"/lang");
4478 bindtextdomain(VIMPACKAGE, (char *)buf);
4485 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4487 * Function given to ExpandGeneric() to obtain an environment variable name.
4491 expand_T *xp UNUSED,
4494 # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4496 * No environ[] on the Amiga and on the Mac (using MPW).
4501 /* Borland C++ 5.2 has this in a header file. */
4502 extern char **environ;
4504 # define ENVNAMELEN 100
4505 static char_u name[ENVNAMELEN];
4509 str = (char_u *)environ[idx];
4513 for (n = 0; n < ENVNAMELEN - 1; ++n)
4515 if (str[n] == '=' || str[n] == NUL)
4525 * Find all user names for user completion.
4526 * Done only once and then cached.
4531 static int lazy_init_done = FALSE;
4536 lazy_init_done = TRUE;
4537 ga_init2(&ga_users, sizeof(char_u *), 20);
4539 # if defined(HAVE_GETPWENT) && defined(HAVE_PWD_H)
4545 while ((pw = getpwent()) != NULL)
4546 /* pw->pw_name shouldn't be NULL but just in case... */
4547 if (pw->pw_name != NULL)
4549 if (ga_grow(&ga_users, 1) == FAIL)
4551 user = vim_strsave((char_u*)pw->pw_name);
4554 ((char_u **)(ga_users.ga_data))[ga_users.ga_len++] = user;
4562 * Function given to ExpandGeneric() to obtain an user names.
4565 get_users(expand_T *xp UNUSED, int idx)
4568 if (idx < ga_users.ga_len)
4569 return ((char_u **)ga_users.ga_data)[idx];
4574 * Check whether name matches a user name. Return:
4575 * 0 if name does not match any user name.
4576 * 1 if name partially matches the beginning of a user name.
4577 * 2 is name fully matches a user name.
4579 int match_user(char_u* name)
4582 int n = (int)STRLEN(name);
4586 for (i = 0; i < ga_users.ga_len; i++)
4588 if (STRCMP(((char_u **)ga_users.ga_data)[i], name) == 0)
4589 return 2; /* full match */
4590 if (STRNCMP(((char_u **)ga_users.ga_data)[i], name, n) == 0)
4591 result = 1; /* partial match */
4598 * Replace home directory by "~" in each space or comma separated file name in
4600 * If anything fails (except when out of space) dst equals src.
4604 buf_T *buf, /* when not NULL, check for help files */
4605 char_u *src, /* input file name */
4606 char_u *dst, /* where to put the result */
4607 int dstlen, /* maximum length of the result */
4608 int one) /* if TRUE, only replace one file name, include
4609 spaces and commas in the file name. */
4611 size_t dirlen = 0, envlen = 0;
4613 char_u *homedir_env, *homedir_env_orig;
4623 * If the file is a help file, remove the path completely.
4625 if (buf != NULL && buf->b_help)
4627 STRCPY(dst, gettail(src));
4632 * We check both the value of the $HOME environment variable and the
4633 * "real" home directory.
4635 if (homedir != NULL)
4636 dirlen = STRLEN(homedir);
4639 homedir_env_orig = homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4641 homedir_env_orig = homedir_env = mch_getenv((char_u *)"HOME");
4643 /* Empty is the same as not set. */
4644 if (homedir_env != NULL && *homedir_env == NUL)
4647 #if defined(FEAT_MODIFY_FNAME) || defined(FEAT_EVAL)
4648 if (homedir_env != NULL && vim_strchr(homedir_env, '~') != NULL)
4652 char_u *fbuf = NULL;
4654 flen = (int)STRLEN(homedir_env);
4655 (void)modify_fname((char_u *)":p", &usedlen,
4656 &homedir_env, &fbuf, &flen);
4657 flen = (int)STRLEN(homedir_env);
4658 if (flen > 0 && vim_ispathsep(homedir_env[flen - 1]))
4659 /* Remove the trailing / that is added to a directory. */
4660 homedir_env[flen - 1] = NUL;
4664 if (homedir_env != NULL)
4665 envlen = STRLEN(homedir_env);
4668 src = skipwhite(src);
4669 while (*src && dstlen > 0)
4672 * Here we are at the beginning of a file name.
4673 * First, check to see if the beginning of the file name matches
4674 * $HOME or the "real" home directory. Check that there is a '/'
4675 * after the match (so that if e.g. the file is "/home/pieter/bla",
4676 * and the home directory is "/home/piet", the file does not end up
4677 * as "~er/bla" (which would seem to indicate the file "bla" in user
4678 * er's home directory)).
4685 && fnamencmp(src, p, len) == 0
4686 && (vim_ispathsep(src[len])
4687 || (!one && (src[len] == ',' || src[len] == ' '))
4688 || src[len] == NUL))
4695 * If it's just the home directory, add "/".
4697 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4701 if (p == homedir_env)
4707 /* if (!one) skip to separator: space or comma */
4708 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4710 /* skip separator */
4711 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4714 /* if (dstlen == 0) out of space, what to do??? */
4718 if (homedir_env != homedir_env_orig)
4719 vim_free(homedir_env);
4723 * Like home_replace, store the replaced string in allocated memory.
4724 * When something fails, NULL is returned.
4728 buf_T *buf, /* when not NULL, check for help files */
4729 char_u *src) /* input file name */
4734 len = 3; /* space for "~/" and trailing NUL */
4735 if (src != NULL) /* just in case */
4736 len += (unsigned)STRLEN(src);
4739 home_replace(buf, src, dst, len, TRUE);
4744 * Compare two file names and return:
4745 * FPC_SAME if they both exist and are the same file.
4746 * FPC_SAMEX if they both don't exist and have the same file name.
4747 * FPC_DIFF if they both exist and are different files.
4748 * FPC_NOTX if they both don't exist.
4749 * FPC_DIFFX if one of them doesn't exist.
4750 * For the first name environment variables are expanded
4756 int checkname) /* when both don't exist, check file names */
4759 char_u exp1[MAXPATHL];
4760 char_u full1[MAXPATHL];
4761 char_u full2[MAXPATHL];
4765 expand_env(s1, exp1, MAXPATHL);
4766 r1 = mch_stat((char *)exp1, &st1);
4767 r2 = mch_stat((char *)s2, &st2);
4768 if (r1 != 0 && r2 != 0)
4770 /* if mch_stat() doesn't work, may compare the names */
4773 if (fnamecmp(exp1, s2) == 0)
4775 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4776 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4777 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4782 if (r1 != 0 || r2 != 0)
4784 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4788 char_u *exp1; /* expanded s1 */
4789 char_u *full1; /* full path of s1 */
4790 char_u *full2; /* full path of s2 */
4791 int retval = FPC_DIFF;
4794 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4795 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4797 full1 = exp1 + MAXPATHL;
4798 full2 = full1 + MAXPATHL;
4800 expand_env(s1, exp1, MAXPATHL);
4801 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4802 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4804 /* If vim_FullName() fails, the file probably doesn't exist. */
4805 if (r1 != OK && r2 != OK)
4807 if (checkname && fnamecmp(exp1, s2) == 0)
4812 else if (r1 != OK || r2 != OK)
4814 else if (fnamecmp(full1, full2))
4825 * Get the tail of a path: the file name.
4826 * When the path ends in a path separator the tail is the NUL after it.
4827 * Fail safe: never returns NULL.
4830 gettail(char_u *fname)
4835 return (char_u *)"";
4836 for (p1 = p2 = get_past_head(fname); *p2; ) /* find last part of path */
4838 if (vim_ispathsep_nocolon(*p2))
4845 #if defined(FEAT_SEARCHPATH)
4846 static char_u *gettail_dir(char_u *fname);
4849 * Return the end of the directory name, on the first path
4851 * "/path/file", "/path/dir/", "/path//dir", "/file"
4855 gettail_dir(char_u *fname)
4857 char_u *dir_end = fname;
4858 char_u *next_dir_end = fname;
4859 int look_for_sep = TRUE;
4862 for (p = fname; *p != NUL; )
4864 if (vim_ispathsep(*p))
4869 look_for_sep = FALSE;
4875 dir_end = next_dir_end;
4876 look_for_sep = TRUE;
4885 * Get pointer to tail of "fname", including path separators. Putting a NUL
4886 * here leaves the directory name. Takes care of "c:/" and "//".
4887 * Always returns a valid pointer.
4890 gettail_sep(char_u *fname)
4895 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4897 while (t > p && after_pathsep(fname, t))
4900 /* path separator is part of the path */
4907 * get the next path component (just after the next path separator).
4910 getnextcomp(char_u *fname)
4912 while (*fname && !vim_ispathsep(*fname))
4920 * Get a pointer to one character past the head of a path name.
4921 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4922 * If there is no head, path is returned.
4925 get_past_head(char_u *path)
4931 if (isalpha(path[0]) && path[1] == ':')
4937 /* may skip "label:" */
4938 retval = vim_strchr(path, ':');
4946 while (vim_ispathsep(*retval))
4953 * Return TRUE if 'c' is a path separator.
4954 * Note that for MS-Windows this includes the colon.
4957 vim_ispathsep(int c)
4960 return (c == '/'); /* UNIX has ':' inside file names */
4962 # ifdef BACKSLASH_IN_FILENAME
4963 return (c == ':' || c == '/' || c == '\\');
4966 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4967 return (c == ':' || c == '[' || c == ']' || c == '/'
4968 || c == '<' || c == '>' || c == '"' );
4970 return (c == ':' || c == '/');
4977 * Like vim_ispathsep(c), but exclude the colon for MS-Windows.
4980 vim_ispathsep_nocolon(int c)
4982 return vim_ispathsep(c)
4983 #ifdef BACKSLASH_IN_FILENAME
4989 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
4991 * return TRUE if 'c' is a path list separator.
4994 vim_ispathlistsep(int c)
4999 return (c == ';'); /* might not be right for every system... */
5004 #if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
5005 || defined(FEAT_EVAL) || defined(PROTO)
5007 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
5008 * It's done in-place.
5011 shorten_dir(char_u *str)
5013 char_u *tail, *s, *d;
5016 tail = gettail(str);
5018 for (s = str; ; ++s)
5020 if (s >= tail) /* copy the whole tail */
5026 else if (vim_ispathsep(*s)) /* copy '/' and next char */
5033 *d++ = *s; /* copy next char */
5034 if (*s != '~' && *s != '.') /* and leading "~" and "." */
5039 int l = mb_ptr2len(s);
5051 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
5052 * Also returns TRUE if there is no directory name.
5053 * "fname" must be writable!.
5056 dir_of_file_exists(char_u *fname)
5062 p = gettail_sep(fname);
5067 retval = mch_isdir(fname);
5073 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally
5074 * and deal with 'fileignorecase'.
5077 vim_fnamecmp(char_u *x, char_u *y)
5079 #ifdef BACKSLASH_IN_FILENAME
5080 return vim_fnamencmp(x, y, MAXPATHL);
5083 return MB_STRICMP(x, y);
5084 return STRCMP(x, y);
5089 vim_fnamencmp(char_u *x, char_u *y, size_t len)
5091 #ifdef BACKSLASH_IN_FILENAME
5101 if (cx == NUL || cy == NUL
5102 || ((p_fic ? MB_TOLOWER(cx) != MB_TOLOWER(cy) : cx != cy)
5103 && !(cx == '/' && cy == '\\')
5104 && !(cx == '\\' && cy == '/')))
5106 len -= MB_PTR2LEN(px);
5107 px += MB_PTR2LEN(px);
5108 py += MB_PTR2LEN(py);
5115 return MB_STRNICMP(x, y, len);
5116 return STRNCMP(x, y, len);
5121 * Concatenate file names fname1 and fname2 into allocated memory.
5122 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
5125 concat_fnames(char_u *fname1, char_u *fname2, int sep)
5129 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
5132 STRCPY(dest, fname1);
5135 STRCAT(dest, fname2);
5141 * Concatenate two strings and return the result in allocated memory.
5142 * Returns NULL when out of memory.
5145 concat_str(char_u *str1, char_u *str2)
5148 size_t l = STRLEN(str1);
5150 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
5154 STRCPY(dest + l, str2);
5160 * Add a path separator to a file name, unless it already ends in a path
5164 add_pathsep(char_u *p)
5166 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
5167 STRCAT(p, PATHSEPSTR);
5171 * FullName_save - Make an allocated copy of a full file name.
5172 * Returns NULL when out of memory.
5177 int force) /* force expansion, even when it already looks
5178 * like a full path name */
5181 char_u *new_fname = NULL;
5186 buf = alloc((unsigned)MAXPATHL);
5189 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
5190 new_fname = vim_strsave(buf);
5192 new_fname = vim_strsave(fname);
5198 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
5200 static char_u *skip_string(char_u *p);
5201 static pos_T *ind_find_start_comment(void);
5202 static pos_T *ind_find_start_CORS(void);
5203 static pos_T *find_start_rawstring(int ind_maxcomment);
5206 * Find the start of a comment, not knowing if we are in a comment right now.
5207 * Search starts at w_cursor.lnum and goes backwards.
5208 * Return NULL when not inside a comment.
5211 ind_find_start_comment(void) /* XXX */
5213 return find_start_comment(curbuf->b_ind_maxcomment);
5217 find_start_comment(int ind_maxcomment) /* XXX */
5222 int cur_maxcomment = ind_maxcomment;
5226 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
5231 * Check if the comment start we found is inside a string.
5232 * If it is then restrict the search to below this line and try again.
5234 line = ml_get(pos->lnum);
5235 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
5237 if ((colnr_T)(p - line) <= pos->col)
5239 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5240 if (cur_maxcomment <= 0)
5250 * Find the start of a comment or raw string, not knowing if we are in a
5251 * comment or raw string right now.
5252 * Search starts at w_cursor.lnum and goes backwards.
5253 * Return NULL when not inside a comment or raw string.
5254 * "CORS" -> Comment Or Raw String
5257 ind_find_start_CORS(void) /* XXX */
5259 static pos_T comment_pos_copy;
5263 comment_pos = find_start_comment(curbuf->b_ind_maxcomment);
5264 if (comment_pos != NULL)
5266 /* Need to make a copy of the static pos in findmatchlimit(),
5267 * calling find_start_rawstring() may change it. */
5268 comment_pos_copy = *comment_pos;
5269 comment_pos = &comment_pos_copy;
5271 rs_pos = find_start_rawstring(curbuf->b_ind_maxcomment);
5273 /* If comment_pos is before rs_pos the raw string is inside the comment.
5274 * If rs_pos is before comment_pos the comment is inside the raw string. */
5275 if (comment_pos == NULL || (rs_pos != NULL
5276 && LT_POS(*rs_pos, *comment_pos)))
5282 * Find the start of a raw string, not knowing if we are in one right now.
5283 * Search starts at w_cursor.lnum and goes backwards.
5284 * Return NULL when not inside a raw string.
5287 find_start_rawstring(int ind_maxcomment) /* XXX */
5292 int cur_maxcomment = ind_maxcomment;
5296 pos = findmatchlimit(NULL, 'R', FM_BACKWARD, cur_maxcomment);
5301 * Check if the raw string start we found is inside a string.
5302 * If it is then restrict the search to below this line and try again.
5304 line = ml_get(pos->lnum);
5305 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
5307 if ((colnr_T)(p - line) <= pos->col)
5309 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
5310 if (cur_maxcomment <= 0)
5320 * Skip to the end of a "string" and a 'c' character.
5321 * If there is no string or character, return argument unmodified.
5324 skip_string(char_u *p)
5329 * We loop, because strings may be concatenated: "date""time".
5333 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
5335 if (!p[1]) /* ' at end of line */
5338 if (p[1] == '\\') /* '\n' or '\000' */
5341 while (vim_isdigit(p[i - 1])) /* '\000' */
5344 if (p[i] == '\'') /* check for trailing ' */
5350 else if (p[0] == '"') /* start of string */
5352 for (++p; p[0]; ++p)
5354 if (p[0] == '\\' && p[1] != NUL)
5356 else if (p[0] == '"') /* end of string */
5360 continue; /* continue for another string */
5362 else if (p[0] == 'R' && p[1] == '"')
5364 /* Raw string: R"[delim](...)[delim]" */
5365 char_u *delim = p + 2;
5366 char_u *paren = vim_strchr(delim, '(');
5370 size_t delim_len = paren - delim;
5372 for (p += 3; *p; ++p)
5373 if (p[0] == ')' && STRNCMP(p + 1, delim, delim_len) == 0
5374 && p[delim_len + 1] == '"')
5380 continue; /* continue for another string */
5383 break; /* no string found */
5386 --p; /* backup from NUL */
5389 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
5391 #if defined(FEAT_CINDENT) || defined(PROTO)
5394 * Do C or expression indenting on the current line.
5397 do_c_expr_indent(void)
5400 if (*curbuf->b_p_inde != NUL)
5401 fixthisline(get_expr_indent);
5404 fixthisline(get_c_indent);
5407 /* Find result cache for cpp_baseclass */
5411 } cpp_baseclass_cache_T;
5414 * Functions for C-indenting.
5415 * Most of this originally comes from Eric Fischer.
5418 * Below "XXX" means that this function may unlock the current line.
5421 static char_u *cin_skipcomment(char_u *);
5422 static int cin_nocode(char_u *);
5423 static pos_T *find_line_comment(void);
5424 static int cin_has_js_key(char_u *text);
5425 static int cin_islabel_skip(char_u **);
5426 static int cin_isdefault(char_u *);
5427 static char_u *after_label(char_u *l);
5428 static int get_indent_nolabel(linenr_T lnum);
5429 static int skip_label(linenr_T, char_u **pp);
5430 static int cin_first_id_amount(void);
5431 static int cin_get_equal_amount(linenr_T lnum);
5432 static int cin_ispreproc(char_u *);
5433 static int cin_iscomment(char_u *);
5434 static int cin_islinecomment(char_u *);
5435 static int cin_isterminated(char_u *, int, int);
5436 static int cin_isinit(void);
5437 static int cin_isfuncdecl(char_u **, linenr_T, linenr_T);
5438 static int cin_isif(char_u *);
5439 static int cin_iselse(char_u *);
5440 static int cin_isdo(char_u *);
5441 static int cin_iswhileofdo(char_u *, linenr_T);
5442 static int cin_is_if_for_while_before_offset(char_u *line, int *poffset);
5443 static int cin_iswhileofdo_end(int terminated);
5444 static int cin_isbreak(char_u *);
5445 static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached);
5446 static int get_baseclass_amount(int col);
5447 static int cin_ends_in(char_u *, char_u *, char_u *);
5448 static int cin_starts_with(char_u *s, char *word);
5449 static int cin_skip2pos(pos_T *trypos);
5450 static pos_T *find_start_brace(void);
5451 static pos_T *find_match_paren(int);
5452 static pos_T *find_match_char(int c, int ind_maxparen);
5453 static int corr_ind_maxparen(pos_T *startpos);
5454 static int find_last_paren(char_u *l, int start, int end);
5455 static int find_match(int lookfor, linenr_T ourscope);
5456 static int cin_is_cpp_namespace(char_u *);
5459 * Skip over white space and C comments within the line.
5460 * Also skip over Perl/shell comments if desired.
5463 cin_skipcomment(char_u *s)
5471 /* Perl/shell # comment comment continues until eol. Require a space
5472 * before # to avoid recognizing $#array. */
5473 if (curbuf->b_ind_hash_comment != 0 && s != prev_s && *s == '#')
5481 if (*s == '/') /* slash-slash comment continues till eol */
5488 for (++s; *s; ++s) /* skip slash-star comment */
5489 if (s[0] == '*' && s[1] == '/')
5499 * Return TRUE if there is no code at *s. White space and comments are
5500 * not considered code.
5503 cin_nocode(char_u *s)
5505 return *cin_skipcomment(s) == NUL;
5509 * Check previous lines for a "//" line comment, skipping over blank lines.
5512 find_line_comment(void) /* XXX */
5518 pos = curwin->w_cursor;
5519 while (--pos.lnum > 0)
5521 line = ml_get(pos.lnum);
5522 p = skipwhite(line);
5523 if (cin_islinecomment(p))
5525 pos.col = (int)(p - line);
5535 * Return TRUE if "text" starts with "key:".
5538 cin_has_js_key(char_u *text)
5540 char_u *s = skipwhite(text);
5543 if (*s == '\'' || *s == '"')
5545 /* can be 'key': or "key": */
5549 if (!vim_isIDc(*s)) /* need at least one ID character */
5552 while (vim_isIDc(*s))
5557 s = cin_skipcomment(s);
5559 /* "::" is not a label, it's C++ */
5560 return (*s == ':' && s[1] != ':');
5564 * Check if string matches "label:"; move to character after ':' if true.
5565 * "*s" must point to the start of the label, if there is one.
5568 cin_islabel_skip(char_u **s)
5570 if (!vim_isIDc(**s)) /* need at least one ID character */
5573 while (vim_isIDc(**s))
5576 *s = cin_skipcomment(*s);
5578 /* "::" is not a label, it's C++ */
5579 return (**s == ':' && *++*s != ':');
5583 * Recognize a label: "label:".
5584 * Note: curwin->w_cursor must be where we are looking for the label.
5587 cin_islabel(void) /* XXX */
5591 s = cin_skipcomment(ml_get_curline());
5594 * Exclude "default" from labels, since it should be indented
5595 * like a switch label. Same for C++ scope declarations.
5597 if (cin_isdefault(s))
5599 if (cin_isscopedecl(s))
5602 if (cin_islabel_skip(&s))
5605 * Only accept a label if the previous line is terminated or is a case
5612 cursor_save = curwin->w_cursor;
5613 while (curwin->w_cursor.lnum > 1)
5615 --curwin->w_cursor.lnum;
5618 * If we're in a comment or raw string now, skip to the start of
5621 curwin->w_cursor.col = 0;
5622 if ((trypos = ind_find_start_CORS()) != NULL) /* XXX */
5623 curwin->w_cursor = *trypos;
5625 line = ml_get_curline();
5626 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5628 if (*(line = cin_skipcomment(line)) == NUL)
5631 curwin->w_cursor = cursor_save;
5632 if (cin_isterminated(line, TRUE, FALSE)
5633 || cin_isscopedecl(line)
5634 || cin_iscase(line, TRUE)
5635 || (cin_islabel_skip(&line) && cin_nocode(line)))
5639 curwin->w_cursor = cursor_save;
5640 return TRUE; /* label at start of file??? */
5646 * Recognize structure initialization and enumerations:
5647 * "[typedef] [static|public|protected|private] enum"
5648 * "[typedef] [static|public|protected|private] = {"
5654 static char *skip[] = {"static", "public", "protected", "private"};
5656 s = cin_skipcomment(ml_get_curline());
5658 if (cin_starts_with(s, "typedef"))
5659 s = cin_skipcomment(s + 7);
5665 for (i = 0; i < (int)(sizeof(skip) / sizeof(char *)); ++i)
5667 l = (int)strlen(skip[i]);
5668 if (cin_starts_with(s, skip[i]))
5670 s = cin_skipcomment(s + l);
5679 if (cin_starts_with(s, "enum"))
5682 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5689 * Recognize a switch label: "case .*:" or "default:".
5694 int strict) /* Allow relaxed check of case statement for JS */
5696 s = cin_skipcomment(s);
5697 if (cin_starts_with(s, "case"))
5699 for (s += 4; *s; ++s)
5701 s = cin_skipcomment(s);
5704 if (s[1] == ':') /* skip over "::" for C++ */
5709 if (*s == '\'' && s[1] && s[2] == '\'')
5710 s += 2; /* skip over ':' */
5711 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5712 return FALSE; /* stop at comment */
5717 return FALSE; /* stop at string */
5725 if (cin_isdefault(s))
5731 * Recognize a "default" switch label.
5734 cin_isdefault(char_u *s)
5736 return (STRNCMP(s, "default", 7) == 0
5737 && *(s = cin_skipcomment(s + 7)) == ':'
5742 * Recognize a "public/private/protected" scope declaration label.
5745 cin_isscopedecl(char_u *s)
5749 s = cin_skipcomment(s);
5750 if (STRNCMP(s, "public", 6) == 0)
5752 else if (STRNCMP(s, "protected", 9) == 0)
5754 else if (STRNCMP(s, "private", 7) == 0)
5758 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5761 /* Maximum number of lines to search back for a "namespace" line. */
5762 #define FIND_NAMESPACE_LIM 20
5765 * Recognize a "namespace" scope declaration.
5768 cin_is_cpp_namespace(char_u *s)
5771 int has_name = FALSE;
5772 int has_name_start = FALSE;
5774 s = cin_skipcomment(s);
5775 if (STRNCMP(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc(s[9])))
5777 p = cin_skipcomment(skipwhite(s + 9));
5780 if (VIM_ISWHITE(*p))
5782 has_name = TRUE; /* found end of a name */
5783 p = cin_skipcomment(skipwhite(p));
5789 else if (vim_iswordc(*p))
5791 has_name_start = TRUE;
5793 return FALSE; /* word character after skipping past name */
5796 else if (p[0] == ':' && p[1] == ':' && vim_iswordc(p[2]))
5798 if (!has_name_start || has_name)
5800 /* C++ 17 nested namespace */
5814 * Recognize a `extern "C"` or `extern "C++"` linkage specifications.
5817 cin_is_cpp_extern_c(char_u *s)
5820 int has_string_literal = FALSE;
5822 s = cin_skipcomment(s);
5823 if (STRNCMP(s, "extern", 6) == 0 && (s[6] == NUL || !vim_iswordc(s[6])))
5825 p = cin_skipcomment(skipwhite(s + 6));
5828 if (VIM_ISWHITE(*p))
5830 p = cin_skipcomment(skipwhite(p));
5836 else if (p[0] == '"' && p[1] == 'C' && p[2] == '"')
5838 if (has_string_literal)
5840 has_string_literal = TRUE;
5843 else if (p[0] == '"' && p[1] == 'C' && p[2] == '+' && p[3] == '+'
5846 if (has_string_literal)
5848 has_string_literal = TRUE;
5856 return has_string_literal ? TRUE : FALSE;
5862 * Return a pointer to the first non-empty non-comment character after a ':'.
5863 * Return NULL if not found.
5868 after_label(char_u *l)
5874 if (l[1] == ':') /* skip over "::" for C++ */
5876 else if (!cin_iscase(l + 1, FALSE))
5879 else if (*l == '\'' && l[1] && l[2] == '\'')
5880 l += 2; /* skip over 'x' */
5884 l = cin_skipcomment(l + 1);
5891 * Get indent of line "lnum", skipping a label.
5892 * Return 0 if there is nothing after the label.
5895 get_indent_nolabel (linenr_T lnum) /* XXX */
5907 fp.col = (colnr_T)(p - l);
5909 getvcol(curwin, &fp, &col, NULL, NULL);
5914 * Find indent for line "lnum", ignoring any case or jump label.
5915 * Also return a pointer to the text (after the label) in "pp".
5916 * label: if (asdf && asdfasdf)
5920 skip_label(linenr_T lnum, char_u **pp)
5926 cursor_save = curwin->w_cursor;
5927 curwin->w_cursor.lnum = lnum;
5928 l = ml_get_curline();
5930 if (cin_iscase(l, FALSE) || cin_isscopedecl(l) || cin_islabel())
5932 amount = get_indent_nolabel(lnum);
5933 l = after_label(ml_get_curline());
5934 if (l == NULL) /* just in case */
5935 l = ml_get_curline();
5939 amount = get_indent();
5940 l = ml_get_curline();
5944 curwin->w_cursor = cursor_save;
5949 * Return the indent of the first variable name after a type in a declaration.
5950 * int a, indent of "a"
5951 * static struct foo b, indent of "b"
5952 * enum bla c, indent of "c"
5953 * Returns zero when it doesn't look like a declaration.
5956 cin_first_id_amount(void)
5958 char_u *line, *p, *s;
5963 line = ml_get_curline();
5964 p = skipwhite(line);
5965 len = (int)(skiptowhite(p) - p);
5966 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5968 p = skipwhite(p + 6);
5969 len = (int)(skiptowhite(p) - p);
5971 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5972 p = skipwhite(p + 6);
5973 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5974 p = skipwhite(p + 4);
5975 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5976 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5978 s = skipwhite(p + len);
5979 if ((STRNCMP(s, "int", 3) == 0 && VIM_ISWHITE(s[3]))
5980 || (STRNCMP(s, "long", 4) == 0 && VIM_ISWHITE(s[4]))
5981 || (STRNCMP(s, "short", 5) == 0 && VIM_ISWHITE(s[5]))
5982 || (STRNCMP(s, "char", 4) == 0 && VIM_ISWHITE(s[4])))
5985 for (len = 0; vim_isIDc(p[len]); ++len)
5987 if (len == 0 || !VIM_ISWHITE(p[len]) || cin_nocode(p))
5990 p = skipwhite(p + len);
5991 fp.lnum = curwin->w_cursor.lnum;
5992 fp.col = (colnr_T)(p - line);
5993 getvcol(curwin, &fp, &col, NULL, NULL);
5998 * Return the indent of the first non-blank after an equal sign.
5999 * char *foo = "here";
6000 * Return zero if no (useful) equal sign found.
6001 * Return -1 if the line above "lnum" ends in a backslash.
6007 cin_get_equal_amount(linenr_T lnum)
6016 line = ml_get(lnum - 1);
6017 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
6021 line = s = ml_get(lnum);
6022 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
6024 if (cin_iscomment(s)) /* ignore comments */
6025 s = cin_skipcomment(s);
6032 s = skipwhite(s + 1);
6036 if (*s == '"') /* nice alignment for continued strings */
6040 fp.col = (colnr_T)(s - line);
6041 getvcol(curwin, &fp, &col, NULL, NULL);
6046 * Recognize a preprocessor statement: Any line that starts with '#'.
6049 cin_ispreproc(char_u *s)
6051 if (*skipwhite(s) == '#')
6057 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
6058 * continuation line of a preprocessor statement. Decrease "*lnump" to the
6059 * start and return the line in "*pp".
6060 * Put the amount of indent in "*amount".
6063 cin_ispreproc_cont(char_u **pp, linenr_T *lnump, int *amount)
6066 linenr_T lnum = *lnump;
6068 int candidate_amount = *amount;
6070 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
6071 candidate_amount = get_indent_lnum(lnum);
6075 if (cin_ispreproc(line))
6083 line = ml_get(--lnum);
6084 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
6089 *pp = ml_get(*lnump);
6091 *amount = candidate_amount;
6096 * Recognize the start of a C or C++ comment.
6099 cin_iscomment(char_u *p)
6101 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
6105 * Recognize the start of a "//" comment.
6108 cin_islinecomment(char_u *p)
6110 return (p[0] == '/' && p[1] == '/');
6114 * Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
6116 * Don't consider "} else" a terminated line.
6117 * If a line begins with an "else", only consider it terminated if no unmatched
6118 * opening braces follow (handle "else { foo();" correctly).
6119 * Return the character terminating the line (ending char's have precedence if
6120 * both apply in order to determine initializations).
6125 int incl_open, /* include '{' at the end as terminator */
6126 int incl_comma) /* recognize a trailing comma */
6128 char_u found_start = 0;
6129 unsigned n_open = 0;
6130 int is_else = FALSE;
6132 s = cin_skipcomment(s);
6134 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
6138 is_else = cin_iselse(s);
6142 /* skip over comments, "" strings and 'c'haracters */
6143 s = skip_string(cin_skipcomment(s));
6144 if (*s == '}' && n_open > 0)
6146 if ((!is_else || n_open == 0)
6147 && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
6148 && cin_nocode(s + 1))
6152 if (incl_open && cin_nocode(s + 1))
6165 * Recognize the basic picture of a function declaration -- it needs to
6166 * have an open paren somewhere and a close paren at the end of the line and
6167 * no semicolons anywhere.
6168 * When a line ends in a comma we continue looking in the next line.
6169 * "sp" points to a string with the line. When looking at other lines it must
6170 * be restored to the line. When it's NULL fetch lines here.
6171 * "first_lnum" is where we start looking.
6172 * "min_lnum" is the line before which we will not be looking.
6177 linenr_T first_lnum,
6181 linenr_T lnum = first_lnum;
6182 linenr_T save_lnum = curwin->w_cursor.lnum;
6185 int just_started = TRUE;
6192 curwin->w_cursor.lnum = lnum;
6193 if (find_last_paren(s, '(', ')')
6194 && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
6196 lnum = trypos->lnum;
6197 if (lnum < min_lnum)
6199 curwin->w_cursor.lnum = save_lnum;
6205 curwin->w_cursor.lnum = save_lnum;
6207 /* Ignore line starting with #. */
6208 if (cin_ispreproc(s))
6211 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
6213 if (cin_iscomment(s)) /* ignore comments */
6214 s = cin_skipcomment(s);
6217 if (*(s + 1) == ':')
6220 /* To avoid a mistake in the following situation:
6221 * A::A(int a, int b)
6222 * : a(0) // <--not a function decl
6232 return FALSE; /* ';', ' or " before any () or no '(' */
6234 while (*s && *s != ';' && *s != '\'' && *s != '"')
6236 if (*s == ')' && cin_nocode(s + 1))
6238 /* ')' at the end: may have found a match
6239 * Check for he previous line not to end in a backslash:
6240 * #if defined(x) && \
6243 lnum = first_lnum - 1;
6245 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
6249 if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s))
6251 int comma = (*s == ',');
6253 /* ',' at the end: continue looking in the next line.
6254 * At the end: check for ',' in the next line, for this style:
6259 if (lnum >= curbuf->b_ml.ml_line_count)
6262 if (!cin_ispreproc(s))
6265 if (lnum >= curbuf->b_ml.ml_line_count)
6267 /* Require a comma at end of the line or a comma or ')' at the
6268 * start of next line. */
6270 if (!just_started && (!comma && *s != ',' && *s != ')'))
6272 just_started = FALSE;
6274 else if (cin_iscomment(s)) /* ignore comments */
6275 s = cin_skipcomment(s);
6279 just_started = FALSE;
6284 if (lnum != first_lnum && sp != NULL)
6285 *sp = ml_get(first_lnum);
6293 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
6300 if (*p == '}') /* accept "} else" */
6301 p = cin_skipcomment(p + 1);
6302 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
6308 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
6312 * Check if this is a "while" that should have a matching "do".
6313 * We only accept a "while (condition) ;", with only white space between the
6314 * ')' and ';'. The condition may be spread over several lines.
6317 cin_iswhileofdo (char_u *p, linenr_T lnum) /* XXX */
6323 p = cin_skipcomment(p);
6324 if (*p == '}') /* accept "} while (cond);" */
6325 p = cin_skipcomment(p + 1);
6326 if (cin_starts_with(p, "while"))
6328 cursor_save = curwin->w_cursor;
6329 curwin->w_cursor.lnum = lnum;
6330 curwin->w_cursor.col = 0;
6331 p = ml_get_curline();
6332 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
6335 ++curwin->w_cursor.col;
6337 if ((trypos = findmatchlimit(NULL, 0, 0,
6338 curbuf->b_ind_maxparen)) != NULL
6339 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
6341 curwin->w_cursor = cursor_save;
6347 * Check whether in "p" there is an "if", "for" or "while" before "*poffset".
6348 * Return 0 if there is none.
6349 * Otherwise return !0 and update "*poffset" to point to the place where the
6353 cin_is_if_for_while_before_offset(char_u *line, int *poffset)
6355 int offset = *poffset;
6359 while (offset > 2 && VIM_ISWHITE(line[offset]))
6363 if (!STRNCMP(line + offset, "if", 2))
6369 if (!STRNCMP(line + offset, "for", 3))
6375 if (!STRNCMP(line + offset, "while", 5))
6382 if (!offset || !vim_isIDc(line[offset - 1]))
6391 * Return TRUE if we are at the end of a do-while.
6396 * Adjust the cursor to the line with "while".
6399 cin_iswhileofdo_end(int terminated)
6407 if (terminated != ';') /* there must be a ';' at the end */
6410 p = line = ml_get_curline();
6413 p = cin_skipcomment(p);
6416 s = skipwhite(p + 1);
6417 if (*s == ';' && cin_nocode(s + 1))
6419 /* Found ");" at end of the line, now check there is "while"
6420 * before the matching '('. XXX */
6421 i = (int)(p - line);
6422 curwin->w_cursor.col = i;
6423 trypos = find_match_paren(curbuf->b_ind_maxparen);
6426 s = cin_skipcomment(ml_get(trypos->lnum));
6427 if (*s == '}') /* accept "} while (cond);" */
6428 s = cin_skipcomment(s + 1);
6429 if (cin_starts_with(s, "while"))
6431 curwin->w_cursor.lnum = trypos->lnum;
6436 /* Searching may have made "line" invalid, get it again. */
6437 line = ml_get_curline();
6448 cin_isbreak(char_u *p)
6450 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
6454 * Find the position of a C++ base-class declaration or
6455 * constructor-initialization. eg:
6458 * baseClass <-- here
6459 * class MyClass : public baseClass,
6460 * anotherBaseClass <-- here (should probably lineup ??)
6461 * MyClass::MyClass(...) :
6462 * baseClass(...) <-- here (constructor-initialization)
6464 * This is a lot of guessing. Watch out for "cond ? func() : foo".
6467 cin_is_cpp_baseclass(
6468 cpp_baseclass_cache_T *cached) /* input and output */
6470 lpos_T *pos = &cached->lpos; /* find position */
6472 int class_or_struct, lookfor_ctor_init, cpp_base_class;
6473 linenr_T lnum = curwin->w_cursor.lnum;
6474 char_u *line = ml_get_curline();
6476 if (pos->lnum <= lnum)
6477 return cached->found; /* Use the cached result */
6481 s = skipwhite(line);
6482 if (*s == '#') /* skip #define FOO x ? (x) : x */
6484 s = cin_skipcomment(s);
6488 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6490 /* Search for a line starting with '#', empty, ending in ';' or containing
6491 * '{' or '}' and start below it. This handles the following situations:
6498 * Foo::Foo (int one, int two)
6505 line = ml_get(lnum - 1);
6506 s = skipwhite(line);
6507 if (*s == '#' || *s == NUL)
6511 s = cin_skipcomment(s);
6512 if (*s == '{' || *s == '}'
6513 || (*s == ';' && cin_nocode(s + 1)))
6524 line = ml_get(lnum);
6530 if (lnum == curwin->w_cursor.lnum)
6532 /* Continue in the cursor line. */
6533 line = ml_get(++lnum);
6538 /* don't recognize "case (foo):" as a baseclass */
6539 if (cin_iscase(s, FALSE))
6541 s = cin_skipcomment(line);
6546 if (s[0] == '"' || (s[0] == 'R' && s[1] == '"'))
6547 s = skip_string(s) + 1;
6548 else if (s[0] == ':')
6552 /* skip double colon. It can't be a constructor
6553 * initialization any more */
6554 lookfor_ctor_init = FALSE;
6555 s = cin_skipcomment(s + 2);
6557 else if (lookfor_ctor_init || class_or_struct)
6559 /* we have something found, that looks like the start of
6560 * cpp-base-class-declaration or constructor-initialization */
6561 cpp_base_class = TRUE;
6562 lookfor_ctor_init = class_or_struct = FALSE;
6564 s = cin_skipcomment(s + 1);
6567 s = cin_skipcomment(s + 1);
6569 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
6570 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
6572 class_or_struct = TRUE;
6573 lookfor_ctor_init = FALSE;
6576 s = cin_skipcomment(s + 5);
6578 s = cin_skipcomment(s + 6);
6582 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
6584 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
6586 else if (s[0] == ')')
6588 /* Constructor-initialization is assumed if we come across
6589 * something like "):" */
6590 class_or_struct = FALSE;
6591 lookfor_ctor_init = TRUE;
6593 else if (s[0] == '?')
6595 /* Avoid seeing '() :' after '?' as constructor init. */
6598 else if (!vim_isIDc(s[0]))
6600 /* if it is not an identifier, we are wrong */
6601 class_or_struct = FALSE;
6602 lookfor_ctor_init = FALSE;
6604 else if (pos->col == 0)
6606 /* it can't be a constructor-initialization any more */
6607 lookfor_ctor_init = FALSE;
6609 /* the first statement starts here: lineup with this one... */
6611 pos->col = (colnr_T)(s - line);
6614 /* When the line ends in a comma don't align with it. */
6615 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
6618 s = cin_skipcomment(s + 1);
6622 cached->found = cpp_base_class;
6625 return cpp_base_class;
6629 get_baseclass_amount(int col)
6637 amount = get_indent();
6638 if (find_last_paren(ml_get_curline(), '(', ')')
6639 && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
6640 amount = get_indent_lnum(trypos->lnum); /* XXX */
6641 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
6642 amount += curbuf->b_ind_cpp_baseclass;
6646 curwin->w_cursor.col = col;
6647 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
6650 if (amount < curbuf->b_ind_cpp_baseclass)
6651 amount = curbuf->b_ind_cpp_baseclass;
6656 * Return TRUE if string "s" ends with the string "find", possibly followed by
6657 * white space and comments. Skip strings and comments.
6658 * Ignore "ignore" after "find" if it's not NULL.
6661 cin_ends_in(char_u *s, char_u *find, char_u *ignore)
6665 int len = (int)STRLEN(find);
6669 p = cin_skipcomment(p);
6670 if (STRNCMP(p, find, len) == 0)
6672 r = skipwhite(p + len);
6673 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
6674 r = skipwhite(r + STRLEN(ignore));
6685 * Return TRUE when "s" starts with "word" and then a non-ID character.
6688 cin_starts_with(char_u *s, char *word)
6690 int l = (int)STRLEN(word);
6692 return (STRNCMP(s, word, l) == 0 && !vim_isIDc(s[l]));
6696 * Skip strings, chars and comments until at or past "trypos".
6697 * Return the column found.
6700 cin_skip2pos(pos_T *trypos)
6706 p = line = ml_get(trypos->lnum);
6707 while (*p && (colnr_T)(p - line) < trypos->col)
6709 if (cin_iscomment(p))
6710 p = cin_skipcomment(p);
6713 new_p = skip_string(p);
6720 return (int)(p - line);
6724 * Find the '{' at the start of the block we are in.
6725 * Return NULL if no match found.
6726 * Ignore a '{' that is in a comment, makes indenting the next three lines
6733 find_start_brace(void) /* XXX */
6738 static pos_T pos_copy;
6740 cursor_save = curwin->w_cursor;
6741 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6743 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6745 curwin->w_cursor = *trypos;
6747 /* ignore the { if it's in a // or / * * / comment */
6748 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6749 && (pos = ind_find_start_CORS()) == NULL) /* XXX */
6752 curwin->w_cursor.lnum = pos->lnum;
6754 curwin->w_cursor = cursor_save;
6759 * Find the matching '(', ignoring it if it is in a comment.
6760 * Return NULL if no match found.
6763 find_match_paren(int ind_maxparen) /* XXX */
6765 return find_match_char('(', ind_maxparen);
6769 find_match_char (int c, int ind_maxparen) /* XXX */
6773 static pos_T pos_copy;
6776 cursor_save = curwin->w_cursor;
6777 ind_maxp_wk = ind_maxparen;
6779 if ((trypos = findmatchlimit(NULL, c, 0, ind_maxp_wk)) != NULL)
6781 /* check if the ( is in a // comment */
6782 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6784 ind_maxp_wk = ind_maxparen - (int)(cursor_save.lnum - trypos->lnum);
6785 if (ind_maxp_wk > 0)
6787 curwin->w_cursor = *trypos;
6788 curwin->w_cursor.col = 0; /* XXX */
6797 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6799 curwin->w_cursor = *trypos;
6800 if ((trypos_wk = ind_find_start_CORS()) != NULL) /* XXX */
6802 ind_maxp_wk = ind_maxparen - (int)(cursor_save.lnum
6804 if (ind_maxp_wk > 0)
6806 curwin->w_cursor = *trypos_wk;
6813 curwin->w_cursor = cursor_save;
6818 * Find the matching '(', ignoring it if it is in a comment or before an
6820 * Return NULL if no match found.
6823 find_match_paren_after_brace (int ind_maxparen) /* XXX */
6825 pos_T *trypos = find_match_paren(ind_maxparen);
6829 pos_T *tryposBrace = find_start_brace();
6831 /* If both an unmatched '(' and '{' is found. Ignore the '('
6832 * position if the '{' is further down. */
6833 if (tryposBrace != NULL
6834 && (trypos->lnum != tryposBrace->lnum
6835 ? trypos->lnum < tryposBrace->lnum
6836 : trypos->col < tryposBrace->col))
6843 * Return ind_maxparen corrected for the difference in line number between the
6844 * cursor position and "startpos". This makes sure that searching for a
6845 * matching paren above the cursor line doesn't find a match because of
6846 * looking a few lines further.
6849 corr_ind_maxparen(pos_T *startpos)
6851 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6853 if (n > 0 && n < curbuf->b_ind_maxparen / 2)
6854 return curbuf->b_ind_maxparen - (int)n;
6855 return curbuf->b_ind_maxparen;
6859 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
6860 * line "l". "l" must point to the start of the line.
6863 find_last_paren(char_u *l, int start, int end)
6869 curwin->w_cursor.col = 0; /* default is start of line */
6871 for (i = 0; l[i] != NUL; i++)
6873 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6874 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6877 else if (l[i] == end)
6883 curwin->w_cursor.col = i;
6892 * Parse 'cinoptions' and set the values in "curbuf".
6893 * Must be called when 'cinoptions', 'shiftwidth' and/or 'tabstop' changes.
6896 parse_cino(buf_T *buf)
6904 int sw = (int)get_sw_value(buf);
6907 * Set the default values.
6909 /* Spaces from a block's opening brace the prevailing indent for that
6910 * block should be. */
6911 buf->b_ind_level = sw;
6913 /* Spaces from the edge of the line an open brace that's at the end of a
6914 * line is imagined to be. */
6915 buf->b_ind_open_imag = 0;
6917 /* Spaces from the prevailing indent for a line that is not preceded by
6918 * an opening brace. */
6919 buf->b_ind_no_brace = 0;
6921 /* Column where the first { of a function should be located }. */
6922 buf->b_ind_first_open = 0;
6924 /* Spaces from the prevailing indent a leftmost open brace should be
6926 buf->b_ind_open_extra = 0;
6928 /* Spaces from the matching open brace (real location for one at the left
6929 * edge; imaginary location from one that ends a line) the matching close
6930 * brace should be located. */
6931 buf->b_ind_close_extra = 0;
6933 /* Spaces from the edge of the line an open brace sitting in the leftmost
6934 * column is imagined to be. */
6935 buf->b_ind_open_left_imag = 0;
6937 /* Spaces jump labels should be shifted to the left if N is non-negative,
6938 * otherwise the jump label will be put to column 1. */
6939 buf->b_ind_jump_label = -1;
6941 /* Spaces from the switch() indent a "case xx" label should be located. */
6942 buf->b_ind_case = sw;
6944 /* Spaces from the "case xx:" code after a switch() should be located. */
6945 buf->b_ind_case_code = sw;
6947 /* Lineup break at end of case in switch() with case label. */
6948 buf->b_ind_case_break = 0;
6950 /* Spaces from the class declaration indent a scope declaration label
6951 * should be located. */
6952 buf->b_ind_scopedecl = sw;
6954 /* Spaces from the scope declaration label code should be located. */
6955 buf->b_ind_scopedecl_code = sw;
6957 /* Amount K&R-style parameters should be indented. */
6958 buf->b_ind_param = sw;
6960 /* Amount a function type spec should be indented. */
6961 buf->b_ind_func_type = sw;
6963 /* Amount a cpp base class declaration or constructor initialization
6964 * should be indented. */
6965 buf->b_ind_cpp_baseclass = sw;
6967 /* additional spaces beyond the prevailing indent a continuation line
6968 * should be located. */
6969 buf->b_ind_continuation = sw;
6971 /* Spaces from the indent of the line with an unclosed parentheses. */
6972 buf->b_ind_unclosed = sw * 2;
6974 /* Spaces from the indent of the line with an unclosed parentheses, which
6975 * itself is also unclosed. */
6976 buf->b_ind_unclosed2 = sw;
6978 /* Suppress ignoring spaces from the indent of a line starting with an
6979 * unclosed parentheses. */
6980 buf->b_ind_unclosed_noignore = 0;
6982 /* If the opening paren is the last nonwhite character on the line, and
6983 * b_ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6984 * context (for very long lines). */
6985 buf->b_ind_unclosed_wrapped = 0;
6987 /* Suppress ignoring white space when lining up with the character after
6988 * an unclosed parentheses. */
6989 buf->b_ind_unclosed_whiteok = 0;
6991 /* Indent a closing parentheses under the line start of the matching
6992 * opening parentheses. */
6993 buf->b_ind_matching_paren = 0;
6995 /* Indent a closing parentheses under the previous line. */
6996 buf->b_ind_paren_prev = 0;
6998 /* Extra indent for comments. */
6999 buf->b_ind_comment = 0;
7001 /* Spaces from the comment opener when there is nothing after it. */
7002 buf->b_ind_in_comment = 3;
7004 /* Boolean: if non-zero, use b_ind_in_comment even if there is something
7005 * after the comment opener. */
7006 buf->b_ind_in_comment2 = 0;
7008 /* Max lines to search for an open paren. */
7009 buf->b_ind_maxparen = 20;
7011 /* Max lines to search for an open comment. */
7012 buf->b_ind_maxcomment = 70;
7014 /* Handle braces for java code. */
7015 buf->b_ind_java = 0;
7017 /* Not to confuse JS object properties with labels. */
7020 /* Handle blocked cases correctly. */
7021 buf->b_ind_keep_case_label = 0;
7023 /* Handle C++ namespace. */
7024 buf->b_ind_cpp_namespace = 0;
7026 /* Handle continuation lines containing conditions of if(), for() and
7028 buf->b_ind_if_for_while = 0;
7030 /* indentation for # comments */
7031 buf->b_ind_hash_comment = 0;
7033 /* Handle C++ extern "C" or "C++" */
7034 buf->b_ind_cpp_extern_c = 0;
7036 for (p = buf->b_p_cino; *p; )
7041 digits = p; /* remember where the digits start */
7044 if (*p == '.') /* ".5s" means a fraction */
7046 fraction = atol((char *)++p);
7047 while (VIM_ISDIGIT(*p))
7056 if (*p == 's') /* "2s" means two times 'shiftwidth' */
7059 n = sw; /* just "s" is one 'shiftwidth' */
7064 n += (sw * fraction + divider / 2) / divider;
7071 /* When adding an entry here, also update the default 'cinoptions' in
7072 * doc/indent.txt, and add explanation for it! */
7075 case '>': buf->b_ind_level = n; break;
7076 case 'e': buf->b_ind_open_imag = n; break;
7077 case 'n': buf->b_ind_no_brace = n; break;
7078 case 'f': buf->b_ind_first_open = n; break;
7079 case '{': buf->b_ind_open_extra = n; break;
7080 case '}': buf->b_ind_close_extra = n; break;
7081 case '^': buf->b_ind_open_left_imag = n; break;
7082 case 'L': buf->b_ind_jump_label = n; break;
7083 case ':': buf->b_ind_case = n; break;
7084 case '=': buf->b_ind_case_code = n; break;
7085 case 'b': buf->b_ind_case_break = n; break;
7086 case 'p': buf->b_ind_param = n; break;
7087 case 't': buf->b_ind_func_type = n; break;
7088 case '/': buf->b_ind_comment = n; break;
7089 case 'c': buf->b_ind_in_comment = n; break;
7090 case 'C': buf->b_ind_in_comment2 = n; break;
7091 case 'i': buf->b_ind_cpp_baseclass = n; break;
7092 case '+': buf->b_ind_continuation = n; break;
7093 case '(': buf->b_ind_unclosed = n; break;
7094 case 'u': buf->b_ind_unclosed2 = n; break;
7095 case 'U': buf->b_ind_unclosed_noignore = n; break;
7096 case 'W': buf->b_ind_unclosed_wrapped = n; break;
7097 case 'w': buf->b_ind_unclosed_whiteok = n; break;
7098 case 'm': buf->b_ind_matching_paren = n; break;
7099 case 'M': buf->b_ind_paren_prev = n; break;
7100 case ')': buf->b_ind_maxparen = n; break;
7101 case '*': buf->b_ind_maxcomment = n; break;
7102 case 'g': buf->b_ind_scopedecl = n; break;
7103 case 'h': buf->b_ind_scopedecl_code = n; break;
7104 case 'j': buf->b_ind_java = n; break;
7105 case 'J': buf->b_ind_js = n; break;
7106 case 'l': buf->b_ind_keep_case_label = n; break;
7107 case '#': buf->b_ind_hash_comment = n; break;
7108 case 'N': buf->b_ind_cpp_namespace = n; break;
7109 case 'k': buf->b_ind_if_for_while = n; break;
7110 case 'E': buf->b_ind_cpp_extern_c = n; break;
7118 * Return the desired indent for C code.
7119 * Return -1 if the indent should be left alone (inside a raw string).
7127 int cur_amount = MAXCOL;
7133 pos_T *tryposBrace = NULL;
7135 pos_T our_paren_pos;
7138 #define BRACE_IN_COL0 1 /* '{' is in column 0 */
7139 #define BRACE_AT_START 2 /* '{' is at start of line */
7140 #define BRACE_AT_END 3 /* '{' is at end of line */
7146 #define LOOKFOR_INITIAL 0
7147 #define LOOKFOR_IF 1
7148 #define LOOKFOR_DO 2
7149 #define LOOKFOR_CASE 3
7150 #define LOOKFOR_ANY 4
7151 #define LOOKFOR_TERM 5
7152 #define LOOKFOR_UNTERM 6
7153 #define LOOKFOR_SCOPEDECL 7
7154 #define LOOKFOR_NOBREAK 8
7155 #define LOOKFOR_CPP_BASECLASS 9
7156 #define LOOKFOR_ENUM_OR_INIT 10
7157 #define LOOKFOR_JS_KEY 11
7158 #define LOOKFOR_COMMA 12
7165 int lookfor_cpp_namespace = FALSE;
7166 int cont_amount = 0; /* amount for continuation line */
7167 int original_line_islabel;
7168 int added_to_amount = 0;
7169 int js_cur_has_key = 0;
7170 cpp_baseclass_cache_T cache_cpp_baseclass = { FALSE, { MAXLNUM, 0 } };
7172 /* make a copy, value is changed below */
7173 int ind_continuation = curbuf->b_ind_continuation;
7175 /* remember where the cursor was when we started */
7176 cur_curpos = curwin->w_cursor;
7178 /* if we are at line 1 zero indent is fine, right? */
7179 if (cur_curpos.lnum == 1)
7182 /* Get a copy of the current contents of the line.
7183 * This is required, because only the most recent line obtained with
7184 * ml_get is valid! */
7185 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
7186 if (linecopy == NULL)
7190 * In insert mode and the cursor is on a ')' truncate the line at the
7191 * cursor position. We don't want to line up with the matching '(' when
7192 * inserting new stuff.
7193 * For unknown reasons the cursor might be past the end of the line, thus
7196 if ((State & INSERT)
7197 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
7198 && linecopy[curwin->w_cursor.col] == ')')
7199 linecopy[curwin->w_cursor.col] = NUL;
7201 theline = skipwhite(linecopy);
7203 /* move the cursor to the start of the line */
7205 curwin->w_cursor.col = 0;
7207 original_line_islabel = cin_islabel(); /* XXX */
7210 * If we are inside a raw string don't change the indent.
7211 * Ignore a raw string inside a comment.
7213 comment_pos = ind_find_start_comment();
7214 if (comment_pos != NULL)
7216 /* findmatchlimit() static pos is overwritten, make a copy */
7217 tryposCopy = *comment_pos;
7218 comment_pos = &tryposCopy;
7220 trypos = find_start_rawstring(curbuf->b_ind_maxcomment);
7221 if (trypos != NULL && (comment_pos == NULL
7222 || LT_POS(*trypos, *comment_pos)))
7229 * #defines and so on always go at the left when included in 'cinkeys'.
7231 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
7233 amount = curbuf->b_ind_hash_comment;
7238 * Is it a non-case label? Then that goes at the left margin too unless:
7240 * - 'L' item has a positive value.
7242 if (original_line_islabel && !curbuf->b_ind_js
7243 && curbuf->b_ind_jump_label < 0)
7250 * If we're inside a "//" comment and there is a "//" comment in a
7251 * previous line, lineup with that one.
7253 if (cin_islinecomment(theline)
7254 && (trypos = find_line_comment()) != NULL) /* XXX */
7256 /* find how indented the line beginning the comment is */
7257 getvcol(curwin, trypos, &col, NULL, NULL);
7263 * If we're inside a comment and not looking at the start of the
7264 * comment, try using the 'comments' option.
7266 if (!cin_iscomment(theline) && comment_pos != NULL) /* XXX */
7268 int lead_start_len = 2;
7269 int lead_middle_len = 1;
7270 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
7271 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
7272 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
7274 int start_align = 0;
7278 /* find how indented the line beginning the comment is */
7279 getvcol(curwin, comment_pos, &col, NULL, NULL);
7284 p = curbuf->b_p_com;
7291 while (*p != NUL && *p != ':')
7293 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
7295 else if (*p == COM_LEFT || *p == COM_RIGHT)
7297 else if (VIM_ISDIGIT(*p) || *p == '-')
7298 off = getdigits(&p);
7305 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
7306 if (what == COM_START)
7308 STRCPY(lead_start, lead_end);
7309 lead_start_len = (int)STRLEN(lead_start);
7311 start_align = align;
7313 else if (what == COM_MIDDLE)
7315 STRCPY(lead_middle, lead_end);
7316 lead_middle_len = (int)STRLEN(lead_middle);
7318 else if (what == COM_END)
7320 /* If our line starts with the middle comment string, line it
7321 * up with the comment opener per the 'comments' option. */
7322 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
7323 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
7326 if (curwin->w_cursor.lnum > 1)
7328 /* If the start comment string matches in the previous
7329 * line, use the indent of that line plus offset. If
7330 * the middle comment string matches in the previous
7331 * line, use the indent of that line. XXX */
7332 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
7333 if (STRNCMP(look, lead_start, lead_start_len) == 0)
7334 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7335 else if (STRNCMP(look, lead_middle,
7336 lead_middle_len) == 0)
7338 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7341 /* If the start comment string doesn't match with the
7342 * start of the comment, skip this entry. XXX */
7343 else if (STRNCMP(ml_get(comment_pos->lnum) + comment_pos->col,
7344 lead_start, lead_start_len) != 0)
7348 amount += start_off;
7349 else if (start_align == COM_RIGHT)
7350 amount += vim_strsize(lead_start)
7351 - vim_strsize(lead_middle);
7355 /* If our line starts with the end comment string, line it up
7356 * with the middle comment */
7357 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
7358 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
7360 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
7364 else if (align == COM_RIGHT)
7365 amount += vim_strsize(lead_start)
7366 - vim_strsize(lead_middle);
7373 /* If our line starts with an asterisk, line up with the
7374 * asterisk in the comment opener; otherwise, line up
7375 * with the first character of the comment text.
7379 else if (theline[0] == '*')
7384 * If we are more than one line away from the comment opener, take
7385 * the indent of the previous non-empty line. If 'cino' has "CO"
7386 * and we are just below the comment opener and there are any
7387 * white characters after it line up with the text after it;
7388 * otherwise, add the amount specified by "c" in 'cino'
7391 for (lnum = cur_curpos.lnum - 1; lnum > comment_pos->lnum; --lnum)
7393 if (linewhite(lnum)) /* skip blank lines */
7395 amount = get_indent_lnum(lnum); /* XXX */
7398 if (amount == -1) /* use the comment opener */
7400 if (!curbuf->b_ind_in_comment2)
7402 start = ml_get(comment_pos->lnum);
7403 look = start + comment_pos->col + 2; /* skip / and * */
7404 if (*look != NUL) /* if something after it */
7405 comment_pos->col = (colnr_T)(skipwhite(look) - start);
7407 getvcol(curwin, comment_pos, &col, NULL, NULL);
7409 if (curbuf->b_ind_in_comment2 || *look == NUL)
7410 amount += curbuf->b_ind_in_comment;
7417 * Are we looking at a ']' that has a match?
7419 if (*skipwhite(theline) == ']'
7420 && (trypos = find_match_char('[', curbuf->b_ind_maxparen)) != NULL)
7422 /* align with the line containing the '['. */
7423 amount = get_indent_lnum(trypos->lnum);
7428 * Are we inside parentheses or braces?
7430 if (((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL
7431 && curbuf->b_ind_java == 0)
7432 || (tryposBrace = find_start_brace()) != NULL
7435 if (trypos != NULL && tryposBrace != NULL)
7437 /* Both an unmatched '(' and '{' is found. Use the one which is
7438 * closer to the current cursor position, set the other to NULL. */
7439 if (trypos->lnum != tryposBrace->lnum
7440 ? trypos->lnum < tryposBrace->lnum
7441 : trypos->col < tryposBrace->col)
7450 * If the matching paren is more than one line away, use the indent of
7451 * a previous non-empty line that matches the same paren.
7453 if (theline[0] == ')' && curbuf->b_ind_paren_prev)
7455 /* Line up with the start of the matching paren line. */
7456 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
7461 our_paren_pos = *trypos;
7462 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
7464 l = skipwhite(ml_get(lnum));
7465 if (cin_nocode(l)) /* skip comment lines */
7467 if (cin_ispreproc_cont(&l, &lnum, &amount))
7468 continue; /* ignore #define, #if, etc. */
7469 curwin->w_cursor.lnum = lnum;
7471 /* Skip a comment or raw string. XXX */
7472 if ((trypos = ind_find_start_CORS()) != NULL)
7474 lnum = trypos->lnum + 1;
7479 if ((trypos = find_match_paren(
7480 corr_ind_maxparen(&cur_curpos))) != NULL
7481 && trypos->lnum == our_paren_pos.lnum
7482 && trypos->col == our_paren_pos.col)
7484 amount = get_indent_lnum(lnum); /* XXX */
7486 if (theline[0] == ')')
7488 if (our_paren_pos.lnum != lnum
7489 && cur_amount > amount)
7490 cur_amount = amount;
7499 * Line up with line where the matching paren is. XXX
7500 * If the line starts with a '(' or the indent for unclosed
7501 * parentheses is zero, line up with the unclosed parentheses.
7505 int ignore_paren_col = 0;
7506 int is_if_for_while = 0;
7508 if (curbuf->b_ind_if_for_while)
7510 /* Look for the outermost opening parenthesis on this line
7511 * and check whether it belongs to an "if", "for" or "while". */
7513 pos_T cursor_save = curwin->w_cursor;
7517 trypos = &our_paren_pos;
7519 outermost = *trypos;
7520 curwin->w_cursor.lnum = outermost.lnum;
7521 curwin->w_cursor.col = outermost.col;
7523 trypos = find_match_paren(curbuf->b_ind_maxparen);
7524 } while (trypos && trypos->lnum == outermost.lnum);
7526 curwin->w_cursor = cursor_save;
7528 line = ml_get(outermost.lnum);
7531 cin_is_if_for_while_before_offset(line, &outermost.col);
7534 amount = skip_label(our_paren_pos.lnum, &look);
7535 look = skipwhite(look);
7538 linenr_T save_lnum = curwin->w_cursor.lnum;
7542 /* Ignore a '(' in front of the line that has a match before
7543 * our matching '('. */
7544 curwin->w_cursor.lnum = our_paren_pos.lnum;
7545 line = ml_get_curline();
7546 look_col = (int)(look - line);
7547 curwin->w_cursor.col = look_col + 1;
7548 if ((trypos = findmatchlimit(NULL, ')', 0,
7549 curbuf->b_ind_maxparen))
7551 && trypos->lnum == our_paren_pos.lnum
7552 && trypos->col < our_paren_pos.col)
7553 ignore_paren_col = trypos->col + 1;
7555 curwin->w_cursor.lnum = save_lnum;
7556 look = ml_get(our_paren_pos.lnum) + look_col;
7558 if (theline[0] == ')' || (curbuf->b_ind_unclosed == 0
7559 && is_if_for_while == 0)
7560 || (!curbuf->b_ind_unclosed_noignore && *look == '('
7561 && ignore_paren_col == 0))
7564 * If we're looking at a close paren, line up right there;
7565 * otherwise, line up with the next (non-white) character.
7566 * When b_ind_unclosed_wrapped is set and the matching paren is
7567 * the last nonwhite character of the line, use either the
7568 * indent of the current line or the indentation of the next
7569 * outer paren and add b_ind_unclosed_wrapped (for very long
7572 if (theline[0] != ')')
7574 cur_amount = MAXCOL;
7575 l = ml_get(our_paren_pos.lnum);
7576 if (curbuf->b_ind_unclosed_wrapped
7577 && cin_ends_in(l, (char_u *)"(", NULL))
7579 /* look for opening unmatched paren, indent one level
7580 * for each additional level */
7582 for (col = 0; col < our_paren_pos.col; ++col)
7591 case '}': if (n > 1)
7597 our_paren_pos.col = 0;
7598 amount += n * curbuf->b_ind_unclosed_wrapped;
7600 else if (curbuf->b_ind_unclosed_whiteok)
7601 our_paren_pos.col++;
7604 col = our_paren_pos.col + 1;
7605 while (VIM_ISWHITE(l[col]))
7607 if (l[col] != NUL) /* In case of trailing space */
7608 our_paren_pos.col = col;
7610 our_paren_pos.col++;
7615 * Find how indented the paren is, or the character after it
7616 * if we did the above "if".
7618 if (our_paren_pos.col > 0)
7620 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
7621 if (cur_amount > (int)col)
7626 if (theline[0] == ')' && curbuf->b_ind_matching_paren)
7628 /* Line up with the start of the matching paren line. */
7630 else if ((curbuf->b_ind_unclosed == 0 && is_if_for_while == 0)
7631 || (!curbuf->b_ind_unclosed_noignore
7632 && *look == '(' && ignore_paren_col == 0))
7634 if (cur_amount != MAXCOL)
7635 amount = cur_amount;
7639 /* Add b_ind_unclosed2 for each '(' before our matching one,
7640 * but ignore (void) before the line (ignore_paren_col). */
7641 col = our_paren_pos.col;
7642 while ((int)our_paren_pos.col > ignore_paren_col)
7644 --our_paren_pos.col;
7645 switch (*ml_get_pos(&our_paren_pos))
7647 case '(': amount += curbuf->b_ind_unclosed2;
7648 col = our_paren_pos.col;
7650 case ')': amount -= curbuf->b_ind_unclosed2;
7656 /* Use b_ind_unclosed once, when the first '(' is not inside
7659 amount += curbuf->b_ind_unclosed;
7662 curwin->w_cursor.lnum = our_paren_pos.lnum;
7663 curwin->w_cursor.col = col;
7664 if (find_match_paren_after_brace(curbuf->b_ind_maxparen)
7666 amount += curbuf->b_ind_unclosed2;
7669 if (is_if_for_while)
7670 amount += curbuf->b_ind_if_for_while;
7672 amount += curbuf->b_ind_unclosed;
7676 * For a line starting with ')' use the minimum of the two
7677 * positions, to avoid giving it more indent than the previous
7679 * func_long_name( if (x
7681 * ) ^ not here ) ^ not here
7683 if (cur_amount < amount)
7684 amount = cur_amount;
7688 /* add extra indent for a comment */
7689 if (cin_iscomment(theline))
7690 amount += curbuf->b_ind_comment;
7695 * We are inside braces, there is a { before this line at the position
7696 * stored in tryposBrace.
7697 * Make a copy of tryposBrace, it may point to pos_copy inside
7698 * find_start_brace(), which may be changed somewhere.
7700 tryposCopy = *tryposBrace;
7701 tryposBrace = &tryposCopy;
7702 trypos = tryposBrace;
7703 ourscope = trypos->lnum;
7704 start = ml_get(ourscope);
7707 * Now figure out how indented the line is in general.
7708 * If the brace was at the start of the line, we use that;
7709 * otherwise, check out the indentation of the line as
7710 * a whole and then add the "imaginary indent" to that.
7712 look = skipwhite(start);
7715 getvcol(curwin, trypos, &col, NULL, NULL);
7718 start_brace = BRACE_IN_COL0;
7720 start_brace = BRACE_AT_START;
7724 /* That opening brace might have been on a continuation
7725 * line. if so, find the start of the line. */
7726 curwin->w_cursor.lnum = ourscope;
7728 /* Position the cursor over the rightmost paren, so that
7729 * matching it will take us back to the start of the line. */
7731 if (find_last_paren(start, '(', ')')
7732 && (trypos = find_match_paren(curbuf->b_ind_maxparen))
7734 lnum = trypos->lnum;
7736 /* It could have been something like
7737 * case 1: if (asdf &&
7741 if ((curbuf->b_ind_js || curbuf->b_ind_keep_case_label)
7742 && cin_iscase(skipwhite(ml_get_curline()), FALSE))
7743 amount = get_indent();
7744 else if (curbuf->b_ind_js)
7745 amount = get_indent_lnum(lnum);
7747 amount = skip_label(lnum, &l);
7749 start_brace = BRACE_AT_END;
7752 /* For Javascript check if the line starts with "key:". */
7753 if (curbuf->b_ind_js)
7754 js_cur_has_key = cin_has_js_key(theline);
7757 * If we're looking at a closing brace, that's where
7758 * we want to be. otherwise, add the amount of room
7759 * that an indent is supposed to be.
7761 if (theline[0] == '}')
7764 * they may want closing braces to line up with something
7765 * other than the open brace. indulge them, if so.
7767 amount += curbuf->b_ind_close_extra;
7772 * If we're looking at an "else", try to find an "if"
7774 * If we're looking at a "while", try to find a "do"
7777 lookfor = LOOKFOR_INITIAL;
7778 if (cin_iselse(theline))
7779 lookfor = LOOKFOR_IF;
7780 else if (cin_iswhileofdo(theline, cur_curpos.lnum)) /* XXX */
7781 lookfor = LOOKFOR_DO;
7782 if (lookfor != LOOKFOR_INITIAL)
7784 curwin->w_cursor.lnum = cur_curpos.lnum;
7785 if (find_match(lookfor, ourscope) == OK)
7787 amount = get_indent(); /* XXX */
7793 * We get here if we are not on an "while-of-do" or "else" (or
7794 * failed to find a matching "if").
7795 * Search backwards for something to line up with.
7796 * First set amount for when we don't find anything.
7800 * if the '{' is _really_ at the left margin, use the imaginary
7801 * location of a left-margin brace. Otherwise, correct the
7802 * location for b_ind_open_extra.
7805 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
7807 amount = curbuf->b_ind_open_left_imag;
7808 lookfor_cpp_namespace = TRUE;
7810 else if (start_brace == BRACE_AT_START &&
7811 lookfor_cpp_namespace) /* '{' is at start */
7814 lookfor_cpp_namespace = TRUE;
7818 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
7820 amount += curbuf->b_ind_open_imag;
7822 l = skipwhite(ml_get_curline());
7823 if (cin_is_cpp_namespace(l))
7824 amount += curbuf->b_ind_cpp_namespace;
7825 else if (cin_is_cpp_extern_c(l))
7826 amount += curbuf->b_ind_cpp_extern_c;
7830 /* Compensate for adding b_ind_open_extra later. */
7831 amount -= curbuf->b_ind_open_extra;
7837 lookfor_break = FALSE;
7839 if (cin_iscase(theline, FALSE)) /* it's a switch() label */
7841 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
7842 amount += curbuf->b_ind_case;
7844 else if (cin_isscopedecl(theline)) /* private:, ... */
7846 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
7847 amount += curbuf->b_ind_scopedecl;
7851 if (curbuf->b_ind_case_break && cin_isbreak(theline))
7853 lookfor_break = TRUE;
7855 lookfor = LOOKFOR_INITIAL;
7856 /* b_ind_level from start of block */
7857 amount += curbuf->b_ind_level;
7859 scope_amount = amount;
7863 * Search backwards. If we find something we recognize, line up
7866 * If we're looking at an open brace, indent
7867 * the usual amount relative to the conditional
7868 * that opens the block.
7870 curwin->w_cursor = cur_curpos;
7873 curwin->w_cursor.lnum--;
7874 curwin->w_cursor.col = 0;
7877 * If we went all the way back to the start of our scope, line
7880 if (curwin->w_cursor.lnum <= ourscope)
7882 /* We reached end of scope:
7883 * If looking for a enum or structure initialization
7885 * If it is an initializer (enum xxx or xxx =), then
7886 * don't add ind_continuation, otherwise it is a variable
7889 * here; <-- add ind_continuation
7891 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7893 if (curwin->w_cursor.lnum == 0
7894 || curwin->w_cursor.lnum
7895 < ourscope - curbuf->b_ind_maxparen)
7897 /* nothing found (abuse curbuf->b_ind_maxparen as
7898 * limit) assume terminated line (i.e. a variable
7899 * initialization) */
7900 if (cont_amount > 0)
7901 amount = cont_amount;
7902 else if (!curbuf->b_ind_js)
7903 amount += ind_continuation;
7907 l = ml_get_curline();
7910 * If we're in a comment or raw string now, skip to
7913 trypos = ind_find_start_CORS();
7916 curwin->w_cursor.lnum = trypos->lnum + 1;
7917 curwin->w_cursor.col = 0;
7922 * Skip preprocessor directives and blank lines.
7924 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum,
7931 terminated = cin_isterminated(l, FALSE, TRUE);
7934 * If we are at top level and the line looks like a
7935 * function declaration, we are done
7936 * (it's a variable declaration).
7938 if (start_brace != BRACE_IN_COL0
7939 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0))
7941 /* if the line is terminated with another ','
7942 * it is a continued variable initialization.
7943 * don't add extra indent.
7944 * TODO: does not work, if a function
7945 * declaration is split over multiple lines:
7946 * cin_isfuncdecl returns FALSE then.
7948 if (terminated == ',')
7951 /* if it es a enum declaration or an assignment,
7954 if (terminated != ';' && cin_isinit())
7957 /* nothing useful found */
7958 if (terminated == 0 || terminated == '{')
7962 if (terminated != ';')
7964 /* Skip parens and braces. Position the cursor
7965 * over the rightmost paren, so that matching it
7966 * will take us back to the start of the line.
7969 if (find_last_paren(l, '(', ')'))
7970 trypos = find_match_paren(
7971 curbuf->b_ind_maxparen);
7973 if (trypos == NULL && find_last_paren(l, '{', '}'))
7974 trypos = find_start_brace();
7978 curwin->w_cursor.lnum = trypos->lnum + 1;
7979 curwin->w_cursor.col = 0;
7984 /* it's a variable declaration, add indentation
7989 if (cont_amount > 0)
7990 amount = cont_amount;
7992 amount += ind_continuation;
7994 else if (lookfor == LOOKFOR_UNTERM)
7996 if (cont_amount > 0)
7997 amount = cont_amount;
7999 amount += ind_continuation;
8003 if (lookfor != LOOKFOR_TERM
8004 && lookfor != LOOKFOR_CPP_BASECLASS
8005 && lookfor != LOOKFOR_COMMA)
8007 amount = scope_amount;
8008 if (theline[0] == '{')
8010 amount += curbuf->b_ind_open_extra;
8011 added_to_amount = curbuf->b_ind_open_extra;
8015 if (lookfor_cpp_namespace)
8018 * Looking for C++ namespace, need to look further
8021 if (curwin->w_cursor.lnum == ourscope)
8024 if (curwin->w_cursor.lnum == 0
8025 || curwin->w_cursor.lnum
8026 < ourscope - FIND_NAMESPACE_LIM)
8029 l = ml_get_curline();
8031 /* If we're in a comment or raw string now, skip
8032 * to the start of it. */
8033 trypos = ind_find_start_CORS();
8036 curwin->w_cursor.lnum = trypos->lnum + 1;
8037 curwin->w_cursor.col = 0;
8041 /* Skip preprocessor directives and blank lines. */
8042 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum,
8046 /* Finally the actual check for "namespace". */
8047 if (cin_is_cpp_namespace(l))
8049 amount += curbuf->b_ind_cpp_namespace
8053 else if (cin_is_cpp_extern_c(l))
8055 amount += curbuf->b_ind_cpp_extern_c
8068 * If we're in a comment or raw string now, skip to the start
8071 if ((trypos = ind_find_start_CORS()) != NULL)
8073 curwin->w_cursor.lnum = trypos->lnum + 1;
8074 curwin->w_cursor.col = 0;
8078 l = ml_get_curline();
8081 * If this is a switch() label, may line up relative to that.
8082 * If this is a C++ scope declaration, do the same.
8084 iscase = cin_iscase(l, FALSE);
8085 if (iscase || cin_isscopedecl(l))
8087 /* we are only looking for cpp base class
8088 * declaration/initialization any longer */
8089 if (lookfor == LOOKFOR_CPP_BASECLASS)
8092 /* When looking for a "do" we are not interested in
8099 * c = 99 + <- this indent plus continuation
8102 if (lookfor == LOOKFOR_UNTERM
8103 || lookfor == LOOKFOR_ENUM_OR_INIT)
8105 if (cont_amount > 0)
8106 amount = cont_amount;
8108 amount += ind_continuation;
8113 * case xx: <- line up with this case
8117 if ( (iscase && lookfor == LOOKFOR_CASE)
8118 || (iscase && lookfor_break)
8119 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
8122 * Check that this case label is not for another
8125 if ((trypos = find_start_brace()) == NULL
8126 || trypos->lnum == ourscope)
8128 amount = get_indent(); /* XXX */
8134 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
8137 * case xx: if (cond) <- line up with this if
8142 * if (cond) <- line up with this line
8146 if (lookfor == LOOKFOR_TERM)
8156 * case xx: x = x + 1; <- line up with this x
8159 * case xx: if (cond) <- line up with this if
8165 l = after_label(ml_get_curline());
8166 if (l != NULL && cin_is_cinword(l))
8168 if (theline[0] == '{')
8169 amount += curbuf->b_ind_open_extra;
8171 amount += curbuf->b_ind_level
8172 + curbuf->b_ind_no_brace;
8178 * Try to get the indent of a statement before the switch
8179 * label. If nothing is found, line up relative to the
8181 * break; <- may line up with this line
8185 scope_amount = get_indent() + (iscase /* XXX */
8186 ? curbuf->b_ind_case_code
8187 : curbuf->b_ind_scopedecl_code);
8188 lookfor = curbuf->b_ind_case_break
8189 ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
8194 * Looking for a switch() label or C++ scope declaration,
8195 * ignore other lines, skip {}-blocks.
8197 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
8199 if (find_last_paren(l, '{', '}')
8200 && (trypos = find_start_brace()) != NULL)
8202 curwin->w_cursor.lnum = trypos->lnum + 1;
8203 curwin->w_cursor.col = 0;
8209 * Ignore jump labels with nothing after them.
8211 if (!curbuf->b_ind_js && cin_islabel())
8213 l = after_label(ml_get_curline());
8214 if (l == NULL || cin_nocode(l))
8219 * Ignore #defines, #if, etc.
8220 * Ignore comment and empty lines.
8221 * (need to get the line again, cin_islabel() may have
8224 l = ml_get_curline();
8225 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount)
8230 * Are we at the start of a cpp base class declaration or
8231 * constructor initialization?
8234 if (lookfor != LOOKFOR_TERM && curbuf->b_ind_cpp_baseclass > 0)
8236 n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
8237 l = ml_get_curline();
8241 if (lookfor == LOOKFOR_UNTERM)
8243 if (cont_amount > 0)
8244 amount = cont_amount;
8246 amount += ind_continuation;
8248 else if (theline[0] == '{')
8250 /* Need to find start of the declaration. */
8251 lookfor = LOOKFOR_UNTERM;
8252 ind_continuation = 0;
8257 amount = get_baseclass_amount(
8258 cache_cpp_baseclass.lpos.col);
8261 else if (lookfor == LOOKFOR_CPP_BASECLASS)
8263 /* only look, whether there is a cpp base class
8264 * declaration or initialization before the opening brace.
8266 if (cin_isterminated(l, TRUE, FALSE))
8273 * What happens next depends on the line being terminated.
8274 * If terminated with a ',' only consider it terminating if
8275 * there is another unterminated statement behind, eg:
8279 * Otherwise check whether it is a enumeration or structure
8280 * initialisation (not indented) or a variable declaration
8283 terminated = cin_isterminated(l, FALSE, TRUE);
8287 js_cur_has_key = 0; /* only check the first line */
8288 if (curbuf->b_ind_js && terminated == ',')
8290 /* For Javascript we might be inside an object:
8291 * key: something, <- align with this
8294 * key: something + <- align with this
8298 lookfor = LOOKFOR_JS_KEY;
8301 if (lookfor == LOOKFOR_JS_KEY && cin_has_js_key(l))
8303 amount = get_indent();
8306 if (lookfor == LOOKFOR_COMMA)
8308 if (tryposBrace != NULL && tryposBrace->lnum
8309 >= curwin->w_cursor.lnum)
8311 if (terminated == ',')
8312 /* line below current line is the one that starts a
8313 * (possibly broken) line ending in a comma. */
8317 amount = get_indent();
8318 if (curwin->w_cursor.lnum - 1 == ourscope)
8319 /* line above is start of the scope, thus current
8320 * line is the one that stars a (possibly broken)
8321 * line ending in a comma. */
8326 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
8327 && terminated == ','))
8329 if (lookfor != LOOKFOR_ENUM_OR_INIT &&
8330 (*skipwhite(l) == '[' || l[STRLEN(l) - 1] == '['))
8331 amount += ind_continuation;
8333 * if we're in the middle of a paren thing,
8334 * go back to the line that starts it so
8335 * we can get the right prevailing indent
8340 * Position the cursor over the rightmost paren, so that
8341 * matching it will take us back to the start of the line.
8342 * Ignore a match before the start of the block.
8344 (void)find_last_paren(l, '(', ')');
8345 trypos = find_match_paren(corr_ind_maxparen(&cur_curpos));
8346 if (trypos != NULL && (trypos->lnum < tryposBrace->lnum
8347 || (trypos->lnum == tryposBrace->lnum
8348 && trypos->col < tryposBrace->col)))
8352 * If we are looking for ',', we also look for matching
8355 if (trypos == NULL && terminated == ','
8356 && find_last_paren(l, '{', '}'))
8357 trypos = find_start_brace();
8362 * Check if we are on a case label now. This is
8364 * case xx: if ( asdf &&
8367 curwin->w_cursor = *trypos;
8368 l = ml_get_curline();
8369 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
8371 ++curwin->w_cursor.lnum;
8372 curwin->w_cursor.col = 0;
8378 * Skip over continuation lines to find the one to get the
8380 * char *usethis = "bla\
8384 if (terminated == ',')
8386 while (curwin->w_cursor.lnum > 1)
8388 l = ml_get(curwin->w_cursor.lnum - 1);
8389 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8391 --curwin->w_cursor.lnum;
8392 curwin->w_cursor.col = 0;
8397 * Get indent and pointer to text for current line,
8398 * ignoring any jump label. XXX
8400 if (curbuf->b_ind_js)
8401 cur_amount = get_indent();
8403 cur_amount = skip_label(curwin->w_cursor.lnum, &l);
8405 * If this is just above the line we are indenting, and it
8406 * starts with a '{', line it up with this line.
8411 if (terminated != ',' && lookfor != LOOKFOR_TERM
8412 && theline[0] == '{')
8414 amount = cur_amount;
8416 * Only add b_ind_open_extra when the current line
8417 * doesn't start with a '{', which must have a match
8418 * in the same line (scope is the same). Probably:
8422 if (*skipwhite(l) != '{')
8423 amount += curbuf->b_ind_open_extra;
8425 if (curbuf->b_ind_cpp_baseclass && !curbuf->b_ind_js)
8427 /* have to look back, whether it is a cpp base
8428 * class declaration or initialization */
8429 lookfor = LOOKFOR_CPP_BASECLASS;
8436 * Check if we are after an "if", "while", etc.
8437 * Also allow " } else".
8439 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
8442 * Found an unterminated line after an if (), line up
8443 * with the last one.
8448 if (lookfor == LOOKFOR_UNTERM
8449 || lookfor == LOOKFOR_ENUM_OR_INIT)
8451 if (cont_amount > 0)
8452 amount = cont_amount;
8454 amount += ind_continuation;
8459 * If this is just above the line we are indenting, we
8463 * Otherwise this indent can be used when the line
8464 * before this is terminated.
8471 amount = cur_amount;
8472 if (theline[0] == '{')
8473 amount += curbuf->b_ind_open_extra;
8474 if (lookfor != LOOKFOR_TERM)
8476 amount += curbuf->b_ind_level
8477 + curbuf->b_ind_no_brace;
8482 * Special trick: when expecting the while () after a
8483 * do, line up with the while()
8488 l = skipwhite(ml_get_curline());
8491 if (whilelevel == 0)
8497 * When searching for a terminated line, don't use the
8498 * one between the "if" and the matching "else".
8499 * Need to use the scope of this "else". XXX
8500 * If whilelevel != 0 continue looking for a "do {".
8502 if (cin_iselse(l) && whilelevel == 0)
8504 /* If we're looking at "} else", let's make sure we
8505 * find the opening brace of the enclosing scope,
8506 * not the one from "if () {". */
8508 curwin->w_cursor.col =
8509 (colnr_T)(l - ml_get_curline()) + 1;
8511 if ((trypos = find_start_brace()) == NULL
8512 || find_match(LOOKFOR_IF, trypos->lnum)
8519 * If we're below an unterminated line that is not an
8520 * "if" or something, we may line up with this line or
8521 * add something for a continuation line, depending on
8522 * the line before this one.
8527 * Found two unterminated lines on a row, line up with
8533 if (lookfor == LOOKFOR_UNTERM)
8535 /* When line ends in a comma add extra indent */
8536 if (terminated == ',')
8537 amount += ind_continuation;
8541 if (lookfor == LOOKFOR_ENUM_OR_INIT)
8543 /* Found two lines ending in ',', lineup with the
8544 * lowest one, but check for cpp base class
8545 * declaration/initialization, if it is an
8546 * opening brace or we are looking just for
8547 * enumerations/initializations. */
8548 if (terminated == ',')
8550 if (curbuf->b_ind_cpp_baseclass == 0)
8553 lookfor = LOOKFOR_CPP_BASECLASS;
8557 /* Ignore unterminated lines in between, but
8559 if (amount > cur_amount)
8560 amount = cur_amount;
8565 * Found first unterminated line on a row, may
8566 * line up with this line, remember its indent
8570 l = ml_get_curline();
8571 amount = cur_amount;
8574 if (terminated == ',' && (*skipwhite(l) == ']'
8575 || (n >=2 && l[n - 2] == ']')))
8579 * If previous line ends in ',', check whether we
8580 * are in an initialization or enum
8585 * or a normal possible continuation line.
8586 * but only, of no other statement has been found
8589 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
8591 if (curbuf->b_ind_js)
8593 /* Search for a line ending in a comma
8594 * and line up with the line below it
8595 * (could be the current line).
8597 * 1, <- line up here
8600 * 3 + <- line up here
8605 if (cin_iscomment(skipwhite(l)))
8607 lookfor = LOOKFOR_COMMA;
8608 trypos = find_match_char('[',
8609 curbuf->b_ind_maxparen);
8613 == curwin->w_cursor.lnum - 1)
8615 /* Current line is first inside
8616 * [], line up with it. */
8619 ourscope = trypos->lnum;
8624 lookfor = LOOKFOR_ENUM_OR_INIT;
8625 cont_amount = cin_first_id_amount();
8630 if (lookfor == LOOKFOR_INITIAL
8632 && l[STRLEN(l) - 1] == '\\')
8634 cont_amount = cin_get_equal_amount(
8635 curwin->w_cursor.lnum);
8636 if (lookfor != LOOKFOR_TERM
8637 && lookfor != LOOKFOR_JS_KEY
8638 && lookfor != LOOKFOR_COMMA)
8639 lookfor = LOOKFOR_UNTERM;
8646 * Check if we are after a while (cond);
8647 * If so: Ignore until the matching "do".
8649 else if (cin_iswhileofdo_end(terminated)) /* XXX */
8652 * Found an unterminated line after a while ();, line up
8653 * with the last one.
8655 * 100 + <- line up with this one
8658 if (lookfor == LOOKFOR_UNTERM
8659 || lookfor == LOOKFOR_ENUM_OR_INIT)
8661 if (cont_amount > 0)
8662 amount = cont_amount;
8664 amount += ind_continuation;
8668 if (whilelevel == 0)
8670 lookfor = LOOKFOR_TERM;
8671 amount = get_indent(); /* XXX */
8672 if (theline[0] == '{')
8673 amount += curbuf->b_ind_open_extra;
8679 * We are after a "normal" statement.
8680 * If we had another statement we can stop now and use the
8681 * indent of that other statement.
8682 * Otherwise the indent of the current statement may be used,
8683 * search backwards for the next "normal" statement.
8688 * Skip single break line, if before a switch label. It
8689 * may be lined up with the case label.
8691 if (lookfor == LOOKFOR_NOBREAK
8692 && cin_isbreak(skipwhite(ml_get_curline())))
8694 lookfor = LOOKFOR_ANY;
8699 * Handle "do {" line.
8703 l = cin_skipcomment(ml_get_curline());
8706 amount = get_indent(); /* XXX */
8713 * Found a terminated line above an unterminated line. Add
8714 * the amount for a continuation line.
8723 if (lookfor == LOOKFOR_UNTERM
8724 || lookfor == LOOKFOR_ENUM_OR_INIT)
8726 if (cont_amount > 0)
8727 amount = cont_amount;
8729 amount += ind_continuation;
8734 * Found a terminated line above a terminated line or "if"
8735 * etc. line. Use the amount of the line below us.
8738 * while (asdf) ->here;
8742 if (lookfor == LOOKFOR_TERM)
8744 if (!lookfor_break && whilelevel == 0)
8749 * First line above the one we're indenting is terminated.
8750 * To know what needs to be done look further backward for
8751 * a terminated line.
8756 * position the cursor over the rightmost paren, so
8757 * that matching it will take us back to the start of
8758 * the line. Helps for:
8764 l = ml_get_curline();
8765 if (find_last_paren(l, '(', ')')
8766 && (trypos = find_match_paren(
8767 curbuf->b_ind_maxparen)) != NULL)
8770 * Check if we are on a case label now. This is
8772 * case xx: if ( asdf &&
8775 curwin->w_cursor = *trypos;
8776 l = ml_get_curline();
8777 if (cin_iscase(l, FALSE) || cin_isscopedecl(l))
8779 ++curwin->w_cursor.lnum;
8780 curwin->w_cursor.col = 0;
8785 /* When aligning with the case statement, don't align
8786 * with a statement after it.
8787 * case 1: { <-- don't use this { position
8794 iscase = (curbuf->b_ind_keep_case_label
8795 && cin_iscase(l, FALSE));
8798 * Get indent and pointer to text for current line,
8799 * ignoring any jump label.
8801 amount = skip_label(curwin->w_cursor.lnum, &l);
8803 if (theline[0] == '{')
8804 amount += curbuf->b_ind_open_extra;
8805 /* See remark above: "Only add b_ind_open_extra.." */
8808 amount -= curbuf->b_ind_open_extra;
8809 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
8812 * When a terminated line starts with "else" skip to
8813 * the matching "if":
8816 * Need to use the scope of this "else". XXX
8817 * If whilelevel != 0 continue looking for a "do {".
8819 if (lookfor == LOOKFOR_TERM
8824 if ((trypos = find_start_brace()) == NULL
8825 || find_match(LOOKFOR_IF, trypos->lnum)
8832 * If we're at the end of a block, skip to the start of
8835 l = ml_get_curline();
8836 if (find_last_paren(l, '{', '}') /* XXX */
8837 && (trypos = find_start_brace()) != NULL)
8839 curwin->w_cursor = *trypos;
8840 /* if not "else {" check for terminated again */
8841 /* but skip block for "} else {" */
8842 l = cin_skipcomment(ml_get_curline());
8843 if (*l == '}' || !cin_iselse(l))
8845 ++curwin->w_cursor.lnum;
8846 curwin->w_cursor.col = 0;
8854 /* add extra indent for a comment */
8855 if (cin_iscomment(theline))
8856 amount += curbuf->b_ind_comment;
8858 /* subtract extra left-shift for jump labels */
8859 if (curbuf->b_ind_jump_label > 0 && original_line_islabel)
8860 amount -= curbuf->b_ind_jump_label;
8866 * ok -- we're not inside any sort of structure at all!
8868 * This means we're at the top level, and everything should
8869 * basically just match where the previous line is, except
8870 * for the lines immediately following a function declaration,
8871 * which are K&R-style parameters and need to be indented.
8873 * if our line starts with an open brace, forget about any
8874 * prevailing indent and make sure it looks like the start
8878 if (theline[0] == '{')
8880 amount = curbuf->b_ind_first_open;
8885 * If the NEXT line is a function declaration, the current
8886 * line needs to be indented as a function type spec.
8887 * Don't do this if the current line looks like a comment or if the
8888 * current line is terminated, ie. ends in ';', or if the current line
8889 * contains { or }: "void f() {\n if (1)"
8891 if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
8892 && !cin_nocode(theline)
8893 && vim_strchr(theline, '{') == NULL
8894 && vim_strchr(theline, '}') == NULL
8895 && !cin_ends_in(theline, (char_u *)":", NULL)
8896 && !cin_ends_in(theline, (char_u *)",", NULL)
8897 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1,
8898 cur_curpos.lnum + 1)
8899 && !cin_isterminated(theline, FALSE, TRUE))
8901 amount = curbuf->b_ind_func_type;
8905 /* search backwards until we find something we recognize */
8907 curwin->w_cursor = cur_curpos;
8908 while (curwin->w_cursor.lnum > 1)
8910 curwin->w_cursor.lnum--;
8911 curwin->w_cursor.col = 0;
8913 l = ml_get_curline();
8916 * If we're in a comment or raw string now, skip to the start
8919 if ((trypos = ind_find_start_CORS()) != NULL)
8921 curwin->w_cursor.lnum = trypos->lnum + 1;
8922 curwin->w_cursor.col = 0;
8927 * Are we at the start of a cpp base class declaration or
8928 * constructor initialization?
8931 if (curbuf->b_ind_cpp_baseclass != 0 && theline[0] != '{')
8933 n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
8934 l = ml_get_curline();
8939 amount = get_baseclass_amount(cache_cpp_baseclass.lpos.col);
8944 * Skip preprocessor directives and blank lines.
8946 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount))
8953 * If the previous line ends in ',', use one level of
8957 * do this before checking for '}' in case of eg.
8965 if (cin_ends_in(l, (char_u *)",", NULL)
8966 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
8968 /* take us back to opening paren */
8969 if (find_last_paren(l, '(', ')')
8970 && (trypos = find_match_paren(
8971 curbuf->b_ind_maxparen)) != NULL)
8972 curwin->w_cursor = *trypos;
8974 /* For a line ending in ',' that is a continuation line go
8975 * back to the first line with a backslash:
8980 while (n == 0 && curwin->w_cursor.lnum > 1)
8982 l = ml_get(curwin->w_cursor.lnum - 1);
8983 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
8985 --curwin->w_cursor.lnum;
8986 curwin->w_cursor.col = 0;
8989 amount = get_indent(); /* XXX */
8992 amount = cin_first_id_amount();
8994 amount = ind_continuation;
8999 * If the line looks like a function declaration, and we're
9000 * not in a comment, put it the left margin.
9002 if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0)) /* XXX */
9004 l = ml_get_curline();
9007 * Finding the closing '}' of a previous function. Put
9008 * current line at the left margin. For when 'cino' has "fs".
9010 if (*skipwhite(l) == '}')
9014 * If the previous line ends on '};' (maybe followed by
9015 * comments) align at column 0. For example:
9016 * char *string_array[] = { "foo",
9017 * / * x * / "b};ar" }; / * foobar * /
9019 if (cin_ends_in(l, (char_u *)"};", NULL))
9023 * If the previous line ends on '[' we are probably in an
9026 * 234, <- extra indent
9028 if (cin_ends_in(l, (char_u *)"[", NULL))
9030 amount = get_indent() + ind_continuation;
9035 * Find a line only has a semicolon that belongs to a previous
9036 * line ending in '}', e.g. before an #endif. Don't increase
9039 if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1))
9041 pos_T curpos_save = curwin->w_cursor;
9043 while (curwin->w_cursor.lnum > 1)
9045 look = ml_get(--curwin->w_cursor.lnum);
9046 if (!(cin_nocode(look) || cin_ispreproc_cont(
9047 &look, &curwin->w_cursor.lnum, &amount)))
9050 if (curwin->w_cursor.lnum > 0
9051 && cin_ends_in(look, (char_u *)"}", NULL))
9054 curwin->w_cursor = curpos_save;
9058 * If the PREVIOUS line is a function declaration, the current
9059 * line (and the ones that follow) needs to be indented as
9062 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0))
9064 amount = curbuf->b_ind_param;
9069 * If the previous line ends in ';' and the line before the
9070 * previous line ends in ',' or '\', ident to column zero:
9075 if (cin_ends_in(l, (char_u *)";", NULL))
9077 l = ml_get(curwin->w_cursor.lnum - 1);
9078 if (cin_ends_in(l, (char_u *)",", NULL)
9079 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
9081 l = ml_get_curline();
9085 * Doesn't look like anything interesting -- so just
9086 * use the indent of this line.
9088 * Position the cursor over the rightmost paren, so that
9089 * matching it will take us back to the start of the line.
9091 find_last_paren(l, '(', ')');
9093 if ((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL)
9094 curwin->w_cursor = *trypos;
9095 amount = get_indent(); /* XXX */
9099 /* add extra indent for a comment */
9100 if (cin_iscomment(theline))
9101 amount += curbuf->b_ind_comment;
9103 /* add extra indent if the previous line ended in a backslash:
9106 * char *foo = "asdf\
9109 if (cur_curpos.lnum > 1)
9111 l = ml_get(cur_curpos.lnum - 1);
9112 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
9114 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
9116 amount = cur_amount;
9117 else if (cur_amount == 0)
9118 amount += ind_continuation;
9127 /* put the cursor back where it belongs */
9128 curwin->w_cursor = cur_curpos;
9136 find_match(int lookfor, linenr_T ourscope)
9144 if (lookfor == LOOKFOR_IF)
9155 curwin->w_cursor.col = 0;
9157 while (curwin->w_cursor.lnum > ourscope + 1)
9159 curwin->w_cursor.lnum--;
9160 curwin->w_cursor.col = 0;
9162 look = cin_skipcomment(ml_get_curline());
9163 if (cin_iselse(look)
9165 || cin_isdo(look) /* XXX */
9166 || cin_iswhileofdo(look, curwin->w_cursor.lnum))
9169 * if we've gone outside the braces entirely,
9170 * we must be out of scope...
9172 theirscope = find_start_brace(); /* XXX */
9173 if (theirscope == NULL)
9177 * and if the brace enclosing this is further
9178 * back than the one enclosing the else, we're
9181 if (theirscope->lnum < ourscope)
9185 * and if they're enclosed in a *deeper* brace,
9186 * then we can ignore it because it's in a
9187 * different scope...
9189 if (theirscope->lnum > ourscope)
9193 * if it was an "else" (that's not an "else if")
9194 * then we need to go back to another if, so
9195 * increment elselevel
9197 look = cin_skipcomment(ml_get_curline());
9198 if (cin_iselse(look))
9200 mightbeif = cin_skipcomment(look + 4);
9201 if (!cin_isif(mightbeif))
9207 * if it was a "while" then we need to go back to
9208 * another "do", so increment whilelevel. XXX
9210 if (cin_iswhileofdo(look, curwin->w_cursor.lnum))
9216 /* If it's an "if" decrement elselevel */
9217 look = cin_skipcomment(ml_get_curline());
9222 * When looking for an "if" ignore "while"s that
9225 if (elselevel == 0 && lookfor == LOOKFOR_IF)
9229 /* If it's a "do" decrement whilelevel */
9234 * if we've used up all the elses, then
9235 * this must be the if that we want!
9236 * match the indent level of that if.
9238 if (elselevel <= 0 && whilelevel <= 0)
9247 # if defined(FEAT_EVAL) || defined(PROTO)
9249 * Get indent level from 'indentexpr'.
9252 get_expr_indent(void)
9257 colnr_T save_curswant;
9258 int save_set_curswant;
9260 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
9263 /* Save and restore cursor position and curswant, in case it was changed
9264 * via :normal commands */
9265 save_pos = curwin->w_cursor;
9266 save_curswant = curwin->w_curswant;
9267 save_set_curswant = curwin->w_set_curswant;
9268 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
9273 /* Need to make a copy, the 'indentexpr' option could be changed while
9275 inde_copy = vim_strsave(curbuf->b_p_inde);
9276 if (inde_copy != NULL)
9278 indent = (int)eval_to_number(inde_copy);
9279 vim_free(inde_copy);
9286 /* Restore the cursor position so that 'indentexpr' doesn't need to.
9287 * Pretend to be in Insert mode, allow cursor past end of line for "o"
9291 curwin->w_cursor = save_pos;
9292 curwin->w_curswant = save_curswant;
9293 curwin->w_set_curswant = save_set_curswant;
9297 /* If there is an error, just keep the current indent. */
9299 indent = get_indent();
9305 #endif /* FEAT_CINDENT */
9307 #if defined(FEAT_LISP) || defined(PROTO)
9309 static int lisp_match(char_u *p);
9312 lisp_match(char_u *p)
9316 char_u *word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords;
9318 while (*word != NUL)
9320 (void)copy_option_part(&word, buf, LSIZE, ",");
9321 len = (int)STRLEN(buf);
9322 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
9329 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
9330 * The incompatible newer method is quite a bit better at indenting
9331 * code in lisp-like languages than the traditional one; it's still
9332 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
9335 * Findmatch() should be adapted for lisp, also to make showmatch
9336 * work correctly: now (v5.3) it seems all C/C++ oriented:
9337 * - it does not recognize the #\( and #\) notations as character literals
9338 * - it doesn't know about comments starting with a semicolon
9339 * - it incorrectly interprets '(' as a character literal
9340 * All this messes up get_lisp_indent in some rare cases.
9341 * Update from Sergey Khorev:
9342 * I tried to fix the first two issues.
9345 get_lisp_indent(void)
9347 pos_T *pos, realpos, paren;
9352 int parencount, quotecount;
9355 /* Set vi_lisp to use the vi-compatible method */
9356 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
9358 realpos = curwin->w_cursor;
9359 curwin->w_cursor.col = 0;
9361 if ((pos = findmatch(NULL, '(')) == NULL)
9362 pos = findmatch(NULL, '[');
9366 pos = findmatch(NULL, '[');
9367 if (pos == NULL || LT_POSP(pos, &paren))
9372 /* Extra trick: Take the indent of the first previous non-white
9373 * line that is at the same () level. */
9377 while (--curwin->w_cursor.lnum >= pos->lnum)
9379 if (linewhite(curwin->w_cursor.lnum))
9381 for (that = ml_get_curline(); *that != NUL; ++that)
9385 while (*(that + 1) != NUL)
9391 if (*(that + 1) != NUL)
9395 if (*that == '"' && *(that + 1) != NUL)
9397 while (*++that && *that != '"')
9399 /* skipping escaped characters in the string */
9412 if (*that == '(' || *that == '[')
9414 else if (*that == ')' || *that == ']')
9417 if (parencount == 0)
9419 amount = get_indent();
9426 curwin->w_cursor.lnum = pos->lnum;
9427 curwin->w_cursor.col = pos->col;
9430 that = ml_get_curline();
9432 if (vi_lisp && get_indent() == 0)
9436 char_u *line = that;
9439 while (*that && col)
9441 amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);
9446 * Some keywords require "body" indenting rules (the
9447 * non-standard-lisp ones are Scheme special forms):
9449 * (let ((a 1)) instead (let ((a 1))
9453 if (!vi_lisp && (*that == '(' || *that == '[')
9454 && lisp_match(that + 1))
9462 while (VIM_ISWHITE(*that))
9464 amount += lbr_chartabsize(line, that, (colnr_T)amount);
9468 if (*that && *that != ';') /* not a comment line */
9470 /* test *that != '(' to accommodate first let/do
9471 * argument if it is more than one line */
9472 if (!vi_lisp && *that != '(' && *that != '[')
9482 && (*that < '0' || *that > '9')))
9485 && (!VIM_ISWHITE(*that)
9488 && (!((*that == '(' || *that == '[')
9494 quotecount = !quotecount;
9495 if ((*that == '(' || *that == '[')
9498 if ((*that == ')' || *that == ']')
9501 if (*that == '\\' && *(that+1) != NUL)
9502 amount += lbr_chartabsize_adv(
9503 line, &that, (colnr_T)amount);
9504 amount += lbr_chartabsize_adv(
9505 line, &that, (colnr_T)amount);
9508 while (VIM_ISWHITE(*that))
9510 amount += lbr_chartabsize(
9511 line, that, (colnr_T)amount);
9514 if (!*that || *that == ';')
9522 amount = 0; /* no matching '(' or '[' found, use zero indent */
9524 curwin->w_cursor = realpos;
9528 #endif /* FEAT_LISP */
9531 prepare_to_exit(void)
9533 #if defined(SIGHUP) && defined(SIG_IGN)
9534 /* Ignore SIGHUP, because a dropped connection causes a read error, which
9535 * makes Vim exit and then handling SIGHUP causes various reentrance
9537 signal(SIGHUP, SIG_IGN);
9544 out_trash(); /* trash any pending output */
9549 windgoto((int)Rows - 1, 0);
9552 * Switch terminal mode back now, so messages end up on the "normal"
9553 * screen (if there are two screens).
9555 settmode(TMODE_COOK);
9562 * Preserve files and exit.
9563 * When called IObuff must contain a message.
9564 * NOTE: This may be called from deathtrap() in a signal handler, avoid unsafe
9565 * functions, such as allocating memory.
9574 /* Setting this will prevent free() calls. That avoids calling free()
9575 * recursively when free() was invoked with a bad pointer. */
9576 really_exiting = TRUE;
9579 screen_start(); /* don't know where cursor is now */
9582 ml_close_notmod(); /* close all not-modified buffers */
9584 FOR_ALL_BUFFERS(buf)
9586 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
9588 OUT_STR("Vim: preserving files...\n");
9589 screen_start(); /* don't know where cursor is now */
9591 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
9596 ml_close_all(FALSE); /* close all memfiles, without deleting */
9598 OUT_STR("Vim: Finished.\n");
9604 * return TRUE if "fname" exists.
9607 vim_fexists(char_u *fname)
9611 if (mch_stat((char *)fname, &st))
9617 * Check for CTRL-C pressed, but only once in a while.
9618 * Should be used instead of ui_breakcheck() for functions that check for
9619 * each line in the file. Calling ui_breakcheck() each time takes too much
9620 * time, because it can be a system call.
9623 #ifndef BREAKCHECK_SKIP
9624 # ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
9625 # define BREAKCHECK_SKIP 200
9627 # define BREAKCHECK_SKIP 32
9631 static int breakcheck_count = 0;
9634 line_breakcheck(void)
9636 if (++breakcheck_count >= BREAKCHECK_SKIP)
9638 breakcheck_count = 0;
9644 * Like line_breakcheck() but check 10 times less often.
9647 fast_breakcheck(void)
9649 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
9651 breakcheck_count = 0;
9657 * Invoke expand_wildcards() for one pattern.
9658 * Expand items like "%:h" before the expansion.
9659 * Returns OK or FAIL.
9662 expand_wildcards_eval(
9663 char_u **pat, /* pointer to input pattern */
9664 int *num_file, /* resulting number of files */
9665 char_u ***file, /* array of resulting files */
9666 int flags) /* EW_DIR, etc. */
9669 char_u *eval_pat = NULL;
9670 char_u *exp_pat = *pat;
9671 char_u *ignored_msg;
9674 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
9677 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
9678 NULL, &ignored_msg, NULL);
9680 if (eval_pat != NULL)
9681 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
9684 if (exp_pat != NULL)
9685 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
9687 if (eval_pat != NULL)
9697 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
9699 * Returns OK or FAIL. When FAIL then "num_files" won't be set.
9703 int num_pat, /* number of input patterns */
9704 char_u **pat, /* array of input patterns */
9705 int *num_files, /* resulting number of files */
9706 char_u ***files, /* array of resulting files */
9707 int flags) /* EW_DIR, etc. */
9712 int non_suf_match; /* number without matching suffix */
9714 retval = gen_expand_wildcards(num_pat, pat, num_files, files, flags);
9716 /* When keeping all matches, return here */
9717 if ((flags & EW_KEEPALL) || retval == FAIL)
9722 * Remove names that match 'wildignore'.
9728 /* check all files in (*files)[] */
9729 for (i = 0; i < *num_files; ++i)
9731 ffname = FullName_save((*files)[i], FALSE);
9732 if (ffname == NULL) /* out of memory */
9735 vms_remove_version(ffname);
9737 if (match_file_list(p_wig, (*files)[i], ffname))
9739 /* remove this matching file from the list */
9740 vim_free((*files)[i]);
9741 for (j = i; j + 1 < *num_files; ++j)
9742 (*files)[j] = (*files)[j + 1];
9749 /* If the number of matches is now zero, we fail. */
9750 if (*num_files == 0)
9760 * Move the names where 'suffixes' match to the end.
9765 for (i = 0; i < *num_files; ++i)
9767 if (!match_suffix((*files)[i]))
9770 * Move the name without matching suffix to the front
9774 for (j = i; j > non_suf_match; --j)
9775 (*files)[j] = (*files)[j - 1];
9776 (*files)[non_suf_match++] = p;
9785 * Return TRUE if "fname" matches with an entry in 'suffixes'.
9788 match_suffix(char_u *fname)
9790 int fnamelen, setsuflen;
9792 #define MAXSUFLEN 30 /* maximum length of a file suffix */
9793 char_u suf_buf[MAXSUFLEN];
9795 fnamelen = (int)STRLEN(fname);
9797 for (setsuf = p_su; *setsuf; )
9799 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
9802 char_u *tail = gettail(fname);
9804 /* empty entry: match name without a '.' */
9805 if (vim_strchr(tail, '.') == NULL)
9813 if (fnamelen >= setsuflen
9814 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
9815 (size_t)setsuflen) == 0)
9820 return (setsuflen != 0);
9823 #if !defined(NO_EXPANDPATH) || defined(PROTO)
9825 # ifdef VIM_BACKTICK
9826 static int vim_backtick(char_u *p);
9827 static int expand_backtick(garray_T *gap, char_u *pat, int flags);
9830 # if defined(WIN3264)
9832 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
9833 * it's shared between these systems.
9838 # ifdef __BORLANDC__
9839 # define _cdecl _RTLENTRYF
9844 * comparison function for qsort in dos_expandpath()
9847 pstrcmp(const void *a, const void *b)
9849 return (pathcmp(*(char **)a, *(char **)b, -1));
9853 * Recursively expand one path component into all matching files and/or
9854 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9855 * Return the number of matches found.
9856 * "path" has backslashes before chars that are not to be expanded, starting
9857 * at "path[wildoff]".
9858 * Return the number of matches found.
9859 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
9866 int flags, /* EW_* flags */
9867 int didstar) /* expanded "**" once already */
9872 int start_len = gap->ga_len;
9874 regmatch_T regmatch;
9875 int starts_with_dot;
9878 int starstar = FALSE;
9879 static int stardepth = 0; /* depth for "**" expansion */
9881 HANDLE hFind = (HANDLE)0;
9883 WIN32_FIND_DATAW wfb;
9884 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
9889 /* Expanding "**" may take a long time, check for CTRL-C. */
9897 /* Make room for file name. When doing encoding conversion the actual
9898 * length may be quite a bit longer, thus use the maximum possible length. */
9899 buf = alloc((int)MAXPATHL);
9904 * Find the first part in the path name that contains a wildcard or a ~1.
9905 * Copy it into buf, including the preceding characters.
9911 while (*path_end != NUL)
9913 /* May ignore a wildcard that has a backslash before it; it will
9914 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9915 if (path_end >= path + wildoff && rem_backslash(path_end))
9917 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
9923 else if (path_end >= path + wildoff
9924 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
9929 len = (*mb_ptr2len)(path_end);
9930 STRNCPY(p, path_end, len);
9941 /* now we have one wildcard component between s and e */
9942 /* Remove backslashes between "wildoff" and the start of the wildcard
9944 for (p = buf + wildoff; p < s; ++p)
9945 if (rem_backslash(p))
9952 /* Check for "**" between "s" and "e". */
9953 for (p = s; p < e; ++p)
9954 if (p[0] == '*' && p[1] == '*')
9957 starts_with_dot = *s == '.';
9958 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9965 /* compile the regexp into a program */
9966 if (flags & (EW_NOERROR | EW_NOTWILD))
9968 regmatch.rm_ic = TRUE; /* Always ignore case */
9969 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9970 if (flags & (EW_NOERROR | EW_NOTWILD))
9974 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
9980 /* remember the pattern or file name being looked for */
9981 matchname = vim_strsave(s);
9983 /* If "**" is by itself, this is the first time we encounter it and more
9984 * is following then find matches without any directory. */
9985 if (!didstar && stardepth < 100 && starstar && e - s == 2
9986 && *path_end == '/')
9988 STRCPY(s, path_end + 1);
9990 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9994 /* Scan all files in the directory with "dir/ *.*" */
9997 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
9999 /* The active codepage differs from 'encoding'. Attempt using the
10000 * wide function. If it fails because it is not implemented fall back
10001 * to the non-wide version (for Windows 98) */
10002 wn = enc_to_utf16(buf, NULL);
10005 hFind = FindFirstFileW(wn, &wfb);
10006 if (hFind == INVALID_HANDLE_VALUE
10007 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
10017 hFind = FindFirstFile((LPCSTR)buf, &fb);
10018 ok = (hFind != INVALID_HANDLE_VALUE);
10024 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
10027 p = (char_u *)fb.cFileName;
10028 /* Ignore entries starting with a dot, unless when asked for. Accept
10029 * all entries found with "matchname". */
10030 if ((p[0] != '.' || starts_with_dot
10031 || ((flags & EW_DODOT)
10032 && p[1] != NUL && (p[1] != '.' || p[2] != NUL)))
10033 && (matchname == NULL
10034 || (regmatch.regprog != NULL
10035 && vim_regexec(®match, p, (colnr_T)0))
10036 || ((flags & EW_NOTWILD)
10037 && fnamencmp(path + (s - buf), p, e - s) == 0)))
10040 len = (int)STRLEN(buf);
10042 if (starstar && stardepth < 100)
10044 /* For "**" in the pattern first go deeper in the tree to
10046 STRCPY(buf + len, "/**");
10047 STRCPY(buf + len + 3, path_end);
10049 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
10053 STRCPY(buf + len, path_end);
10054 if (mch_has_exp_wildcard(path_end))
10056 /* need to expand another component of the path */
10057 /* remove backslashes for the remaining components only */
10058 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
10062 /* no more wildcards, check if there is a match */
10063 /* remove backslashes for the remaining components only */
10064 if (*path_end != 0)
10065 backslash_halve(buf + len + 1);
10066 if (mch_getperm(buf) >= 0) /* add existing file */
10067 addfile(gap, buf, flags);
10075 ok = FindNextFileW(hFind, &wfb);
10079 ok = FindNextFile(hFind, &fb);
10081 /* If no more matches and no match was used, try expanding the name
10082 * itself. Finds the long name of a short filename. */
10083 if (!ok && matchname != NULL && gap->ga_len == start_len)
10085 STRCPY(s, matchname);
10091 wn = enc_to_utf16(buf, NULL);
10093 hFind = FindFirstFileW(wn, &wfb);
10097 hFind = FindFirstFile((LPCSTR)buf, &fb);
10098 ok = (hFind != INVALID_HANDLE_VALUE);
10099 vim_free(matchname);
10109 vim_regfree(regmatch.regprog);
10110 vim_free(matchname);
10112 matches = gap->ga_len - start_len;
10114 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
10115 sizeof(char_u *), pstrcmp);
10123 int flags) /* EW_* flags */
10125 return dos_expandpath(gap, path, 0, flags, FALSE);
10127 # endif /* WIN3264 */
10129 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
10132 * Unix style wildcard expansion code.
10133 * It's here because it's used both for Unix and Mac.
10135 static int pstrcmp(const void *, const void *);
10138 pstrcmp(const void *a, const void *b)
10140 return (pathcmp(*(char **)a, *(char **)b, -1));
10144 * Recursively expand one path component into all matching files and/or
10145 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
10146 * "path" has backslashes before chars that are not to be expanded, starting
10147 * at "path + wildoff".
10148 * Return the number of matches found.
10149 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
10156 int flags, /* EW_* flags */
10157 int didstar) /* expanded "**" once already */
10162 int start_len = gap->ga_len;
10164 regmatch_T regmatch;
10165 int starts_with_dot;
10168 int starstar = FALSE;
10169 static int stardepth = 0; /* depth for "**" expansion */
10174 /* Expanding "**" may take a long time, check for CTRL-C. */
10182 /* make room for file name */
10183 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
10188 * Find the first part in the path name that contains a wildcard.
10189 * When EW_ICASE is set every letter is considered to be a wildcard.
10190 * Copy it into "buf", including the preceding characters.
10196 while (*path_end != NUL)
10198 /* May ignore a wildcard that has a backslash before it; it will
10199 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
10200 if (path_end >= path + wildoff && rem_backslash(path_end))
10201 *p++ = *path_end++;
10202 else if (*path_end == '/')
10208 else if (path_end >= path + wildoff
10209 && (vim_strchr((char_u *)"*?[{~$", *path_end) != NULL
10210 || (!p_fic && (flags & EW_ICASE)
10211 && isalpha(PTR2CHAR(path_end)))))
10216 len = (*mb_ptr2len)(path_end);
10217 STRNCPY(p, path_end, len);
10223 *p++ = *path_end++;
10228 /* Now we have one wildcard component between "s" and "e". */
10229 /* Remove backslashes between "wildoff" and the start of the wildcard
10231 for (p = buf + wildoff; p < s; ++p)
10232 if (rem_backslash(p))
10239 /* Check for "**" between "s" and "e". */
10240 for (p = s; p < e; ++p)
10241 if (p[0] == '*' && p[1] == '*')
10244 /* convert the file pattern to a regexp pattern */
10245 starts_with_dot = *s == '.';
10246 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
10253 /* compile the regexp into a program */
10254 if (flags & EW_ICASE)
10255 regmatch.rm_ic = TRUE; /* 'wildignorecase' set */
10257 regmatch.rm_ic = p_fic; /* ignore case when 'fileignorecase' is set */
10258 if (flags & (EW_NOERROR | EW_NOTWILD))
10260 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
10261 if (flags & (EW_NOERROR | EW_NOTWILD))
10265 if (regmatch.regprog == NULL && (flags & EW_NOTWILD) == 0)
10271 /* If "**" is by itself, this is the first time we encounter it and more
10272 * is following then find matches without any directory. */
10273 if (!didstar && stardepth < 100 && starstar && e - s == 2
10274 && *path_end == '/')
10276 STRCPY(s, path_end + 1);
10278 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
10282 /* open the directory for scanning */
10284 dirp = opendir(*buf == NUL ? "." : (char *)buf);
10286 /* Find all matching entries */
10291 dp = readdir(dirp);
10294 if ((dp->d_name[0] != '.' || starts_with_dot
10295 || ((flags & EW_DODOT)
10296 && dp->d_name[1] != NUL
10297 && (dp->d_name[1] != '.' || dp->d_name[2] != NUL)))
10298 && ((regmatch.regprog != NULL && vim_regexec(®match,
10299 (char_u *)dp->d_name, (colnr_T)0))
10300 || ((flags & EW_NOTWILD)
10301 && fnamencmp(path + (s - buf), dp->d_name, e - s) == 0)))
10303 STRCPY(s, dp->d_name);
10306 if (starstar && stardepth < 100)
10308 /* For "**" in the pattern first go deeper in the tree to
10310 STRCPY(buf + len, "/**");
10311 STRCPY(buf + len + 3, path_end);
10313 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
10317 STRCPY(buf + len, path_end);
10318 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
10320 /* need to expand another component of the path */
10321 /* remove backslashes for the remaining components only */
10322 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
10328 /* no more wildcards, check if there is a match */
10329 /* remove backslashes for the remaining components only */
10330 if (*path_end != NUL)
10331 backslash_halve(buf + len + 1);
10332 /* add existing file or symbolic link */
10333 if ((flags & EW_ALLLINKS) ? mch_lstat((char *)buf, &sb) >= 0
10334 : mch_getperm(buf) >= 0)
10336 #ifdef MACOS_CONVERT
10337 size_t precomp_len = STRLEN(buf)+1;
10338 char_u *precomp_buf =
10339 mac_precompose_path(buf, precomp_len, &precomp_len);
10343 mch_memmove(buf, precomp_buf, precomp_len);
10344 vim_free(precomp_buf);
10347 addfile(gap, buf, flags);
10357 vim_regfree(regmatch.regprog);
10359 matches = gap->ga_len - start_len;
10361 qsort(((char_u **)gap->ga_data) + start_len, matches,
10362 sizeof(char_u *), pstrcmp);
10367 #if defined(FEAT_SEARCHPATH)
10368 static int find_previous_pathsep(char_u *path, char_u **psep);
10369 static int is_unique(char_u *maybe_unique, garray_T *gap, int i);
10370 static void expand_path_option(char_u *curdir, garray_T *gap);
10371 static char_u *get_path_cutoff(char_u *fname, garray_T *gap);
10372 static void uniquefy_paths(garray_T *gap, char_u *pattern);
10373 static int expand_in_path(garray_T *gap, char_u *pattern, int flags);
10376 * Moves "*psep" back to the previous path separator in "path".
10377 * Returns FAIL is "*psep" ends up at the beginning of "path".
10380 find_previous_pathsep(char_u *path, char_u **psep)
10382 /* skip the current separator */
10383 if (*psep > path && vim_ispathsep(**psep))
10386 /* find the previous separator */
10387 while (*psep > path)
10389 if (vim_ispathsep(**psep))
10391 MB_PTR_BACK(path, *psep);
10398 * Returns TRUE if "maybe_unique" is unique wrt other_paths in "gap".
10399 * "maybe_unique" is the end portion of "((char_u **)gap->ga_data)[i]".
10402 is_unique(char_u *maybe_unique, garray_T *gap, int i)
10406 int other_path_len;
10407 char_u **other_paths = (char_u **)gap->ga_data;
10410 for (j = 0; j < gap->ga_len; j++)
10413 continue; /* don't compare it with itself */
10415 candidate_len = (int)STRLEN(maybe_unique);
10416 other_path_len = (int)STRLEN(other_paths[j]);
10417 if (other_path_len < candidate_len)
10418 continue; /* it's different when it's shorter */
10420 rival = other_paths[j] + other_path_len - candidate_len;
10421 if (fnamecmp(maybe_unique, rival) == 0
10422 && (rival == other_paths[j] || vim_ispathsep(*(rival - 1))))
10423 return FALSE; /* match */
10426 return TRUE; /* no match found */
10430 * Split the 'path' option into an array of strings in garray_T. Relative
10431 * paths are expanded to their equivalent fullpath. This includes the "."
10432 * (relative to current buffer directory) and empty path (relative to current
10433 * directory) notations.
10435 * TODO: handle upward search (;) and path limiter (**N) notations by
10436 * expanding each into their equivalent path(s).
10439 expand_path_option(char_u *curdir, garray_T *gap)
10441 char_u *path_option = *curbuf->b_p_path == NUL
10442 ? p_path : curbuf->b_p_path;
10447 if ((buf = alloc((int)MAXPATHL)) == NULL)
10450 while (*path_option != NUL)
10452 copy_option_part(&path_option, buf, MAXPATHL, " ,");
10454 if (buf[0] == '.' && (buf[1] == NUL || vim_ispathsep(buf[1])))
10456 /* Relative to current buffer:
10457 * "/path/file" + "." -> "/path/"
10458 * "/path/file" + "./subdir" -> "/path/subdir" */
10459 if (curbuf->b_ffname == NULL)
10461 p = gettail(curbuf->b_ffname);
10462 len = (int)(p - curbuf->b_ffname);
10463 if (len + (int)STRLEN(buf) >= MAXPATHL)
10468 STRMOVE(buf + len, buf + 2);
10469 mch_memmove(buf, curbuf->b_ffname, len);
10470 simplify_filename(buf);
10472 else if (buf[0] == NUL)
10473 /* relative to current directory */
10474 STRCPY(buf, curdir);
10475 else if (path_with_url(buf))
10476 /* URL can't be used here */
10478 else if (!mch_isFullName(buf))
10480 /* Expand relative path to their full path equivalent */
10481 len = (int)STRLEN(curdir);
10482 if (len + (int)STRLEN(buf) + 3 > MAXPATHL)
10484 STRMOVE(buf + len + 1, buf);
10485 STRCPY(buf, curdir);
10486 buf[len] = PATHSEP;
10487 simplify_filename(buf);
10490 if (ga_grow(gap, 1) == FAIL)
10493 # if defined(MSWIN)
10494 /* Avoid the path ending in a backslash, it fails when a comma is
10496 len = (int)STRLEN(buf);
10497 if (buf[len - 1] == '\\')
10498 buf[len - 1] = '/';
10501 p = vim_strsave(buf);
10504 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
10511 * Returns a pointer to the file or directory name in "fname" that matches the
10512 * longest path in "ga"p, or NULL if there is no match. For example:
10514 * path: /foo/bar/baz
10515 * fname: /foo/bar/baz/quux.txt
10519 get_path_cutoff(char_u *fname, garray_T *gap)
10523 char_u **path_part = (char_u **)gap->ga_data;
10524 char_u *cutoff = NULL;
10526 for (i = 0; i < gap->ga_len; i++)
10530 while ((fname[j] == path_part[i][j]
10531 # if defined(MSWIN)
10532 || (vim_ispathsep(fname[j]) && vim_ispathsep(path_part[i][j]))
10534 ) && fname[j] != NUL && path_part[i][j] != NUL)
10539 cutoff = &fname[j];
10543 /* skip to the file or directory name */
10544 if (cutoff != NULL)
10545 while (vim_ispathsep(*cutoff))
10546 MB_PTR_ADV(cutoff);
10552 * Sorts, removes duplicates and modifies all the fullpath names in "gap" so
10553 * that they are unique with respect to each other while conserving the part
10554 * that matches the pattern. Beware, this is at least O(n^2) wrt "gap->ga_len".
10557 uniquefy_paths(garray_T *gap, char_u *pattern)
10561 char_u **fnames = (char_u **)gap->ga_data;
10562 int sort_again = FALSE;
10564 char_u *file_pattern;
10566 regmatch_T regmatch;
10568 char_u **in_curdir = NULL;
10569 char_u *short_name;
10571 remove_duplicates(gap);
10572 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
10575 * We need to prepend a '*' at the beginning of file_pattern so that the
10576 * regex matches anywhere in the path. FIXME: is this valid for all
10577 * possible patterns?
10579 len = (int)STRLEN(pattern);
10580 file_pattern = alloc(len + 2);
10581 if (file_pattern == NULL)
10583 file_pattern[0] = '*';
10584 file_pattern[1] = NUL;
10585 STRCAT(file_pattern, pattern);
10586 pat = file_pat_to_reg_pat(file_pattern, NULL, NULL, TRUE);
10587 vim_free(file_pattern);
10591 regmatch.rm_ic = TRUE; /* always ignore case */
10592 regmatch.regprog = vim_regcomp(pat, RE_MAGIC + RE_STRING);
10594 if (regmatch.regprog == NULL)
10597 if ((curdir = alloc((int)(MAXPATHL))) == NULL)
10599 mch_dirname(curdir, MAXPATHL);
10600 expand_path_option(curdir, &path_ga);
10602 in_curdir = (char_u **)alloc_clear(gap->ga_len * sizeof(char_u *));
10603 if (in_curdir == NULL)
10606 for (i = 0; i < gap->ga_len && !got_int; i++)
10608 char_u *path = fnames[i];
10610 char_u *dir_end = gettail_dir(path);
10612 char_u *path_cutoff;
10614 len = (int)STRLEN(path);
10615 is_in_curdir = fnamencmp(curdir, path, dir_end - path) == 0
10616 && curdir[dir_end - path] == NUL;
10618 in_curdir[i] = vim_strsave(path);
10620 /* Shorten the filename while maintaining its uniqueness */
10621 path_cutoff = get_path_cutoff(path, &path_ga);
10623 /* Don't assume all files can be reached without path when search
10624 * pattern starts with star star slash, so only remove path_cutoff
10625 * when possible. */
10626 if (pattern[0] == '*' && pattern[1] == '*'
10627 && vim_ispathsep_nocolon(pattern[2])
10628 && path_cutoff != NULL
10629 && vim_regexec(®match, path_cutoff, (colnr_T)0)
10630 && is_unique(path_cutoff, gap, i))
10633 mch_memmove(path, path_cutoff, STRLEN(path_cutoff) + 1);
10637 /* Here all files can be reached without path, so get shortest
10638 * unique path. We start at the end of the path. */
10639 pathsep_p = path + len - 1;
10641 while (find_previous_pathsep(path, &pathsep_p))
10642 if (vim_regexec(®match, pathsep_p + 1, (colnr_T)0)
10643 && is_unique(pathsep_p + 1, gap, i)
10644 && path_cutoff != NULL && pathsep_p + 1 >= path_cutoff)
10647 mch_memmove(path, pathsep_p + 1, STRLEN(pathsep_p));
10652 if (mch_isFullName(path))
10655 * Last resort: shorten relative to curdir if possible.
10656 * 'possible' means:
10657 * 1. It is under the current directory.
10658 * 2. The result is actually shorter than the original.
10660 * Before curdir After
10661 * /foo/bar/file.txt /foo/bar ./file.txt
10662 * c:\foo\bar\file.txt c:\foo\bar .\file.txt
10663 * /file.txt / /file.txt
10664 * c:\file.txt c:\ .\file.txt
10666 short_name = shorten_fname(path, curdir);
10667 if (short_name != NULL && short_name > path + 1
10670 * shorten_fname("c:\a\a.txt", "c:\a\b")
10671 * returns "\a\a.txt", which is not really the short
10673 && !vim_ispathsep(*short_name)
10679 STRMOVE(path + STRLEN(path), short_name);
10685 /* Shorten filenames in /in/current/directory/{filename} */
10686 for (i = 0; i < gap->ga_len && !got_int; i++)
10689 char_u *path = in_curdir[i];
10694 /* If the {filename} is not unique, change it to ./{filename}.
10695 * Else reduce it to {filename} */
10696 short_name = shorten_fname(path, curdir);
10697 if (short_name == NULL)
10699 if (is_unique(short_name, gap, i))
10701 STRCPY(fnames[i], short_name);
10705 rel_path = alloc((int)(STRLEN(short_name) + STRLEN(PATHSEPSTR) + 2));
10706 if (rel_path == NULL)
10708 STRCPY(rel_path, ".");
10709 add_pathsep(rel_path);
10710 STRCAT(rel_path, short_name);
10712 vim_free(fnames[i]);
10713 fnames[i] = rel_path;
10720 if (in_curdir != NULL)
10722 for (i = 0; i < gap->ga_len; i++)
10723 vim_free(in_curdir[i]);
10724 vim_free(in_curdir);
10726 ga_clear_strings(&path_ga);
10727 vim_regfree(regmatch.regprog);
10730 remove_duplicates(gap);
10734 * Calls globpath() with 'path' values for the given pattern and stores the
10736 * Returns the total number of matches.
10742 int flags) /* EW_* flags */
10746 char_u *paths = NULL;
10748 if ((curdir = alloc((unsigned)MAXPATHL)) == NULL)
10750 mch_dirname(curdir, MAXPATHL);
10752 ga_init2(&path_ga, (int)sizeof(char_u *), 1);
10753 expand_path_option(curdir, &path_ga);
10755 if (path_ga.ga_len == 0)
10758 paths = ga_concat_strings(&path_ga, ",");
10759 ga_clear_strings(&path_ga);
10763 globpath(paths, pattern, gap, (flags & EW_ICASE) ? WILD_ICASE : 0);
10766 return gap->ga_len;
10770 #if defined(FEAT_SEARCHPATH) || defined(FEAT_CMDL_COMPL) || defined(PROTO)
10772 * Sort "gap" and remove duplicate entries. "gap" is expected to contain a
10773 * list of file names in allocated memory.
10776 remove_duplicates(garray_T *gap)
10780 char_u **fnames = (char_u **)gap->ga_data;
10782 sort_strings(fnames, gap->ga_len);
10783 for (i = gap->ga_len - 1; i > 0; --i)
10784 if (fnamecmp(fnames[i - 1], fnames[i]) == 0)
10786 vim_free(fnames[i]);
10787 for (j = i + 1; j < gap->ga_len; ++j)
10788 fnames[j - 1] = fnames[j];
10794 static int has_env_var(char_u *p);
10797 * Return TRUE if "p" contains what looks like an environment variable.
10798 * Allowing for escaping.
10801 has_env_var(char_u *p)
10803 for ( ; *p; MB_PTR_ADV(p))
10805 if (*p == '\\' && p[1] != NUL)
10807 else if (vim_strchr((char_u *)
10819 #ifdef SPECIAL_WILDCHAR
10820 static int has_special_wildchar(char_u *p);
10823 * Return TRUE if "p" contains a special wildcard character, one that Vim
10824 * cannot expand, requires using a shell.
10827 has_special_wildchar(char_u *p)
10829 for ( ; *p; MB_PTR_ADV(p))
10831 /* Allow for escaping. */
10832 if (*p == '\\' && p[1] != NUL)
10834 else if (vim_strchr((char_u *)SPECIAL_WILDCHAR, *p) != NULL)
10842 * Generic wildcard expansion code.
10844 * Characters in "pat" that should not be expanded must be preceded with a
10845 * backslash. E.g., "/path\ with\ spaces/my\*star*"
10847 * Return FAIL when no single file was found. In this case "num_file" is not
10848 * set, and "file" may contain an error message.
10849 * Return OK when some files found. "num_file" is set to the number of
10850 * matches, "file" to the array of matches. Call FreeWild() later.
10853 gen_expand_wildcards(
10854 int num_pat, /* number of input patterns */
10855 char_u **pat, /* array of input patterns */
10856 int *num_file, /* resulting number of files */
10857 char_u ***file, /* array of resulting files */
10858 int flags) /* EW_* flags */
10863 static int recursive = FALSE;
10866 #if defined(FEAT_SEARCHPATH)
10867 int did_expand_in_path = FALSE;
10871 * expand_env() is called to expand things like "~user". If this fails,
10872 * it calls ExpandOne(), which brings us back here. In this case, always
10873 * call the machine specific expansion function, if possible. Otherwise,
10877 #ifdef SPECIAL_WILDCHAR
10878 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10883 #ifdef SPECIAL_WILDCHAR
10885 * If there are any special wildcard characters which we cannot handle
10886 * here, call machine specific function for all the expansion. This
10887 * avoids starting the shell for each argument separately.
10888 * For `=expr` do use the internal function.
10890 for (i = 0; i < num_pat; i++)
10892 if (has_special_wildchar(pat[i])
10893 # ifdef VIM_BACKTICK
10894 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
10897 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
10904 * The matching file names are stored in a growarray. Init it empty.
10906 ga_init2(&ga, (int)sizeof(char_u *), 30);
10908 for (i = 0; i < num_pat; ++i)
10913 #ifdef VIM_BACKTICK
10914 if (vim_backtick(p))
10916 add_pat = expand_backtick(&ga, p, flags);
10924 * First expand environment variables, "~/" and "~user/".
10926 if (has_env_var(p) || *p == '~')
10928 p = expand_env_save_opt(p, TRUE);
10933 * On Unix, if expand_env() can't expand an environment
10934 * variable, use the shell to do that. Discard previously
10935 * found file names and start all over again.
10937 else if (has_env_var(p) || *p == '~')
10940 ga_clear_strings(&ga);
10941 i = mch_expand_wildcards(num_pat, pat, num_file, file,
10942 flags|EW_KEEPDOLLAR);
10950 * If there are wildcards: Expand file names and add each match to
10951 * the list. If there is no match, and EW_NOTFOUND is given, add
10953 * If there are no wildcards: Add the file name if it exists or
10954 * when EW_NOTFOUND is given.
10956 if (mch_has_exp_wildcard(p))
10958 #if defined(FEAT_SEARCHPATH)
10959 if ((flags & EW_PATH)
10960 && !mch_isFullName(p)
10962 && (vim_ispathsep(p[1])
10963 || (p[1] == '.' && vim_ispathsep(p[2]))))
10966 /* :find completion where 'path' is used.
10967 * Recursiveness is OK here. */
10969 add_pat = expand_in_path(&ga, p, flags);
10971 did_expand_in_path = TRUE;
10975 add_pat = mch_expandpath(&ga, p, flags);
10979 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
10981 char_u *t = backslash_halve_save(p);
10983 #if defined(MACOS_CLASSIC)
10986 /* When EW_NOTFOUND is used, always add files and dirs. Makes
10987 * "vim c:/" work. */
10988 if (flags & EW_NOTFOUND)
10989 addfile(&ga, t, flags | EW_DIR | EW_FILE);
10991 addfile(&ga, t, flags);
10995 #if defined(FEAT_SEARCHPATH)
10996 if (did_expand_in_path && ga.ga_len > 0 && (flags & EW_PATH))
10997 uniquefy_paths(&ga, p);
11003 *num_file = ga.ga_len;
11004 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
11008 return ((flags & EW_EMPTYOK) || ga.ga_data != NULL) ? retval : FAIL;
11011 # ifdef VIM_BACKTICK
11014 * Return TRUE if we can expand this backtick thing here.
11017 vim_backtick(char_u *p)
11019 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
11023 * Expand an item in `backticks` by executing it as a command.
11024 * Currently only works when pat[] starts and ends with a `.
11025 * Returns number of file names found, -1 if an error is encountered.
11031 int flags) /* EW_* flags */
11039 /* Create the command: lop off the backticks. */
11040 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
11045 if (*cmd == '=') /* `={expr}`: Expand expression */
11046 buffer = eval_to_string(cmd + 1, &p, TRUE);
11049 buffer = get_cmd_output(cmd, NULL,
11050 (flags & EW_SILENT) ? SHELL_SILENT : 0, NULL);
11052 if (buffer == NULL)
11056 while (*cmd != NUL)
11058 cmd = skipwhite(cmd); /* skip over white space */
11060 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
11062 /* add an entry if it is not empty */
11067 addfile(gap, cmd, flags);
11072 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
11079 # endif /* VIM_BACKTICK */
11082 * Add a file to a file list. Accepted flags:
11083 * EW_DIR add directories
11084 * EW_FILE add files
11085 * EW_EXEC add executable files
11086 * EW_NOTFOUND add even when it doesn't exist
11087 * EW_ADDSLASH add slash after directory name
11088 * EW_ALLLINKS add symlink also when the referred file does not exist
11093 char_u *f, /* filename */
11100 /* if the file/dir/link doesn't exist, may not add it */
11101 if (!(flags & EW_NOTFOUND) && ((flags & EW_ALLLINKS)
11102 ? mch_lstat((char *)f, &sb) < 0 : mch_getperm(f) < 0))
11105 #ifdef FNAME_ILLEGAL
11106 /* if the file/dir contains illegal characters, don't add it */
11107 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
11111 isdir = mch_isdir(f);
11112 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
11115 /* If the file isn't executable, may not add it. Do accept directories.
11116 * When invoked from expand_shellcmd() do not use $PATH. */
11117 if (!isdir && (flags & EW_EXEC)
11118 && !mch_can_exe(f, NULL, !(flags & EW_SHELLCMD)))
11121 /* Make room for another item in the file list. */
11122 if (ga_grow(gap, 1) == FAIL)
11125 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
11130 #ifdef BACKSLASH_IN_FILENAME
11134 * Append a slash or backslash after directory names if none is present.
11136 #ifndef DONT_ADD_PATHSEP_TO_DIR
11137 if (isdir && (flags & EW_ADDSLASH))
11140 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
11142 #endif /* !NO_EXPANDPATH */
11144 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
11147 # define SEEK_SET 0
11150 # define SEEK_END 2
11154 * Get the stdout of an external command.
11155 * If "ret_len" is NULL replace NUL characters with NL. When "ret_len" is not
11156 * NULL store the length there.
11157 * Returns an allocated string, or NULL for error.
11162 char_u *infile, /* optional input file name */
11163 int flags, /* can be SHELL_SILENT */
11168 char_u *buffer = NULL;
11173 if (check_restricted() || check_secure())
11176 /* get a name for the temp file */
11177 if ((tempname = vim_tempname('o', FALSE)) == NULL)
11183 /* Add the redirection stuff */
11184 command = make_filter_cmd(cmd, infile, tempname);
11185 if (command == NULL)
11189 * Call the shell to execute the command (errors are ignored).
11190 * Don't check timestamps here.
11192 ++no_check_timestamps;
11193 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
11194 --no_check_timestamps;
11199 * read the names from the file into memory
11202 /* created temporary file is not always readable as binary */
11203 fd = mch_fopen((char *)tempname, "r");
11205 fd = mch_fopen((char *)tempname, READBIN);
11210 EMSG2(_(e_notopen), tempname);
11214 fseek(fd, 0L, SEEK_END);
11215 len = ftell(fd); /* get size of temp file */
11216 fseek(fd, 0L, SEEK_SET);
11218 buffer = alloc(len + 1);
11219 if (buffer != NULL)
11220 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
11222 mch_remove(tempname);
11223 if (buffer == NULL)
11226 len = i; /* VMS doesn't give us what we asked for... */
11230 EMSG2(_(e_notread), tempname);
11234 else if (ret_len == NULL)
11236 /* Change NUL into SOH, otherwise the string is truncated. */
11237 for (i = 0; i < len; ++i)
11238 if (buffer[i] == NUL)
11241 buffer[len] = NUL; /* make sure the buffer is terminated */
11247 vim_free(tempname);
11253 * Free the list of files returned by expand_wildcards() or other expansion
11257 FreeWild(int count, char_u **files)
11259 if (count <= 0 || files == NULL)
11262 vim_free(files[count]);
11267 * Return TRUE when need to go to Insert mode because of 'insertmode'.
11268 * Don't do this when still processing a command or a mapping.
11269 * Don't do this when inside a ":normal" command.
11274 return (p_im && stuff_empty() && typebuf_typed());
11278 * Returns the isolated name of the shell in allocated memory:
11279 * - Skip beyond any path. E.g., "/usr/bin/csh -f" -> "csh -f".
11280 * - Remove any argument. E.g., "csh -f" -> "csh".
11281 * But don't allow a space in the path, so that this works:
11282 * "/usr/bin/csh --rcfile ~/.cshrc"
11283 * But don't do that for Windows, it's common to have a space in the path.
11286 get_isolated_shell_name(void)
11292 p = vim_strnsave(p, (int)(skiptowhite(p) - p));
11294 p = skiptowhite(p_sh);
11297 /* No white space, use the tail. */
11298 p = vim_strsave(gettail(p_sh));
11304 /* Find the last path separator before the space. */
11306 for (p2 = p_sh; p2 < p; MB_PTR_ADV(p2))
11307 if (vim_ispathsep(*p2))
11309 p = vim_strnsave(p1, (int)(p - p1));