1 /* vi:set ts=8 sts=4 sw=4:
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
18 # include <fcntl.h> /* for chdir() */
21 static char_u
*vim_version_dir
__ARGS((char_u
*vimdir
));
22 static char_u
*remove_tail
__ARGS((char_u
*p
, char_u
*pend
, char_u
*name
));
23 static int copy_indent
__ARGS((int size
, char_u
*src
));
26 * Count the size (in window cells) of the indent in the current line.
31 return get_indent_str(ml_get_curline(), (int)curbuf
->b_p_ts
);
35 * Count the size (in window cells) of the indent in line "lnum".
41 return get_indent_str(ml_get(lnum
), (int)curbuf
->b_p_ts
);
44 #if defined(FEAT_FOLDING) || defined(PROTO)
46 * Count the size (in window cells) of the indent in line "lnum" of buffer
50 get_indent_buf(buf
, lnum
)
54 return get_indent_str(ml_get_buf(buf
, lnum
, FALSE
), (int)buf
->b_p_ts
);
59 * count the size (in window cells) of the indent in line "ptr", with
63 get_indent_str(ptr
, ts
)
71 if (*ptr
== TAB
) /* count a tab for what it is worth */
72 count
+= ts
- (count
% ts
);
74 ++count
; /* count a space for one */
82 * Set the indent of the current line.
83 * Leaves the cursor on the first non-blank in the line.
84 * Caller must take care of undo.
86 * SIN_CHANGED: call changed_bytes() if the line was changed.
87 * SIN_INSERT: insert the indent in front of the line.
88 * SIN_UNDO: save line for undo before changing it.
89 * Returns TRUE if the line was changed.
92 set_indent(size
, flags
)
93 int size
; /* measured in spaces */
101 int ind_len
; /* measured in characters */
104 int ind_done
= 0; /* measured in spaces */
107 int orig_char_len
= -1; /* number of initial whitespace chars when
108 'et' and 'pi' are both set */
111 * First check if there is anything to do and compute the number of
112 * characters needed for the indent.
116 p
= oldline
= ml_get_curline();
118 /* Calculate the buffer size for the new indent, and check to see if it
119 * isn't already set */
121 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
122 * 'preserveindent' are set count the number of characters at the
123 * beginning of the line to be copied */
124 if (!curbuf
->b_p_et
|| (!(flags
& SIN_INSERT
) && curbuf
->b_p_pi
))
126 /* If 'preserveindent' is set then reuse as much as possible of
127 * the existing indent structure for the new indent */
128 if (!(flags
& SIN_INSERT
) && curbuf
->b_p_pi
)
132 /* count as many characters as we can use */
133 while (todo
> 0 && vim_iswhite(*p
))
137 tab_pad
= (int)curbuf
->b_p_ts
138 - (ind_done
% (int)curbuf
->b_p_ts
);
139 /* stop if this tab will overshoot the target */
155 /* Set initial number of whitespace chars to copy if we are
156 * preserving indent but expandtab is set */
158 orig_char_len
= ind_len
;
160 /* Fill to next tabstop with a tab, if possible */
161 tab_pad
= (int)curbuf
->b_p_ts
- (ind_done
% (int)curbuf
->b_p_ts
);
162 if (todo
>= tab_pad
&& orig_char_len
== -1)
167 /* ind_done += tab_pad; */
171 /* count tabs required for indent */
172 while (todo
>= (int)curbuf
->b_p_ts
)
178 todo
-= (int)curbuf
->b_p_ts
;
180 /* ind_done += (int)curbuf->b_p_ts; */
183 /* count spaces required for indent */
195 /* Return if the indent is OK already. */
196 if (!doit
&& !vim_iswhite(*p
) && !(flags
& SIN_INSERT
))
199 /* Allocate memory for the new line. */
200 if (flags
& SIN_INSERT
)
204 line_len
= (int)STRLEN(p
) + 1;
206 /* If 'preserveindent' and 'expandtab' are both set keep the original
207 * characters and allocate accordingly. We will fill the rest with spaces
208 * after the if (!curbuf->b_p_et) below. */
209 if (orig_char_len
!= -1)
211 newline
= alloc(orig_char_len
+ size
- ind_done
+ line_len
);
214 todo
= size
- ind_done
;
215 ind_len
= orig_char_len
+ todo
; /* Set total length of indent in
216 * characters, which may have been
217 * undercounted until now */
220 while (orig_char_len
> 0)
225 /* Skip over any additional white space (useful when newindent is less
227 while (vim_iswhite(*p
))
234 newline
= alloc(ind_len
+ line_len
);
240 /* Put the characters in the new line. */
241 /* if 'expandtab' isn't set: use TABs */
244 /* If 'preserveindent' is set then reuse as much as possible of
245 * the existing indent structure for the new indent */
246 if (!(flags
& SIN_INSERT
) && curbuf
->b_p_pi
)
251 while (todo
> 0 && vim_iswhite(*p
))
255 tab_pad
= (int)curbuf
->b_p_ts
256 - (ind_done
% (int)curbuf
->b_p_ts
);
257 /* stop if this tab will overshoot the target */
271 /* Fill to next tabstop with a tab, if possible */
272 tab_pad
= (int)curbuf
->b_p_ts
- (ind_done
% (int)curbuf
->b_p_ts
);
282 while (todo
>= (int)curbuf
->b_p_ts
)
285 todo
-= (int)curbuf
->b_p_ts
;
293 mch_memmove(s
, p
, (size_t)line_len
);
295 /* Replace the line (unless undo fails). */
296 if (!(flags
& SIN_UNDO
) || u_savesub(curwin
->w_cursor
.lnum
) == OK
)
298 ml_replace(curwin
->w_cursor
.lnum
, newline
, FALSE
);
299 if (flags
& SIN_CHANGED
)
300 changed_bytes(curwin
->w_cursor
.lnum
, 0);
301 /* Correct saved cursor position if it's after the indent. */
302 if (saved_cursor
.lnum
== curwin
->w_cursor
.lnum
303 && saved_cursor
.col
>= (colnr_T
)(p
- oldline
))
304 saved_cursor
.col
+= ind_len
- (colnr_T
)(p
- oldline
);
310 curwin
->w_cursor
.col
= ind_len
;
315 * Copy the indent from ptr to the current line (and fill to size)
316 * Leaves the cursor on the first non-blank in the line.
317 * Returns TRUE if the line was changed.
320 copy_indent(size
, src
)
334 /* Round 1: compute the number of characters needed for the indent
335 * Round 2: copy the characters. */
336 for (round
= 1; round
<= 2; ++round
)
343 /* Count/copy the usable portion of the source line */
344 while (todo
> 0 && vim_iswhite(*s
))
348 tab_pad
= (int)curbuf
->b_p_ts
349 - (ind_done
% (int)curbuf
->b_p_ts
);
350 /* Stop if this tab will overshoot the target */
367 /* Fill to next tabstop with a tab, if possible */
368 tab_pad
= (int)curbuf
->b_p_ts
- (ind_done
% (int)curbuf
->b_p_ts
);
377 /* Add tabs required for indent */
378 while (todo
>= (int)curbuf
->b_p_ts
)
380 todo
-= (int)curbuf
->b_p_ts
;
386 /* Count/add spaces required for indent */
397 /* Allocate memory for the result: the copied indent, new indent
398 * and the rest of the line. */
399 line_len
= (int)STRLEN(ml_get_curline()) + 1;
400 line
= alloc(ind_len
+ line_len
);
407 /* Append the original line */
408 mch_memmove(p
, ml_get_curline(), (size_t)line_len
);
410 /* Replace the line */
411 ml_replace(curwin
->w_cursor
.lnum
, line
, FALSE
);
413 /* Put the cursor after the indent. */
414 curwin
->w_cursor
.col
= ind_len
;
419 * Return the indent of the current line after a number. Return -1 if no
420 * number was found. Used for 'n' in 'formatoptions': numbered list.
421 * Since a pattern is used it can actually handle more than numbers.
424 get_number_indent(lnum
)
429 regmmatch_T regmatch
;
431 if (lnum
> curbuf
->b_ml
.ml_line_count
)
434 regmatch
.regprog
= vim_regcomp(curbuf
->b_p_flp
, RE_MAGIC
);
435 if (regmatch
.regprog
!= NULL
)
437 regmatch
.rmm_ic
= FALSE
;
438 regmatch
.rmm_maxcol
= 0;
439 if (vim_regexec_multi(®match
, curwin
, curbuf
, lnum
, (colnr_T
)0))
441 pos
.lnum
= regmatch
.endpos
[0].lnum
+ lnum
;
442 pos
.col
= regmatch
.endpos
[0].col
;
443 #ifdef FEAT_VIRTUALEDIT
447 vim_free(regmatch
.regprog
);
450 if (pos
.lnum
== 0 || *ml_get_pos(&pos
) == NUL
)
452 getvcol(curwin
, &pos
, &col
, NULL
, NULL
);
456 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
458 static int cin_is_cinword
__ARGS((char_u
*line
));
461 * Return TRUE if the string "line" starts with a word from 'cinwords'.
473 cinw_len
= (int)STRLEN(curbuf
->b_p_cinw
) + 1;
474 cinw_buf
= alloc((unsigned)cinw_len
);
475 if (cinw_buf
!= NULL
)
477 line
= skipwhite(line
);
478 for (cinw
= curbuf
->b_p_cinw
; *cinw
; )
480 len
= copy_option_part(&cinw
, cinw_buf
, cinw_len
, ",");
481 if (STRNCMP(line
, cinw_buf
, len
) == 0
482 && (!vim_iswordc(line
[len
]) || !vim_iswordc(line
[len
- 1])))
495 * open_line: Add a new line below or above the current line.
497 * For VREPLACE mode, we only add a new line when we get to the end of the
498 * file, otherwise we just start replacing the next line.
500 * Caller must take care of undo. Since VREPLACE may affect any number of
501 * lines however, it may call u_save_cursor() again when starting to change a
503 * "flags": OPENLINE_DELSPACES delete spaces after cursor
504 * OPENLINE_DO_COM format comments
505 * OPENLINE_KEEPTRAIL keep trailing spaces
506 * OPENLINE_MARKFIX adjust mark positions after the line break
508 * Return TRUE for success, FALSE for failure
511 open_line(dir
, flags
, old_indent
)
512 int dir
; /* FORWARD or BACKWARD */
514 int old_indent
; /* indent for after ^^D in Insert mode */
516 char_u
*saved_line
; /* copy of the original line */
517 char_u
*next_line
= NULL
; /* copy of the next line */
518 char_u
*p_extra
= NULL
; /* what goes to next line */
519 int less_cols
= 0; /* less columns for mark in new line */
520 int less_cols_off
= 0; /* columns to skip for mark adjust */
521 pos_T old_cursor
; /* old cursor position */
522 int newcol
= 0; /* new cursor column */
523 int newindent
= 0; /* auto-indent of the new line */
525 int trunc_line
= FALSE
; /* truncate current line afterwards */
526 int retval
= FALSE
; /* return value, default is FAIL */
528 int extra_len
= 0; /* length of p_extra string */
529 int lead_len
; /* length of comment leader */
530 char_u
*lead_flags
; /* position in 'comments' for comment leader */
531 char_u
*leader
= NULL
; /* copy of comment leader */
533 char_u
*allocated
= NULL
; /* allocated memory */
534 #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
535 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
538 int saved_char
= NUL
; /* init for GCC */
539 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
542 #ifdef FEAT_SMARTINDENT
543 int do_si
= (!p_paste
&& curbuf
->b_p_si
548 int no_si
= FALSE
; /* reset did_si afterwards */
549 int first_char
= NUL
; /* init for GCC */
551 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
554 int did_append
; /* appended a new line */
555 int saved_pi
= curbuf
->b_p_pi
; /* copy of preserveindent setting */
558 * make a copy of the current line so we can mess with it
560 saved_line
= vim_strsave(ml_get_curline());
561 if (saved_line
== NULL
) /* out of memory! */
565 if (State
& VREPLACE_FLAG
)
568 * With VREPLACE we make a copy of the next line, which we will be
569 * starting to replace. First make the new line empty and let vim play
570 * with the indenting and comment leader to its heart's content. Then
571 * we grab what it ended up putting on the new line, put back the
572 * original line, and call ins_char() to put each new character onto
573 * the line, replacing what was there before and pushing the right
574 * stuff onto the replace stack. -- webb.
576 if (curwin
->w_cursor
.lnum
< orig_line_count
)
577 next_line
= vim_strsave(ml_get(curwin
->w_cursor
.lnum
+ 1));
579 next_line
= vim_strsave((char_u
*)"");
580 if (next_line
== NULL
) /* out of memory! */
584 * In VREPLACE mode, a NL replaces the rest of the line, and starts
585 * replacing the next line, so push all of the characters left on the
586 * line onto the replace stack. We'll push any other characters that
587 * might be replaced at the start of the next line (due to autoindent
590 replace_push(NUL
); /* Call twice because BS over NL expects it */
592 p
= saved_line
+ curwin
->w_cursor
.col
;
595 saved_line
[curwin
->w_cursor
.col
] = NUL
;
601 && !(State
& VREPLACE_FLAG
)
605 p_extra
= saved_line
+ curwin
->w_cursor
.col
;
606 #ifdef FEAT_SMARTINDENT
607 if (do_si
) /* need first char after new line break */
609 p
= skipwhite(p_extra
);
614 extra_len
= (int)STRLEN(p_extra
);
616 saved_char
= *p_extra
;
620 u_clearline(); /* cannot do "U" command when adding lines */
621 #ifdef FEAT_SMARTINDENT
627 * If we just did an auto-indent, then we didn't type anything on
628 * the prior line, and it should be truncated. Do this even if 'ai' is not
629 * set because automatically inserting a comment leader also sets did_ai.
631 if (dir
== FORWARD
&& did_ai
)
635 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
636 * indent to use for the new line.
639 #ifdef FEAT_SMARTINDENT
645 * count white space on current line
647 newindent
= get_indent_str(saved_line
, (int)curbuf
->b_p_ts
);
649 newindent
= old_indent
; /* for ^^D command in insert mode */
651 #ifdef FEAT_SMARTINDENT
653 * Do smart indenting.
654 * In insert/replace mode (only when dir == FORWARD)
655 * we may move some text to the next line. If it starts with '{'
656 * don't add an indent. Fixes inserting a NL before '{' in line
659 if (!trunc_line
&& do_si
&& *saved_line
!= NUL
660 && (p_extra
== NULL
|| first_char
!= '{'))
665 old_cursor
= curwin
->w_cursor
;
667 # ifdef FEAT_COMMENTS
668 if (flags
& OPENLINE_DO_COM
)
669 lead_len
= get_leader_len(ptr
, NULL
, FALSE
);
676 * Skip preprocessor directives, unless they are
677 * recognised as comments.
680 # ifdef FEAT_COMMENTS
685 while (ptr
[0] == '#' && curwin
->w_cursor
.lnum
> 1)
686 ptr
= ml_get(--curwin
->w_cursor
.lnum
);
687 newindent
= get_indent();
689 # ifdef FEAT_COMMENTS
690 if (flags
& OPENLINE_DO_COM
)
691 lead_len
= get_leader_len(ptr
, NULL
, FALSE
);
697 * This case gets the following right:
699 * * A comment (read '\' as '/').
702 * This should line up here;
705 if (p
[0] == '/' && p
[1] == '*')
711 if (p
[0] == '/' && p
[-1] == '*')
714 * End of C comment, indent should line up
715 * with the line containing the start of
718 curwin
->w_cursor
.col
= (colnr_T
)(p
- ptr
);
719 if ((pos
= findmatch(NULL
, NUL
)) != NULL
)
721 curwin
->w_cursor
.lnum
= pos
->lnum
;
722 newindent
= get_indent();
728 else /* Not a comment line */
731 /* Find last non-blank in line */
732 p
= ptr
+ STRLEN(ptr
) - 1;
733 while (p
> ptr
&& vim_iswhite(*p
))
738 * find the character just before the '{' or ';'
740 if (last_char
== '{' || last_char
== ';')
744 while (p
> ptr
&& vim_iswhite(*p
))
748 * Try to catch lines that are split over multiple
752 * Should line up here!
757 curwin
->w_cursor
.col
= (colnr_T
)(p
- ptr
);
758 if ((pos
= findmatch(NULL
, '(')) != NULL
)
760 curwin
->w_cursor
.lnum
= pos
->lnum
;
761 newindent
= get_indent();
762 ptr
= ml_get_curline();
766 * If last character is '{' do indent, without
767 * checking for "if" and the like.
769 if (last_char
== '{')
771 did_si
= TRUE
; /* do indent */
772 no_si
= TRUE
; /* don't delete it when '{' typed */
775 * Look for "if" and the like, use 'cinwords'.
776 * Don't do this if the previous line ended in ';' or
779 else if (last_char
!= ';' && last_char
!= '}'
780 && cin_is_cinword(ptr
))
784 else /* dir == BACKWARD */
787 * Skip preprocessor directives, unless they are
788 * recognised as comments.
791 # ifdef FEAT_COMMENTS
796 int was_backslashed
= FALSE
;
798 while ((ptr
[0] == '#' || was_backslashed
) &&
799 curwin
->w_cursor
.lnum
< curbuf
->b_ml
.ml_line_count
)
801 if (*ptr
&& ptr
[STRLEN(ptr
) - 1] == '\\')
802 was_backslashed
= TRUE
;
804 was_backslashed
= FALSE
;
805 ptr
= ml_get(++curwin
->w_cursor
.lnum
);
808 newindent
= 0; /* Got to end of file */
810 newindent
= get_indent();
813 if (*p
== '}') /* if line starts with '}': do indent */
815 else /* can delete indent when '{' typed */
818 curwin
->w_cursor
= old_cursor
;
822 #endif /* FEAT_SMARTINDENT */
829 * Find out if the current line starts with a comment leader.
830 * This may then be inserted in front of the new line.
832 end_comment_pending
= NUL
;
833 if (flags
& OPENLINE_DO_COM
)
834 lead_len
= get_leader_len(saved_line
, &lead_flags
, dir
== BACKWARD
);
839 char_u
*lead_repl
= NULL
; /* replaces comment leader */
840 int lead_repl_len
= 0; /* length of *lead_repl */
841 char_u lead_middle
[COM_MAX_LEN
]; /* middle-comment string */
842 char_u lead_end
[COM_MAX_LEN
]; /* end-comment string */
843 char_u
*comment_end
= NULL
; /* where lead_end has been found */
844 int extra_space
= FALSE
; /* append extra space */
846 int require_blank
= FALSE
; /* requires blank after middle */
850 * If the comment leader has the start, middle or end flag, it may not
851 * be used or may be replaced with the middle leader.
853 for (p
= lead_flags
; *p
&& *p
!= ':'; ++p
)
857 require_blank
= TRUE
;
860 if (*p
== COM_START
|| *p
== COM_MIDDLE
)
866 * Doing "O" on a start of comment does not insert leader.
874 /* find start of middle part */
875 (void)copy_option_part(&p
, lead_middle
, COM_MAX_LEN
, ",");
876 require_blank
= FALSE
;
880 * Isolate the strings of the middle and end leader.
882 while (*p
&& p
[-1] != ':') /* find end of middle flags */
885 require_blank
= TRUE
;
888 (void)copy_option_part(&p
, lead_middle
, COM_MAX_LEN
, ",");
890 while (*p
&& p
[-1] != ':') /* find end of end flags */
892 /* Check whether we allow automatic ending of comments */
893 if (*p
== COM_AUTO_END
)
894 end_comment_pending
= -1; /* means we want to set it */
897 n
= copy_option_part(&p
, lead_end
, COM_MAX_LEN
, ",");
899 if (end_comment_pending
== -1) /* we can set it now */
900 end_comment_pending
= lead_end
[n
- 1];
903 * If the end of the comment is in the same line, don't use
904 * the comment leader.
908 for (p
= saved_line
+ lead_len
; *p
; ++p
)
909 if (STRNCMP(p
, lead_end
, n
) == 0)
918 * Doing "o" on a start of comment inserts the middle leader.
922 if (current_flag
== COM_START
)
924 lead_repl
= lead_middle
;
925 lead_repl_len
= (int)STRLEN(lead_middle
);
929 * If we have hit RETURN immediately after the start
930 * comment leader, then put a space after the middle
931 * comment leader on the next line.
933 if (!vim_iswhite(saved_line
[lead_len
- 1])
935 && (int)curwin
->w_cursor
.col
== lead_len
)
937 && saved_line
[lead_len
] == NUL
)
946 * Doing "o" on the end of a comment does not insert leader.
947 * Remember where the end is, might want to use it to find the
948 * start (for C-comments).
952 comment_end
= skipwhite(saved_line
);
958 * Doing "O" on the end of a comment inserts the middle leader.
959 * Find the string for the middle leader, searching backwards.
961 while (p
> curbuf
->b_p_com
&& *p
!= ',')
963 for (lead_repl
= p
; lead_repl
> curbuf
->b_p_com
964 && lead_repl
[-1] != ':'; --lead_repl
)
966 lead_repl_len
= (int)(p
- lead_repl
);
968 /* We can probably always add an extra space when doing "O" on
972 /* Check whether we allow automatic ending of comments */
973 for (p2
= p
; *p2
&& *p2
!= ':'; p2
++)
975 if (*p2
== COM_AUTO_END
)
976 end_comment_pending
= -1; /* means we want to set it */
978 if (end_comment_pending
== -1)
980 /* Find last character in end-comment string */
981 while (*p2
&& *p2
!= ',')
983 end_comment_pending
= p2
[-1];
990 * Comment leader for first line only: Don't repeat leader
991 * when using "O", blank out leader when using "o".
997 lead_repl
= (char_u
*)"";
1005 /* allocate buffer (may concatenate p_exta later) */
1006 leader
= alloc(lead_len
+ lead_repl_len
+ extra_space
+
1008 allocated
= leader
; /* remember to free it later */
1014 vim_strncpy(leader
, saved_line
, lead_len
);
1017 * Replace leader with lead_repl, right or left adjusted
1019 if (lead_repl
!= NULL
)
1024 for (p
= lead_flags
; *p
&& *p
!= ':'; ++p
)
1026 if (*p
== COM_RIGHT
|| *p
== COM_LEFT
)
1028 else if (VIM_ISDIGIT(*p
) || *p
== '-')
1029 off
= getdigits(&p
);
1031 if (c
== COM_RIGHT
) /* right adjusted leader */
1033 /* find last non-white in the leader to line up with */
1034 for (p
= leader
+ lead_len
- 1; p
> leader
1035 && vim_iswhite(*p
); --p
)
1040 /* Compute the length of the replaced characters in
1041 * screen characters, not bytes. */
1043 int repl_size
= vim_strnsize(lead_repl
,
1049 while (old_size
< repl_size
&& p
> leader
)
1051 mb_ptr_back(leader
, p
);
1052 old_size
+= ptr2cells(p
);
1054 l
= lead_repl_len
- (int)(endp
- p
);
1056 mch_memmove(endp
+ l
, endp
,
1057 (size_t)((leader
+ lead_len
) - endp
));
1061 if (p
< leader
+ lead_repl_len
)
1066 mch_memmove(p
, lead_repl
, (size_t)lead_repl_len
);
1067 if (p
+ lead_repl_len
> leader
+ lead_len
)
1068 p
[lead_repl_len
] = NUL
;
1070 /* blank-out any other chars from the old leader. */
1071 while (--p
>= leader
)
1074 int l
= mb_head_off(leader
, p
);
1079 if (ptr2cells(p
) > 1)
1084 mch_memmove(p
+ 1, p
+ l
+ 1,
1085 (size_t)((leader
+ lead_len
) - (p
+ l
+ 1)));
1091 if (!vim_iswhite(*p
))
1095 else /* left adjusted leader */
1097 p
= skipwhite(leader
);
1099 /* Compute the length of the replaced characters in
1100 * screen characters, not bytes. Move the part that is
1101 * not to be overwritten. */
1103 int repl_size
= vim_strnsize(lead_repl
,
1108 for (i
= 0; p
[i
] != NUL
&& i
< lead_len
; i
+= l
)
1110 l
= (*mb_ptr2len
)(p
+ i
);
1111 if (vim_strnsize(p
, i
+ l
) > repl_size
)
1114 if (i
!= lead_repl_len
)
1116 mch_memmove(p
+ lead_repl_len
, p
+ i
,
1117 (size_t)(lead_len
- i
- (leader
- p
)));
1118 lead_len
+= lead_repl_len
- i
;
1122 mch_memmove(p
, lead_repl
, (size_t)lead_repl_len
);
1124 /* Replace any remaining non-white chars in the old
1125 * leader by spaces. Keep Tabs, the indent must
1126 * remain the same. */
1127 for (p
+= lead_repl_len
; p
< leader
+ lead_len
; ++p
)
1128 if (!vim_iswhite(*p
))
1130 /* Don't put a space before a TAB. */
1131 if (p
+ 1 < leader
+ lead_len
&& p
[1] == TAB
)
1134 mch_memmove(p
, p
+ 1,
1135 (leader
+ lead_len
) - p
);
1140 int l
= (*mb_ptr2len
)(p
);
1144 if (ptr2cells(p
) > 1)
1146 /* Replace a double-wide char with
1151 mch_memmove(p
+ 1, p
+ l
,
1152 (leader
+ lead_len
) - p
);
1162 /* Recompute the indent, it may have changed. */
1164 #ifdef FEAT_SMARTINDENT
1168 newindent
= get_indent_str(leader
, (int)curbuf
->b_p_ts
);
1170 /* Add the indent offset */
1171 if (newindent
+ off
< 0)
1179 /* Correct trailing spaces for the shift, so that
1180 * alignment remains equal. */
1181 while (off
> 0 && lead_len
> 0
1182 && leader
[lead_len
- 1] == ' ')
1184 /* Don't do it when there is a tab before the space */
1185 if (vim_strchr(skipwhite(leader
), '\t') != NULL
)
1191 /* If the leader ends in white space, don't add an
1193 if (lead_len
> 0 && vim_iswhite(leader
[lead_len
- 1]))
1194 extra_space
= FALSE
;
1195 leader
[lead_len
] = NUL
;
1200 leader
[lead_len
++] = ' ';
1201 leader
[lead_len
] = NUL
;
1207 * if a new indent will be set below, remove the indent that
1208 * is in the comment leader
1211 #ifdef FEAT_SMARTINDENT
1216 while (lead_len
&& vim_iswhite(*leader
))
1225 #ifdef FEAT_SMARTINDENT
1226 did_si
= can_si
= FALSE
;
1229 else if (comment_end
!= NULL
)
1232 * We have finished a comment, so we don't use the leader.
1233 * If this was a C-comment and 'ai' or 'si' is set do a normal
1234 * indent to align with the line containing the start of the
1237 if (comment_end
[0] == '*' && comment_end
[1] == '/' &&
1239 #ifdef FEAT_SMARTINDENT
1244 old_cursor
= curwin
->w_cursor
;
1245 curwin
->w_cursor
.col
= (colnr_T
)(comment_end
- saved_line
);
1246 if ((pos
= findmatch(NULL
, NUL
)) != NULL
)
1248 curwin
->w_cursor
.lnum
= pos
->lnum
;
1249 newindent
= get_indent();
1251 curwin
->w_cursor
= old_cursor
;
1257 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1258 if (p_extra
!= NULL
)
1260 *p_extra
= saved_char
; /* restore char that NUL replaced */
1263 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1266 * When in REPLACE mode, put the deleted blanks on the replace stack,
1267 * preceded by a NUL, so they can be put back when a BS is entered.
1269 if (REPLACE_NORMAL(State
))
1270 replace_push(NUL
); /* end of extra blanks */
1271 if (curbuf
->b_p_ai
|| (flags
& OPENLINE_DELSPACES
))
1273 while ((*p_extra
== ' ' || *p_extra
== '\t')
1276 || !utf_iscomposing(utf_ptr2char(p_extra
+ 1)))
1280 if (REPLACE_NORMAL(State
))
1281 replace_push(*p_extra
);
1286 if (*p_extra
!= NUL
)
1287 did_ai
= FALSE
; /* append some text, don't truncate now */
1289 /* columns for marks adjusted for removed columns */
1290 less_cols
= (int)(p_extra
- saved_line
);
1293 if (p_extra
== NULL
)
1294 p_extra
= (char_u
*)""; /* append empty line */
1296 #ifdef FEAT_COMMENTS
1297 /* concatenate leader and p_extra, if there is a leader */
1300 STRCAT(leader
, p_extra
);
1302 did_ai
= TRUE
; /* So truncating blanks works with comments */
1303 less_cols
-= lead_len
;
1306 end_comment_pending
= NUL
; /* turns out there was no leader */
1309 old_cursor
= curwin
->w_cursor
;
1310 if (dir
== BACKWARD
)
1311 --curwin
->w_cursor
.lnum
;
1312 #ifdef FEAT_VREPLACE
1313 if (!(State
& VREPLACE_FLAG
) || old_cursor
.lnum
>= orig_line_count
)
1316 if (ml_append(curwin
->w_cursor
.lnum
, p_extra
, (colnr_T
)0, FALSE
)
1319 /* Postpone calling changed_lines(), because it would mess up folding
1321 mark_adjust(curwin
->w_cursor
.lnum
+ 1, (linenr_T
)MAXLNUM
, 1L, 0L);
1324 #ifdef FEAT_VREPLACE
1328 * In VREPLACE mode we are starting to replace the next line.
1330 curwin
->w_cursor
.lnum
++;
1331 if (curwin
->w_cursor
.lnum
>= Insstart
.lnum
+ vr_lines_changed
)
1333 /* In case we NL to a new line, BS to the previous one, and NL
1334 * again, we don't want to save the new line for undo twice.
1336 (void)u_save_cursor(); /* errors are ignored! */
1339 ml_replace(curwin
->w_cursor
.lnum
, p_extra
, TRUE
);
1340 changed_bytes(curwin
->w_cursor
.lnum
, 0);
1341 curwin
->w_cursor
.lnum
--;
1347 #ifdef FEAT_SMARTINDENT
1352 ++curwin
->w_cursor
.lnum
;
1353 #ifdef FEAT_SMARTINDENT
1357 newindent
-= newindent
% (int)curbuf
->b_p_sw
;
1358 newindent
+= (int)curbuf
->b_p_sw
;
1361 /* Copy the indent */
1364 (void)copy_indent(newindent
, saved_line
);
1367 * Set the 'preserveindent' option so that any further screwing
1368 * with the line doesn't entirely destroy our efforts to preserve
1369 * it. It gets restored at the function end.
1371 curbuf
->b_p_pi
= TRUE
;
1374 (void)set_indent(newindent
, SIN_INSERT
);
1375 less_cols
-= curwin
->w_cursor
.col
;
1377 ai_col
= curwin
->w_cursor
.col
;
1380 * In REPLACE mode, for each character in the new indent, there must
1381 * be a NUL on the replace stack, for when it is deleted with BS
1383 if (REPLACE_NORMAL(State
))
1384 for (n
= 0; n
< (int)curwin
->w_cursor
.col
; ++n
)
1386 newcol
+= curwin
->w_cursor
.col
;
1387 #ifdef FEAT_SMARTINDENT
1393 #ifdef FEAT_COMMENTS
1395 * In REPLACE mode, for each character in the extra leader, there must be
1396 * a NUL on the replace stack, for when it is deleted with BS.
1398 if (REPLACE_NORMAL(State
))
1399 while (lead_len
-- > 0)
1403 curwin
->w_cursor
= old_cursor
;
1407 if (trunc_line
|| (State
& INSERT
))
1409 /* truncate current line at cursor */
1410 saved_line
[curwin
->w_cursor
.col
] = NUL
;
1411 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1412 if (trunc_line
&& !(flags
& OPENLINE_KEEPTRAIL
))
1413 truncate_spaces(saved_line
);
1414 ml_replace(curwin
->w_cursor
.lnum
, saved_line
, FALSE
);
1418 changed_lines(curwin
->w_cursor
.lnum
, curwin
->w_cursor
.col
,
1419 curwin
->w_cursor
.lnum
+ 1, 1L);
1422 /* Move marks after the line break to the new line. */
1423 if (flags
& OPENLINE_MARKFIX
)
1424 mark_col_adjust(curwin
->w_cursor
.lnum
,
1425 curwin
->w_cursor
.col
+ less_cols_off
,
1426 1L, (long)-less_cols
);
1429 changed_bytes(curwin
->w_cursor
.lnum
, curwin
->w_cursor
.col
);
1433 * Put the cursor on the new line. Careful: the scrollup() above may
1434 * have moved w_cursor, we must use old_cursor.
1436 curwin
->w_cursor
.lnum
= old_cursor
.lnum
+ 1;
1439 changed_lines(curwin
->w_cursor
.lnum
, 0, curwin
->w_cursor
.lnum
, 1L);
1441 curwin
->w_cursor
.col
= newcol
;
1442 #ifdef FEAT_VIRTUALEDIT
1443 curwin
->w_cursor
.coladd
= 0;
1446 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1448 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1449 * fixthisline() from doing it (via change_indent()) by telling it we're in
1450 * normal INSERT mode.
1452 if (State
& VREPLACE_FLAG
)
1454 vreplace_mode
= State
; /* So we know to put things right later */
1462 * May do lisp indenting.
1465 # ifdef FEAT_COMMENTS
1471 fixthisline(get_lisp_indent
);
1472 p
= ml_get_curline();
1473 ai_col
= (colnr_T
)(skipwhite(p
) - p
);
1478 * May do indenting after opening a new line.
1483 || *curbuf
->b_p_inde
!= NUL
1486 && in_cinkeys(dir
== FORWARD
1488 : KEY_OPEN_BACK
, ' ', linewhite(curwin
->w_cursor
.lnum
)))
1491 p
= ml_get_curline();
1492 ai_col
= (colnr_T
)(skipwhite(p
) - p
);
1495 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1496 if (vreplace_mode
!= 0)
1497 State
= vreplace_mode
;
1500 #ifdef FEAT_VREPLACE
1502 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1503 * original line, and inserts the new stuff char by char, pushing old stuff
1504 * onto the replace stack (via ins_char()).
1506 if (State
& VREPLACE_FLAG
)
1508 /* Put new line in p_extra */
1509 p_extra
= vim_strsave(ml_get_curline());
1510 if (p_extra
== NULL
)
1513 /* Put back original line */
1514 ml_replace(curwin
->w_cursor
.lnum
, next_line
, FALSE
);
1516 /* Insert new stuff into line again */
1517 curwin
->w_cursor
.col
= 0;
1518 #ifdef FEAT_VIRTUALEDIT
1519 curwin
->w_cursor
.coladd
= 0;
1521 ins_bytes(p_extra
); /* will call changed_bytes() */
1527 retval
= TRUE
; /* success! */
1529 curbuf
->b_p_pi
= saved_pi
;
1530 vim_free(saved_line
);
1531 vim_free(next_line
);
1532 vim_free(allocated
);
1536 #if defined(FEAT_COMMENTS) || defined(PROTO)
1538 * get_leader_len() returns the length of the prefix of the given string
1539 * which introduces a comment. If this string is not a comment then 0 is
1541 * When "flags" is not NULL, it is set to point to the flags of the recognized
1543 * "backward" must be true for the "O" command.
1546 get_leader_len(line
, flags
, backward
)
1552 int got_com
= FALSE
;
1554 char_u part_buf
[COM_MAX_LEN
]; /* buffer for one option part */
1555 char_u
*string
; /* pointer to comment string */
1559 while (vim_iswhite(line
[i
])) /* leading white space is ignored */
1563 * Repeat to match several nested comment strings.
1568 * scan through the 'comments' option for a match
1571 for (list
= curbuf
->b_p_com
; *list
; )
1574 * Get one option part into part_buf[]. Advance list to next one.
1575 * put string at start of string.
1577 if (!got_com
&& flags
!= NULL
) /* remember where flags started */
1579 (void)copy_option_part(&list
, part_buf
, COM_MAX_LEN
, ",");
1580 string
= vim_strchr(part_buf
, ':');
1581 if (string
== NULL
) /* missing ':', ignore this part */
1583 *string
++ = NUL
; /* isolate flags from string */
1586 * When already found a nested comment, only accept further
1589 if (got_com
&& vim_strchr(part_buf
, COM_NEST
) == NULL
)
1592 /* When 'O' flag used don't use for "O" command */
1593 if (backward
&& vim_strchr(part_buf
, COM_NOBACK
) != NULL
)
1597 * Line contents and string must match.
1598 * When string starts with white space, must have some white space
1599 * (but the amount does not need to match, there might be a mix of
1602 if (vim_iswhite(string
[0]))
1604 if (i
== 0 || !vim_iswhite(line
[i
- 1]))
1606 while (vim_iswhite(string
[0]))
1609 for (j
= 0; string
[j
] != NUL
&& string
[j
] == line
[i
+ j
]; ++j
)
1611 if (string
[j
] != NUL
)
1615 * When 'b' flag used, there must be white space or an
1616 * end-of-line after the string in the line.
1618 if (vim_strchr(part_buf
, COM_BLANK
) != NULL
1619 && !vim_iswhite(line
[i
+ j
]) && line
[i
+ j
] != NUL
)
1623 * We have found a match, stop searching.
1632 * No match found, stop scanning.
1638 * Include any trailing white space.
1640 while (vim_iswhite(line
[i
]))
1644 * If this comment doesn't nest, stop here.
1646 if (vim_strchr(part_buf
, COM_NEST
) == NULL
)
1649 return (got_com
? i
: 0);
1654 * Return the number of window lines occupied by buffer line "lnum".
1660 return plines_win(curwin
, lnum
, TRUE
);
1664 plines_win(wp
, lnum
, winheight
)
1667 int winheight
; /* when TRUE limit to window height */
1669 #if defined(FEAT_DIFF) || defined(PROTO)
1670 /* Check for filler lines above this buffer line. When folded the result
1671 * is one line anyway. */
1672 return plines_win_nofill(wp
, lnum
, winheight
) + diff_check_fill(wp
, lnum
);
1679 return plines_win_nofill(curwin
, lnum
, TRUE
);
1683 plines_win_nofill(wp
, lnum
, winheight
)
1686 int winheight
; /* when TRUE limit to window height */
1694 #ifdef FEAT_VERTSPLIT
1695 if (wp
->w_width
== 0)
1700 /* A folded lines is handled just like an empty line. */
1701 /* NOTE: Caller must handle lines that are MAYBE folded. */
1702 if (lineFolded(wp
, lnum
) == TRUE
)
1706 lines
= plines_win_nofold(wp
, lnum
);
1707 if (winheight
> 0 && lines
> wp
->w_height
)
1708 return (int)wp
->w_height
;
1713 * Return number of window lines physical line "lnum" will occupy in window
1714 * "wp". Does not care about folding, 'wrap' or 'diff'.
1717 plines_win_nofold(wp
, lnum
)
1725 s
= ml_get_buf(wp
->w_buffer
, lnum
, FALSE
);
1726 if (*s
== NUL
) /* empty line */
1728 col
= win_linetabsize(wp
, s
, (colnr_T
)MAXCOL
);
1731 * If list mode is on, then the '$' at the end of the line may take up one
1734 if (wp
->w_p_list
&& lcs_eol
!= NUL
)
1738 * Add column offset for 'number' and 'foldcolumn'.
1740 width
= W_WIDTH(wp
) - win_col_off(wp
);
1746 width
+= win_col_off2(wp
);
1747 return (col
+ (width
- 1)) / width
+ 1;
1751 * Like plines_win(), but only reports the number of physical screen lines
1752 * used from the start of the line to the given column number.
1755 plines_win_col(wp
, lnum
, column
)
1766 /* Check for filler lines above this buffer line. When folded the result
1767 * is one line anyway. */
1768 lines
= diff_check_fill(wp
, lnum
);
1774 #ifdef FEAT_VERTSPLIT
1775 if (wp
->w_width
== 0)
1779 s
= ml_get_buf(wp
->w_buffer
, lnum
, FALSE
);
1782 while (*s
!= NUL
&& --column
>= 0)
1784 col
+= win_lbr_chartabsize(wp
, s
, (colnr_T
)col
, NULL
);
1789 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1790 * INSERT mode, then col must be adjusted so that it represents the last
1791 * screen position of the TAB. This only fixes an error when the TAB wraps
1792 * from one screen line to the next (when 'columns' is not a multiple of
1795 if (*s
== TAB
&& (State
& NORMAL
) && (!wp
->w_p_list
|| lcs_tab1
))
1796 col
+= win_lbr_chartabsize(wp
, s
, (colnr_T
)col
, NULL
) - 1;
1799 * Add column offset for 'number', 'foldcolumn', etc.
1801 width
= W_WIDTH(wp
) - win_col_off(wp
);
1807 lines
+= (col
- width
) / (width
+ win_col_off2(wp
)) + 1;
1812 plines_m_win(wp
, first
, last
)
1814 linenr_T first
, last
;
1818 while (first
<= last
)
1823 /* Check if there are any really folded lines, but also included lines
1824 * that are maybe folded. */
1825 x
= foldedCount(wp
, first
, NULL
);
1828 ++count
; /* count 1 for "+-- folded" line */
1835 if (first
== wp
->w_topline
)
1836 count
+= plines_win_nofill(wp
, first
, TRUE
) + wp
->w_topfill
;
1839 count
+= plines_win(wp
, first
, TRUE
);
1846 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1848 * Insert string "p" at the cursor position. Stops at a NUL byte.
1849 * Handles Replace mode and multi-byte characters.
1855 ins_bytes_len(p
, (int)STRLEN(p
));
1859 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1860 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1862 * Insert string "p" with length "len" at the cursor position.
1863 * Handles Replace mode and multi-byte characters.
1866 ins_bytes_len(p
, len
)
1874 for (i
= 0; i
< len
; i
+= n
)
1876 n
= (*mb_ptr2len
)(p
+ i
);
1877 ins_char_bytes(p
+ i
, n
);
1880 for (i
= 0; i
< len
; ++i
)
1887 * Insert or replace a single character at the cursor position.
1888 * When in REPLACE or VREPLACE mode, replace any existing character.
1889 * Caller must have prepared for undo.
1890 * For multi-byte characters we get the whole character, the caller must
1891 * convert bytes to a character.
1897 #if defined(FEAT_MBYTE) || defined(PROTO)
1898 char_u buf
[MB_MAXBYTES
];
1901 n
= (*mb_char2bytes
)(c
, buf
);
1903 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1904 * Happens for CTRL-Vu9900. */
1908 ins_char_bytes(buf
, n
);
1912 ins_char_bytes(buf
, charlen
)
1919 int newlen
; /* nr of bytes inserted */
1920 int oldlen
; /* nr of bytes deleted (0 when not replacing) */
1924 int linelen
; /* length of old line including NUL */
1926 linenr_T lnum
= curwin
->w_cursor
.lnum
;
1929 #ifdef FEAT_VIRTUALEDIT
1930 /* Break tabs if needed. */
1931 if (virtual_active() && curwin
->w_cursor
.coladd
> 0)
1932 coladvance_force(getviscol());
1935 col
= curwin
->w_cursor
.col
;
1936 oldp
= ml_get(lnum
);
1937 linelen
= (int)STRLEN(oldp
) + 1;
1939 /* The lengths default to the values for when not replacing. */
1947 if (State
& REPLACE_FLAG
)
1949 #ifdef FEAT_VREPLACE
1950 if (State
& VREPLACE_FLAG
)
1952 colnr_T new_vcol
= 0; /* init for GCC */
1960 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1961 * Returns the old value of list, so when finished,
1962 * curwin->w_p_list should be set back to this.
1964 old_list
= curwin
->w_p_list
;
1965 if (old_list
&& vim_strchr(p_cpo
, CPO_LISTWM
) == NULL
)
1966 curwin
->w_p_list
= FALSE
;
1969 * In virtual replace mode each character may replace one or more
1970 * characters (zero if it's a TAB). Count the number of bytes to
1971 * be deleted to make room for the new character, counting screen
1972 * cells. May result in adding spaces to fill a gap.
1974 getvcol(curwin
, &curwin
->w_cursor
, NULL
, &vcol
, NULL
);
1979 new_vcol
= vcol
+ chartabsize(buf
, vcol
);
1980 while (oldp
[col
+ oldlen
] != NUL
&& vcol
< new_vcol
)
1982 vcol
+= chartabsize(oldp
+ col
+ oldlen
, vcol
);
1983 /* Don't need to remove a TAB that takes us to the right
1985 if (vcol
> new_vcol
&& oldp
[col
+ oldlen
] == TAB
)
1988 oldlen
+= (*mb_ptr2len
)(oldp
+ col
+ oldlen
);
1992 /* Deleted a bit too much, insert spaces. */
1993 if (vcol
> new_vcol
)
1994 newlen
+= vcol
- new_vcol
;
1996 curwin
->w_p_list
= old_list
;
2000 if (oldp
[col
] != NUL
)
2002 /* normal replace */
2004 oldlen
= (*mb_ptr2len
)(oldp
+ col
);
2011 /* Push the replaced bytes onto the replace stack, so that they can be
2012 * put back when BS is used. The bytes of a multi-byte character are
2013 * done the other way around, so that the first byte is popped off
2014 * first (it tells the byte length of the character). */
2016 for (i
= 0; i
< oldlen
; ++i
)
2019 l
= (*mb_ptr2len
)(oldp
+ col
+ i
) - 1;
2020 for (j
= l
; j
>= 0; --j
)
2021 replace_push(oldp
[col
+ i
+ j
]);
2024 replace_push(oldp
[col
+ i
]);
2029 newp
= alloc_check((unsigned)(linelen
+ newlen
- oldlen
));
2033 /* Copy bytes before the cursor. */
2035 mch_memmove(newp
, oldp
, (size_t)col
);
2037 /* Copy bytes after the changed character(s). */
2039 mch_memmove(p
+ newlen
, oldp
+ col
+ oldlen
,
2040 (size_t)(linelen
- col
- oldlen
));
2042 /* Insert or overwrite the new character. */
2044 mch_memmove(p
, buf
, charlen
);
2051 /* Fill with spaces when necessary. */
2055 /* Replace the line in the buffer. */
2056 ml_replace(lnum
, newp
, FALSE
);
2058 /* mark the buffer as changed and prepare for displaying */
2059 changed_bytes(lnum
, col
);
2062 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2063 * show the match for right parens and braces.
2065 if (p_sm
&& (State
& INSERT
)
2070 #ifdef FEAT_INS_EXPAND
2071 && !ins_compl_active()
2076 #ifdef FEAT_RIGHTLEFT
2077 if (!p_ri
|| (State
& REPLACE_FLAG
))
2080 /* Normal insert: move cursor right */
2082 curwin
->w_cursor
.col
+= charlen
;
2084 ++curwin
->w_cursor
.col
;
2088 * TODO: should try to update w_row here, to avoid recomputing it later.
2093 * Insert a string at the cursor position.
2094 * Note: Does NOT handle Replace mode.
2095 * Caller must have prepared for undo.
2101 char_u
*oldp
, *newp
;
2102 int newlen
= (int)STRLEN(s
);
2105 linenr_T lnum
= curwin
->w_cursor
.lnum
;
2107 #ifdef FEAT_VIRTUALEDIT
2108 if (virtual_active() && curwin
->w_cursor
.coladd
> 0)
2109 coladvance_force(getviscol());
2112 col
= curwin
->w_cursor
.col
;
2113 oldp
= ml_get(lnum
);
2114 oldlen
= (int)STRLEN(oldp
);
2116 newp
= alloc_check((unsigned)(oldlen
+ newlen
+ 1));
2120 mch_memmove(newp
, oldp
, (size_t)col
);
2121 mch_memmove(newp
+ col
, s
, (size_t)newlen
);
2122 mch_memmove(newp
+ col
+ newlen
, oldp
+ col
, (size_t)(oldlen
- col
+ 1));
2123 ml_replace(lnum
, newp
, FALSE
);
2124 changed_bytes(lnum
, col
);
2125 curwin
->w_cursor
.col
+= newlen
;
2129 * Delete one character under the cursor.
2130 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2131 * Caller must have prepared for undo.
2133 * return FAIL for failure, OK otherwise
2142 /* Make sure the cursor is at the start of a character. */
2144 if (*ml_get_cursor() == NUL
)
2146 return del_chars(1L, fixpos
);
2149 return del_bytes(1L, fixpos
, TRUE
);
2152 #if defined(FEAT_MBYTE) || defined(PROTO)
2154 * Like del_bytes(), but delete characters instead of bytes.
2157 del_chars(count
, fixpos
)
2166 p
= ml_get_cursor();
2167 for (i
= 0; i
< count
&& *p
!= NUL
; ++i
)
2169 l
= (*mb_ptr2len
)(p
);
2173 return del_bytes(bytes
, fixpos
, TRUE
);
2178 * Delete "count" bytes under the cursor.
2179 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2180 * Caller must have prepared for undo.
2182 * return FAIL for failure, OK otherwise
2186 del_bytes(count
, fixpos_arg
, use_delcombine
)
2189 int use_delcombine
; /* 'delcombine' option applies */
2191 char_u
*oldp
, *newp
;
2193 linenr_T lnum
= curwin
->w_cursor
.lnum
;
2194 colnr_T col
= curwin
->w_cursor
.col
;
2197 int fixpos
= fixpos_arg
;
2199 oldp
= ml_get(lnum
);
2200 oldlen
= (int)STRLEN(oldp
);
2203 * Can't do anything when the cursor is on the NUL after the line.
2209 /* If 'delcombine' is set and deleting (less than) one character, only
2210 * delete the last combining character. */
2211 if (p_deco
&& use_delcombine
&& enc_utf8
2212 && utfc_ptr2len(oldp
+ col
) >= count
)
2217 (void)utfc_ptr2char(oldp
+ col
, cc
);
2220 /* Find the last composing char, there can be several. */
2225 count
= utf_ptr2len(oldp
+ n
);
2227 } while (UTF_COMPOSINGLIKE(oldp
+ col
, oldp
+ n
));
2234 * When count is too big, reduce it.
2236 movelen
= (long)oldlen
- (long)col
- count
+ 1; /* includes trailing NUL */
2240 * If we just took off the last character of a non-blank line, and
2241 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2242 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2244 if (col
> 0 && fixpos
&& restart_edit
== 0
2245 #ifdef FEAT_VIRTUALEDIT
2246 && (ve_flags
& VE_ONEMORE
) == 0
2250 --curwin
->w_cursor
.col
;
2251 #ifdef FEAT_VIRTUALEDIT
2252 curwin
->w_cursor
.coladd
= 0;
2256 curwin
->w_cursor
.col
-=
2257 (*mb_head_off
)(oldp
, oldp
+ curwin
->w_cursor
.col
);
2260 count
= oldlen
- col
;
2265 * If the old line has been allocated the deletion can be done in the
2266 * existing line. Otherwise a new line has to be allocated
2268 was_alloced
= ml_line_alloced(); /* check if oldp was allocated */
2269 #ifdef FEAT_NETBEANS_INTG
2270 if (was_alloced
&& usingNetbeans
)
2271 netbeans_removed(curbuf
, lnum
, col
, count
);
2272 /* else is handled by ml_replace() */
2275 newp
= oldp
; /* use same allocated memory */
2277 { /* need to allocate a new line */
2278 newp
= alloc((unsigned)(oldlen
+ 1 - count
));
2281 mch_memmove(newp
, oldp
, (size_t)col
);
2283 mch_memmove(newp
+ col
, oldp
+ col
+ count
, (size_t)movelen
);
2285 ml_replace(lnum
, newp
, FALSE
);
2287 /* mark the buffer as changed and prepare for displaying */
2288 changed_bytes(lnum
, curwin
->w_cursor
.col
);
2294 * Delete from cursor to end of line.
2295 * Caller must have prepared for undo.
2297 * return FAIL for failure, OK otherwise
2300 truncate_line(fixpos
)
2301 int fixpos
; /* if TRUE fix the cursor position when done */
2304 linenr_T lnum
= curwin
->w_cursor
.lnum
;
2305 colnr_T col
= curwin
->w_cursor
.col
;
2308 newp
= vim_strsave((char_u
*)"");
2310 newp
= vim_strnsave(ml_get(lnum
), col
);
2315 ml_replace(lnum
, newp
, FALSE
);
2317 /* mark the buffer as changed and prepare for displaying */
2318 changed_bytes(lnum
, curwin
->w_cursor
.col
);
2321 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2323 if (fixpos
&& curwin
->w_cursor
.col
> 0)
2324 --curwin
->w_cursor
.col
;
2330 * Delete "nlines" lines at the cursor.
2331 * Saves the lines for undo first if "undo" is TRUE.
2334 del_lines(nlines
, undo
)
2335 long nlines
; /* number of lines to delete */
2336 int undo
; /* if TRUE, prepare for undo */
2343 /* save the deleted lines for undo */
2344 if (undo
&& u_savedel(curwin
->w_cursor
.lnum
, nlines
) == FAIL
)
2347 for (n
= 0; n
< nlines
; )
2349 if (curbuf
->b_ml
.ml_flags
& ML_EMPTY
) /* nothing to delete */
2352 ml_delete(curwin
->w_cursor
.lnum
, TRUE
);
2355 /* If we delete the last line in the file, stop */
2356 if (curwin
->w_cursor
.lnum
> curbuf
->b_ml
.ml_line_count
)
2359 /* adjust marks, mark the buffer as changed and prepare for displaying */
2360 deleted_lines_mark(curwin
->w_cursor
.lnum
, n
);
2362 curwin
->w_cursor
.col
= 0;
2363 check_cursor_lnum();
2370 char_u
*ptr
= ml_get_pos(pos
);
2374 return (*mb_ptr2char
)(ptr
);
2384 return (*mb_ptr2char
)(ml_get_cursor());
2386 return (int)*ml_get_cursor();
2390 * Write a character at the current cursor position.
2391 * It is directly written into the block.
2397 *(ml_get_buf(curbuf
, curwin
->w_cursor
.lnum
, TRUE
)
2398 + curwin
->w_cursor
.col
) = c
;
2401 #if 0 /* not used */
2403 * Put *pos at end of current buffer
2411 pos
->lnum
= curbuf
->b_ml
.ml_line_count
;
2413 p
= ml_get(pos
->lnum
);
2420 * When extra == 0: Return TRUE if the cursor is before or on the first
2421 * non-blank in the line.
2422 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2432 for (col
= 0, ptr
= ml_get_curline(); vim_iswhite(*ptr
); ++col
)
2434 if (col
>= curwin
->w_cursor
.col
+ extra
)
2441 * Skip to next part of an option argument: Skip space and comma.
2444 skip_to_option_part(p
)
2455 * changed() is called when something in the current buffer is changed.
2457 * Most often called through changed_bytes() and changed_lines(), which also
2458 * mark the area of the display to be redrawn.
2463 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2464 /* The text of the preediting area is inserted, but this doesn't
2465 * mean a change of the buffer yet. That is delayed until the
2466 * text is committed. (this means preedit becomes empty) */
2467 if (im_is_preediting() && !xim_changed_while_preediting
)
2469 xim_changed_while_preediting
= FALSE
;
2472 if (!curbuf
->b_changed
)
2474 int save_msg_scroll
= msg_scroll
;
2476 /* Give a warning about changing a read-only file. This may also
2477 * check-out the file, thus change "curbuf"! */
2480 /* Create a swap file if that is wanted.
2481 * Don't do this for "nofile" and "nowrite" buffer types. */
2482 if (curbuf
->b_may_swap
2483 #ifdef FEAT_QUICKFIX
2484 && !bt_dontwrite(curbuf
)
2488 ml_open_file(curbuf
);
2490 /* The ml_open_file() can cause an ATTENTION message.
2491 * Wait two seconds, to make sure the user reads this unexpected
2492 * message. Since we could be anywhere, call wait_return() now,
2493 * and don't let the emsg() set msg_scroll. */
2494 if (need_wait_return
&& emsg_silent
== 0)
2497 ui_delay(2000L, TRUE
);
2499 msg_scroll
= save_msg_scroll
;
2502 curbuf
->b_changed
= TRUE
;
2503 ml_setflags(curbuf
);
2505 check_status(curbuf
);
2506 redraw_tabline
= TRUE
;
2509 need_maketitle
= TRUE
; /* set window title later */
2512 ++curbuf
->b_changedtick
;
2515 static void changedOneline
__ARGS((buf_T
*buf
, linenr_T lnum
));
2516 static void changed_lines_buf
__ARGS((buf_T
*buf
, linenr_T lnum
, linenr_T lnume
, long xtra
));
2517 static void changed_common
__ARGS((linenr_T lnum
, colnr_T col
, linenr_T lnume
, long xtra
));
2520 * Changed bytes within a single line for the current buffer.
2521 * - marks the windows on this buffer to be redisplayed
2522 * - marks the buffer changed by calling changed()
2523 * - invalidates cached values
2526 changed_bytes(lnum
, col
)
2530 changedOneline(curbuf
, lnum
);
2531 changed_common(lnum
, col
, lnum
+ 1, 0L);
2534 /* Diff highlighting in other diff windows may need to be updated too. */
2535 if (curwin
->w_p_diff
)
2540 for (wp
= firstwin
; wp
!= NULL
; wp
= wp
->w_next
)
2541 if (wp
->w_p_diff
&& wp
!= curwin
)
2543 redraw_win_later(wp
, VALID
);
2544 wlnum
= diff_lnum_win(lnum
, wp
);
2546 changedOneline(wp
->w_buffer
, wlnum
);
2553 changedOneline(buf
, lnum
)
2559 /* find the maximum area that must be redisplayed */
2560 if (lnum
< buf
->b_mod_top
)
2561 buf
->b_mod_top
= lnum
;
2562 else if (lnum
>= buf
->b_mod_bot
)
2563 buf
->b_mod_bot
= lnum
+ 1;
2567 /* set the area that must be redisplayed to one line */
2568 buf
->b_mod_set
= TRUE
;
2569 buf
->b_mod_top
= lnum
;
2570 buf
->b_mod_bot
= lnum
+ 1;
2571 buf
->b_mod_xlines
= 0;
2576 * Appended "count" lines below line "lnum" in the current buffer.
2577 * Must be called AFTER the change and after mark_adjust().
2578 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2581 appended_lines(lnum
, count
)
2585 changed_lines(lnum
+ 1, 0, lnum
+ 1, count
);
2589 * Like appended_lines(), but adjust marks first.
2592 appended_lines_mark(lnum
, count
)
2596 mark_adjust(lnum
+ 1, (linenr_T
)MAXLNUM
, count
, 0L);
2597 changed_lines(lnum
+ 1, 0, lnum
+ 1, count
);
2601 * Deleted "count" lines at line "lnum" in the current buffer.
2602 * Must be called AFTER the change and after mark_adjust().
2603 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2606 deleted_lines(lnum
, count
)
2610 changed_lines(lnum
, 0, lnum
+ count
, -count
);
2614 * Like deleted_lines(), but adjust marks first.
2617 deleted_lines_mark(lnum
, count
)
2621 mark_adjust(lnum
, (linenr_T
)(lnum
+ count
- 1), (long)MAXLNUM
, -count
);
2622 changed_lines(lnum
, 0, lnum
+ count
, -count
);
2626 * Changed lines for the current buffer.
2627 * Must be called AFTER the change and after mark_adjust().
2628 * - mark the buffer changed by calling changed()
2629 * - mark the windows on this buffer to be redisplayed
2630 * - invalidate cached values
2631 * "lnum" is the first line that needs displaying, "lnume" the first line
2632 * below the changed lines (BEFORE the change).
2633 * When only inserting lines, "lnum" and "lnume" are equal.
2634 * Takes care of calling changed() and updating b_mod_*.
2637 changed_lines(lnum
, col
, lnume
, xtra
)
2638 linenr_T lnum
; /* first line with change */
2639 colnr_T col
; /* column in first line with change */
2640 linenr_T lnume
; /* line below last changed line */
2641 long xtra
; /* number of extra lines (negative when deleting) */
2643 changed_lines_buf(curbuf
, lnum
, lnume
, xtra
);
2646 if (xtra
== 0 && curwin
->w_p_diff
)
2648 /* When the number of lines doesn't change then mark_adjust() isn't
2649 * called and other diff buffers still need to be marked for
2654 for (wp
= firstwin
; wp
!= NULL
; wp
= wp
->w_next
)
2655 if (wp
->w_p_diff
&& wp
!= curwin
)
2657 redraw_win_later(wp
, VALID
);
2658 wlnum
= diff_lnum_win(lnum
, wp
);
2660 changed_lines_buf(wp
->w_buffer
, wlnum
,
2661 lnume
- lnum
+ wlnum
, 0L);
2666 changed_common(lnum
, col
, lnume
, xtra
);
2670 changed_lines_buf(buf
, lnum
, lnume
, xtra
)
2672 linenr_T lnum
; /* first line with change */
2673 linenr_T lnume
; /* line below last changed line */
2674 long xtra
; /* number of extra lines (negative when deleting) */
2678 /* find the maximum area that must be redisplayed */
2679 if (lnum
< buf
->b_mod_top
)
2680 buf
->b_mod_top
= lnum
;
2681 if (lnum
< buf
->b_mod_bot
)
2683 /* adjust old bot position for xtra lines */
2684 buf
->b_mod_bot
+= xtra
;
2685 if (buf
->b_mod_bot
< lnum
)
2686 buf
->b_mod_bot
= lnum
;
2688 if (lnume
+ xtra
> buf
->b_mod_bot
)
2689 buf
->b_mod_bot
= lnume
+ xtra
;
2690 buf
->b_mod_xlines
+= xtra
;
2694 /* set the area that must be redisplayed */
2695 buf
->b_mod_set
= TRUE
;
2696 buf
->b_mod_top
= lnum
;
2697 buf
->b_mod_bot
= lnume
+ xtra
;
2698 buf
->b_mod_xlines
= xtra
;
2703 changed_common(lnum
, col
, lnume
, xtra
)
2711 #ifdef FEAT_JUMPLIST
2717 /* mark the buffer as modified */
2720 /* set the '. mark */
2721 if (!cmdmod
.keepjumps
)
2723 curbuf
->b_last_change
.lnum
= lnum
;
2724 curbuf
->b_last_change
.col
= col
;
2726 #ifdef FEAT_JUMPLIST
2727 /* Create a new entry if a new undo-able change was started or we
2728 * don't have an entry yet. */
2729 if (curbuf
->b_new_change
|| curbuf
->b_changelistlen
== 0)
2731 if (curbuf
->b_changelistlen
== 0)
2735 /* Don't create a new entry when the line number is the same
2736 * as the last one and the column is not too far away. Avoids
2737 * creating many entries for typing "xxxxx". */
2738 p
= &curbuf
->b_changelist
[curbuf
->b_changelistlen
- 1];
2739 if (p
->lnum
!= lnum
)
2743 cols
= comp_textwidth(FALSE
);
2746 add
= (p
->col
+ cols
< col
|| col
+ cols
< p
->col
);
2751 /* This is the first of a new sequence of undo-able changes
2752 * and it's at some distance of the last change. Use a new
2753 * position in the changelist. */
2754 curbuf
->b_new_change
= FALSE
;
2756 if (curbuf
->b_changelistlen
== JUMPLISTSIZE
)
2758 /* changelist is full: remove oldest entry */
2759 curbuf
->b_changelistlen
= JUMPLISTSIZE
- 1;
2760 mch_memmove(curbuf
->b_changelist
, curbuf
->b_changelist
+ 1,
2761 sizeof(pos_T
) * (JUMPLISTSIZE
- 1));
2764 /* Correct position in changelist for other windows on
2766 if (wp
->w_buffer
== curbuf
&& wp
->w_changelistidx
> 0)
2767 --wp
->w_changelistidx
;
2772 /* For other windows, if the position in the changelist is
2773 * at the end it stays at the end. */
2774 if (wp
->w_buffer
== curbuf
2775 && wp
->w_changelistidx
== curbuf
->b_changelistlen
)
2776 ++wp
->w_changelistidx
;
2778 ++curbuf
->b_changelistlen
;
2781 curbuf
->b_changelist
[curbuf
->b_changelistlen
- 1] =
2782 curbuf
->b_last_change
;
2783 /* The current window is always after the last change, so that "g,"
2784 * takes you back to it. */
2785 curwin
->w_changelistidx
= curbuf
->b_changelistlen
;
2791 if (wp
->w_buffer
== curbuf
)
2793 /* Mark this window to be redrawn later. */
2794 if (wp
->w_redr_type
< VALID
)
2795 wp
->w_redr_type
= VALID
;
2797 /* Check if a change in the buffer has invalidated the cached
2798 * values for the cursor. */
2801 * Update the folds for this window. Can't postpone this, because
2802 * a following operator might work on the whole fold: ">>dd".
2804 foldUpdate(wp
, lnum
, lnume
+ xtra
- 1);
2806 /* The change may cause lines above or below the change to become
2807 * included in a fold. Set lnum/lnume to the first/last line that
2808 * might be displayed differently.
2809 * Set w_cline_folded here as an efficient way to update it when
2810 * inserting lines just above a closed fold. */
2811 i
= hasFoldingWin(wp
, lnum
, &lnum
, NULL
, FALSE
, NULL
);
2812 if (wp
->w_cursor
.lnum
== lnum
)
2813 wp
->w_cline_folded
= i
;
2814 i
= hasFoldingWin(wp
, lnume
, NULL
, &lnume
, FALSE
, NULL
);
2815 if (wp
->w_cursor
.lnum
== lnume
)
2816 wp
->w_cline_folded
= i
;
2818 /* If the changed line is in a range of previously folded lines,
2819 * compare with the first line in that range. */
2820 if (wp
->w_cursor
.lnum
<= lnum
)
2822 i
= find_wl_entry(wp
, lnum
);
2823 if (i
>= 0 && wp
->w_cursor
.lnum
> wp
->w_lines
[i
].wl_lnum
)
2824 changed_line_abv_curs_win(wp
);
2828 if (wp
->w_cursor
.lnum
> lnum
)
2829 changed_line_abv_curs_win(wp
);
2830 else if (wp
->w_cursor
.lnum
== lnum
&& wp
->w_cursor
.col
>= col
)
2831 changed_cline_bef_curs_win(wp
);
2832 if (wp
->w_botline
>= lnum
)
2834 /* Assume that botline doesn't change (inserted lines make
2835 * other lines scroll down below botline). */
2836 approximate_botline_win(wp
);
2839 /* Check if any w_lines[] entries have become invalid.
2840 * For entries below the change: Correct the lnums for
2841 * inserted/deleted lines. Makes it possible to stop displaying
2842 * after the change. */
2843 for (i
= 0; i
< wp
->w_lines_valid
; ++i
)
2844 if (wp
->w_lines
[i
].wl_valid
)
2846 if (wp
->w_lines
[i
].wl_lnum
>= lnum
)
2848 if (wp
->w_lines
[i
].wl_lnum
< lnume
)
2850 /* line included in change */
2851 wp
->w_lines
[i
].wl_valid
= FALSE
;
2855 /* line below change */
2856 wp
->w_lines
[i
].wl_lnum
+= xtra
;
2858 wp
->w_lines
[i
].wl_lastlnum
+= xtra
;
2863 else if (wp
->w_lines
[i
].wl_lastlnum
>= lnum
)
2865 /* change somewhere inside this range of folded lines,
2866 * may need to be redrawn */
2867 wp
->w_lines
[i
].wl_valid
= FALSE
;
2874 /* Call update_screen() later, which checks out what needs to be redrawn,
2875 * since it notices b_mod_set and then uses b_mod_*. */
2876 if (must_redraw
< VALID
)
2877 must_redraw
= VALID
;
2880 /* when the cursor line is changed always trigger CursorMoved */
2881 if (lnum
<= curwin
->w_cursor
.lnum
2882 && lnume
+ (xtra
< 0 ? -xtra
: xtra
) > curwin
->w_cursor
.lnum
)
2883 last_cursormoved
.lnum
= 0;
2888 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2893 int ff
; /* also reset 'fileformat' */
2895 if (buf
->b_changed
|| (ff
&& file_ff_differs(buf
)))
2903 redraw_tabline
= TRUE
;
2906 need_maketitle
= TRUE
; /* set window title later */
2909 ++buf
->b_changedtick
;
2910 #ifdef FEAT_NETBEANS_INTG
2911 netbeans_unmodified(buf
);
2915 #if defined(FEAT_WINDOWS) || defined(PROTO)
2917 * check_status: called when the status bars for the buffer 'buf'
2918 * need to be updated
2926 for (wp
= firstwin
; wp
!= NULL
; wp
= wp
->w_next
)
2927 if (wp
->w_buffer
== buf
&& wp
->w_status_height
)
2929 wp
->w_redr_status
= TRUE
;
2930 if (must_redraw
< VALID
)
2931 must_redraw
= VALID
;
2937 * If the file is readonly, give a warning message with the first change.
2938 * Don't do this for autocommands.
2939 * Don't use emsg(), because it flushes the macro buffer.
2940 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
2945 int col
; /* column for message; non-zero when in insert
2946 mode and 'showmode' is on */
2948 if (curbuf
->b_did_warn
== FALSE
2949 && curbufIsChanged() == 0
2957 apply_autocmds(EVENT_FILECHANGEDRO
, NULL
, NULL
, FALSE
, curbuf
);
2959 if (!curbuf
->b_p_ro
)
2963 * Do what msg() does, but with a column offset if the warning should
2964 * be after the mode message.
2967 if (msg_row
== Rows
- 1)
2969 msg_source(hl_attr(HLF_W
));
2970 MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
2971 hl_attr(HLF_W
) | MSG_HIST
);
2974 if (msg_silent
== 0 && !silent_mode
)
2977 ui_delay(1000L, TRUE
); /* give the user time to think about it */
2979 curbuf
->b_did_warn
= TRUE
;
2980 redraw_cmdline
= FALSE
; /* don't redraw and erase the message */
2981 if (msg_row
< Rows
- 1)
2987 * Ask for a reply from the user, a 'y' or a 'n'.
2988 * No other characters are accepted, the message is repeated until a valid
2989 * reply is entered or CTRL-C is hit.
2990 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
2991 * from any buffers but directly from the user.
2993 * return the 'y' or 'n'
2996 ask_yesno(str
, direct
)
3001 int save_State
= State
;
3003 if (exiting
) /* put terminal in raw mode for this question */
3004 settmode(TMODE_RAW
);
3006 #ifdef USE_ON_FLY_SCROLL
3007 dont_scroll
= TRUE
; /* disallow scrolling here */
3009 State
= CONFIRM
; /* mouse behaves like with :confirm */
3011 setmouse(); /* disables mouse for xterm */
3014 ++allow_keys
; /* no mapping here, but recognize keys */
3016 while (r
!= 'y' && r
!= 'n')
3018 /* same highlighting as for wait_return */
3019 smsg_attr(hl_attr(HLF_R
), (char_u
*)"%s (y/n)?", str
);
3021 r
= get_keystroke();
3024 if (r
== Ctrl_C
|| r
== ESC
)
3026 msg_putchar(r
); /* show what you typed */
3041 * Get a key stroke directly from the user.
3042 * Ignores mouse clicks and scrollbar events, except a click for the left
3043 * button (used at the more prompt).
3044 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3045 * Disadvantage: typeahead is ignored.
3046 * Translates the interrupt character for unix to ESC.
3052 char_u buf
[CBUFLEN
];
3055 int save_mapped_ctrl_c
= mapped_ctrl_c
;
3058 mapped_ctrl_c
= FALSE
; /* mappings are not used here */
3064 /* First time: blocking wait. Second time: wait up to 100ms for a
3065 * terminal code to complete. Leave some room for check_termcode() to
3066 * insert a key code into (max 5 chars plus NUL). And
3067 * fix_input_buffer() can triple the number of bytes. */
3068 n
= ui_inchar(buf
+ len
, (CBUFLEN
- 6 - len
) / 3,
3069 len
== 0 ? -1L : 100L, 0);
3072 /* Replace zero and CSI by a special key code. */
3073 n
= fix_input_buffer(buf
+ len
, n
, FALSE
);
3078 ++waited
; /* keep track of the waiting time */
3080 /* Incomplete termcode and not timed out yet: get more characters */
3081 if ((n
= check_termcode(1, buf
, len
)) < 0
3082 && (!p_ttimeout
|| waited
* 100L < (p_ttm
< 0 ? p_tm
: p_ttm
)))
3085 /* found a termcode: adjust length */
3088 if (len
== 0) /* nothing typed yet */
3091 /* Handle modifier and/or special key code. */
3095 n
= TO_SPECIAL(buf
[1], buf
[2]);
3096 if (buf
[1] == KS_MODIFIER
3099 || n
== K_LEFTMOUSE_NM
3101 || n
== K_LEFTRELEASE
3102 || n
== K_LEFTRELEASE_NM
3103 || n
== K_MIDDLEMOUSE
3104 || n
== K_MIDDLEDRAG
3105 || n
== K_MIDDLERELEASE
3106 || n
== K_RIGHTMOUSE
3108 || n
== K_RIGHTRELEASE
3118 || n
== K_VER_SCROLLBAR
3119 || n
== K_HOR_SCROLLBAR
3124 if (buf
[1] == KS_MODIFIER
)
3128 mch_memmove(buf
, buf
+ 3, (size_t)len
);
3136 if (MB_BYTE2LEN(n
) > len
)
3137 continue; /* more bytes to get */
3138 buf
[len
>= CBUFLEN
? CBUFLEN
- 1 : len
] = NUL
;
3139 n
= (*mb_ptr2char
)(buf
);
3149 mapped_ctrl_c
= save_mapped_ctrl_c
;
3154 * Get a number from the user.
3155 * When "mouse_used" is not NULL allow using the mouse.
3158 get_number(colon
, mouse_used
)
3159 int colon
; /* allow colon to abort */
3166 if (mouse_used
!= NULL
)
3167 *mouse_used
= FALSE
;
3169 /* When not printing messages, the user won't know what to type, return a
3170 * zero (as if CR was hit). */
3171 if (msg_silent
!= 0)
3174 #ifdef USE_ON_FLY_SCROLL
3175 dont_scroll
= TRUE
; /* disallow scrolling here */
3178 ++allow_keys
; /* no mapping here, but recognize keys */
3181 windgoto(msg_row
, msg_col
);
3185 n
= n
* 10 + c
- '0';
3189 else if (c
== K_DEL
|| c
== K_KDEL
|| c
== K_BS
|| c
== Ctrl_H
)
3199 else if (mouse_used
!= NULL
&& c
== K_LEFTMOUSE
)
3206 else if (n
== 0 && c
== ':' && colon
)
3208 stuffcharReadbuff(':');
3210 cmdline_row
= msg_row
;
3211 skip_redraw
= TRUE
; /* skip redraw once */
3215 else if (c
== CAR
|| c
== NL
|| c
== Ctrl_C
|| c
== ESC
)
3224 * Ask the user to enter a number.
3225 * When "mouse_used" is not NULL allow using the mouse and in that case return
3229 prompt_for_number(mouse_used
)
3233 int save_cmdline_row
;
3236 /* When using ":silent" assume that <CR> was entered. */
3237 if (mouse_used
!= NULL
)
3238 MSG_PUTS(_("Type number or click with mouse (<Enter> cancels): "));
3240 MSG_PUTS(_("Choice number (<Enter> cancels): "));
3242 /* Set the state such that text can be selected/copied/pasted and we still
3243 * get mouse events. */
3244 save_cmdline_row
= cmdline_row
;
3249 i
= get_number(TRUE
, mouse_used
);
3252 /* don't call wait_return() now */
3253 /* msg_putchar('\n'); */
3254 cmdline_row
= msg_row
- 1;
3255 need_wait_return
= FALSE
;
3259 cmdline_row
= save_cmdline_row
;
3271 if (global_busy
/* no messages now, wait until global is finished */
3272 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3275 /* We don't want to overwrite another important message, but do overwrite
3276 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3277 * then "put" reports the last action. */
3278 if (keep_msg
!= NULL
&& !keep_msg_more
)
3291 STRCPY(msg_buf
, _("1 more line"));
3293 STRCPY(msg_buf
, _("1 line less"));
3298 sprintf((char *)msg_buf
, _("%ld more lines"), pn
);
3300 sprintf((char *)msg_buf
, _("%ld fewer lines"), pn
);
3303 STRCAT(msg_buf
, _(" (Interrupted)"));
3306 set_keep_msg(msg_buf
, 0);
3307 keep_msg_more
= TRUE
;
3313 * flush map and typeahead buffers and give a warning for an error
3318 if (emsg_silent
== 0)
3320 flush_buffers(FALSE
);
3326 * give a warning for an error
3331 if (emsg_silent
== 0)
3335 /* While the GUI is starting up the termcap is set for the GUI
3336 * but the output still goes to a terminal. */
3337 && !(gui
.in_use
&& gui
.starting
)
3347 * The number of beeps outputted is reduced to avoid having to wait
3348 * for all the beeps to finish. This is only a problem on systems
3349 * where the beeps don't overlap.
3351 if (beep_count
== 0 || beep_count
== 10)
3363 /* When 'verbose' is set and we are sourcing a script or executing a
3364 * function give the user a hint where the beep comes from. */
3365 if (vim_strchr(p_debug
, 'e') != NULL
)
3367 msg_source(hl_attr(HLF_W
));
3368 msg_attr((char_u
*)_("Beep!"), hl_attr(HLF_W
));
3374 * To get the "real" home directory:
3375 * - get value of $HOME
3377 * - go to that directory
3378 * - do mch_dirname() to get the real name of that directory.
3379 * This also works with mounts and links.
3380 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3382 static char_u
*homedir
= NULL
;
3389 /* In case we are called a second time (when 'encoding' changes). */
3394 var
= mch_getenv((char_u
*)"SYS$LOGIN");
3396 var
= mch_getenv((char_u
*)"HOME");
3399 if (var
!= NULL
&& *var
== NUL
) /* empty is same as not set */
3404 * Weird but true: $HOME may contain an indirect reference to another
3405 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3406 * when $HOME is being set.
3408 if (var
!= NULL
&& *var
== '%')
3413 p
= vim_strchr(var
+ 1, '%');
3416 vim_strncpy(NameBuff
, var
+ 1, p
- (var
+ 1));
3417 exp
= mch_getenv(NameBuff
);
3418 if (exp
!= NULL
&& *exp
!= NUL
3419 && STRLEN(exp
) + STRLEN(p
) < MAXPATHL
)
3421 vim_snprintf((char *)NameBuff
, MAXPATHL
, "%s%s", exp
, p
+ 1);
3423 /* Also set $HOME, it's needed for _viminfo. */
3424 vim_setenv((char_u
*)"HOME", NameBuff
);
3430 * Typically, $HOME is not defined on Windows, unless the user has
3431 * specifically defined it for Vim's sake. However, on Windows NT
3432 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3433 * each user. Try constructing $HOME from these.
3437 char_u
*homedrive
, *homepath
;
3439 homedrive
= mch_getenv((char_u
*)"HOMEDRIVE");
3440 homepath
= mch_getenv((char_u
*)"HOMEPATH");
3441 if (homedrive
!= NULL
&& homepath
!= NULL
3442 && STRLEN(homedrive
) + STRLEN(homepath
) < MAXPATHL
)
3444 sprintf((char *)NameBuff
, "%s%s", homedrive
, homepath
);
3445 if (NameBuff
[0] != NUL
)
3448 /* Also set $HOME, it's needed for _viminfo. */
3449 vim_setenv((char_u
*)"HOME", NameBuff
);
3454 # if defined(FEAT_MBYTE)
3455 if (enc_utf8
&& var
!= NULL
)
3460 /* Convert from active codepage to UTF-8. Other conversions are
3461 * not done, because they would fail for non-ASCII characters. */
3462 acp_to_enc(var
, (int)STRLEN(var
), &pp
, &len
);
3472 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3474 * Default home dir is C:/
3475 * Best assumption we can make in such a situation.
3484 * Change to the directory and get the actual path. This resolves
3485 * links. Don't do it when we can't return.
3487 if (mch_dirname(NameBuff
, MAXPATHL
) == OK
3488 && mch_chdir((char *)NameBuff
) == 0)
3490 if (!mch_chdir((char *)var
) && mch_dirname(IObuff
, IOSIZE
) == OK
)
3492 if (mch_chdir((char *)NameBuff
) != 0)
3493 EMSG(_(e_prev_dir
));
3496 homedir
= vim_strsave(var
);
3500 #if defined(EXITFREE) || defined(PROTO)
3509 * Call expand_env() and store the result in an allocated string.
3510 * This is not very memory efficient, this expects the result to be freed
3514 expand_env_save(src
)
3517 return expand_env_save_opt(src
, FALSE
);
3521 * Idem, but when "one" is TRUE handle the string as one file name, only
3522 * expand "~" at the start.
3525 expand_env_save_opt(src
, one
)
3531 p
= alloc(MAXPATHL
);
3533 expand_env_esc(src
, p
, MAXPATHL
, FALSE
, one
, NULL
);
3538 * Expand environment variable with path name.
3539 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3540 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
3541 * If anything fails no expansion is done and dst equals src.
3544 expand_env(src
, dst
, dstlen
)
3545 char_u
*src
; /* input string e.g. "$HOME/vim.hlp" */
3546 char_u
*dst
; /* where to put the result */
3547 int dstlen
; /* maximum length of the result */
3549 expand_env_esc(src
, dst
, dstlen
, FALSE
, FALSE
, NULL
);
3553 expand_env_esc(srcp
, dst
, dstlen
, esc
, one
, startstr
)
3554 char_u
*srcp
; /* input string e.g. "$HOME/vim.hlp" */
3555 char_u
*dst
; /* where to put the result */
3556 int dstlen
; /* maximum length of the result */
3557 int esc
; /* escape spaces in expanded variables */
3558 int one
; /* "srcp" is one file name */
3559 char_u
*startstr
; /* start again after this (can be NULL) */
3566 int mustfree
; /* var was allocated, need to free it later */
3567 int at_start
= TRUE
; /* at start of a name */
3568 int startstr_len
= 0;
3570 if (startstr
!= NULL
)
3571 startstr_len
= (int)STRLEN(startstr
);
3573 src
= skipwhite(srcp
);
3574 --dstlen
; /* leave one char space for "\," */
3575 while (*src
&& dstlen
> 0)
3583 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3586 || (*src
== '~' && at_start
))
3591 * The variable name is copied into dst temporarily, because it may
3592 * be a string in read-only memory and a NUL needs to be appended.
3594 if (*src
!= '~') /* environment var */
3601 /* Unix has ${var-name} type environment vars */
3602 if (*tail
== '{' && !vim_isIDc('{'))
3604 tail
++; /* ignore '{' */
3605 while (c
-- > 0 && *tail
&& *tail
!= '}')
3611 while (c
-- > 0 && *tail
!= NUL
&& ((vim_isIDc(*tail
))
3612 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3613 || (*src
== '%' && *tail
!= '%')
3617 #ifdef OS2 /* env vars only in uppercase */
3618 *var
++ = TOUPPER_LOC(*tail
);
3619 tail
++; /* toupper() may be a macro! */
3626 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3628 if (src
[1] == '{' && *tail
!= '}')
3630 if (*src
== '%' && *tail
!= '%')
3643 var
= vim_getenv(dst
, &mustfree
);
3644 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3648 /* home directory */
3649 else if ( src
[1] == NUL
3650 || vim_ispathsep(src
[1])
3651 || vim_strchr((char_u
*)" ,\t\n", src
[1]) != NULL
)
3656 else /* user directory */
3658 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3660 * Copy ~user to dst[], so we can put a NUL after it.
3667 && vim_isfilec(*tail
)
3668 && !vim_ispathsep(*tail
))
3673 * If the system supports getpwnam(), use it.
3674 * Otherwise, or if getpwnam() fails, the shell is used to
3675 * expand ~user. This is slower and may fail if the shell
3676 * does not support ~user (old versions of /bin/sh).
3678 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3682 /* Note: memory allocated by getpwnam() is never freed.
3683 * Calling endpwent() apparently doesn't help. */
3684 pw
= getpwnam((char *)dst
+ 1);
3686 var
= (char_u
*)pw
->pw_dir
;
3696 xpc
.xp_context
= EXPAND_FILES
;
3697 var
= ExpandOne(&xpc
, dst
, NULL
,
3698 WILD_ADD_SLASH
|WILD_SILENT
, WILD_EXPAND_FREE
);
3702 # else /* !UNIX, thus VMS */
3704 * USER_HOME is a comma-separated list of
3705 * directories to search for the user account in.
3708 char_u test
[MAXPATHL
], paths
[MAXPATHL
];
3709 char_u
*path
, *next_path
, *ptr
;
3712 STRCPY(paths
, USER_HOME
);
3716 for (path
= next_path
; *next_path
&& *next_path
!= ',';
3722 STRCAT(test
, dst
+ 1);
3723 if (mch_stat(test
, &st
) == 0)
3725 var
= alloc(STRLEN(test
) + 1);
3734 /* cannot expand user's home directory, so don't try */
3736 tail
= (char_u
*)""; /* for gcc */
3737 #endif /* UNIX || VMS */
3740 #ifdef BACKSLASH_IN_FILENAME
3741 /* If 'shellslash' is set change backslashes to forward slashes.
3742 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3743 if (p_ssl
&& var
!= NULL
&& vim_strchr(var
, '\\') != NULL
)
3745 char_u
*p
= vim_strsave(var
);
3758 /* If "var" contains white space, escape it with a backslash.
3759 * Required for ":e ~/tt" when $HOME includes a space. */
3760 if (esc
&& var
!= NULL
&& vim_strpbrk(var
, (char_u
*)" \t") != NULL
)
3762 char_u
*p
= vim_strsave_escaped(var
, (char_u
*)" \t");
3773 if (var
!= NULL
&& *var
!= NUL
3774 && (STRLEN(var
) + STRLEN(tail
) + 1 < (unsigned)dstlen
))
3777 dstlen
-= (int)STRLEN(var
);
3778 c
= (int)STRLEN(var
);
3779 /* if var[] ends in a path separator and tail[] starts
3780 * with it, skip a character */
3781 if (*var
!= NUL
&& after_pathsep(dst
, dst
+ c
)
3782 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3785 && vim_ispathsep(*tail
))
3795 if (copy_char
) /* copy at least one char */
3798 * Recognize the start of a new name, for '~'.
3799 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3800 * ":edit foo ~ foo".
3803 if (src
[0] == '\\' && src
[1] != NUL
)
3808 else if ((src
[0] == ' ' || src
[0] == ',') && !one
)
3813 if (startstr
!= NULL
&& src
- startstr_len
>= srcp
3814 && STRNCMP(src
- startstr_len
, startstr
, startstr_len
) == 0)
3822 * Vim's version of getenv().
3823 * Special handling of $HOME, $VIM and $VIMRUNTIME.
3824 * Also does ACP to 'enc' conversion for Win32.
3827 vim_getenv(name
, mustfree
)
3829 int *mustfree
; /* set to TRUE when returned is allocated */
3835 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3836 /* use "C:/" when $HOME is not set */
3837 if (STRCMP(name
, "HOME") == 0)
3841 p
= mch_getenv(name
);
3842 if (p
!= NULL
&& *p
== NUL
) /* empty is the same as not set */
3847 #if defined(FEAT_MBYTE) && defined(WIN3264)
3853 /* Convert from active codepage to UTF-8. Other conversions are
3854 * not done, because they would fail for non-ASCII characters. */
3855 acp_to_enc(p
, (int)STRLEN(p
), &pp
, &len
);
3866 vimruntime
= (STRCMP(name
, "VIMRUNTIME") == 0);
3867 if (!vimruntime
&& STRCMP(name
, "VIM") != 0)
3871 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3872 * Don't do this when default_vimruntime_dir is non-empty.
3876 && *default_vimruntime_dir
== NUL
3880 p
= mch_getenv((char_u
*)"VIM");
3881 if (p
!= NULL
&& *p
== NUL
) /* empty is the same as not set */
3885 p
= vim_version_dir(p
);
3889 p
= mch_getenv((char_u
*)"VIM");
3891 #if defined(FEAT_MBYTE) && defined(WIN3264)
3897 /* Convert from active codepage to UTF-8. Other conversions
3898 * are not done, because they would fail for non-ASCII
3900 acp_to_enc(p
, (int)STRLEN(p
), &pp
, &len
);
3914 * When expanding $VIM or $VIMRUNTIME fails, try using:
3915 * - the directory name from 'helpfile' (unless it contains '$')
3916 * - the executable name from argv[0]
3920 if (p_hf
!= NULL
&& vim_strchr(p_hf
, '$') == NULL
)
3924 * Use the name of the executable, obtained from argv[0].
3931 /* remove the file name */
3934 /* remove "doc/" from 'helpfile', if present */
3936 pend
= remove_tail(p
, pend
, (char_u
*)"doc");
3940 /* remove "MacOS" from exe_name and add "Resources/vim" */
3946 pend1
= remove_tail(p
, pend
, (char_u
*)"MacOS");
3949 pnew
= alloc((unsigned)(pend1
- p
) + 15);
3952 STRNCPY(pnew
, p
, (pend1
- p
));
3953 STRCPY(pnew
+ (pend1
- p
), "Resources/vim");
3955 pend
= p
+ STRLEN(p
);
3960 /* remove "src/" from exe_name, if present */
3962 pend
= remove_tail(p
, pend
, (char_u
*)"src");
3965 /* for $VIM, remove "runtime/" or "vim54/", if present */
3968 pend
= remove_tail(p
, pend
, (char_u
*)RUNTIME_DIRNAME
);
3969 pend
= remove_tail(p
, pend
, (char_u
*)VIM_VERSION_NODOT
);
3972 /* remove trailing path separator */
3973 #ifndef MACOS_CLASSIC
3974 /* With MacOS path (with colons) the final colon is required */
3975 /* to avoid confusion between absoulute and relative path */
3976 if (pend
> p
&& after_pathsep(p
, pend
))
3981 if (p
== exe_name
|| p
== p_hf
)
3983 /* check that the result is a directory name */
3984 p
= vim_strnsave(p
, (int)(pend
- p
));
3986 if (p
!= NULL
&& !mch_isdir(p
))
3994 /* may add "/vim54" or "/runtime" if it exists */
3995 if (vimruntime
&& (pend
= vim_version_dir(p
)) != NULL
)
4007 /* When there is a pathdef.c file we can use default_vim_dir and
4008 * default_vimruntime_dir */
4011 /* Only use default_vimruntime_dir when it is not empty */
4012 if (vimruntime
&& *default_vimruntime_dir
!= NUL
)
4014 p
= default_vimruntime_dir
;
4017 else if (*default_vim_dir
!= NUL
)
4019 if (vimruntime
&& (p
= vim_version_dir(default_vim_dir
)) != NULL
)
4023 p
= default_vim_dir
;
4031 * Set the environment variable, so that the new value can be found fast
4032 * next time, and others can also use it (e.g. Perl).
4038 vim_setenv((char_u
*)"VIMRUNTIME", p
);
4039 didset_vimruntime
= TRUE
;
4042 char_u
*buf
= concat_str(p
, (char_u
*)"/lang");
4046 bindtextdomain(VIMPACKAGE
, (char *)buf
);
4054 vim_setenv((char_u
*)"VIM", p
);
4062 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4063 * Return NULL if not, return its name in allocated memory otherwise.
4066 vim_version_dir(vimdir
)
4071 if (vimdir
== NULL
|| *vimdir
== NUL
)
4073 p
= concat_fnames(vimdir
, (char_u
*)VIM_VERSION_NODOT
, TRUE
);
4074 if (p
!= NULL
&& mch_isdir(p
))
4077 p
= concat_fnames(vimdir
, (char_u
*)RUNTIME_DIRNAME
, TRUE
);
4078 if (p
!= NULL
&& mch_isdir(p
))
4085 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4086 * the length of "name/". Otherwise return "pend".
4089 remove_tail(p
, pend
, name
)
4094 int len
= (int)STRLEN(name
) + 1;
4095 char_u
*newend
= pend
- len
;
4098 && fnamencmp(newend
, name
, len
- 1) == 0
4099 && (newend
== p
|| after_pathsep(p
, newend
)))
4105 * Our portable version of setenv.
4108 vim_setenv(name
, val
)
4113 mch_setenv((char *)name
, (char *)val
, 1);
4118 * Putenv does not copy the string, it has to remain
4119 * valid. The allocated memory will never be freed.
4121 envbuf
= alloc((unsigned)(STRLEN(name
) + STRLEN(val
) + 2));
4124 sprintf((char *)envbuf
, "%s=%s", name
, val
);
4125 putenv((char *)envbuf
);
4130 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4132 * Function given to ExpandGeneric() to obtain an environment variable name.
4136 get_env_name(xp
, idx
)
4140 # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4142 * No environ[] on the Amiga and on the Mac (using MPW).
4147 /* Borland C++ 5.2 has this in a header file. */
4148 extern char **environ
;
4150 # define ENVNAMELEN 100
4151 static char_u name
[ENVNAMELEN
];
4155 str
= (char_u
*)environ
[idx
];
4159 for (n
= 0; n
< ENVNAMELEN
- 1; ++n
)
4161 if (str
[n
] == '=' || str
[n
] == NUL
)
4172 * Replace home directory by "~" in each space or comma separated file name in
4174 * If anything fails (except when out of space) dst equals src.
4177 home_replace(buf
, src
, dst
, dstlen
, one
)
4178 buf_T
*buf
; /* when not NULL, check for help files */
4179 char_u
*src
; /* input file name */
4180 char_u
*dst
; /* where to put the result */
4181 int dstlen
; /* maximum length of the result */
4182 int one
; /* if TRUE, only replace one file name, include
4183 spaces and commas in the file name. */
4185 size_t dirlen
= 0, envlen
= 0;
4187 char_u
*homedir_env
;
4197 * If the file is a help file, remove the path completely.
4199 if (buf
!= NULL
&& buf
->b_help
)
4201 STRCPY(dst
, gettail(src
));
4206 * We check both the value of the $HOME environment variable and the
4207 * "real" home directory.
4209 if (homedir
!= NULL
)
4210 dirlen
= STRLEN(homedir
);
4213 homedir_env
= mch_getenv((char_u
*)"SYS$LOGIN");
4215 homedir_env
= mch_getenv((char_u
*)"HOME");
4218 if (homedir_env
!= NULL
&& *homedir_env
== NUL
)
4220 if (homedir_env
!= NULL
)
4221 envlen
= STRLEN(homedir_env
);
4224 src
= skipwhite(src
);
4225 while (*src
&& dstlen
> 0)
4228 * Here we are at the beginning of a file name.
4229 * First, check to see if the beginning of the file name matches
4230 * $HOME or the "real" home directory. Check that there is a '/'
4231 * after the match (so that if e.g. the file is "/home/pieter/bla",
4232 * and the home directory is "/home/piet", the file does not end up
4233 * as "~er/bla" (which would seem to indicate the file "bla" in user
4234 * er's home directory)).
4241 && fnamencmp(src
, p
, len
) == 0
4242 && (vim_ispathsep(src
[len
])
4243 || (!one
&& (src
[len
] == ',' || src
[len
] == ' '))
4244 || src
[len
] == NUL
))
4251 * If it's just the home directory, add "/".
4253 if (!vim_ispathsep(src
[0]) && --dstlen
> 0)
4257 if (p
== homedir_env
)
4263 /* if (!one) skip to separator: space or comma */
4264 while (*src
&& (one
|| (*src
!= ',' && *src
!= ' ')) && --dstlen
> 0)
4266 /* skip separator */
4267 while ((*src
== ' ' || *src
== ',') && --dstlen
> 0)
4270 /* if (dstlen == 0) out of space, what to do??? */
4276 * Like home_replace, store the replaced string in allocated memory.
4277 * When something fails, NULL is returned.
4280 home_replace_save(buf
, src
)
4281 buf_T
*buf
; /* when not NULL, check for help files */
4282 char_u
*src
; /* input file name */
4287 len
= 3; /* space for "~/" and trailing NUL */
4288 if (src
!= NULL
) /* just in case */
4289 len
+= (unsigned)STRLEN(src
);
4292 home_replace(buf
, src
, dst
, len
, TRUE
);
4297 * Compare two file names and return:
4298 * FPC_SAME if they both exist and are the same file.
4299 * FPC_SAMEX if they both don't exist and have the same file name.
4300 * FPC_DIFF if they both exist and are different files.
4301 * FPC_NOTX if they both don't exist.
4302 * FPC_DIFFX if one of them doesn't exist.
4303 * For the first name environment variables are expanded
4306 fullpathcmp(s1
, s2
, checkname
)
4308 int checkname
; /* when both don't exist, check file names */
4311 char_u exp1
[MAXPATHL
];
4312 char_u full1
[MAXPATHL
];
4313 char_u full2
[MAXPATHL
];
4314 struct stat st1
, st2
;
4317 expand_env(s1
, exp1
, MAXPATHL
);
4318 r1
= mch_stat((char *)exp1
, &st1
);
4319 r2
= mch_stat((char *)s2
, &st2
);
4320 if (r1
!= 0 && r2
!= 0)
4322 /* if mch_stat() doesn't work, may compare the names */
4325 if (fnamecmp(exp1
, s2
) == 0)
4327 r1
= vim_FullName(exp1
, full1
, MAXPATHL
, FALSE
);
4328 r2
= vim_FullName(s2
, full2
, MAXPATHL
, FALSE
);
4329 if (r1
== OK
&& r2
== OK
&& fnamecmp(full1
, full2
) == 0)
4334 if (r1
!= 0 || r2
!= 0)
4336 if (st1
.st_dev
== st2
.st_dev
&& st1
.st_ino
== st2
.st_ino
)
4340 char_u
*exp1
; /* expanded s1 */
4341 char_u
*full1
; /* full path of s1 */
4342 char_u
*full2
; /* full path of s2 */
4343 int retval
= FPC_DIFF
;
4346 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4347 if ((exp1
= alloc(MAXPATHL
* 3)) != NULL
)
4349 full1
= exp1
+ MAXPATHL
;
4350 full2
= full1
+ MAXPATHL
;
4352 expand_env(s1
, exp1
, MAXPATHL
);
4353 r1
= vim_FullName(exp1
, full1
, MAXPATHL
, FALSE
);
4354 r2
= vim_FullName(s2
, full2
, MAXPATHL
, FALSE
);
4356 /* If vim_FullName() fails, the file probably doesn't exist. */
4357 if (r1
!= OK
&& r2
!= OK
)
4359 if (checkname
&& fnamecmp(exp1
, s2
) == 0)
4364 else if (r1
!= OK
|| r2
!= OK
)
4366 else if (fnamecmp(full1
, full2
))
4377 * Get the tail of a path: the file name.
4378 * Fail safe: never returns NULL.
4387 return (char_u
*)"";
4388 for (p1
= p2
= fname
; *p2
; ) /* find last part of path */
4390 if (vim_ispathsep(*p2
))
4398 * Get pointer to tail of "fname", including path separators. Putting a NUL
4399 * here leaves the directory name. Takes care of "c:/" and "//".
4400 * Always returns a valid pointer.
4409 p
= get_past_head(fname
); /* don't remove the '/' from "c:/file" */
4411 while (t
> p
&& after_pathsep(fname
, t
))
4414 /* path separator is part of the path */
4421 * get the next path component (just after the next path separator).
4427 while (*fname
&& !vim_ispathsep(*fname
))
4435 * Get a pointer to one character past the head of a path name.
4436 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4437 * If there is no head, path is returned.
4445 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4447 if (isalpha(path
[0]) && path
[1] == ':')
4453 /* may skip "label:" */
4454 retval
= vim_strchr(path
, ':');
4462 while (vim_ispathsep(*retval
))
4469 * return TRUE if 'c' is a path separator.
4476 return (c
== '.' || c
== ':');
4479 return (c
== '/'); /* UNIX has ':' inside file names */
4481 # ifdef BACKSLASH_IN_FILENAME
4482 return (c
== ':' || c
== '/' || c
== '\\');
4485 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4486 return (c
== ':' || c
== '[' || c
== ']' || c
== '/'
4487 || c
== '<' || c
== '>' || c
== '"' );
4489 return (c
== ':' || c
== '/');
4493 #endif /* RISC OS */
4496 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
4498 * return TRUE if 'c' is a path list separator.
4501 vim_ispathlistsep(c
)
4507 return (c
== ';'); /* might not be right for every system... */
4512 #if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4513 || defined(FEAT_EVAL) || defined(PROTO)
4515 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4516 * It's done in-place.
4522 char_u
*tail
, *s
, *d
;
4525 tail
= gettail(str
);
4527 for (s
= str
; ; ++s
)
4529 if (s
>= tail
) /* copy the whole tail */
4535 else if (vim_ispathsep(*s
)) /* copy '/' and next char */
4542 *d
++ = *s
; /* copy next char */
4543 if (*s
!= '~' && *s
!= '.') /* and leading "~" and "." */
4548 int l
= mb_ptr2len(s
);
4560 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4561 * Also returns TRUE if there is no directory name.
4562 * "fname" must be writable!.
4565 dir_of_file_exists(fname
)
4572 p
= gettail_sep(fname
);
4577 retval
= mch_isdir(fname
);
4582 #if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4585 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4591 return vim_fnamencmp(x
, y
, MAXPATHL
);
4595 vim_fnamencmp(x
, y
, len
)
4599 while (len
> 0 && *x
&& *y
)
4601 if (TOLOWER_LOC(*x
) != TOLOWER_LOC(*y
)
4602 && !(*x
== '/' && *y
== '\\')
4603 && !(*x
== '\\' && *y
== '/'))
4616 * Concatenate file names fname1 and fname2 into allocated memory.
4617 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
4620 concat_fnames(fname1
, fname2
, sep
)
4627 dest
= alloc((unsigned)(STRLEN(fname1
) + STRLEN(fname2
) + 3));
4630 STRCPY(dest
, fname1
);
4633 STRCAT(dest
, fname2
);
4638 #if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4640 * Concatenate two strings and return the result in allocated memory.
4641 * Returns NULL when out of memory.
4644 concat_str(str1
, str2
)
4649 size_t l
= STRLEN(str1
);
4651 dest
= alloc((unsigned)(l
+ STRLEN(str2
) + 1L));
4655 STRCPY(dest
+ l
, str2
);
4662 * Add a path separator to a file name, unless it already ends in a path
4669 if (*p
!= NUL
&& !after_pathsep(p
, p
+ STRLEN(p
)))
4670 STRCAT(p
, PATHSEPSTR
);
4674 * FullName_save - Make an allocated copy of a full file name.
4675 * Returns NULL when out of memory.
4678 FullName_save(fname
, force
)
4680 int force
; /* force expansion, even when it already looks
4681 like a full path name */
4684 char_u
*new_fname
= NULL
;
4689 buf
= alloc((unsigned)MAXPATHL
);
4692 if (vim_FullName(fname
, buf
, MAXPATHL
, force
) != FAIL
)
4693 new_fname
= vim_strsave(buf
);
4695 new_fname
= vim_strsave(fname
);
4701 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4703 static char_u
*skip_string
__ARGS((char_u
*p
));
4706 * Find the start of a comment, not knowing if we are in a comment right now.
4707 * Search starts at w_cursor.lnum and goes backwards.
4710 find_start_comment(ind_maxcomment
) /* XXX */
4716 int cur_maxcomment
= ind_maxcomment
;
4720 pos
= findmatchlimit(NULL
, '*', FM_BACKWARD
, cur_maxcomment
);
4725 * Check if the comment start we found is inside a string.
4726 * If it is then restrict the search to below this line and try again.
4728 line
= ml_get(pos
->lnum
);
4729 for (p
= line
; *p
&& (unsigned)(p
- line
) < pos
->col
; ++p
)
4731 if ((unsigned)(p
- line
) <= pos
->col
)
4733 cur_maxcomment
= curwin
->w_cursor
.lnum
- pos
->lnum
- 1;
4734 if (cur_maxcomment
<= 0)
4744 * Skip to the end of a "string" and a 'c' character.
4745 * If there is no string or character, return argument unmodified.
4754 * We loop, because strings may be concatenated: "date""time".
4758 if (p
[0] == '\'') /* 'c' or '\n' or '\000' */
4760 if (!p
[1]) /* ' at end of line */
4763 if (p
[1] == '\\') /* '\n' or '\000' */
4766 while (vim_isdigit(p
[i
- 1])) /* '\000' */
4769 if (p
[i
] == '\'') /* check for trailing ' */
4775 else if (p
[0] == '"') /* start of string */
4777 for (++p
; p
[0]; ++p
)
4779 if (p
[0] == '\\' && p
[1] != NUL
)
4781 else if (p
[0] == '"') /* end of string */
4787 break; /* no string found */
4790 --p
; /* backup from NUL */
4793 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
4795 #if defined(FEAT_CINDENT) || defined(PROTO)
4798 * Do C or expression indenting on the current line.
4804 if (*curbuf
->b_p_inde
!= NUL
)
4805 fixthisline(get_expr_indent
);
4808 fixthisline(get_c_indent
);
4812 * Functions for C-indenting.
4813 * Most of this originally comes from Eric Fischer.
4816 * Below "XXX" means that this function may unlock the current line.
4819 static char_u
*cin_skipcomment
__ARGS((char_u
*));
4820 static int cin_nocode
__ARGS((char_u
*));
4821 static pos_T
*find_line_comment
__ARGS((void));
4822 static int cin_islabel_skip
__ARGS((char_u
**));
4823 static int cin_isdefault
__ARGS((char_u
*));
4824 static char_u
*after_label
__ARGS((char_u
*l
));
4825 static int get_indent_nolabel
__ARGS((linenr_T lnum
));
4826 static int skip_label
__ARGS((linenr_T
, char_u
**pp
, int ind_maxcomment
));
4827 static int cin_first_id_amount
__ARGS((void));
4828 static int cin_get_equal_amount
__ARGS((linenr_T lnum
));
4829 static int cin_ispreproc
__ARGS((char_u
*));
4830 static int cin_ispreproc_cont
__ARGS((char_u
**pp
, linenr_T
*lnump
));
4831 static int cin_iscomment
__ARGS((char_u
*));
4832 static int cin_islinecomment
__ARGS((char_u
*));
4833 static int cin_isterminated
__ARGS((char_u
*, int, int));
4834 static int cin_isinit
__ARGS((void));
4835 static int cin_isfuncdecl
__ARGS((char_u
**, linenr_T
));
4836 static int cin_isif
__ARGS((char_u
*));
4837 static int cin_iselse
__ARGS((char_u
*));
4838 static int cin_isdo
__ARGS((char_u
*));
4839 static int cin_iswhileofdo
__ARGS((char_u
*, linenr_T
, int));
4840 static int cin_iswhileofdo_end
__ARGS((int terminated
, int ind_maxparen
, int ind_maxcomment
));
4841 static int cin_isbreak
__ARGS((char_u
*));
4842 static int cin_is_cpp_baseclass
__ARGS((colnr_T
*col
));
4843 static int get_baseclass_amount
__ARGS((int col
, int ind_maxparen
, int ind_maxcomment
, int ind_cpp_baseclass
));
4844 static int cin_ends_in
__ARGS((char_u
*, char_u
*, char_u
*));
4845 static int cin_skip2pos
__ARGS((pos_T
*trypos
));
4846 static pos_T
*find_start_brace
__ARGS((int));
4847 static pos_T
*find_match_paren
__ARGS((int, int));
4848 static int corr_ind_maxparen
__ARGS((int ind_maxparen
, pos_T
*startpos
));
4849 static int find_last_paren
__ARGS((char_u
*l
, int start
, int end
));
4850 static int find_match
__ARGS((int lookfor
, linenr_T ourscope
, int ind_maxparen
, int ind_maxcomment
));
4852 static int ind_hash_comment
= 0; /* # starts a comment */
4855 * Skip over white space and C comments within the line.
4856 * Also skip over Perl/shell comments if desired.
4868 /* Perl/shell # comment comment continues until eol. Require a space
4869 * before # to avoid recognizing $#array. */
4870 if (ind_hash_comment
!= 0 && s
!= prev_s
&& *s
== '#')
4878 if (*s
== '/') /* slash-slash comment continues till eol */
4885 for (++s
; *s
; ++s
) /* skip slash-star comment */
4886 if (s
[0] == '*' && s
[1] == '/')
4896 * Return TRUE if there there is no code at *s. White space and comments are
4897 * not considered code.
4903 return *cin_skipcomment(s
) == NUL
;
4907 * Check previous lines for a "//" line comment, skipping over blank lines.
4910 find_line_comment() /* XXX */
4916 pos
= curwin
->w_cursor
;
4917 while (--pos
.lnum
> 0)
4919 line
= ml_get(pos
.lnum
);
4920 p
= skipwhite(line
);
4921 if (cin_islinecomment(p
))
4923 pos
.col
= (int)(p
- line
);
4933 * Check if string matches "label:"; move to character after ':' if true.
4939 if (!vim_isIDc(**s
)) /* need at least one ID character */
4942 while (vim_isIDc(**s
))
4945 *s
= cin_skipcomment(*s
);
4947 /* "::" is not a label, it's C++ */
4948 return (**s
== ':' && *++*s
!= ':');
4952 * Recognize a label: "label:".
4953 * Note: curwin->w_cursor must be where we are looking for the label.
4956 cin_islabel(ind_maxcomment
) /* XXX */
4961 s
= cin_skipcomment(ml_get_curline());
4964 * Exclude "default" from labels, since it should be indented
4965 * like a switch label. Same for C++ scope declarations.
4967 if (cin_isdefault(s
))
4969 if (cin_isscopedecl(s
))
4972 if (cin_islabel_skip(&s
))
4975 * Only accept a label if the previous line is terminated or is a case
4982 cursor_save
= curwin
->w_cursor
;
4983 while (curwin
->w_cursor
.lnum
> 1)
4985 --curwin
->w_cursor
.lnum
;
4988 * If we're in a comment now, skip to the start of the comment.
4990 curwin
->w_cursor
.col
= 0;
4991 if ((trypos
= find_start_comment(ind_maxcomment
)) != NULL
) /* XXX */
4992 curwin
->w_cursor
= *trypos
;
4994 line
= ml_get_curline();
4995 if (cin_ispreproc(line
)) /* ignore #defines, #if, etc. */
4997 if (*(line
= cin_skipcomment(line
)) == NUL
)
5000 curwin
->w_cursor
= cursor_save
;
5001 if (cin_isterminated(line
, TRUE
, FALSE
)
5002 || cin_isscopedecl(line
)
5004 || (cin_islabel_skip(&line
) && cin_nocode(line
)))
5008 curwin
->w_cursor
= cursor_save
;
5009 return TRUE
; /* label at start of file??? */
5015 * Recognize structure initialization and enumerations.
5016 * Q&D-Implementation:
5017 * check for "=" at end or "[typedef] enum" at beginning of line.
5024 s
= cin_skipcomment(ml_get_curline());
5026 if (STRNCMP(s
, "typedef", 7) == 0 && !vim_isIDc(s
[7]))
5027 s
= cin_skipcomment(s
+ 7);
5029 if (STRNCMP(s
, "enum", 4) == 0 && !vim_isIDc(s
[4]))
5032 if (cin_ends_in(s
, (char_u
*)"=", (char_u
*)"{"))
5039 * Recognize a switch label: "case .*:" or "default:".
5045 s
= cin_skipcomment(s
);
5046 if (STRNCMP(s
, "case", 4) == 0 && !vim_isIDc(s
[4]))
5048 for (s
+= 4; *s
; ++s
)
5050 s
= cin_skipcomment(s
);
5053 if (s
[1] == ':') /* skip over "::" for C++ */
5058 if (*s
== '\'' && s
[1] && s
[2] == '\'')
5059 s
+= 2; /* skip over '.' */
5060 else if (*s
== '/' && (s
[1] == '*' || s
[1] == '/'))
5061 return FALSE
; /* stop at comment */
5063 return FALSE
; /* stop at string */
5068 if (cin_isdefault(s
))
5074 * Recognize a "default" switch label.
5080 return (STRNCMP(s
, "default", 7) == 0
5081 && *(s
= cin_skipcomment(s
+ 7)) == ':'
5086 * Recognize a "public/private/proctected" scope declaration label.
5094 s
= cin_skipcomment(s
);
5095 if (STRNCMP(s
, "public", 6) == 0)
5097 else if (STRNCMP(s
, "protected", 9) == 0)
5099 else if (STRNCMP(s
, "private", 7) == 0)
5103 return (*(s
= cin_skipcomment(s
+ i
)) == ':' && s
[1] != ':');
5107 * Return a pointer to the first non-empty non-comment character after a ':'.
5108 * Return NULL if not found.
5120 if (l
[1] == ':') /* skip over "::" for C++ */
5122 else if (!cin_iscase(l
+ 1))
5125 else if (*l
== '\'' && l
[1] && l
[2] == '\'')
5126 l
+= 2; /* skip over 'x' */
5130 l
= cin_skipcomment(l
+ 1);
5137 * Get indent of line "lnum", skipping a label.
5138 * Return 0 if there is nothing after the label.
5141 get_indent_nolabel(lnum
) /* XXX */
5154 fp
.col
= (colnr_T
)(p
- l
);
5156 getvcol(curwin
, &fp
, &col
, NULL
, NULL
);
5161 * Find indent for line "lnum", ignoring any case or jump label.
5162 * Also return a pointer to the text (after the label) in "pp".
5163 * label: if (asdf && asdfasdf)
5167 skip_label(lnum
, pp
, ind_maxcomment
)
5176 cursor_save
= curwin
->w_cursor
;
5177 curwin
->w_cursor
.lnum
= lnum
;
5178 l
= ml_get_curline();
5180 if (cin_iscase(l
) || cin_isscopedecl(l
) || cin_islabel(ind_maxcomment
))
5182 amount
= get_indent_nolabel(lnum
);
5183 l
= after_label(ml_get_curline());
5184 if (l
== NULL
) /* just in case */
5185 l
= ml_get_curline();
5189 amount
= get_indent();
5190 l
= ml_get_curline();
5194 curwin
->w_cursor
= cursor_save
;
5199 * Return the indent of the first variable name after a type in a declaration.
5200 * int a, indent of "a"
5201 * static struct foo b, indent of "b"
5202 * enum bla c, indent of "c"
5203 * Returns zero when it doesn't look like a declaration.
5206 cin_first_id_amount()
5208 char_u
*line
, *p
, *s
;
5213 line
= ml_get_curline();
5214 p
= skipwhite(line
);
5215 len
= (int)(skiptowhite(p
) - p
);
5216 if (len
== 6 && STRNCMP(p
, "static", 6) == 0)
5218 p
= skipwhite(p
+ 6);
5219 len
= (int)(skiptowhite(p
) - p
);
5221 if (len
== 6 && STRNCMP(p
, "struct", 6) == 0)
5222 p
= skipwhite(p
+ 6);
5223 else if (len
== 4 && STRNCMP(p
, "enum", 4) == 0)
5224 p
= skipwhite(p
+ 4);
5225 else if ((len
== 8 && STRNCMP(p
, "unsigned", 8) == 0)
5226 || (len
== 6 && STRNCMP(p
, "signed", 6) == 0))
5228 s
= skipwhite(p
+ len
);
5229 if ((STRNCMP(s
, "int", 3) == 0 && vim_iswhite(s
[3]))
5230 || (STRNCMP(s
, "long", 4) == 0 && vim_iswhite(s
[4]))
5231 || (STRNCMP(s
, "short", 5) == 0 && vim_iswhite(s
[5]))
5232 || (STRNCMP(s
, "char", 4) == 0 && vim_iswhite(s
[4])))
5235 for (len
= 0; vim_isIDc(p
[len
]); ++len
)
5237 if (len
== 0 || !vim_iswhite(p
[len
]) || cin_nocode(p
))
5240 p
= skipwhite(p
+ len
);
5241 fp
.lnum
= curwin
->w_cursor
.lnum
;
5242 fp
.col
= (colnr_T
)(p
- line
);
5243 getvcol(curwin
, &fp
, &col
, NULL
, NULL
);
5248 * Return the indent of the first non-blank after an equal sign.
5249 * char *foo = "here";
5250 * Return zero if no (useful) equal sign found.
5251 * Return -1 if the line above "lnum" ends in a backslash.
5257 cin_get_equal_amount(lnum
)
5267 line
= ml_get(lnum
- 1);
5268 if (*line
!= NUL
&& line
[STRLEN(line
) - 1] == '\\')
5272 line
= s
= ml_get(lnum
);
5273 while (*s
!= NUL
&& vim_strchr((char_u
*)"=;{}\"'", *s
) == NULL
)
5275 if (cin_iscomment(s
)) /* ignore comments */
5276 s
= cin_skipcomment(s
);
5283 s
= skipwhite(s
+ 1);
5287 if (*s
== '"') /* nice alignment for continued strings */
5291 fp
.col
= (colnr_T
)(s
- line
);
5292 getvcol(curwin
, &fp
, &col
, NULL
, NULL
);
5297 * Recognize a preprocessor statement: Any line that starts with '#'.
5310 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5311 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5312 * start and return the line in "*pp".
5315 cin_ispreproc_cont(pp
, lnump
)
5320 linenr_T lnum
= *lnump
;
5325 if (cin_ispreproc(line
))
5333 line
= ml_get(--lnum
);
5334 if (*line
== NUL
|| line
[STRLEN(line
) - 1] != '\\')
5339 *pp
= ml_get(*lnump
);
5344 * Recognize the start of a C or C++ comment.
5350 return (p
[0] == '/' && (p
[1] == '*' || p
[1] == '/'));
5354 * Recognize the start of a "//" comment.
5357 cin_islinecomment(p
)
5360 return (p
[0] == '/' && p
[1] == '/');
5364 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5365 * Don't consider "} else" a terminated line.
5366 * Return the character terminating the line (ending char's have precedence if
5367 * both apply in order to determine initializations).
5370 cin_isterminated(s
, incl_open
, incl_comma
)
5372 int incl_open
; /* include '{' at the end as terminator */
5373 int incl_comma
; /* recognize a trailing comma */
5375 char_u found_start
= 0;
5377 s
= cin_skipcomment(s
);
5379 if (*s
== '{' || (*s
== '}' && !cin_iselse(s
)))
5384 /* skip over comments, "" strings and 'c'haracters */
5385 s
= skip_string(cin_skipcomment(s
));
5386 if ((*s
== ';' || (incl_open
&& *s
== '{') || *s
== '}'
5387 || (incl_comma
&& *s
== ','))
5388 && cin_nocode(s
+ 1))
5398 * Recognize the basic picture of a function declaration -- it needs to
5399 * have an open paren somewhere and a close paren at the end of the line and
5400 * no semicolons anywhere.
5401 * When a line ends in a comma we continue looking in the next line.
5402 * "sp" points to a string with the line. When looking at other lines it must
5403 * be restored to the line. When it's NULL fetch lines here.
5404 * "lnum" is where we start looking.
5407 cin_isfuncdecl(sp
, first_lnum
)
5409 linenr_T first_lnum
;
5412 linenr_T lnum
= first_lnum
;
5420 while (*s
&& *s
!= '(' && *s
!= ';' && *s
!= '\'' && *s
!= '"')
5422 if (cin_iscomment(s
)) /* ignore comments */
5423 s
= cin_skipcomment(s
);
5428 return FALSE
; /* ';', ' or " before any () or no '(' */
5430 while (*s
&& *s
!= ';' && *s
!= '\'' && *s
!= '"')
5432 if (*s
== ')' && cin_nocode(s
+ 1))
5434 /* ')' at the end: may have found a match
5435 * Check for he previous line not to end in a backslash:
5436 * #if defined(x) && \
5439 lnum
= first_lnum
- 1;
5441 if (*s
== NUL
|| s
[STRLEN(s
) - 1] != '\\')
5445 if (*s
== ',' && cin_nocode(s
+ 1))
5447 /* ',' at the end: continue looking in the next line */
5448 if (lnum
>= curbuf
->b_ml
.ml_line_count
)
5453 else if (cin_iscomment(s
)) /* ignore comments */
5454 s
= cin_skipcomment(s
);
5460 if (lnum
!= first_lnum
&& sp
!= NULL
)
5461 *sp
= ml_get(first_lnum
);
5470 return (STRNCMP(p
, "if", 2) == 0 && !vim_isIDc(p
[2]));
5477 if (*p
== '}') /* accept "} else" */
5478 p
= cin_skipcomment(p
+ 1);
5479 return (STRNCMP(p
, "else", 4) == 0 && !vim_isIDc(p
[4]));
5486 return (STRNCMP(p
, "do", 2) == 0 && !vim_isIDc(p
[2]));
5490 * Check if this is a "while" that should have a matching "do".
5491 * We only accept a "while (condition) ;", with only white space between the
5492 * ')' and ';'. The condition may be spread over several lines.
5495 cin_iswhileofdo(p
, lnum
, ind_maxparen
) /* XXX */
5504 p
= cin_skipcomment(p
);
5505 if (*p
== '}') /* accept "} while (cond);" */
5506 p
= cin_skipcomment(p
+ 1);
5507 if (STRNCMP(p
, "while", 5) == 0 && !vim_isIDc(p
[5]))
5509 cursor_save
= curwin
->w_cursor
;
5510 curwin
->w_cursor
.lnum
= lnum
;
5511 curwin
->w_cursor
.col
= 0;
5512 p
= ml_get_curline();
5513 while (*p
&& *p
!= 'w') /* skip any '}', until the 'w' of the "while" */
5516 ++curwin
->w_cursor
.col
;
5518 if ((trypos
= findmatchlimit(NULL
, 0, 0, ind_maxparen
)) != NULL
5519 && *cin_skipcomment(ml_get_pos(trypos
) + 1) == ';')
5521 curwin
->w_cursor
= cursor_save
;
5527 * Return TRUE if we are at the end of a do-while.
5532 * Adjust the cursor to the line with "while".
5535 cin_iswhileofdo_end(terminated
, ind_maxparen
, ind_maxcomment
)
5546 if (terminated
!= ';') /* there must be a ';' at the end */
5549 p
= line
= ml_get_curline();
5552 p
= cin_skipcomment(p
);
5555 s
= skipwhite(p
+ 1);
5556 if (*s
== ';' && cin_nocode(s
+ 1))
5558 /* Found ");" at end of the line, now check there is "while"
5559 * before the matching '('. XXX */
5560 i
= (int)(p
- line
);
5561 curwin
->w_cursor
.col
= i
;
5562 trypos
= find_match_paren(ind_maxparen
, ind_maxcomment
);
5565 s
= cin_skipcomment(ml_get(trypos
->lnum
));
5566 if (*s
== '}') /* accept "} while (cond);" */
5567 s
= cin_skipcomment(s
+ 1);
5568 if (STRNCMP(s
, "while", 5) == 0 && !vim_isIDc(s
[5]))
5570 curwin
->w_cursor
.lnum
= trypos
->lnum
;
5575 /* Searching may have made "line" invalid, get it again. */
5576 line
= ml_get_curline();
5590 return (STRNCMP(p
, "break", 5) == 0 && !vim_isIDc(p
[5]));
5594 * Find the position of a C++ base-class declaration or
5595 * constructor-initialization. eg:
5598 * baseClass <-- here
5599 * class MyClass : public baseClass,
5600 * anotherBaseClass <-- here (should probably lineup ??)
5601 * MyClass::MyClass(...) :
5602 * baseClass(...) <-- here (constructor-initialization)
5604 * This is a lot of guessing. Watch out for "cond ? func() : foo".
5607 cin_is_cpp_baseclass(col
)
5608 colnr_T
*col
; /* return: column to align with */
5611 int class_or_struct
, lookfor_ctor_init
, cpp_base_class
;
5612 linenr_T lnum
= curwin
->w_cursor
.lnum
;
5613 char_u
*line
= ml_get_curline();
5617 s
= skipwhite(line
);
5618 if (*s
== '#') /* skip #define FOO x ? (x) : x */
5620 s
= cin_skipcomment(s
);
5624 cpp_base_class
= lookfor_ctor_init
= class_or_struct
= FALSE
;
5626 /* Search for a line starting with '#', empty, ending in ';' or containing
5627 * '{' or '}' and start below it. This handles the following situations:
5634 * Foo::Foo (int one, int two)
5641 line
= ml_get(lnum
- 1);
5642 s
= skipwhite(line
);
5643 if (*s
== '#' || *s
== NUL
)
5647 s
= cin_skipcomment(s
);
5648 if (*s
== '{' || *s
== '}'
5649 || (*s
== ';' && cin_nocode(s
+ 1)))
5659 line
= ml_get(lnum
);
5660 s
= cin_skipcomment(line
);
5665 if (lnum
== curwin
->w_cursor
.lnum
)
5667 /* Continue in the cursor line. */
5668 line
= ml_get(++lnum
);
5669 s
= cin_skipcomment(line
);
5678 /* skip double colon. It can't be a constructor
5679 * initialization any more */
5680 lookfor_ctor_init
= FALSE
;
5681 s
= cin_skipcomment(s
+ 2);
5683 else if (lookfor_ctor_init
|| class_or_struct
)
5685 /* we have something found, that looks like the start of
5686 * cpp-base-class-declaration or contructor-initialization */
5687 cpp_base_class
= TRUE
;
5688 lookfor_ctor_init
= class_or_struct
= FALSE
;
5690 s
= cin_skipcomment(s
+ 1);
5693 s
= cin_skipcomment(s
+ 1);
5695 else if ((STRNCMP(s
, "class", 5) == 0 && !vim_isIDc(s
[5]))
5696 || (STRNCMP(s
, "struct", 6) == 0 && !vim_isIDc(s
[6])))
5698 class_or_struct
= TRUE
;
5699 lookfor_ctor_init
= FALSE
;
5702 s
= cin_skipcomment(s
+ 5);
5704 s
= cin_skipcomment(s
+ 6);
5708 if (s
[0] == '{' || s
[0] == '}' || s
[0] == ';')
5710 cpp_base_class
= lookfor_ctor_init
= class_or_struct
= FALSE
;
5712 else if (s
[0] == ')')
5714 /* Constructor-initialization is assumed if we come across
5715 * something like "):" */
5716 class_or_struct
= FALSE
;
5717 lookfor_ctor_init
= TRUE
;
5719 else if (s
[0] == '?')
5721 /* Avoid seeing '() :' after '?' as constructor init. */
5724 else if (!vim_isIDc(s
[0]))
5726 /* if it is not an identifier, we are wrong */
5727 class_or_struct
= FALSE
;
5728 lookfor_ctor_init
= FALSE
;
5732 /* it can't be a constructor-initialization any more */
5733 lookfor_ctor_init
= FALSE
;
5735 /* the first statement starts here: lineup with this one... */
5737 *col
= (colnr_T
)(s
- line
);
5740 /* When the line ends in a comma don't align with it. */
5741 if (lnum
== curwin
->w_cursor
.lnum
&& *s
== ',' && cin_nocode(s
+ 1))
5744 s
= cin_skipcomment(s
+ 1);
5748 return cpp_base_class
;
5752 get_baseclass_amount(col
, ind_maxparen
, ind_maxcomment
, ind_cpp_baseclass
)
5756 int ind_cpp_baseclass
;
5764 amount
= get_indent();
5765 if (find_last_paren(ml_get_curline(), '(', ')')
5766 && (trypos
= find_match_paren(ind_maxparen
,
5767 ind_maxcomment
)) != NULL
)
5768 amount
= get_indent_lnum(trypos
->lnum
); /* XXX */
5769 if (!cin_ends_in(ml_get_curline(), (char_u
*)",", NULL
))
5770 amount
+= ind_cpp_baseclass
;
5774 curwin
->w_cursor
.col
= col
;
5775 getvcol(curwin
, &curwin
->w_cursor
, &vcol
, NULL
, NULL
);
5778 if (amount
< ind_cpp_baseclass
)
5779 amount
= ind_cpp_baseclass
;
5784 * Return TRUE if string "s" ends with the string "find", possibly followed by
5785 * white space and comments. Skip strings and comments.
5786 * Ignore "ignore" after "find" if it's not NULL.
5789 cin_ends_in(s
, find
, ignore
)
5796 int len
= (int)STRLEN(find
);
5800 p
= cin_skipcomment(p
);
5801 if (STRNCMP(p
, find
, len
) == 0)
5803 r
= skipwhite(p
+ len
);
5804 if (ignore
!= NULL
&& STRNCMP(r
, ignore
, STRLEN(ignore
)) == 0)
5805 r
= skipwhite(r
+ STRLEN(ignore
));
5816 * Skip strings, chars and comments until at or past "trypos".
5817 * Return the column found.
5820 cin_skip2pos(trypos
)
5826 p
= line
= ml_get(trypos
->lnum
);
5827 while (*p
&& (colnr_T
)(p
- line
) < trypos
->col
)
5829 if (cin_iscomment(p
))
5830 p
= cin_skipcomment(p
);
5837 return (int)(p
- line
);
5841 * Find the '{' at the start of the block we are in.
5842 * Return NULL if no match found.
5843 * Ignore a '{' that is in a comment, makes indenting the next three lines
5850 find_start_brace(ind_maxcomment
) /* XXX */
5856 static pos_T pos_copy
;
5858 cursor_save
= curwin
->w_cursor
;
5859 while ((trypos
= findmatchlimit(NULL
, '{', FM_BLOCKSTOP
, 0)) != NULL
)
5861 pos_copy
= *trypos
; /* copy pos_T, next findmatch will change it */
5863 curwin
->w_cursor
= *trypos
;
5865 /* ignore the { if it's in a // or / * * / comment */
5866 if ((colnr_T
)cin_skip2pos(trypos
) == trypos
->col
5867 && (pos
= find_start_comment(ind_maxcomment
)) == NULL
) /* XXX */
5870 curwin
->w_cursor
.lnum
= pos
->lnum
;
5872 curwin
->w_cursor
= cursor_save
;
5877 * Find the matching '(', failing if it is in a comment.
5878 * Return NULL of no match found.
5881 find_match_paren(ind_maxparen
, ind_maxcomment
) /* XXX */
5887 static pos_T pos_copy
;
5889 cursor_save
= curwin
->w_cursor
;
5890 if ((trypos
= findmatchlimit(NULL
, '(', 0, ind_maxparen
)) != NULL
)
5892 /* check if the ( is in a // comment */
5893 if ((colnr_T
)cin_skip2pos(trypos
) > trypos
->col
)
5897 pos_copy
= *trypos
; /* copy trypos, findmatch will change it */
5899 curwin
->w_cursor
= *trypos
;
5900 if (find_start_comment(ind_maxcomment
) != NULL
) /* XXX */
5904 curwin
->w_cursor
= cursor_save
;
5909 * Return ind_maxparen corrected for the difference in line number between the
5910 * cursor position and "startpos". This makes sure that searching for a
5911 * matching paren above the cursor line doesn't find a match because of
5912 * looking a few lines further.
5915 corr_ind_maxparen(ind_maxparen
, startpos
)
5919 long n
= (long)startpos
->lnum
- (long)curwin
->w_cursor
.lnum
;
5921 if (n
> 0 && n
< ind_maxparen
/ 2)
5922 return ind_maxparen
- (int)n
;
5923 return ind_maxparen
;
5927 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5931 find_last_paren(l
, start
, end
)
5939 curwin
->w_cursor
.col
= 0; /* default is start of line */
5941 for (i
= 0; l
[i
]; i
++)
5943 i
= (int)(cin_skipcomment(l
+ i
) - l
); /* ignore parens in comments */
5944 i
= (int)(skip_string(l
+ i
) - l
); /* ignore parens in quotes */
5947 else if (l
[i
] == end
)
5953 curwin
->w_cursor
.col
= i
;
5965 * spaces from a block's opening brace the prevailing indent for that
5968 int ind_level
= curbuf
->b_p_sw
;
5971 * spaces from the edge of the line an open brace that's at the end of a
5972 * line is imagined to be.
5974 int ind_open_imag
= 0;
5977 * spaces from the prevailing indent for a line that is not precededof by
5980 int ind_no_brace
= 0;
5983 * column where the first { of a function should be located }
5985 int ind_first_open
= 0;
5988 * spaces from the prevailing indent a leftmost open brace should be
5991 int ind_open_extra
= 0;
5994 * spaces from the matching open brace (real location for one at the left
5995 * edge; imaginary location from one that ends a line) the matching close
5996 * brace should be located
5998 int ind_close_extra
= 0;
6001 * spaces from the edge of the line an open brace sitting in the leftmost
6002 * column is imagined to be
6004 int ind_open_left_imag
= 0;
6007 * spaces from the switch() indent a "case xx" label should be located
6009 int ind_case
= curbuf
->b_p_sw
;
6012 * spaces from the "case xx:" code after a switch() should be located
6014 int ind_case_code
= curbuf
->b_p_sw
;
6017 * lineup break at end of case in switch() with case label
6019 int ind_case_break
= 0;
6022 * spaces from the class declaration indent a scope declaration label
6025 int ind_scopedecl
= curbuf
->b_p_sw
;
6028 * spaces from the scope declaration label code should be located
6030 int ind_scopedecl_code
= curbuf
->b_p_sw
;
6033 * amount K&R-style parameters should be indented
6035 int ind_param
= curbuf
->b_p_sw
;
6038 * amount a function type spec should be indented
6040 int ind_func_type
= curbuf
->b_p_sw
;
6043 * amount a cpp base class declaration or constructor initialization
6044 * should be indented
6046 int ind_cpp_baseclass
= curbuf
->b_p_sw
;
6049 * additional spaces beyond the prevailing indent a continuation line
6052 int ind_continuation
= curbuf
->b_p_sw
;
6055 * spaces from the indent of the line with an unclosed parentheses
6057 int ind_unclosed
= curbuf
->b_p_sw
* 2;
6060 * spaces from the indent of the line with an unclosed parentheses, which
6061 * itself is also unclosed
6063 int ind_unclosed2
= curbuf
->b_p_sw
;
6066 * suppress ignoring spaces from the indent of a line starting with an
6067 * unclosed parentheses.
6069 int ind_unclosed_noignore
= 0;
6072 * If the opening paren is the last nonwhite character on the line, and
6073 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6074 * context (for very long lines).
6076 int ind_unclosed_wrapped
= 0;
6079 * suppress ignoring white space when lining up with the character after
6080 * an unclosed parentheses.
6082 int ind_unclosed_whiteok
= 0;
6085 * indent a closing parentheses under the line start of the matching
6086 * opening parentheses.
6088 int ind_matching_paren
= 0;
6091 * indent a closing parentheses under the previous line.
6093 int ind_paren_prev
= 0;
6096 * Extra indent for comments.
6098 int ind_comment
= 0;
6101 * spaces from the comment opener when there is nothing after it.
6103 int ind_in_comment
= 3;
6106 * boolean: if non-zero, use ind_in_comment even if there is something
6107 * after the comment opener.
6109 int ind_in_comment2
= 0;
6112 * max lines to search for an open paren
6114 int ind_maxparen
= 20;
6117 * max lines to search for an open comment
6119 int ind_maxcomment
= 70;
6122 * handle braces for java code
6127 * handle blocked cases correctly
6129 int ind_keep_case_label
= 0;
6134 int cur_amount
= MAXCOL
;
6139 pos_T
*tryposBrace
= NULL
;
6140 pos_T our_paren_pos
;
6143 #define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
6144 #define BRACE_AT_START 2 /* '{' is at start of line */
6145 #define BRACE_AT_END 3 /* '{' is at end of line */
6151 #define LOOKFOR_INITIAL 0
6152 #define LOOKFOR_IF 1
6153 #define LOOKFOR_DO 2
6154 #define LOOKFOR_CASE 3
6155 #define LOOKFOR_ANY 4
6156 #define LOOKFOR_TERM 5
6157 #define LOOKFOR_UNTERM 6
6158 #define LOOKFOR_SCOPEDECL 7
6159 #define LOOKFOR_NOBREAK 8
6160 #define LOOKFOR_CPP_BASECLASS 9
6161 #define LOOKFOR_ENUM_OR_INIT 10
6166 int fraction
= 0; /* init for GCC */
6171 int cont_amount
= 0; /* amount for continuation line */
6173 for (options
= curbuf
->b_p_cino
; *options
; )
6176 if (*options
== '-')
6178 n
= getdigits(&options
);
6180 if (*options
== '.') /* ".5s" means a fraction */
6182 fraction
= atol((char *)++options
);
6183 while (VIM_ISDIGIT(*options
))
6192 if (*options
== 's') /* "2s" means two times 'shiftwidth' */
6194 if (n
== 0 && fraction
== 0)
6195 n
= curbuf
->b_p_sw
; /* just "s" is one 'shiftwidth' */
6198 n
*= curbuf
->b_p_sw
;
6200 n
+= (curbuf
->b_p_sw
* fraction
+ divider
/ 2) / divider
;
6206 /* When adding an entry here, also update the default 'cinoptions' in
6207 * doc/indent.txt, and add explanation for it! */
6210 case '>': ind_level
= n
; break;
6211 case 'e': ind_open_imag
= n
; break;
6212 case 'n': ind_no_brace
= n
; break;
6213 case 'f': ind_first_open
= n
; break;
6214 case '{': ind_open_extra
= n
; break;
6215 case '}': ind_close_extra
= n
; break;
6216 case '^': ind_open_left_imag
= n
; break;
6217 case ':': ind_case
= n
; break;
6218 case '=': ind_case_code
= n
; break;
6219 case 'b': ind_case_break
= n
; break;
6220 case 'p': ind_param
= n
; break;
6221 case 't': ind_func_type
= n
; break;
6222 case '/': ind_comment
= n
; break;
6223 case 'c': ind_in_comment
= n
; break;
6224 case 'C': ind_in_comment2
= n
; break;
6225 case 'i': ind_cpp_baseclass
= n
; break;
6226 case '+': ind_continuation
= n
; break;
6227 case '(': ind_unclosed
= n
; break;
6228 case 'u': ind_unclosed2
= n
; break;
6229 case 'U': ind_unclosed_noignore
= n
; break;
6230 case 'W': ind_unclosed_wrapped
= n
; break;
6231 case 'w': ind_unclosed_whiteok
= n
; break;
6232 case 'm': ind_matching_paren
= n
; break;
6233 case 'M': ind_paren_prev
= n
; break;
6234 case ')': ind_maxparen
= n
; break;
6235 case '*': ind_maxcomment
= n
; break;
6236 case 'g': ind_scopedecl
= n
; break;
6237 case 'h': ind_scopedecl_code
= n
; break;
6238 case 'j': ind_java
= n
; break;
6239 case 'l': ind_keep_case_label
= n
; break;
6240 case '#': ind_hash_comment
= n
; break;
6244 /* remember where the cursor was when we started */
6245 cur_curpos
= curwin
->w_cursor
;
6247 /* Get a copy of the current contents of the line.
6248 * This is required, because only the most recent line obtained with
6249 * ml_get is valid! */
6250 linecopy
= vim_strsave(ml_get(cur_curpos
.lnum
));
6251 if (linecopy
== NULL
)
6255 * In insert mode and the cursor is on a ')' truncate the line at the
6256 * cursor position. We don't want to line up with the matching '(' when
6257 * inserting new stuff.
6258 * For unknown reasons the cursor might be past the end of the line, thus
6261 if ((State
& INSERT
)
6262 && curwin
->w_cursor
.col
< STRLEN(linecopy
)
6263 && linecopy
[curwin
->w_cursor
.col
] == ')')
6264 linecopy
[curwin
->w_cursor
.col
] = NUL
;
6266 theline
= skipwhite(linecopy
);
6268 /* move the cursor to the start of the line */
6270 curwin
->w_cursor
.col
= 0;
6273 * #defines and so on always go at the left when included in 'cinkeys'.
6275 if (*theline
== '#' && (*linecopy
== '#' || in_cinkeys('#', ' ', TRUE
)))
6281 * Is it a non-case label? Then that goes at the left margin too.
6283 else if (cin_islabel(ind_maxcomment
)) /* XXX */
6289 * If we're inside a "//" comment and there is a "//" comment in a
6290 * previous line, lineup with that one.
6292 else if (cin_islinecomment(theline
)
6293 && (trypos
= find_line_comment()) != NULL
) /* XXX */
6295 /* find how indented the line beginning the comment is */
6296 getvcol(curwin
, trypos
, &col
, NULL
, NULL
);
6301 * If we're inside a comment and not looking at the start of the
6302 * comment, try using the 'comments' option.
6304 else if (!cin_iscomment(theline
)
6305 && (trypos
= find_start_comment(ind_maxcomment
)) != NULL
) /* XXX */
6307 int lead_start_len
= 2;
6308 int lead_middle_len
= 1;
6309 char_u lead_start
[COM_MAX_LEN
]; /* start-comment string */
6310 char_u lead_middle
[COM_MAX_LEN
]; /* middle-comment string */
6311 char_u lead_end
[COM_MAX_LEN
]; /* end-comment string */
6313 int start_align
= 0;
6317 /* find how indented the line beginning the comment is */
6318 getvcol(curwin
, trypos
, &col
, NULL
, NULL
);
6321 p
= curbuf
->b_p_com
;
6328 while (*p
!= NUL
&& *p
!= ':')
6330 if (*p
== COM_START
|| *p
== COM_END
|| *p
== COM_MIDDLE
)
6332 else if (*p
== COM_LEFT
|| *p
== COM_RIGHT
)
6334 else if (VIM_ISDIGIT(*p
) || *p
== '-')
6335 off
= getdigits(&p
);
6342 (void)copy_option_part(&p
, lead_end
, COM_MAX_LEN
, ",");
6343 if (what
== COM_START
)
6345 STRCPY(lead_start
, lead_end
);
6346 lead_start_len
= (int)STRLEN(lead_start
);
6348 start_align
= align
;
6350 else if (what
== COM_MIDDLE
)
6352 STRCPY(lead_middle
, lead_end
);
6353 lead_middle_len
= (int)STRLEN(lead_middle
);
6355 else if (what
== COM_END
)
6357 /* If our line starts with the middle comment string, line it
6358 * up with the comment opener per the 'comments' option. */
6359 if (STRNCMP(theline
, lead_middle
, lead_middle_len
) == 0
6360 && STRNCMP(theline
, lead_end
, STRLEN(lead_end
)) != 0)
6363 if (curwin
->w_cursor
.lnum
> 1)
6365 /* If the start comment string matches in the previous
6366 * line, use the indent of that line pluss offset. If
6367 * the middle comment string matches in the previous
6368 * line, use the indent of that line. XXX */
6369 look
= skipwhite(ml_get(curwin
->w_cursor
.lnum
- 1));
6370 if (STRNCMP(look
, lead_start
, lead_start_len
) == 0)
6371 amount
= get_indent_lnum(curwin
->w_cursor
.lnum
- 1);
6372 else if (STRNCMP(look
, lead_middle
,
6373 lead_middle_len
) == 0)
6375 amount
= get_indent_lnum(curwin
->w_cursor
.lnum
- 1);
6378 /* If the start comment string doesn't match with the
6379 * start of the comment, skip this entry. XXX */
6380 else if (STRNCMP(ml_get(trypos
->lnum
) + trypos
->col
,
6381 lead_start
, lead_start_len
) != 0)
6385 amount
+= start_off
;
6386 else if (start_align
== COM_RIGHT
)
6387 amount
+= vim_strsize(lead_start
)
6388 - vim_strsize(lead_middle
);
6392 /* If our line starts with the end comment string, line it up
6393 * with the middle comment */
6394 if (STRNCMP(theline
, lead_middle
, lead_middle_len
) != 0
6395 && STRNCMP(theline
, lead_end
, STRLEN(lead_end
)) == 0)
6397 amount
= get_indent_lnum(curwin
->w_cursor
.lnum
- 1);
6401 else if (align
== COM_RIGHT
)
6402 amount
+= vim_strsize(lead_start
)
6403 - vim_strsize(lead_middle
);
6410 /* If our line starts with an asterisk, line up with the
6411 * asterisk in the comment opener; otherwise, line up
6412 * with the first character of the comment text.
6416 else if (theline
[0] == '*')
6421 * If we are more than one line away from the comment opener, take
6422 * the indent of the previous non-empty line. If 'cino' has "CO"
6423 * and we are just below the comment opener and there are any
6424 * white characters after it line up with the text after it;
6425 * otherwise, add the amount specified by "c" in 'cino'
6428 for (lnum
= cur_curpos
.lnum
- 1; lnum
> trypos
->lnum
; --lnum
)
6430 if (linewhite(lnum
)) /* skip blank lines */
6432 amount
= get_indent_lnum(lnum
); /* XXX */
6435 if (amount
== -1) /* use the comment opener */
6437 if (!ind_in_comment2
)
6439 start
= ml_get(trypos
->lnum
);
6440 look
= start
+ trypos
->col
+ 2; /* skip / and * */
6441 if (*look
!= NUL
) /* if something after it */
6442 trypos
->col
= (colnr_T
)(skipwhite(look
) - start
);
6444 getvcol(curwin
, trypos
, &col
, NULL
, NULL
);
6446 if (ind_in_comment2
|| *look
== NUL
)
6447 amount
+= ind_in_comment
;
6453 * Are we inside parentheses or braces?
6455 else if (((trypos
= find_match_paren(ind_maxparen
, ind_maxcomment
)) != NULL
6457 || (tryposBrace
= find_start_brace(ind_maxcomment
)) != NULL
6460 if (trypos
!= NULL
&& tryposBrace
!= NULL
)
6462 /* Both an unmatched '(' and '{' is found. Use the one which is
6463 * closer to the current cursor position, set the other to NULL. */
6464 if (trypos
->lnum
!= tryposBrace
->lnum
6465 ? trypos
->lnum
< tryposBrace
->lnum
6466 : trypos
->col
< tryposBrace
->col
)
6475 * If the matching paren is more than one line away, use the indent of
6476 * a previous non-empty line that matches the same paren.
6478 if (theline
[0] == ')' && ind_paren_prev
)
6480 /* Line up with the start of the matching paren line. */
6481 amount
= get_indent_lnum(curwin
->w_cursor
.lnum
- 1); /* XXX */
6486 our_paren_pos
= *trypos
;
6487 for (lnum
= cur_curpos
.lnum
- 1; lnum
> our_paren_pos
.lnum
; --lnum
)
6489 l
= skipwhite(ml_get(lnum
));
6490 if (cin_nocode(l
)) /* skip comment lines */
6492 if (cin_ispreproc_cont(&l
, &lnum
))
6493 continue; /* ignore #define, #if, etc. */
6494 curwin
->w_cursor
.lnum
= lnum
;
6496 /* Skip a comment. XXX */
6497 if ((trypos
= find_start_comment(ind_maxcomment
)) != NULL
)
6499 lnum
= trypos
->lnum
+ 1;
6504 if ((trypos
= find_match_paren(
6505 corr_ind_maxparen(ind_maxparen
, &cur_curpos
),
6506 ind_maxcomment
)) != NULL
6507 && trypos
->lnum
== our_paren_pos
.lnum
6508 && trypos
->col
== our_paren_pos
.col
)
6510 amount
= get_indent_lnum(lnum
); /* XXX */
6512 if (theline
[0] == ')')
6514 if (our_paren_pos
.lnum
!= lnum
6515 && cur_amount
> amount
)
6516 cur_amount
= amount
;
6525 * Line up with line where the matching paren is. XXX
6526 * If the line starts with a '(' or the indent for unclosed
6527 * parentheses is zero, line up with the unclosed parentheses.
6531 int ignore_paren_col
= 0;
6533 amount
= skip_label(our_paren_pos
.lnum
, &look
, ind_maxcomment
);
6534 look
= skipwhite(look
);
6537 linenr_T save_lnum
= curwin
->w_cursor
.lnum
;
6541 /* Ignore a '(' in front of the line that has a match before
6542 * our matching '('. */
6543 curwin
->w_cursor
.lnum
= our_paren_pos
.lnum
;
6544 line
= ml_get_curline();
6545 look_col
= (int)(look
- line
);
6546 curwin
->w_cursor
.col
= look_col
+ 1;
6547 if ((trypos
= findmatchlimit(NULL
, ')', 0, ind_maxparen
))
6549 && trypos
->lnum
== our_paren_pos
.lnum
6550 && trypos
->col
< our_paren_pos
.col
)
6551 ignore_paren_col
= trypos
->col
+ 1;
6553 curwin
->w_cursor
.lnum
= save_lnum
;
6554 look
= ml_get(our_paren_pos
.lnum
) + look_col
;
6556 if (theline
[0] == ')' || ind_unclosed
== 0
6557 || (!ind_unclosed_noignore
&& *look
== '('
6558 && ignore_paren_col
== 0))
6561 * If we're looking at a close paren, line up right there;
6562 * otherwise, line up with the next (non-white) character.
6563 * When ind_unclosed_wrapped is set and the matching paren is
6564 * the last nonwhite character of the line, use either the
6565 * indent of the current line or the indentation of the next
6566 * outer paren and add ind_unclosed_wrapped (for very long
6569 if (theline
[0] != ')')
6571 cur_amount
= MAXCOL
;
6572 l
= ml_get(our_paren_pos
.lnum
);
6573 if (ind_unclosed_wrapped
6574 && cin_ends_in(l
, (char_u
*)"(", NULL
))
6576 /* look for opening unmatched paren, indent one level
6577 * for each additional level */
6579 for (col
= 0; col
< our_paren_pos
.col
; ++col
)
6588 case '}': if (n
> 1)
6594 our_paren_pos
.col
= 0;
6595 amount
+= n
* ind_unclosed_wrapped
;
6597 else if (ind_unclosed_whiteok
)
6598 our_paren_pos
.col
++;
6601 col
= our_paren_pos
.col
+ 1;
6602 while (vim_iswhite(l
[col
]))
6604 if (l
[col
] != NUL
) /* In case of trailing space */
6605 our_paren_pos
.col
= col
;
6607 our_paren_pos
.col
++;
6612 * Find how indented the paren is, or the character after it
6613 * if we did the above "if".
6615 if (our_paren_pos
.col
> 0)
6617 getvcol(curwin
, &our_paren_pos
, &col
, NULL
, NULL
);
6618 if (cur_amount
> (int)col
)
6623 if (theline
[0] == ')' && ind_matching_paren
)
6625 /* Line up with the start of the matching paren line. */
6627 else if (ind_unclosed
== 0 || (!ind_unclosed_noignore
6628 && *look
== '(' && ignore_paren_col
== 0))
6630 if (cur_amount
!= MAXCOL
)
6631 amount
= cur_amount
;
6635 /* Add ind_unclosed2 for each '(' before our matching one, but
6636 * ignore (void) before the line (ignore_paren_col). */
6637 col
= our_paren_pos
.col
;
6638 while ((int)our_paren_pos
.col
> ignore_paren_col
)
6640 --our_paren_pos
.col
;
6641 switch (*ml_get_pos(&our_paren_pos
))
6643 case '(': amount
+= ind_unclosed2
;
6644 col
= our_paren_pos
.col
;
6646 case ')': amount
-= ind_unclosed2
;
6652 /* Use ind_unclosed once, when the first '(' is not inside
6655 amount
+= ind_unclosed
;
6658 curwin
->w_cursor
.lnum
= our_paren_pos
.lnum
;
6659 curwin
->w_cursor
.col
= col
;
6660 if ((trypos
= find_match_paren(ind_maxparen
,
6661 ind_maxcomment
)) != NULL
)
6662 amount
+= ind_unclosed2
;
6664 amount
+= ind_unclosed
;
6667 * For a line starting with ')' use the minimum of the two
6668 * positions, to avoid giving it more indent than the previous
6670 * func_long_name( if (x
6672 * ) ^ not here ) ^ not here
6674 if (cur_amount
< amount
)
6675 amount
= cur_amount
;
6679 /* add extra indent for a comment */
6680 if (cin_iscomment(theline
))
6681 amount
+= ind_comment
;
6685 * Are we at least inside braces, then?
6689 trypos
= tryposBrace
;
6691 ourscope
= trypos
->lnum
;
6692 start
= ml_get(ourscope
);
6695 * Now figure out how indented the line is in general.
6696 * If the brace was at the start of the line, we use that;
6697 * otherwise, check out the indentation of the line as
6698 * a whole and then add the "imaginary indent" to that.
6700 look
= skipwhite(start
);
6703 getvcol(curwin
, trypos
, &col
, NULL
, NULL
);
6706 start_brace
= BRACE_IN_COL0
;
6708 start_brace
= BRACE_AT_START
;
6713 * that opening brace might have been on a continuation
6714 * line. if so, find the start of the line.
6716 curwin
->w_cursor
.lnum
= ourscope
;
6719 * position the cursor over the rightmost paren, so that
6720 * matching it will take us back to the start of the line.
6723 if (find_last_paren(start
, '(', ')')
6724 && (trypos
= find_match_paren(ind_maxparen
,
6725 ind_maxcomment
)) != NULL
)
6726 lnum
= trypos
->lnum
;
6729 * It could have been something like
6730 * case 1: if (asdf &&
6734 if (ind_keep_case_label
&& cin_iscase(skipwhite(ml_get_curline())))
6735 amount
= get_indent();
6737 amount
= skip_label(lnum
, &l
, ind_maxcomment
);
6739 start_brace
= BRACE_AT_END
;
6743 * if we're looking at a closing brace, that's where
6744 * we want to be. otherwise, add the amount of room
6745 * that an indent is supposed to be.
6747 if (theline
[0] == '}')
6750 * they may want closing braces to line up with something
6751 * other than the open brace. indulge them, if so.
6753 amount
+= ind_close_extra
;
6758 * If we're looking at an "else", try to find an "if"
6760 * If we're looking at a "while", try to find a "do"
6763 lookfor
= LOOKFOR_INITIAL
;
6764 if (cin_iselse(theline
))
6765 lookfor
= LOOKFOR_IF
;
6766 else if (cin_iswhileofdo(theline
, cur_curpos
.lnum
, ind_maxparen
))
6768 lookfor
= LOOKFOR_DO
;
6769 if (lookfor
!= LOOKFOR_INITIAL
)
6771 curwin
->w_cursor
.lnum
= cur_curpos
.lnum
;
6772 if (find_match(lookfor
, ourscope
, ind_maxparen
,
6773 ind_maxcomment
) == OK
)
6775 amount
= get_indent(); /* XXX */
6781 * We get here if we are not on an "while-of-do" or "else" (or
6782 * failed to find a matching "if").
6783 * Search backwards for something to line up with.
6784 * First set amount for when we don't find anything.
6788 * if the '{' is _really_ at the left margin, use the imaginary
6789 * location of a left-margin brace. Otherwise, correct the
6790 * location for ind_open_extra.
6793 if (start_brace
== BRACE_IN_COL0
) /* '{' is in column 0 */
6795 amount
= ind_open_left_imag
;
6799 if (start_brace
== BRACE_AT_END
) /* '{' is at end of line */
6800 amount
+= ind_open_imag
;
6803 /* Compensate for adding ind_open_extra later. */
6804 amount
-= ind_open_extra
;
6810 lookfor_break
= FALSE
;
6812 if (cin_iscase(theline
)) /* it's a switch() label */
6814 lookfor
= LOOKFOR_CASE
; /* find a previous switch() label */
6817 else if (cin_isscopedecl(theline
)) /* private:, ... */
6819 lookfor
= LOOKFOR_SCOPEDECL
; /* class decl is this block */
6820 amount
+= ind_scopedecl
;
6824 if (ind_case_break
&& cin_isbreak(theline
)) /* break; ... */
6825 lookfor_break
= TRUE
;
6827 lookfor
= LOOKFOR_INITIAL
;
6828 amount
+= ind_level
; /* ind_level from start of block */
6830 scope_amount
= amount
;
6834 * Search backwards. If we find something we recognize, line up
6837 * if we're looking at an open brace, indent
6838 * the usual amount relative to the conditional
6839 * that opens the block.
6841 curwin
->w_cursor
= cur_curpos
;
6844 curwin
->w_cursor
.lnum
--;
6845 curwin
->w_cursor
.col
= 0;
6848 * If we went all the way back to the start of our scope, line
6851 if (curwin
->w_cursor
.lnum
<= ourscope
)
6853 /* we reached end of scope:
6854 * if looking for a enum or structure initialization
6856 * if it is an initializer (enum xxx or xxx =), then
6857 * don't add ind_continuation, otherwise it is a variable
6860 * here; <-- add ind_continuation
6862 if (lookfor
== LOOKFOR_ENUM_OR_INIT
)
6864 if (curwin
->w_cursor
.lnum
== 0
6865 || curwin
->w_cursor
.lnum
6866 < ourscope
- ind_maxparen
)
6868 /* nothing found (abuse ind_maxparen as limit)
6869 * assume terminated line (i.e. a variable
6870 * initialization) */
6871 if (cont_amount
> 0)
6872 amount
= cont_amount
;
6874 amount
+= ind_continuation
;
6878 l
= ml_get_curline();
6881 * If we're in a comment now, skip to the start of the
6884 trypos
= find_start_comment(ind_maxcomment
);
6887 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
6892 * Skip preprocessor directives and blank lines.
6894 if (cin_ispreproc_cont(&l
, &curwin
->w_cursor
.lnum
))
6900 terminated
= cin_isterminated(l
, FALSE
, TRUE
);
6903 * If we are at top level and the line looks like a
6904 * function declaration, we are done
6905 * (it's a variable declaration).
6907 if (start_brace
!= BRACE_IN_COL0
6908 || !cin_isfuncdecl(&l
, curwin
->w_cursor
.lnum
))
6910 /* if the line is terminated with another ','
6911 * it is a continued variable initialization.
6912 * don't add extra indent.
6913 * TODO: does not work, if a function
6914 * declaration is split over multiple lines:
6915 * cin_isfuncdecl returns FALSE then.
6917 if (terminated
== ',')
6920 /* if it es a enum declaration or an assignment,
6923 if (terminated
!= ';' && cin_isinit())
6926 /* nothing useful found */
6927 if (terminated
== 0 || terminated
== '{')
6931 if (terminated
!= ';')
6933 /* Skip parens and braces. Position the cursor
6934 * over the rightmost paren, so that matching it
6935 * will take us back to the start of the line.
6938 if (find_last_paren(l
, '(', ')'))
6939 trypos
= find_match_paren(ind_maxparen
,
6942 if (trypos
== NULL
&& find_last_paren(l
, '{', '}'))
6943 trypos
= find_start_brace(ind_maxcomment
);
6947 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
6952 /* it's a variable declaration, add indentation
6957 if (cont_amount
> 0)
6958 amount
= cont_amount
;
6960 amount
+= ind_continuation
;
6962 else if (lookfor
== LOOKFOR_UNTERM
)
6964 if (cont_amount
> 0)
6965 amount
= cont_amount
;
6967 amount
+= ind_continuation
;
6969 else if (lookfor
!= LOOKFOR_TERM
6970 && lookfor
!= LOOKFOR_CPP_BASECLASS
)
6972 amount
= scope_amount
;
6973 if (theline
[0] == '{')
6974 amount
+= ind_open_extra
;
6980 * If we're in a comment now, skip to the start of the comment.
6982 if ((trypos
= find_start_comment(ind_maxcomment
)) != NULL
)
6984 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
6988 l
= ml_get_curline();
6991 * If this is a switch() label, may line up relative to that.
6992 * If this is a C++ scope declaration, do the same.
6994 iscase
= cin_iscase(l
);
6995 if (iscase
|| cin_isscopedecl(l
))
6997 /* we are only looking for cpp base class
6998 * declaration/initialization any longer */
6999 if (lookfor
== LOOKFOR_CPP_BASECLASS
)
7002 /* When looking for a "do" we are not interested in
7009 * c = 99 + <- this indent plus continuation
7012 if (lookfor
== LOOKFOR_UNTERM
7013 || lookfor
== LOOKFOR_ENUM_OR_INIT
)
7015 if (cont_amount
> 0)
7016 amount
= cont_amount
;
7018 amount
+= ind_continuation
;
7023 * case xx: <- line up with this case
7027 if ( (iscase
&& lookfor
== LOOKFOR_CASE
)
7028 || (iscase
&& lookfor_break
)
7029 || (!iscase
&& lookfor
== LOOKFOR_SCOPEDECL
))
7032 * Check that this case label is not for another
7035 if ((trypos
= find_start_brace(ind_maxcomment
)) ==
7036 NULL
|| trypos
->lnum
== ourscope
)
7038 amount
= get_indent(); /* XXX */
7044 n
= get_indent_nolabel(curwin
->w_cursor
.lnum
); /* XXX */
7047 * case xx: if (cond) <- line up with this if
7052 * if (cond) <- line up with this line
7056 if (lookfor
== LOOKFOR_TERM
)
7066 * case xx: x = x + 1; <- line up with this x
7069 * case xx: if (cond) <- line up with this if
7075 l
= after_label(ml_get_curline());
7076 if (l
!= NULL
&& cin_is_cinword(l
))
7078 if (theline
[0] == '{')
7079 amount
+= ind_open_extra
;
7081 amount
+= ind_level
+ ind_no_brace
;
7087 * Try to get the indent of a statement before the switch
7088 * label. If nothing is found, line up relative to the
7090 * break; <- may line up with this line
7094 scope_amount
= get_indent() + (iscase
/* XXX */
7095 ? ind_case_code
: ind_scopedecl_code
);
7096 lookfor
= ind_case_break
? LOOKFOR_NOBREAK
: LOOKFOR_ANY
;
7101 * Looking for a switch() label or C++ scope declaration,
7102 * ignore other lines, skip {}-blocks.
7104 if (lookfor
== LOOKFOR_CASE
|| lookfor
== LOOKFOR_SCOPEDECL
)
7106 if (find_last_paren(l
, '{', '}') && (trypos
=
7107 find_start_brace(ind_maxcomment
)) != NULL
)
7108 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
7113 * Ignore jump labels with nothing after them.
7115 if (cin_islabel(ind_maxcomment
))
7117 l
= after_label(ml_get_curline());
7118 if (l
== NULL
|| cin_nocode(l
))
7123 * Ignore #defines, #if, etc.
7124 * Ignore comment and empty lines.
7125 * (need to get the line again, cin_islabel() may have
7128 l
= ml_get_curline();
7129 if (cin_ispreproc_cont(&l
, &curwin
->w_cursor
.lnum
)
7134 * Are we at the start of a cpp base class declaration or
7135 * constructor initialization?
7138 if (lookfor
!= LOOKFOR_TERM
&& ind_cpp_baseclass
> 0)
7140 n
= cin_is_cpp_baseclass(&col
);
7141 l
= ml_get_curline();
7145 if (lookfor
== LOOKFOR_UNTERM
)
7147 if (cont_amount
> 0)
7148 amount
= cont_amount
;
7150 amount
+= ind_continuation
;
7152 else if (theline
[0] == '{')
7154 /* Need to find start of the declaration. */
7155 lookfor
= LOOKFOR_UNTERM
;
7156 ind_continuation
= 0;
7161 amount
= get_baseclass_amount(col
, ind_maxparen
,
7162 ind_maxcomment
, ind_cpp_baseclass
);
7165 else if (lookfor
== LOOKFOR_CPP_BASECLASS
)
7167 /* only look, whether there is a cpp base class
7168 * declaration or initialization before the opening brace.
7170 if (cin_isterminated(l
, TRUE
, FALSE
))
7177 * What happens next depends on the line being terminated.
7178 * If terminated with a ',' only consider it terminating if
7179 * there is another unterminated statement behind, eg:
7183 * Otherwise check whether it is a enumeration or structure
7184 * initialisation (not indented) or a variable declaration
7187 terminated
= cin_isterminated(l
, FALSE
, TRUE
);
7189 if (terminated
== 0 || (lookfor
!= LOOKFOR_UNTERM
7190 && terminated
== ','))
7193 * if we're in the middle of a paren thing,
7194 * go back to the line that starts it so
7195 * we can get the right prevailing indent
7200 * position the cursor over the rightmost paren, so that
7201 * matching it will take us back to the start of the line.
7203 (void)find_last_paren(l
, '(', ')');
7204 trypos
= find_match_paren(
7205 corr_ind_maxparen(ind_maxparen
, &cur_curpos
),
7209 * If we are looking for ',', we also look for matching
7212 if (trypos
== NULL
&& terminated
== ','
7213 && find_last_paren(l
, '{', '}'))
7214 trypos
= find_start_brace(ind_maxcomment
);
7219 * Check if we are on a case label now. This is
7221 * case xx: if ( asdf &&
7224 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7225 l
= ml_get_curline();
7226 if (cin_iscase(l
) || cin_isscopedecl(l
))
7228 ++curwin
->w_cursor
.lnum
;
7234 * Skip over continuation lines to find the one to get the
7236 * char *usethis = "bla\
7240 if (terminated
== ',')
7242 while (curwin
->w_cursor
.lnum
> 1)
7244 l
= ml_get(curwin
->w_cursor
.lnum
- 1);
7245 if (*l
== NUL
|| l
[STRLEN(l
) - 1] != '\\')
7247 --curwin
->w_cursor
.lnum
;
7252 * Get indent and pointer to text for current line,
7253 * ignoring any jump label. XXX
7255 cur_amount
= skip_label(curwin
->w_cursor
.lnum
,
7256 &l
, ind_maxcomment
);
7259 * If this is just above the line we are indenting, and it
7260 * starts with a '{', line it up with this line.
7265 if (terminated
!= ',' && lookfor
!= LOOKFOR_TERM
7266 && theline
[0] == '{')
7268 amount
= cur_amount
;
7270 * Only add ind_open_extra when the current line
7271 * doesn't start with a '{', which must have a match
7272 * in the same line (scope is the same). Probably:
7276 if (*skipwhite(l
) != '{')
7277 amount
+= ind_open_extra
;
7279 if (ind_cpp_baseclass
)
7281 /* have to look back, whether it is a cpp base
7282 * class declaration or initialization */
7283 lookfor
= LOOKFOR_CPP_BASECLASS
;
7290 * Check if we are after an "if", "while", etc.
7291 * Also allow " } else".
7293 if (cin_is_cinword(l
) || cin_iselse(skipwhite(l
)))
7296 * Found an unterminated line after an if (), line up
7297 * with the last one.
7302 if (lookfor
== LOOKFOR_UNTERM
7303 || lookfor
== LOOKFOR_ENUM_OR_INIT
)
7305 if (cont_amount
> 0)
7306 amount
= cont_amount
;
7308 amount
+= ind_continuation
;
7313 * If this is just above the line we are indenting, we
7317 * Otherwise this indent can be used when the line
7318 * before this is terminated.
7325 amount
= cur_amount
;
7326 if (theline
[0] == '{')
7327 amount
+= ind_open_extra
;
7328 if (lookfor
!= LOOKFOR_TERM
)
7330 amount
+= ind_level
+ ind_no_brace
;
7335 * Special trick: when expecting the while () after a
7336 * do, line up with the while()
7341 l
= skipwhite(ml_get_curline());
7344 if (whilelevel
== 0)
7350 * When searching for a terminated line, don't use the
7351 * one between the "if" and the "else".
7352 * Need to use the scope of this "else". XXX
7353 * If whilelevel != 0 continue looking for a "do {".
7357 && ((trypos
= find_start_brace(ind_maxcomment
))
7359 || find_match(LOOKFOR_IF
, trypos
->lnum
,
7360 ind_maxparen
, ind_maxcomment
) == FAIL
))
7365 * If we're below an unterminated line that is not an
7366 * "if" or something, we may line up with this line or
7367 * add something for a continuation line, depending on
7368 * the line before this one.
7373 * Found two unterminated lines on a row, line up with
7379 if (lookfor
== LOOKFOR_UNTERM
)
7381 /* When line ends in a comma add extra indent */
7382 if (terminated
== ',')
7383 amount
+= ind_continuation
;
7387 if (lookfor
== LOOKFOR_ENUM_OR_INIT
)
7389 /* Found two lines ending in ',', lineup with the
7390 * lowest one, but check for cpp base class
7391 * declaration/initialization, if it is an
7392 * opening brace or we are looking just for
7393 * enumerations/initializations. */
7394 if (terminated
== ',')
7396 if (ind_cpp_baseclass
== 0)
7399 lookfor
= LOOKFOR_CPP_BASECLASS
;
7403 /* Ignore unterminated lines in between, but
7405 if (amount
> cur_amount
)
7406 amount
= cur_amount
;
7411 * Found first unterminated line on a row, may
7412 * line up with this line, remember its indent
7416 amount
= cur_amount
;
7419 * If previous line ends in ',', check whether we
7420 * are in an initialization or enum
7425 * or a normal possible continuation line.
7426 * but only, of no other statement has been found
7429 if (lookfor
== LOOKFOR_INITIAL
&& terminated
== ',')
7431 lookfor
= LOOKFOR_ENUM_OR_INIT
;
7432 cont_amount
= cin_first_id_amount();
7436 if (lookfor
== LOOKFOR_INITIAL
7438 && l
[STRLEN(l
) - 1] == '\\')
7440 cont_amount
= cin_get_equal_amount(
7441 curwin
->w_cursor
.lnum
);
7442 if (lookfor
!= LOOKFOR_TERM
)
7443 lookfor
= LOOKFOR_UNTERM
;
7450 * Check if we are after a while (cond);
7451 * If so: Ignore until the matching "do".
7454 else if (cin_iswhileofdo_end(terminated
, ind_maxparen
,
7458 * Found an unterminated line after a while ();, line up
7459 * with the last one.
7461 * 100 + <- line up with this one
7464 if (lookfor
== LOOKFOR_UNTERM
7465 || lookfor
== LOOKFOR_ENUM_OR_INIT
)
7467 if (cont_amount
> 0)
7468 amount
= cont_amount
;
7470 amount
+= ind_continuation
;
7474 if (whilelevel
== 0)
7476 lookfor
= LOOKFOR_TERM
;
7477 amount
= get_indent(); /* XXX */
7478 if (theline
[0] == '{')
7479 amount
+= ind_open_extra
;
7485 * We are after a "normal" statement.
7486 * If we had another statement we can stop now and use the
7487 * indent of that other statement.
7488 * Otherwise the indent of the current statement may be used,
7489 * search backwards for the next "normal" statement.
7494 * Skip single break line, if before a switch label. It
7495 * may be lined up with the case label.
7497 if (lookfor
== LOOKFOR_NOBREAK
7498 && cin_isbreak(skipwhite(ml_get_curline())))
7500 lookfor
= LOOKFOR_ANY
;
7505 * Handle "do {" line.
7509 l
= cin_skipcomment(ml_get_curline());
7512 amount
= get_indent(); /* XXX */
7519 * Found a terminated line above an unterminated line. Add
7520 * the amount for a continuation line.
7529 if (lookfor
== LOOKFOR_UNTERM
7530 || lookfor
== LOOKFOR_ENUM_OR_INIT
)
7532 if (cont_amount
> 0)
7533 amount
= cont_amount
;
7535 amount
+= ind_continuation
;
7540 * Found a terminated line above a terminated line or "if"
7541 * etc. line. Use the amount of the line below us.
7544 * while (asdf) ->here;
7548 if (lookfor
== LOOKFOR_TERM
)
7550 if (!lookfor_break
&& whilelevel
== 0)
7555 * First line above the one we're indenting is terminated.
7556 * To know what needs to be done look further backward for
7557 * a terminated line.
7562 * position the cursor over the rightmost paren, so
7563 * that matching it will take us back to the start of
7564 * the line. Helps for:
7570 l
= ml_get_curline();
7571 if (find_last_paren(l
, '(', ')')
7572 && (trypos
= find_match_paren(ind_maxparen
,
7573 ind_maxcomment
)) != NULL
)
7576 * Check if we are on a case label now. This is
7578 * case xx: if ( asdf &&
7581 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7582 l
= ml_get_curline();
7583 if (cin_iscase(l
) || cin_isscopedecl(l
))
7585 ++curwin
->w_cursor
.lnum
;
7590 /* When aligning with the case statement, don't align
7591 * with a statement after it.
7592 * case 1: { <-- don't use this { position
7599 iscase
= (ind_keep_case_label
&& cin_iscase(l
));
7602 * Get indent and pointer to text for current line,
7603 * ignoring any jump label.
7605 amount
= skip_label(curwin
->w_cursor
.lnum
,
7606 &l
, ind_maxcomment
);
7608 if (theline
[0] == '{')
7609 amount
+= ind_open_extra
;
7610 /* See remark above: "Only add ind_open_extra.." */
7613 amount
-= ind_open_extra
;
7614 lookfor
= iscase
? LOOKFOR_ANY
: LOOKFOR_TERM
;
7617 * When a terminated line starts with "else" skip to
7618 * the matching "if":
7621 * Need to use the scope of this "else". XXX
7622 * If whilelevel != 0 continue looking for a "do {".
7624 if (lookfor
== LOOKFOR_TERM
7629 if ((trypos
= find_start_brace(ind_maxcomment
))
7631 || find_match(LOOKFOR_IF
, trypos
->lnum
,
7632 ind_maxparen
, ind_maxcomment
) == FAIL
)
7638 * If we're at the end of a block, skip to the start of
7641 curwin
->w_cursor
.col
= 0;
7642 if (*cin_skipcomment(l
) == '}'
7643 && (trypos
= find_start_brace(ind_maxcomment
))
7646 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7647 /* if not "else {" check for terminated again */
7648 /* but skip block for "} else {" */
7649 l
= cin_skipcomment(ml_get_curline());
7650 if (*l
== '}' || !cin_iselse(l
))
7652 ++curwin
->w_cursor
.lnum
;
7660 /* add extra indent for a comment */
7661 if (cin_iscomment(theline
))
7662 amount
+= ind_comment
;
7666 * ok -- we're not inside any sort of structure at all!
7668 * this means we're at the top level, and everything should
7669 * basically just match where the previous line is, except
7670 * for the lines immediately following a function declaration,
7671 * which are K&R-style parameters and need to be indented.
7676 * if our line starts with an open brace, forget about any
7677 * prevailing indent and make sure it looks like the start
7681 if (theline
[0] == '{')
7683 amount
= ind_first_open
;
7687 * If the NEXT line is a function declaration, the current
7688 * line needs to be indented as a function type spec.
7689 * Don't do this if the current line looks like a comment
7690 * or if the current line is terminated, ie. ends in ';'.
7692 else if (cur_curpos
.lnum
< curbuf
->b_ml
.ml_line_count
7693 && !cin_nocode(theline
)
7694 && !cin_ends_in(theline
, (char_u
*)":", NULL
)
7695 && !cin_ends_in(theline
, (char_u
*)",", NULL
)
7696 && cin_isfuncdecl(NULL
, cur_curpos
.lnum
+ 1)
7697 && !cin_isterminated(theline
, FALSE
, TRUE
))
7699 amount
= ind_func_type
;
7704 curwin
->w_cursor
= cur_curpos
;
7706 /* search backwards until we find something we recognize */
7708 while (curwin
->w_cursor
.lnum
> 1)
7710 curwin
->w_cursor
.lnum
--;
7711 curwin
->w_cursor
.col
= 0;
7713 l
= ml_get_curline();
7716 * If we're in a comment now, skip to the start of the comment.
7718 if ((trypos
= find_start_comment(ind_maxcomment
)) != NULL
)
7720 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
7725 * Are we at the start of a cpp base class declaration or
7726 * constructor initialization?
7729 if (ind_cpp_baseclass
!= 0 && theline
[0] != '{')
7731 n
= cin_is_cpp_baseclass(&col
);
7732 l
= ml_get_curline();
7737 amount
= get_baseclass_amount(col
, ind_maxparen
,
7738 ind_maxcomment
, ind_cpp_baseclass
);
7743 * Skip preprocessor directives and blank lines.
7745 if (cin_ispreproc_cont(&l
, &curwin
->w_cursor
.lnum
))
7752 * If the previous line ends in ',', use one level of
7756 * do this before checking for '}' in case of eg.
7764 if (cin_ends_in(l
, (char_u
*)",", NULL
)
7765 || (*l
!= NUL
&& (n
= l
[STRLEN(l
) - 1]) == '\\'))
7767 /* take us back to opening paren */
7768 if (find_last_paren(l
, '(', ')')
7769 && (trypos
= find_match_paren(ind_maxparen
,
7770 ind_maxcomment
)) != NULL
)
7771 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7773 /* For a line ending in ',' that is a continuation line go
7774 * back to the first line with a backslash:
7779 while (n
== 0 && curwin
->w_cursor
.lnum
> 1)
7781 l
= ml_get(curwin
->w_cursor
.lnum
- 1);
7782 if (*l
== NUL
|| l
[STRLEN(l
) - 1] != '\\')
7784 --curwin
->w_cursor
.lnum
;
7787 amount
= get_indent(); /* XXX */
7790 amount
= cin_first_id_amount();
7792 amount
= ind_continuation
;
7797 * If the line looks like a function declaration, and we're
7798 * not in a comment, put it the left margin.
7800 if (cin_isfuncdecl(NULL
, cur_curpos
.lnum
)) /* XXX */
7802 l
= ml_get_curline();
7805 * Finding the closing '}' of a previous function. Put
7806 * current line at the left margin. For when 'cino' has "fs".
7808 if (*skipwhite(l
) == '}')
7812 * If the previous line ends on '};' (maybe followed by
7813 * comments) align at column 0. For example:
7814 * char *string_array[] = { "foo",
7815 * / * x * / "b};ar" }; / * foobar * /
7817 if (cin_ends_in(l
, (char_u
*)"};", NULL
))
7821 * If the PREVIOUS line is a function declaration, the current
7822 * line (and the ones that follow) needs to be indented as
7825 if (cin_isfuncdecl(&l
, curwin
->w_cursor
.lnum
))
7832 * If the previous line ends in ';' and the line before the
7833 * previous line ends in ',' or '\', ident to column zero:
7838 if (cin_ends_in(l
, (char_u
*)";", NULL
))
7840 l
= ml_get(curwin
->w_cursor
.lnum
- 1);
7841 if (cin_ends_in(l
, (char_u
*)",", NULL
)
7842 || (*l
!= NUL
&& l
[STRLEN(l
) - 1] == '\\'))
7844 l
= ml_get_curline();
7848 * Doesn't look like anything interesting -- so just
7849 * use the indent of this line.
7851 * Position the cursor over the rightmost paren, so that
7852 * matching it will take us back to the start of the line.
7854 find_last_paren(l
, '(', ')');
7856 if ((trypos
= find_match_paren(ind_maxparen
,
7857 ind_maxcomment
)) != NULL
)
7858 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7859 amount
= get_indent(); /* XXX */
7863 /* add extra indent for a comment */
7864 if (cin_iscomment(theline
))
7865 amount
+= ind_comment
;
7867 /* add extra indent if the previous line ended in a backslash:
7870 * char *foo = "asdf\
7873 if (cur_curpos
.lnum
> 1)
7875 l
= ml_get(cur_curpos
.lnum
- 1);
7876 if (*l
!= NUL
&& l
[STRLEN(l
) - 1] == '\\')
7878 cur_amount
= cin_get_equal_amount(cur_curpos
.lnum
- 1);
7880 amount
= cur_amount
;
7881 else if (cur_amount
== 0)
7882 amount
+= ind_continuation
;
7889 /* put the cursor back where it belongs */
7890 curwin
->w_cursor
= cur_curpos
;
7900 find_match(lookfor
, ourscope
, ind_maxparen
, ind_maxcomment
)
7912 if (lookfor
== LOOKFOR_IF
)
7923 curwin
->w_cursor
.col
= 0;
7925 while (curwin
->w_cursor
.lnum
> ourscope
+ 1)
7927 curwin
->w_cursor
.lnum
--;
7928 curwin
->w_cursor
.col
= 0;
7930 look
= cin_skipcomment(ml_get_curline());
7931 if (cin_iselse(look
)
7933 || cin_isdo(look
) /* XXX */
7934 || cin_iswhileofdo(look
, curwin
->w_cursor
.lnum
, ind_maxparen
))
7937 * if we've gone outside the braces entirely,
7938 * we must be out of scope...
7940 theirscope
= find_start_brace(ind_maxcomment
); /* XXX */
7941 if (theirscope
== NULL
)
7945 * and if the brace enclosing this is further
7946 * back than the one enclosing the else, we're
7949 if (theirscope
->lnum
< ourscope
)
7953 * and if they're enclosed in a *deeper* brace,
7954 * then we can ignore it because it's in a
7955 * different scope...
7957 if (theirscope
->lnum
> ourscope
)
7961 * if it was an "else" (that's not an "else if")
7962 * then we need to go back to another if, so
7963 * increment elselevel
7965 look
= cin_skipcomment(ml_get_curline());
7966 if (cin_iselse(look
))
7968 mightbeif
= cin_skipcomment(look
+ 4);
7969 if (!cin_isif(mightbeif
))
7975 * if it was a "while" then we need to go back to
7976 * another "do", so increment whilelevel. XXX
7978 if (cin_iswhileofdo(look
, curwin
->w_cursor
.lnum
, ind_maxparen
))
7984 /* If it's an "if" decrement elselevel */
7985 look
= cin_skipcomment(ml_get_curline());
7990 * When looking for an "if" ignore "while"s that
7993 if (elselevel
== 0 && lookfor
== LOOKFOR_IF
)
7997 /* If it's a "do" decrement whilelevel */
8002 * if we've used up all the elses, then
8003 * this must be the if that we want!
8004 * match the indent level of that if.
8006 if (elselevel
<= 0 && whilelevel
<= 0)
8015 # if defined(FEAT_EVAL) || defined(PROTO)
8017 * Get indent level from 'indentexpr'.
8025 int use_sandbox
= was_set_insecurely((char_u
*)"indentexpr",
8028 pos
= curwin
->w_cursor
;
8029 set_vim_var_nr(VV_LNUM
, curwin
->w_cursor
.lnum
);
8033 indent
= eval_to_number(curbuf
->b_p_inde
);
8038 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8039 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8043 curwin
->w_cursor
= pos
;
8047 /* If there is an error, just keep the current indent. */
8049 indent
= get_indent();
8055 #endif /* FEAT_CINDENT */
8057 #if defined(FEAT_LISP) || defined(PROTO)
8059 static int lisp_match
__ARGS((char_u
*p
));
8067 char_u
*word
= p_lispwords
;
8069 while (*word
!= NUL
)
8071 (void)copy_option_part(&word
, buf
, LSIZE
, ",");
8072 len
= (int)STRLEN(buf
);
8073 if (STRNCMP(buf
, p
, len
) == 0 && p
[len
] == ' ')
8080 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8081 * The incompatible newer method is quite a bit better at indenting
8082 * code in lisp-like languages than the traditional one; it's still
8083 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8086 * Findmatch() should be adapted for lisp, also to make showmatch
8087 * work correctly: now (v5.3) it seems all C/C++ oriented:
8088 * - it does not recognize the #\( and #\) notations as character literals
8089 * - it doesn't know about comments starting with a semicolon
8090 * - it incorrectly interprets '(' as a character literal
8091 * All this messes up get_lisp_indent in some rare cases.
8092 * Update from Sergey Khorev:
8093 * I tried to fix the first two issues.
8098 pos_T
*pos
, realpos
, paren
;
8103 int parencount
, quotecount
;
8106 /* Set vi_lisp to use the vi-compatible method */
8107 vi_lisp
= (vim_strchr(p_cpo
, CPO_LISP
) != NULL
);
8109 realpos
= curwin
->w_cursor
;
8110 curwin
->w_cursor
.col
= 0;
8112 if ((pos
= findmatch(NULL
, '(')) == NULL
)
8113 pos
= findmatch(NULL
, '[');
8117 pos
= findmatch(NULL
, '[');
8118 if (pos
== NULL
|| ltp(pos
, &paren
))
8123 /* Extra trick: Take the indent of the first previous non-white
8124 * line that is at the same () level. */
8128 while (--curwin
->w_cursor
.lnum
>= pos
->lnum
)
8130 if (linewhite(curwin
->w_cursor
.lnum
))
8132 for (that
= ml_get_curline(); *that
!= NUL
; ++that
)
8136 while (*(that
+ 1) != NUL
)
8142 if (*(that
+ 1) != NUL
)
8146 if (*that
== '"' && *(that
+ 1) != NUL
)
8148 while (*++that
&& *that
!= '"')
8150 /* skipping escaped characters in the string */
8163 if (*that
== '(' || *that
== '[')
8165 else if (*that
== ')' || *that
== ']')
8168 if (parencount
== 0)
8170 amount
= get_indent();
8177 curwin
->w_cursor
.lnum
= pos
->lnum
;
8178 curwin
->w_cursor
.col
= pos
->col
;
8181 that
= ml_get_curline();
8183 if (vi_lisp
&& get_indent() == 0)
8188 while (*that
&& col
)
8190 amount
+= lbr_chartabsize_adv(&that
, (colnr_T
)amount
);
8195 * Some keywords require "body" indenting rules (the
8196 * non-standard-lisp ones are Scheme special forms):
8198 * (let ((a 1)) instead (let ((a 1))
8202 if (!vi_lisp
&& (*that
== '(' || *that
== '[')
8203 && lisp_match(that
+ 1))
8211 while (vim_iswhite(*that
))
8213 amount
+= lbr_chartabsize(that
, (colnr_T
)amount
);
8217 if (*that
&& *that
!= ';') /* not a comment line */
8219 /* test *that != '(' to accomodate first let/do
8220 * argument if it is more than one line */
8221 if (!vi_lisp
&& *that
!= '(' && *that
!= '[')
8231 && (*that
< '0' || *that
> '9')))
8234 && (!vim_iswhite(*that
)
8237 && (!((*that
== '(' || *that
== '[')
8243 quotecount
= !quotecount
;
8244 if ((*that
== '(' || *that
== '[')
8247 if ((*that
== ')' || *that
== ']')
8250 if (*that
== '\\' && *(that
+1) != NUL
)
8251 amount
+= lbr_chartabsize_adv(&that
,
8253 amount
+= lbr_chartabsize_adv(&that
,
8257 while (vim_iswhite(*that
))
8259 amount
+= lbr_chartabsize(that
, (colnr_T
)amount
);
8262 if (!*that
|| *that
== ';')
8270 amount
= 0; /* no matching '(' or '[' found, use zero indent */
8272 curwin
->w_cursor
= realpos
;
8276 #endif /* FEAT_LISP */
8281 #if defined(SIGHUP) && defined(SIG_IGN)
8282 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8283 * makes Vim exit and then handling SIGHUP causes various reentrance
8285 signal(SIGHUP
, SIG_IGN
);
8292 out_trash(); /* trash any pending output */
8297 windgoto((int)Rows
- 1, 0);
8300 * Switch terminal mode back now, so messages end up on the "normal"
8301 * screen (if there are two screens).
8303 settmode(TMODE_COOK
);
8305 if (can_end_termcap_mode(FALSE
) == TRUE
)
8313 * Preserve files and exit.
8314 * When called IObuff must contain a message.
8323 /* Setting this will prevent free() calls. That avoids calling free()
8324 * recursively when free() was invoked with a bad pointer. */
8325 really_exiting
= TRUE
;
8328 screen_start(); /* don't know where cursor is now */
8331 ml_close_notmod(); /* close all not-modified buffers */
8333 for (buf
= firstbuf
; buf
!= NULL
; buf
= buf
->b_next
)
8335 if (buf
->b_ml
.ml_mfp
!= NULL
&& buf
->b_ml
.ml_mfp
->mf_fname
!= NULL
)
8337 OUT_STR(_("Vim: preserving files...\n"));
8338 screen_start(); /* don't know where cursor is now */
8340 ml_sync_all(FALSE
, FALSE
); /* preserve all swap files */
8345 ml_close_all(FALSE
); /* close all memfiles, without deleting */
8347 OUT_STR(_("Vim: Finished.\n"));
8353 * return TRUE if "fname" exists.
8361 if (mch_stat((char *)fname
, &st
))
8367 * Check for CTRL-C pressed, but only once in a while.
8368 * Should be used instead of ui_breakcheck() for functions that check for
8369 * each line in the file. Calling ui_breakcheck() each time takes too much
8370 * time, because it can be a system call.
8373 #ifndef BREAKCHECK_SKIP
8374 # ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8375 # define BREAKCHECK_SKIP 200
8377 # define BREAKCHECK_SKIP 32
8381 static int breakcheck_count
= 0;
8386 if (++breakcheck_count
>= BREAKCHECK_SKIP
)
8388 breakcheck_count
= 0;
8394 * Like line_breakcheck() but check 10 times less often.
8399 if (++breakcheck_count
>= BREAKCHECK_SKIP
* 10)
8401 breakcheck_count
= 0;
8407 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8409 * Returns OK or FAIL.
8412 expand_wildcards(num_pat
, pat
, num_file
, file
, flags
)
8413 int num_pat
; /* number of input patterns */
8414 char_u
**pat
; /* array of input patterns */
8415 int *num_file
; /* resulting number of files */
8416 char_u
***file
; /* array of resulting files */
8417 int flags
; /* EW_DIR, etc. */
8422 int non_suf_match
; /* number without matching suffix */
8424 retval
= gen_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
);
8426 /* When keeping all matches, return here */
8427 if (flags
& EW_KEEPALL
)
8432 * Remove names that match 'wildignore'.
8438 /* check all files in (*file)[] */
8439 for (i
= 0; i
< *num_file
; ++i
)
8441 ffname
= FullName_save((*file
)[i
], FALSE
);
8442 if (ffname
== NULL
) /* out of memory */
8445 vms_remove_version(ffname
);
8447 if (match_file_list(p_wig
, (*file
)[i
], ffname
))
8449 /* remove this matching file from the list */
8450 vim_free((*file
)[i
]);
8451 for (j
= i
; j
+ 1 < *num_file
; ++j
)
8452 (*file
)[j
] = (*file
)[j
+ 1];
8462 * Move the names where 'suffixes' match to the end.
8467 for (i
= 0; i
< *num_file
; ++i
)
8469 if (!match_suffix((*file
)[i
]))
8472 * Move the name without matching suffix to the front
8476 for (j
= i
; j
> non_suf_match
; --j
)
8477 (*file
)[j
] = (*file
)[j
- 1];
8478 (*file
)[non_suf_match
++] = p
;
8487 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8493 int fnamelen
, setsuflen
;
8495 #define MAXSUFLEN 30 /* maximum length of a file suffix */
8496 char_u suf_buf
[MAXSUFLEN
];
8498 fnamelen
= (int)STRLEN(fname
);
8500 for (setsuf
= p_su
; *setsuf
; )
8502 setsuflen
= copy_option_part(&setsuf
, suf_buf
, MAXSUFLEN
, ".,");
8503 if (fnamelen
>= setsuflen
8504 && fnamencmp(suf_buf
, fname
+ fnamelen
- setsuflen
,
8505 (size_t)setsuflen
) == 0)
8509 return (setsuflen
!= 0);
8512 #if !defined(NO_EXPANDPATH) || defined(PROTO)
8514 # ifdef VIM_BACKTICK
8515 static int vim_backtick
__ARGS((char_u
*p
));
8516 static int expand_backtick
__ARGS((garray_T
*gap
, char_u
*pat
, int flags
));
8519 # if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8521 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8522 * it's shared between these systems.
8524 # if defined(DJGPP) || defined(PROTO)
8525 # define _cdecl /* DJGPP doesn't have this */
8527 # ifdef __BORLANDC__
8528 # define _cdecl _RTLENTRYF
8533 * comparison function for qsort in dos_expandpath()
8536 pstrcmp(const void *a
, const void *b
)
8538 return (pathcmp(*(char **)a
, *(char **)b
, -1));
8548 if (USE_LONG_FNAME
) /* don't lower case on Windows 95/NT systems */
8554 *d
++ = TOLOWER_LOC(*s
++);
8560 * Recursively expand one path component into all matching files and/or
8561 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8562 * Return the number of matches found.
8563 * "path" has backslashes before chars that are not to be expanded, starting
8564 * at "path[wildoff]".
8565 * Return the number of matches found.
8566 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
8573 int flags
, /* EW_* flags */
8574 int didstar
) /* expanded "**" once already */
8579 int start_len
= gap
->ga_len
;
8581 regmatch_T regmatch
;
8582 int starts_with_dot
;
8585 int starstar
= FALSE
;
8586 static int stardepth
= 0; /* depth for "**" expansion */
8589 HANDLE hFind
= (HANDLE
)0;
8591 WIN32_FIND_DATAW wfb
;
8592 WCHAR
*wn
= NULL
; /* UCS-2 name, NULL when not used. */
8600 /* Expanding "**" may take a long time, check for CTRL-C. */
8608 /* make room for file name */
8609 buf
= alloc((int)STRLEN(path
) + BASENAMELEN
+ 5);
8614 * Find the first part in the path name that contains a wildcard or a ~1.
8615 * Copy it into buf, including the preceding characters.
8621 while (*path_end
!= NUL
)
8623 /* May ignore a wildcard that has a backslash before it; it will
8624 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8625 if (path_end
>= path
+ wildoff
&& rem_backslash(path_end
))
8627 else if (*path_end
== '\\' || *path_end
== ':' || *path_end
== '/')
8633 else if (path_end
>= path
+ wildoff
8634 && vim_strchr((char_u
*)"*?[~", *path_end
) != NULL
)
8639 len
= (*mb_ptr2len
)(path_end
);
8640 STRNCPY(p
, path_end
, len
);
8651 /* now we have one wildcard component between s and e */
8652 /* Remove backslashes between "wildoff" and the start of the wildcard
8654 for (p
= buf
+ wildoff
; p
< s
; ++p
)
8655 if (rem_backslash(p
))
8657 mch_memmove(p
, p
+ 1, STRLEN(p
));
8662 /* Check for "**" between "s" and "e". */
8663 for (p
= s
; p
< e
; ++p
)
8664 if (p
[0] == '*' && p
[1] == '*')
8667 starts_with_dot
= (*s
== '.');
8668 pat
= file_pat_to_reg_pat(s
, e
, NULL
, FALSE
);
8675 /* compile the regexp into a program */
8676 regmatch
.rm_ic
= TRUE
; /* Always ignore case */
8677 regmatch
.regprog
= vim_regcomp(pat
, RE_MAGIC
);
8680 if (regmatch
.regprog
== NULL
)
8686 /* remember the pattern or file name being looked for */
8687 matchname
= vim_strsave(s
);
8689 /* If "**" is by itself, this is the first time we encounter it and more
8690 * is following then find matches without any directory. */
8691 if (!didstar
&& stardepth
< 100 && starstar
&& e
- s
== 2
8692 && *path_end
== '/')
8694 STRCPY(s
, path_end
+ 1);
8696 (void)dos_expandpath(gap
, buf
, (int)(s
- buf
), flags
, TRUE
);
8700 /* Scan all files in the directory with "dir/ *.*" */
8704 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
8706 /* The active codepage differs from 'encoding'. Attempt using the
8707 * wide function. If it fails because it is not implemented fall back
8708 * to the non-wide version (for Windows 98) */
8709 wn
= enc_to_ucs2(buf
, NULL
);
8712 hFind
= FindFirstFileW(wn
, &wfb
);
8713 if (hFind
== INVALID_HANDLE_VALUE
8714 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
8724 hFind
= FindFirstFile(buf
, &fb
);
8725 ok
= (hFind
!= INVALID_HANDLE_VALUE
);
8727 /* If we are expanding wildcards we try both files and directories */
8728 ok
= (findfirst((char *)buf
, &fb
,
8729 (*path_end
!= NUL
|| (flags
& EW_DIR
)) ? FA_DIREC
: 0) == 0);
8737 p
= ucs2_to_enc(wfb
.cFileName
, NULL
); /* p is allocated here */
8740 p
= (char_u
*)fb
.cFileName
;
8742 p
= (char_u
*)fb
.ff_name
;
8744 /* Ignore entries starting with a dot, unless when asked for. Accept
8745 * all entries found with "matchname". */
8746 if ((p
[0] != '.' || starts_with_dot
)
8747 && (matchname
== NULL
8748 || vim_regexec(®match
, p
, (colnr_T
)0)))
8755 len
= (int)STRLEN(buf
);
8757 if (starstar
&& stardepth
< 100)
8759 /* For "**" in the pattern first go deeper in the tree to
8761 STRCPY(buf
+ len
, "/**");
8762 STRCPY(buf
+ len
+ 3, path_end
);
8764 (void)dos_expandpath(gap
, buf
, len
+ 1, flags
, TRUE
);
8768 STRCPY(buf
+ len
, path_end
);
8769 if (mch_has_exp_wildcard(path_end
))
8771 /* need to expand another component of the path */
8772 /* remove backslashes for the remaining components only */
8773 (void)dos_expandpath(gap
, buf
, len
+ 1, flags
, FALSE
);
8777 /* no more wildcards, check if there is a match */
8778 /* remove backslashes for the remaining components only */
8780 backslash_halve(buf
+ len
+ 1);
8781 if (mch_getperm(buf
) >= 0) /* add existing file */
8782 addfile(gap
, buf
, flags
);
8791 ok
= FindNextFileW(hFind
, &wfb
);
8795 ok
= FindNextFile(hFind
, &fb
);
8797 ok
= (findnext(&fb
) == 0);
8800 /* If no more matches and no match was used, try expanding the name
8801 * itself. Finds the long name of a short filename. */
8802 if (!ok
&& matchname
!= NULL
&& gap
->ga_len
== start_len
)
8804 STRCPY(s
, matchname
);
8811 wn
= enc_to_ucs2(buf
, NULL
);
8813 hFind
= FindFirstFileW(wn
, &wfb
);
8817 hFind
= FindFirstFile(buf
, &fb
);
8818 ok
= (hFind
!= INVALID_HANDLE_VALUE
);
8820 ok
= (findfirst((char *)buf
, &fb
,
8821 (*path_end
!= NUL
|| (flags
& EW_DIR
)) ? FA_DIREC
: 0) == 0);
8823 vim_free(matchname
);
8835 vim_free(regmatch
.regprog
);
8836 vim_free(matchname
);
8838 matches
= gap
->ga_len
- start_len
;
8840 qsort(((char_u
**)gap
->ga_data
) + start_len
, (size_t)matches
,
8841 sizeof(char_u
*), pstrcmp
);
8849 int flags
) /* EW_* flags */
8851 return dos_expandpath(gap
, path
, 0, flags
, FALSE
);
8853 # endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8855 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8858 * Unix style wildcard expansion code.
8859 * It's here because it's used both for Unix and Mac.
8861 static int pstrcmp
__ARGS((const void *, const void *));
8867 return (pathcmp(*(char **)a
, *(char **)b
, -1));
8871 * Recursively expand one path component into all matching files and/or
8872 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8873 * "path" has backslashes before chars that are not to be expanded, starting
8874 * at "path + wildoff".
8875 * Return the number of matches found.
8876 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8879 unix_expandpath(gap
, path
, wildoff
, flags
, didstar
)
8883 int flags
; /* EW_* flags */
8884 int didstar
; /* expanded "**" once already */
8889 int start_len
= gap
->ga_len
;
8891 regmatch_T regmatch
;
8892 int starts_with_dot
;
8895 int starstar
= FALSE
;
8896 static int stardepth
= 0; /* depth for "**" expansion */
8901 /* Expanding "**" may take a long time, check for CTRL-C. */
8909 /* make room for file name */
8910 buf
= alloc((int)STRLEN(path
) + BASENAMELEN
+ 5);
8915 * Find the first part in the path name that contains a wildcard.
8916 * Copy it into "buf", including the preceding characters.
8922 while (*path_end
!= NUL
)
8924 /* May ignore a wildcard that has a backslash before it; it will
8925 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8926 if (path_end
>= path
+ wildoff
&& rem_backslash(path_end
))
8928 else if (*path_end
== '/')
8934 else if (path_end
>= path
+ wildoff
8935 && vim_strchr((char_u
*)"*?[{~$", *path_end
) != NULL
)
8940 len
= (*mb_ptr2len
)(path_end
);
8941 STRNCPY(p
, path_end
, len
);
8952 /* now we have one wildcard component between "s" and "e" */
8953 /* Remove backslashes between "wildoff" and the start of the wildcard
8955 for (p
= buf
+ wildoff
; p
< s
; ++p
)
8956 if (rem_backslash(p
))
8958 mch_memmove(p
, p
+ 1, STRLEN(p
));
8963 /* Check for "**" between "s" and "e". */
8964 for (p
= s
; p
< e
; ++p
)
8965 if (p
[0] == '*' && p
[1] == '*')
8968 /* convert the file pattern to a regexp pattern */
8969 starts_with_dot
= (*s
== '.');
8970 pat
= file_pat_to_reg_pat(s
, e
, NULL
, FALSE
);
8977 /* compile the regexp into a program */
8978 #ifdef CASE_INSENSITIVE_FILENAME
8979 regmatch
.rm_ic
= TRUE
; /* Behave like Terminal.app */
8981 regmatch
.rm_ic
= FALSE
; /* Don't ever ignore case */
8983 regmatch
.regprog
= vim_regcomp(pat
, RE_MAGIC
);
8986 if (regmatch
.regprog
== NULL
)
8992 /* If "**" is by itself, this is the first time we encounter it and more
8993 * is following then find matches without any directory. */
8994 if (!didstar
&& stardepth
< 100 && starstar
&& e
- s
== 2
8995 && *path_end
== '/')
8997 STRCPY(s
, path_end
+ 1);
8999 (void)unix_expandpath(gap
, buf
, (int)(s
- buf
), flags
, TRUE
);
9003 /* open the directory for scanning */
9005 dirp
= opendir(*buf
== NUL
? "." : (char *)buf
);
9007 /* Find all matching entries */
9015 if ((dp
->d_name
[0] != '.' || starts_with_dot
)
9016 && vim_regexec(®match
, (char_u
*)dp
->d_name
, (colnr_T
)0))
9018 STRCPY(s
, dp
->d_name
);
9021 if (starstar
&& stardepth
< 100)
9023 /* For "**" in the pattern first go deeper in the tree to
9025 STRCPY(buf
+ len
, "/**");
9026 STRCPY(buf
+ len
+ 3, path_end
);
9028 (void)unix_expandpath(gap
, buf
, len
+ 1, flags
, TRUE
);
9032 STRCPY(buf
+ len
, path_end
);
9033 if (mch_has_exp_wildcard(path_end
)) /* handle more wildcards */
9035 /* need to expand another component of the path */
9036 /* remove backslashes for the remaining components only */
9037 (void)unix_expandpath(gap
, buf
, len
+ 1, flags
, FALSE
);
9041 /* no more wildcards, check if there is a match */
9042 /* remove backslashes for the remaining components only */
9043 if (*path_end
!= NUL
)
9044 backslash_halve(buf
+ len
+ 1);
9045 if (mch_getperm(buf
) >= 0) /* add existing file */
9047 #ifdef MACOS_CONVERT
9048 size_t precomp_len
= STRLEN(buf
)+1;
9049 char_u
*precomp_buf
=
9050 mac_precompose_path(buf
, precomp_len
, &precomp_len
);
9054 mch_memmove(buf
, precomp_buf
, precomp_len
);
9055 vim_free(precomp_buf
);
9058 addfile(gap
, buf
, flags
);
9068 vim_free(regmatch
.regprog
);
9070 matches
= gap
->ga_len
- start_len
;
9072 qsort(((char_u
**)gap
->ga_data
) + start_len
, matches
,
9073 sizeof(char_u
*), pstrcmp
);
9079 * Generic wildcard expansion code.
9081 * Characters in "pat" that should not be expanded must be preceded with a
9082 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9084 * Return FAIL when no single file was found. In this case "num_file" is not
9085 * set, and "file" may contain an error message.
9086 * Return OK when some files found. "num_file" is set to the number of
9087 * matches, "file" to the array of matches. Call FreeWild() later.
9090 gen_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
)
9091 int num_pat
; /* number of input patterns */
9092 char_u
**pat
; /* array of input patterns */
9093 int *num_file
; /* resulting number of files */
9094 char_u
***file
; /* array of resulting files */
9095 int flags
; /* EW_* flags */
9100 static int recursive
= FALSE
;
9104 * expand_env() is called to expand things like "~user". If this fails,
9105 * it calls ExpandOne(), which brings us back here. In this case, always
9106 * call the machine specific expansion function, if possible. Otherwise,
9110 #ifdef SPECIAL_WILDCHAR
9111 return mch_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
);
9116 #ifdef SPECIAL_WILDCHAR
9118 * If there are any special wildcard characters which we cannot handle
9119 * here, call machine specific function for all the expansion. This
9120 * avoids starting the shell for each argument separately.
9121 * For `=expr` do use the internal function.
9123 for (i
= 0; i
< num_pat
; i
++)
9125 if (vim_strpbrk(pat
[i
], (char_u
*)SPECIAL_WILDCHAR
) != NULL
9126 # ifdef VIM_BACKTICK
9127 && !(vim_backtick(pat
[i
]) && pat
[i
][1] == '=')
9130 return mch_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
);
9137 * The matching file names are stored in a growarray. Init it empty.
9139 ga_init2(&ga
, (int)sizeof(char_u
*), 30);
9141 for (i
= 0; i
< num_pat
; ++i
)
9147 if (vim_backtick(p
))
9148 add_pat
= expand_backtick(&ga
, p
, flags
);
9153 * First expand environment variables, "~/" and "~user/".
9155 if (vim_strpbrk(p
, (char_u
*)"$~") != NULL
)
9157 p
= expand_env_save_opt(p
, TRUE
);
9162 * On Unix, if expand_env() can't expand an environment
9163 * variable, use the shell to do that. Discard previously
9164 * found file names and start all over again.
9166 else if (vim_strpbrk(p
, (char_u
*)"$~") != NULL
)
9170 i
= mch_expand_wildcards(num_pat
, pat
, num_file
, file
,
9179 * If there are wildcards: Expand file names and add each match to
9180 * the list. If there is no match, and EW_NOTFOUND is given, add
9182 * If there are no wildcards: Add the file name if it exists or
9183 * when EW_NOTFOUND is given.
9185 if (mch_has_exp_wildcard(p
))
9186 add_pat
= mch_expandpath(&ga
, p
, flags
);
9189 if (add_pat
== -1 || (add_pat
== 0 && (flags
& EW_NOTFOUND
)))
9191 char_u
*t
= backslash_halve_save(p
);
9193 #if defined(MACOS_CLASSIC)
9196 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9197 * "vim c:/" work. */
9198 if (flags
& EW_NOTFOUND
)
9199 addfile(&ga
, t
, flags
| EW_DIR
| EW_FILE
);
9200 else if (mch_getperm(t
) >= 0)
9201 addfile(&ga
, t
, flags
);
9209 *num_file
= ga
.ga_len
;
9210 *file
= (ga
.ga_data
!= NULL
) ? (char_u
**)ga
.ga_data
: (char_u
**)"";
9214 return (ga
.ga_data
!= NULL
) ? OK
: FAIL
;
9217 # ifdef VIM_BACKTICK
9220 * Return TRUE if we can expand this backtick thing here.
9226 return (*p
== '`' && *(p
+ 1) != NUL
&& *(p
+ STRLEN(p
) - 1) == '`');
9230 * Expand an item in `backticks` by executing it as a command.
9231 * Currently only works when pat[] starts and ends with a `.
9232 * Returns number of file names found.
9235 expand_backtick(gap
, pat
, flags
)
9238 int flags
; /* EW_* flags */
9246 /* Create the command: lop off the backticks. */
9247 cmd
= vim_strnsave(pat
+ 1, (int)STRLEN(pat
) - 2);
9252 if (*cmd
== '=') /* `={expr}`: Expand expression */
9253 buffer
= eval_to_string(cmd
+ 1, &p
, TRUE
);
9256 buffer
= get_cmd_output(cmd
, NULL
,
9257 (flags
& EW_SILENT
) ? SHELL_SILENT
: 0);
9265 cmd
= skipwhite(cmd
); /* skip over white space */
9267 while (*p
!= NUL
&& *p
!= '\r' && *p
!= '\n') /* skip over entry */
9269 /* add an entry if it is not empty */
9274 addfile(gap
, cmd
, flags
);
9279 while (*cmd
!= NUL
&& (*cmd
== '\r' || *cmd
== '\n'))
9286 # endif /* VIM_BACKTICK */
9289 * Add a file to a file list. Accepted flags:
9290 * EW_DIR add directories
9292 * EW_EXEC add executable files
9293 * EW_NOTFOUND add even when it doesn't exist
9294 * EW_ADDSLASH add slash after directory name
9297 addfile(gap
, f
, flags
)
9299 char_u
*f
; /* filename */
9305 /* if the file/dir doesn't exist, may not add it */
9306 if (!(flags
& EW_NOTFOUND
) && mch_getperm(f
) < 0)
9309 #ifdef FNAME_ILLEGAL
9310 /* if the file/dir contains illegal characters, don't add it */
9311 if (vim_strpbrk(f
, (char_u
*)FNAME_ILLEGAL
) != NULL
)
9315 isdir
= mch_isdir(f
);
9316 if ((isdir
&& !(flags
& EW_DIR
)) || (!isdir
&& !(flags
& EW_FILE
)))
9319 /* If the file isn't executable, may not add it. Do accept directories. */
9320 if (!isdir
&& (flags
& EW_EXEC
) && !mch_can_exe(f
))
9323 /* Make room for another item in the file list. */
9324 if (ga_grow(gap
, 1) == FAIL
)
9327 p
= alloc((unsigned)(STRLEN(f
) + 1 + isdir
));
9332 #ifdef BACKSLASH_IN_FILENAME
9336 * Append a slash or backslash after directory names if none is present.
9338 #ifndef DONT_ADD_PATHSEP_TO_DIR
9339 if (isdir
&& (flags
& EW_ADDSLASH
))
9342 ((char_u
**)gap
->ga_data
)[gap
->ga_len
++] = p
;
9344 #endif /* !NO_EXPANDPATH */
9346 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9356 * Get the stdout of an external command.
9357 * Returns an allocated string, or NULL for error.
9360 get_cmd_output(cmd
, infile
, flags
)
9362 char_u
*infile
; /* optional input file name */
9363 int flags
; /* can be SHELL_SILENT */
9367 char_u
*buffer
= NULL
;
9372 if (check_restricted() || check_secure())
9375 /* get a name for the temp file */
9376 if ((tempname
= vim_tempname('o')) == NULL
)
9382 /* Add the redirection stuff */
9383 command
= make_filter_cmd(cmd
, infile
, tempname
);
9384 if (command
== NULL
)
9388 * Call the shell to execute the command (errors are ignored).
9389 * Don't check timestamps here.
9391 ++no_check_timestamps
;
9392 call_shell(command
, SHELL_DOOUT
| SHELL_EXPAND
| flags
);
9393 --no_check_timestamps
;
9398 * read the names from the file into memory
9401 /* created temporary file is not always readable as binary */
9402 fd
= mch_fopen((char *)tempname
, "r");
9404 fd
= mch_fopen((char *)tempname
, READBIN
);
9409 EMSG2(_(e_notopen
), tempname
);
9413 fseek(fd
, 0L, SEEK_END
);
9414 len
= ftell(fd
); /* get size of temp file */
9415 fseek(fd
, 0L, SEEK_SET
);
9417 buffer
= alloc(len
+ 1);
9419 i
= (int)fread((char *)buffer
, (size_t)1, (size_t)len
, fd
);
9421 mch_remove(tempname
);
9425 len
= i
; /* VMS doesn't give us what we asked for... */
9429 EMSG2(_(e_notread
), tempname
);
9434 buffer
[len
] = '\0'; /* make sure the buffer is terminated */
9443 * Free the list of files returned by expand_wildcards() or other expansion
9447 FreeWild(count
, files
)
9451 if (count
<= 0 || files
== NULL
)
9453 #if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9455 * Is this still OK for when other functions than expand_wildcards() have
9458 _fnexplodefree((char **)files
);
9461 vim_free(files
[count
]);
9467 * return TRUE when need to go to Insert mode because of 'insertmode'.
9468 * Don't do this when still processing a command or a mapping.
9469 * Don't do this when inside a ":normal" command.
9474 return (p_im
&& stuff_empty() && typebuf_typed());