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
= 0; /* 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
== 0)
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
!= 0)
211 newline
= alloc(orig_char_len
+ size
- ind_done
+ line_len
);
216 while (orig_char_len
> 0)
221 /* Skip over any additional white space (useful when newindent is less
223 while (vim_iswhite(*p
))
225 todo
= size
- ind_done
;
226 ind_len
+= todo
; /* Set total length of indent in characters,
227 * which may have been undercounted until now */
233 newline
= alloc(ind_len
+ line_len
);
239 /* Put the characters in the new line. */
240 /* if 'expandtab' isn't set: use TABs */
243 /* If 'preserveindent' is set then reuse as much as possible of
244 * the existing indent structure for the new indent */
245 if (!(flags
& SIN_INSERT
) && curbuf
->b_p_pi
)
250 while (todo
> 0 && vim_iswhite(*p
))
254 tab_pad
= (int)curbuf
->b_p_ts
255 - (ind_done
% (int)curbuf
->b_p_ts
);
256 /* stop if this tab will overshoot the target */
270 /* Fill to next tabstop with a tab, if possible */
271 tab_pad
= (int)curbuf
->b_p_ts
- (ind_done
% (int)curbuf
->b_p_ts
);
281 while (todo
>= (int)curbuf
->b_p_ts
)
284 todo
-= (int)curbuf
->b_p_ts
;
292 mch_memmove(s
, p
, (size_t)line_len
);
294 /* Replace the line (unless undo fails). */
295 if (!(flags
& SIN_UNDO
) || u_savesub(curwin
->w_cursor
.lnum
) == OK
)
297 ml_replace(curwin
->w_cursor
.lnum
, newline
, FALSE
);
298 if (flags
& SIN_CHANGED
)
299 changed_bytes(curwin
->w_cursor
.lnum
, 0);
300 /* Correct saved cursor position if it's after the indent. */
301 if (saved_cursor
.lnum
== curwin
->w_cursor
.lnum
302 && saved_cursor
.col
>= (colnr_T
)(p
- oldline
))
303 saved_cursor
.col
+= ind_len
- (colnr_T
)(p
- oldline
);
309 curwin
->w_cursor
.col
= ind_len
;
314 * Copy the indent from ptr to the current line (and fill to size)
315 * Leaves the cursor on the first non-blank in the line.
316 * Returns TRUE if the line was changed.
319 copy_indent(size
, src
)
333 /* Round 1: compute the number of characters needed for the indent
334 * Round 2: copy the characters. */
335 for (round
= 1; round
<= 2; ++round
)
342 /* Count/copy the usable portion of the source line */
343 while (todo
> 0 && vim_iswhite(*s
))
347 tab_pad
= (int)curbuf
->b_p_ts
348 - (ind_done
% (int)curbuf
->b_p_ts
);
349 /* Stop if this tab will overshoot the target */
366 /* Fill to next tabstop with a tab, if possible */
367 tab_pad
= (int)curbuf
->b_p_ts
- (ind_done
% (int)curbuf
->b_p_ts
);
376 /* Add tabs required for indent */
377 while (todo
>= (int)curbuf
->b_p_ts
)
379 todo
-= (int)curbuf
->b_p_ts
;
385 /* Count/add spaces required for indent */
396 /* Allocate memory for the result: the copied indent, new indent
397 * and the rest of the line. */
398 line_len
= (int)STRLEN(ml_get_curline()) + 1;
399 line
= alloc(ind_len
+ line_len
);
406 /* Append the original line */
407 mch_memmove(p
, ml_get_curline(), (size_t)line_len
);
409 /* Replace the line */
410 ml_replace(curwin
->w_cursor
.lnum
, line
, FALSE
);
412 /* Put the cursor after the indent. */
413 curwin
->w_cursor
.col
= ind_len
;
418 * Return the indent of the current line after a number. Return -1 if no
419 * number was found. Used for 'n' in 'formatoptions': numbered list.
420 * Since a pattern is used it can actually handle more than numbers.
423 get_number_indent(lnum
)
428 regmmatch_T regmatch
;
430 if (lnum
> curbuf
->b_ml
.ml_line_count
)
433 regmatch
.regprog
= vim_regcomp(curbuf
->b_p_flp
, RE_MAGIC
);
434 if (regmatch
.regprog
!= NULL
)
436 regmatch
.rmm_ic
= FALSE
;
437 regmatch
.rmm_maxcol
= 0;
438 if (vim_regexec_multi(®match
, curwin
, curbuf
, lnum
, (colnr_T
)0))
440 pos
.lnum
= regmatch
.endpos
[0].lnum
+ lnum
;
441 pos
.col
= regmatch
.endpos
[0].col
;
442 #ifdef FEAT_VIRTUALEDIT
446 vim_free(regmatch
.regprog
);
449 if (pos
.lnum
== 0 || *ml_get_pos(&pos
) == NUL
)
451 getvcol(curwin
, &pos
, &col
, NULL
, NULL
);
455 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
457 static int cin_is_cinword
__ARGS((char_u
*line
));
460 * Return TRUE if the string "line" starts with a word from 'cinwords'.
472 cinw_len
= (int)STRLEN(curbuf
->b_p_cinw
) + 1;
473 cinw_buf
= alloc((unsigned)cinw_len
);
474 if (cinw_buf
!= NULL
)
476 line
= skipwhite(line
);
477 for (cinw
= curbuf
->b_p_cinw
; *cinw
; )
479 len
= copy_option_part(&cinw
, cinw_buf
, cinw_len
, ",");
480 if (STRNCMP(line
, cinw_buf
, len
) == 0
481 && (!vim_iswordc(line
[len
]) || !vim_iswordc(line
[len
- 1])))
494 * open_line: Add a new line below or above the current line.
496 * For VREPLACE mode, we only add a new line when we get to the end of the
497 * file, otherwise we just start replacing the next line.
499 * Caller must take care of undo. Since VREPLACE may affect any number of
500 * lines however, it may call u_save_cursor() again when starting to change a
502 * "flags": OPENLINE_DELSPACES delete spaces after cursor
503 * OPENLINE_DO_COM format comments
504 * OPENLINE_KEEPTRAIL keep trailing spaces
505 * OPENLINE_MARKFIX adjust mark positions after the line break
507 * Return TRUE for success, FALSE for failure
510 open_line(dir
, flags
, old_indent
)
511 int dir
; /* FORWARD or BACKWARD */
513 int old_indent
; /* indent for after ^^D in Insert mode */
515 char_u
*saved_line
; /* copy of the original line */
516 char_u
*next_line
= NULL
; /* copy of the next line */
517 char_u
*p_extra
= NULL
; /* what goes to next line */
518 int less_cols
= 0; /* less columns for mark in new line */
519 int less_cols_off
= 0; /* columns to skip for mark adjust */
520 pos_T old_cursor
; /* old cursor position */
521 int newcol
= 0; /* new cursor column */
522 int newindent
= 0; /* auto-indent of the new line */
524 int trunc_line
= FALSE
; /* truncate current line afterwards */
525 int retval
= FALSE
; /* return value, default is FAIL */
527 int extra_len
= 0; /* length of p_extra string */
528 int lead_len
; /* length of comment leader */
529 char_u
*lead_flags
; /* position in 'comments' for comment leader */
530 char_u
*leader
= NULL
; /* copy of comment leader */
532 char_u
*allocated
= NULL
; /* allocated memory */
533 #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
534 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
537 int saved_char
= NUL
; /* init for GCC */
538 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
541 #ifdef FEAT_SMARTINDENT
542 int do_si
= (!p_paste
&& curbuf
->b_p_si
547 int no_si
= FALSE
; /* reset did_si afterwards */
548 int first_char
= NUL
; /* init for GCC */
550 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
553 int did_append
; /* appended a new line */
554 int saved_pi
= curbuf
->b_p_pi
; /* copy of preserveindent setting */
557 * make a copy of the current line so we can mess with it
559 saved_line
= vim_strsave(ml_get_curline());
560 if (saved_line
== NULL
) /* out of memory! */
564 if (State
& VREPLACE_FLAG
)
567 * With VREPLACE we make a copy of the next line, which we will be
568 * starting to replace. First make the new line empty and let vim play
569 * with the indenting and comment leader to its heart's content. Then
570 * we grab what it ended up putting on the new line, put back the
571 * original line, and call ins_char() to put each new character onto
572 * the line, replacing what was there before and pushing the right
573 * stuff onto the replace stack. -- webb.
575 if (curwin
->w_cursor
.lnum
< orig_line_count
)
576 next_line
= vim_strsave(ml_get(curwin
->w_cursor
.lnum
+ 1));
578 next_line
= vim_strsave((char_u
*)"");
579 if (next_line
== NULL
) /* out of memory! */
583 * In VREPLACE mode, a NL replaces the rest of the line, and starts
584 * replacing the next line, so push all of the characters left on the
585 * line onto the replace stack. We'll push any other characters that
586 * might be replaced at the start of the next line (due to autoindent
589 replace_push(NUL
); /* Call twice because BS over NL expects it */
591 p
= saved_line
+ curwin
->w_cursor
.col
;
594 saved_line
[curwin
->w_cursor
.col
] = NUL
;
600 && !(State
& VREPLACE_FLAG
)
604 p_extra
= saved_line
+ curwin
->w_cursor
.col
;
605 #ifdef FEAT_SMARTINDENT
606 if (do_si
) /* need first char after new line break */
608 p
= skipwhite(p_extra
);
613 extra_len
= (int)STRLEN(p_extra
);
615 saved_char
= *p_extra
;
619 u_clearline(); /* cannot do "U" command when adding lines */
620 #ifdef FEAT_SMARTINDENT
626 * If we just did an auto-indent, then we didn't type anything on
627 * the prior line, and it should be truncated. Do this even if 'ai' is not
628 * set because automatically inserting a comment leader also sets did_ai.
630 if (dir
== FORWARD
&& did_ai
)
634 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
635 * indent to use for the new line.
638 #ifdef FEAT_SMARTINDENT
644 * count white space on current line
646 newindent
= get_indent_str(saved_line
, (int)curbuf
->b_p_ts
);
648 newindent
= old_indent
; /* for ^^D command in insert mode */
650 #ifdef FEAT_SMARTINDENT
652 * Do smart indenting.
653 * In insert/replace mode (only when dir == FORWARD)
654 * we may move some text to the next line. If it starts with '{'
655 * don't add an indent. Fixes inserting a NL before '{' in line
658 if (!trunc_line
&& do_si
&& *saved_line
!= NUL
659 && (p_extra
== NULL
|| first_char
!= '{'))
664 old_cursor
= curwin
->w_cursor
;
666 # ifdef FEAT_COMMENTS
667 if (flags
& OPENLINE_DO_COM
)
668 lead_len
= get_leader_len(ptr
, NULL
, FALSE
);
675 * Skip preprocessor directives, unless they are
676 * recognised as comments.
679 # ifdef FEAT_COMMENTS
684 while (ptr
[0] == '#' && curwin
->w_cursor
.lnum
> 1)
685 ptr
= ml_get(--curwin
->w_cursor
.lnum
);
686 newindent
= get_indent();
688 # ifdef FEAT_COMMENTS
689 if (flags
& OPENLINE_DO_COM
)
690 lead_len
= get_leader_len(ptr
, NULL
, FALSE
);
696 * This case gets the following right:
698 * * A comment (read '\' as '/').
701 * This should line up here;
704 if (p
[0] == '/' && p
[1] == '*')
710 if (p
[0] == '/' && p
[-1] == '*')
713 * End of C comment, indent should line up
714 * with the line containing the start of
717 curwin
->w_cursor
.col
= (colnr_T
)(p
- ptr
);
718 if ((pos
= findmatch(NULL
, NUL
)) != NULL
)
720 curwin
->w_cursor
.lnum
= pos
->lnum
;
721 newindent
= get_indent();
727 else /* Not a comment line */
730 /* Find last non-blank in line */
731 p
= ptr
+ STRLEN(ptr
) - 1;
732 while (p
> ptr
&& vim_iswhite(*p
))
737 * find the character just before the '{' or ';'
739 if (last_char
== '{' || last_char
== ';')
743 while (p
> ptr
&& vim_iswhite(*p
))
747 * Try to catch lines that are split over multiple
751 * Should line up here!
756 curwin
->w_cursor
.col
= (colnr_T
)(p
- ptr
);
757 if ((pos
= findmatch(NULL
, '(')) != NULL
)
759 curwin
->w_cursor
.lnum
= pos
->lnum
;
760 newindent
= get_indent();
761 ptr
= ml_get_curline();
765 * If last character is '{' do indent, without
766 * checking for "if" and the like.
768 if (last_char
== '{')
770 did_si
= TRUE
; /* do indent */
771 no_si
= TRUE
; /* don't delete it when '{' typed */
774 * Look for "if" and the like, use 'cinwords'.
775 * Don't do this if the previous line ended in ';' or
778 else if (last_char
!= ';' && last_char
!= '}'
779 && cin_is_cinword(ptr
))
783 else /* dir == BACKWARD */
786 * Skip preprocessor directives, unless they are
787 * recognised as comments.
790 # ifdef FEAT_COMMENTS
795 int was_backslashed
= FALSE
;
797 while ((ptr
[0] == '#' || was_backslashed
) &&
798 curwin
->w_cursor
.lnum
< curbuf
->b_ml
.ml_line_count
)
800 if (*ptr
&& ptr
[STRLEN(ptr
) - 1] == '\\')
801 was_backslashed
= TRUE
;
803 was_backslashed
= FALSE
;
804 ptr
= ml_get(++curwin
->w_cursor
.lnum
);
807 newindent
= 0; /* Got to end of file */
809 newindent
= get_indent();
812 if (*p
== '}') /* if line starts with '}': do indent */
814 else /* can delete indent when '{' typed */
817 curwin
->w_cursor
= old_cursor
;
821 #endif /* FEAT_SMARTINDENT */
828 * Find out if the current line starts with a comment leader.
829 * This may then be inserted in front of the new line.
831 end_comment_pending
= NUL
;
832 if (flags
& OPENLINE_DO_COM
)
833 lead_len
= get_leader_len(saved_line
, &lead_flags
, dir
== BACKWARD
);
838 char_u
*lead_repl
= NULL
; /* replaces comment leader */
839 int lead_repl_len
= 0; /* length of *lead_repl */
840 char_u lead_middle
[COM_MAX_LEN
]; /* middle-comment string */
841 char_u lead_end
[COM_MAX_LEN
]; /* end-comment string */
842 char_u
*comment_end
= NULL
; /* where lead_end has been found */
843 int extra_space
= FALSE
; /* append extra space */
845 int require_blank
= FALSE
; /* requires blank after middle */
849 * If the comment leader has the start, middle or end flag, it may not
850 * be used or may be replaced with the middle leader.
852 for (p
= lead_flags
; *p
&& *p
!= ':'; ++p
)
856 require_blank
= TRUE
;
859 if (*p
== COM_START
|| *p
== COM_MIDDLE
)
865 * Doing "O" on a start of comment does not insert leader.
873 /* find start of middle part */
874 (void)copy_option_part(&p
, lead_middle
, COM_MAX_LEN
, ",");
875 require_blank
= FALSE
;
879 * Isolate the strings of the middle and end leader.
881 while (*p
&& p
[-1] != ':') /* find end of middle flags */
884 require_blank
= TRUE
;
887 (void)copy_option_part(&p
, lead_middle
, COM_MAX_LEN
, ",");
889 while (*p
&& p
[-1] != ':') /* find end of end flags */
891 /* Check whether we allow automatic ending of comments */
892 if (*p
== COM_AUTO_END
)
893 end_comment_pending
= -1; /* means we want to set it */
896 n
= copy_option_part(&p
, lead_end
, COM_MAX_LEN
, ",");
898 if (end_comment_pending
== -1) /* we can set it now */
899 end_comment_pending
= lead_end
[n
- 1];
902 * If the end of the comment is in the same line, don't use
903 * the comment leader.
907 for (p
= saved_line
+ lead_len
; *p
; ++p
)
908 if (STRNCMP(p
, lead_end
, n
) == 0)
917 * Doing "o" on a start of comment inserts the middle leader.
921 if (current_flag
== COM_START
)
923 lead_repl
= lead_middle
;
924 lead_repl_len
= (int)STRLEN(lead_middle
);
928 * If we have hit RETURN immediately after the start
929 * comment leader, then put a space after the middle
930 * comment leader on the next line.
932 if (!vim_iswhite(saved_line
[lead_len
- 1])
934 && (int)curwin
->w_cursor
.col
== lead_len
)
936 && saved_line
[lead_len
] == NUL
)
945 * Doing "o" on the end of a comment does not insert leader.
946 * Remember where the end is, might want to use it to find the
947 * start (for C-comments).
951 comment_end
= skipwhite(saved_line
);
957 * Doing "O" on the end of a comment inserts the middle leader.
958 * Find the string for the middle leader, searching backwards.
960 while (p
> curbuf
->b_p_com
&& *p
!= ',')
962 for (lead_repl
= p
; lead_repl
> curbuf
->b_p_com
963 && lead_repl
[-1] != ':'; --lead_repl
)
965 lead_repl_len
= (int)(p
- lead_repl
);
967 /* We can probably always add an extra space when doing "O" on
971 /* Check whether we allow automatic ending of comments */
972 for (p2
= p
; *p2
&& *p2
!= ':'; p2
++)
974 if (*p2
== COM_AUTO_END
)
975 end_comment_pending
= -1; /* means we want to set it */
977 if (end_comment_pending
== -1)
979 /* Find last character in end-comment string */
980 while (*p2
&& *p2
!= ',')
982 end_comment_pending
= p2
[-1];
989 * Comment leader for first line only: Don't repeat leader
990 * when using "O", blank out leader when using "o".
996 lead_repl
= (char_u
*)"";
1004 /* allocate buffer (may concatenate p_exta later) */
1005 leader
= alloc(lead_len
+ lead_repl_len
+ extra_space
+
1007 allocated
= leader
; /* remember to free it later */
1013 vim_strncpy(leader
, saved_line
, lead_len
);
1016 * Replace leader with lead_repl, right or left adjusted
1018 if (lead_repl
!= NULL
)
1023 for (p
= lead_flags
; *p
&& *p
!= ':'; ++p
)
1025 if (*p
== COM_RIGHT
|| *p
== COM_LEFT
)
1027 else if (VIM_ISDIGIT(*p
) || *p
== '-')
1028 off
= getdigits(&p
);
1030 if (c
== COM_RIGHT
) /* right adjusted leader */
1032 /* find last non-white in the leader to line up with */
1033 for (p
= leader
+ lead_len
- 1; p
> leader
1034 && vim_iswhite(*p
); --p
)
1039 /* Compute the length of the replaced characters in
1040 * screen characters, not bytes. */
1042 int repl_size
= vim_strnsize(lead_repl
,
1048 while (old_size
< repl_size
&& p
> leader
)
1050 mb_ptr_back(leader
, p
);
1051 old_size
+= ptr2cells(p
);
1053 l
= lead_repl_len
- (int)(endp
- p
);
1055 mch_memmove(endp
+ l
, endp
,
1056 (size_t)((leader
+ lead_len
) - endp
));
1060 if (p
< leader
+ lead_repl_len
)
1065 mch_memmove(p
, lead_repl
, (size_t)lead_repl_len
);
1066 if (p
+ lead_repl_len
> leader
+ lead_len
)
1067 p
[lead_repl_len
] = NUL
;
1069 /* blank-out any other chars from the old leader. */
1070 while (--p
>= leader
)
1073 int l
= mb_head_off(leader
, p
);
1078 if (ptr2cells(p
) > 1)
1083 mch_memmove(p
+ 1, p
+ l
+ 1,
1084 (size_t)((leader
+ lead_len
) - (p
+ l
+ 1)));
1090 if (!vim_iswhite(*p
))
1094 else /* left adjusted leader */
1096 p
= skipwhite(leader
);
1098 /* Compute the length of the replaced characters in
1099 * screen characters, not bytes. Move the part that is
1100 * not to be overwritten. */
1102 int repl_size
= vim_strnsize(lead_repl
,
1107 for (i
= 0; p
[i
] != NUL
&& i
< lead_len
; i
+= l
)
1109 l
= (*mb_ptr2len
)(p
+ i
);
1110 if (vim_strnsize(p
, i
+ l
) > repl_size
)
1113 if (i
!= lead_repl_len
)
1115 mch_memmove(p
+ lead_repl_len
, p
+ i
,
1116 (size_t)(lead_len
- i
- (leader
- p
)));
1117 lead_len
+= lead_repl_len
- i
;
1121 mch_memmove(p
, lead_repl
, (size_t)lead_repl_len
);
1123 /* Replace any remaining non-white chars in the old
1124 * leader by spaces. Keep Tabs, the indent must
1125 * remain the same. */
1126 for (p
+= lead_repl_len
; p
< leader
+ lead_len
; ++p
)
1127 if (!vim_iswhite(*p
))
1129 /* Don't put a space before a TAB. */
1130 if (p
+ 1 < leader
+ lead_len
&& p
[1] == TAB
)
1133 mch_memmove(p
, p
+ 1,
1134 (leader
+ lead_len
) - p
);
1139 int l
= (*mb_ptr2len
)(p
);
1143 if (ptr2cells(p
) > 1)
1145 /* Replace a double-wide char with
1150 mch_memmove(p
+ 1, p
+ l
,
1151 (leader
+ lead_len
) - p
);
1161 /* Recompute the indent, it may have changed. */
1163 #ifdef FEAT_SMARTINDENT
1167 newindent
= get_indent_str(leader
, (int)curbuf
->b_p_ts
);
1169 /* Add the indent offset */
1170 if (newindent
+ off
< 0)
1178 /* Correct trailing spaces for the shift, so that
1179 * alignment remains equal. */
1180 while (off
> 0 && lead_len
> 0
1181 && leader
[lead_len
- 1] == ' ')
1183 /* Don't do it when there is a tab before the space */
1184 if (vim_strchr(skipwhite(leader
), '\t') != NULL
)
1190 /* If the leader ends in white space, don't add an
1192 if (lead_len
> 0 && vim_iswhite(leader
[lead_len
- 1]))
1193 extra_space
= FALSE
;
1194 leader
[lead_len
] = NUL
;
1199 leader
[lead_len
++] = ' ';
1200 leader
[lead_len
] = NUL
;
1206 * if a new indent will be set below, remove the indent that
1207 * is in the comment leader
1210 #ifdef FEAT_SMARTINDENT
1215 while (lead_len
&& vim_iswhite(*leader
))
1224 #ifdef FEAT_SMARTINDENT
1225 did_si
= can_si
= FALSE
;
1228 else if (comment_end
!= NULL
)
1231 * We have finished a comment, so we don't use the leader.
1232 * If this was a C-comment and 'ai' or 'si' is set do a normal
1233 * indent to align with the line containing the start of the
1236 if (comment_end
[0] == '*' && comment_end
[1] == '/' &&
1238 #ifdef FEAT_SMARTINDENT
1243 old_cursor
= curwin
->w_cursor
;
1244 curwin
->w_cursor
.col
= (colnr_T
)(comment_end
- saved_line
);
1245 if ((pos
= findmatch(NULL
, NUL
)) != NULL
)
1247 curwin
->w_cursor
.lnum
= pos
->lnum
;
1248 newindent
= get_indent();
1250 curwin
->w_cursor
= old_cursor
;
1256 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1257 if (p_extra
!= NULL
)
1259 *p_extra
= saved_char
; /* restore char that NUL replaced */
1262 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1265 * When in REPLACE mode, put the deleted blanks on the replace stack,
1266 * preceded by a NUL, so they can be put back when a BS is entered.
1268 if (REPLACE_NORMAL(State
))
1269 replace_push(NUL
); /* end of extra blanks */
1270 if (curbuf
->b_p_ai
|| (flags
& OPENLINE_DELSPACES
))
1272 while ((*p_extra
== ' ' || *p_extra
== '\t')
1275 || !utf_iscomposing(utf_ptr2char(p_extra
+ 1)))
1279 if (REPLACE_NORMAL(State
))
1280 replace_push(*p_extra
);
1285 if (*p_extra
!= NUL
)
1286 did_ai
= FALSE
; /* append some text, don't truncate now */
1288 /* columns for marks adjusted for removed columns */
1289 less_cols
= (int)(p_extra
- saved_line
);
1292 if (p_extra
== NULL
)
1293 p_extra
= (char_u
*)""; /* append empty line */
1295 #ifdef FEAT_COMMENTS
1296 /* concatenate leader and p_extra, if there is a leader */
1299 STRCAT(leader
, p_extra
);
1301 did_ai
= TRUE
; /* So truncating blanks works with comments */
1302 less_cols
-= lead_len
;
1305 end_comment_pending
= NUL
; /* turns out there was no leader */
1308 old_cursor
= curwin
->w_cursor
;
1309 if (dir
== BACKWARD
)
1310 --curwin
->w_cursor
.lnum
;
1311 #ifdef FEAT_VREPLACE
1312 if (!(State
& VREPLACE_FLAG
) || old_cursor
.lnum
>= orig_line_count
)
1315 if (ml_append(curwin
->w_cursor
.lnum
, p_extra
, (colnr_T
)0, FALSE
)
1318 /* Postpone calling changed_lines(), because it would mess up folding
1320 mark_adjust(curwin
->w_cursor
.lnum
+ 1, (linenr_T
)MAXLNUM
, 1L, 0L);
1323 #ifdef FEAT_VREPLACE
1327 * In VREPLACE mode we are starting to replace the next line.
1329 curwin
->w_cursor
.lnum
++;
1330 if (curwin
->w_cursor
.lnum
>= Insstart
.lnum
+ vr_lines_changed
)
1332 /* In case we NL to a new line, BS to the previous one, and NL
1333 * again, we don't want to save the new line for undo twice.
1335 (void)u_save_cursor(); /* errors are ignored! */
1338 ml_replace(curwin
->w_cursor
.lnum
, p_extra
, TRUE
);
1339 changed_bytes(curwin
->w_cursor
.lnum
, 0);
1340 curwin
->w_cursor
.lnum
--;
1346 #ifdef FEAT_SMARTINDENT
1351 ++curwin
->w_cursor
.lnum
;
1352 #ifdef FEAT_SMARTINDENT
1356 newindent
-= newindent
% (int)curbuf
->b_p_sw
;
1357 newindent
+= (int)curbuf
->b_p_sw
;
1360 /* Copy the indent */
1363 (void)copy_indent(newindent
, saved_line
);
1366 * Set the 'preserveindent' option so that any further screwing
1367 * with the line doesn't entirely destroy our efforts to preserve
1368 * it. It gets restored at the function end.
1370 curbuf
->b_p_pi
= TRUE
;
1373 (void)set_indent(newindent
, SIN_INSERT
);
1374 less_cols
-= curwin
->w_cursor
.col
;
1376 ai_col
= curwin
->w_cursor
.col
;
1379 * In REPLACE mode, for each character in the new indent, there must
1380 * be a NUL on the replace stack, for when it is deleted with BS
1382 if (REPLACE_NORMAL(State
))
1383 for (n
= 0; n
< (int)curwin
->w_cursor
.col
; ++n
)
1385 newcol
+= curwin
->w_cursor
.col
;
1386 #ifdef FEAT_SMARTINDENT
1392 #ifdef FEAT_COMMENTS
1394 * In REPLACE mode, for each character in the extra leader, there must be
1395 * a NUL on the replace stack, for when it is deleted with BS.
1397 if (REPLACE_NORMAL(State
))
1398 while (lead_len
-- > 0)
1402 curwin
->w_cursor
= old_cursor
;
1406 if (trunc_line
|| (State
& INSERT
))
1408 /* truncate current line at cursor */
1409 saved_line
[curwin
->w_cursor
.col
] = NUL
;
1410 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1411 if (trunc_line
&& !(flags
& OPENLINE_KEEPTRAIL
))
1412 truncate_spaces(saved_line
);
1413 ml_replace(curwin
->w_cursor
.lnum
, saved_line
, FALSE
);
1417 changed_lines(curwin
->w_cursor
.lnum
, curwin
->w_cursor
.col
,
1418 curwin
->w_cursor
.lnum
+ 1, 1L);
1421 /* Move marks after the line break to the new line. */
1422 if (flags
& OPENLINE_MARKFIX
)
1423 mark_col_adjust(curwin
->w_cursor
.lnum
,
1424 curwin
->w_cursor
.col
+ less_cols_off
,
1425 1L, (long)-less_cols
);
1428 changed_bytes(curwin
->w_cursor
.lnum
, curwin
->w_cursor
.col
);
1432 * Put the cursor on the new line. Careful: the scrollup() above may
1433 * have moved w_cursor, we must use old_cursor.
1435 curwin
->w_cursor
.lnum
= old_cursor
.lnum
+ 1;
1438 changed_lines(curwin
->w_cursor
.lnum
, 0, curwin
->w_cursor
.lnum
, 1L);
1440 curwin
->w_cursor
.col
= newcol
;
1441 #ifdef FEAT_VIRTUALEDIT
1442 curwin
->w_cursor
.coladd
= 0;
1445 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1447 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1448 * fixthisline() from doing it (via change_indent()) by telling it we're in
1449 * normal INSERT mode.
1451 if (State
& VREPLACE_FLAG
)
1453 vreplace_mode
= State
; /* So we know to put things right later */
1461 * May do lisp indenting.
1464 # ifdef FEAT_COMMENTS
1470 fixthisline(get_lisp_indent
);
1471 p
= ml_get_curline();
1472 ai_col
= (colnr_T
)(skipwhite(p
) - p
);
1477 * May do indenting after opening a new line.
1482 || *curbuf
->b_p_inde
!= NUL
1485 && in_cinkeys(dir
== FORWARD
1487 : KEY_OPEN_BACK
, ' ', linewhite(curwin
->w_cursor
.lnum
)))
1490 p
= ml_get_curline();
1491 ai_col
= (colnr_T
)(skipwhite(p
) - p
);
1494 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1495 if (vreplace_mode
!= 0)
1496 State
= vreplace_mode
;
1499 #ifdef FEAT_VREPLACE
1501 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1502 * original line, and inserts the new stuff char by char, pushing old stuff
1503 * onto the replace stack (via ins_char()).
1505 if (State
& VREPLACE_FLAG
)
1507 /* Put new line in p_extra */
1508 p_extra
= vim_strsave(ml_get_curline());
1509 if (p_extra
== NULL
)
1512 /* Put back original line */
1513 ml_replace(curwin
->w_cursor
.lnum
, next_line
, FALSE
);
1515 /* Insert new stuff into line again */
1516 curwin
->w_cursor
.col
= 0;
1517 #ifdef FEAT_VIRTUALEDIT
1518 curwin
->w_cursor
.coladd
= 0;
1520 ins_bytes(p_extra
); /* will call changed_bytes() */
1526 retval
= TRUE
; /* success! */
1528 curbuf
->b_p_pi
= saved_pi
;
1529 vim_free(saved_line
);
1530 vim_free(next_line
);
1531 vim_free(allocated
);
1535 #if defined(FEAT_COMMENTS) || defined(PROTO)
1537 * get_leader_len() returns the length of the prefix of the given string
1538 * which introduces a comment. If this string is not a comment then 0 is
1540 * When "flags" is not NULL, it is set to point to the flags of the recognized
1542 * "backward" must be true for the "O" command.
1545 get_leader_len(line
, flags
, backward
)
1551 int got_com
= FALSE
;
1553 char_u part_buf
[COM_MAX_LEN
]; /* buffer for one option part */
1554 char_u
*string
; /* pointer to comment string */
1558 while (vim_iswhite(line
[i
])) /* leading white space is ignored */
1562 * Repeat to match several nested comment strings.
1567 * scan through the 'comments' option for a match
1570 for (list
= curbuf
->b_p_com
; *list
; )
1573 * Get one option part into part_buf[]. Advance list to next one.
1574 * put string at start of string.
1576 if (!got_com
&& flags
!= NULL
) /* remember where flags started */
1578 (void)copy_option_part(&list
, part_buf
, COM_MAX_LEN
, ",");
1579 string
= vim_strchr(part_buf
, ':');
1580 if (string
== NULL
) /* missing ':', ignore this part */
1582 *string
++ = NUL
; /* isolate flags from string */
1585 * When already found a nested comment, only accept further
1588 if (got_com
&& vim_strchr(part_buf
, COM_NEST
) == NULL
)
1591 /* When 'O' flag used don't use for "O" command */
1592 if (backward
&& vim_strchr(part_buf
, COM_NOBACK
) != NULL
)
1596 * Line contents and string must match.
1597 * When string starts with white space, must have some white space
1598 * (but the amount does not need to match, there might be a mix of
1601 if (vim_iswhite(string
[0]))
1603 if (i
== 0 || !vim_iswhite(line
[i
- 1]))
1605 while (vim_iswhite(string
[0]))
1608 for (j
= 0; string
[j
] != NUL
&& string
[j
] == line
[i
+ j
]; ++j
)
1610 if (string
[j
] != NUL
)
1614 * When 'b' flag used, there must be white space or an
1615 * end-of-line after the string in the line.
1617 if (vim_strchr(part_buf
, COM_BLANK
) != NULL
1618 && !vim_iswhite(line
[i
+ j
]) && line
[i
+ j
] != NUL
)
1622 * We have found a match, stop searching.
1631 * No match found, stop scanning.
1637 * Include any trailing white space.
1639 while (vim_iswhite(line
[i
]))
1643 * If this comment doesn't nest, stop here.
1645 if (vim_strchr(part_buf
, COM_NEST
) == NULL
)
1648 return (got_com
? i
: 0);
1653 * Return the number of window lines occupied by buffer line "lnum".
1659 return plines_win(curwin
, lnum
, TRUE
);
1663 plines_win(wp
, lnum
, winheight
)
1666 int winheight
; /* when TRUE limit to window height */
1668 #if defined(FEAT_DIFF) || defined(PROTO)
1669 /* Check for filler lines above this buffer line. When folded the result
1670 * is one line anyway. */
1671 return plines_win_nofill(wp
, lnum
, winheight
) + diff_check_fill(wp
, lnum
);
1678 return plines_win_nofill(curwin
, lnum
, TRUE
);
1682 plines_win_nofill(wp
, lnum
, winheight
)
1685 int winheight
; /* when TRUE limit to window height */
1693 #ifdef FEAT_VERTSPLIT
1694 if (wp
->w_width
== 0)
1699 /* A folded lines is handled just like an empty line. */
1700 /* NOTE: Caller must handle lines that are MAYBE folded. */
1701 if (lineFolded(wp
, lnum
) == TRUE
)
1705 lines
= plines_win_nofold(wp
, lnum
);
1706 if (winheight
> 0 && lines
> wp
->w_height
)
1707 return (int)wp
->w_height
;
1712 * Return number of window lines physical line "lnum" will occupy in window
1713 * "wp". Does not care about folding, 'wrap' or 'diff'.
1716 plines_win_nofold(wp
, lnum
)
1724 s
= ml_get_buf(wp
->w_buffer
, lnum
, FALSE
);
1725 if (*s
== NUL
) /* empty line */
1727 col
= win_linetabsize(wp
, s
, (colnr_T
)MAXCOL
);
1730 * If list mode is on, then the '$' at the end of the line may take up one
1733 if (wp
->w_p_list
&& lcs_eol
!= NUL
)
1737 * Add column offset for 'number' and 'foldcolumn'.
1739 width
= W_WIDTH(wp
) - win_col_off(wp
);
1745 width
+= win_col_off2(wp
);
1746 return (col
+ (width
- 1)) / width
+ 1;
1750 * Like plines_win(), but only reports the number of physical screen lines
1751 * used from the start of the line to the given column number.
1754 plines_win_col(wp
, lnum
, column
)
1765 /* Check for filler lines above this buffer line. When folded the result
1766 * is one line anyway. */
1767 lines
= diff_check_fill(wp
, lnum
);
1773 #ifdef FEAT_VERTSPLIT
1774 if (wp
->w_width
== 0)
1778 s
= ml_get_buf(wp
->w_buffer
, lnum
, FALSE
);
1781 while (*s
!= NUL
&& --column
>= 0)
1783 col
+= win_lbr_chartabsize(wp
, s
, (colnr_T
)col
, NULL
);
1788 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1789 * INSERT mode, then col must be adjusted so that it represents the last
1790 * screen position of the TAB. This only fixes an error when the TAB wraps
1791 * from one screen line to the next (when 'columns' is not a multiple of
1794 if (*s
== TAB
&& (State
& NORMAL
) && (!wp
->w_p_list
|| lcs_tab1
))
1795 col
+= win_lbr_chartabsize(wp
, s
, (colnr_T
)col
, NULL
) - 1;
1798 * Add column offset for 'number', 'foldcolumn', etc.
1800 width
= W_WIDTH(wp
) - win_col_off(wp
);
1806 lines
+= (col
- width
) / (width
+ win_col_off2(wp
)) + 1;
1811 plines_m_win(wp
, first
, last
)
1813 linenr_T first
, last
;
1817 while (first
<= last
)
1822 /* Check if there are any really folded lines, but also included lines
1823 * that are maybe folded. */
1824 x
= foldedCount(wp
, first
, NULL
);
1827 ++count
; /* count 1 for "+-- folded" line */
1834 if (first
== wp
->w_topline
)
1835 count
+= plines_win_nofill(wp
, first
, TRUE
) + wp
->w_topfill
;
1838 count
+= plines_win(wp
, first
, TRUE
);
1845 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1847 * Insert string "p" at the cursor position. Stops at a NUL byte.
1848 * Handles Replace mode and multi-byte characters.
1854 ins_bytes_len(p
, (int)STRLEN(p
));
1858 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1859 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1861 * Insert string "p" with length "len" at the cursor position.
1862 * Handles Replace mode and multi-byte characters.
1865 ins_bytes_len(p
, len
)
1873 for (i
= 0; i
< len
; i
+= n
)
1875 n
= (*mb_ptr2len
)(p
+ i
);
1876 ins_char_bytes(p
+ i
, n
);
1879 for (i
= 0; i
< len
; ++i
)
1886 * Insert or replace a single character at the cursor position.
1887 * When in REPLACE or VREPLACE mode, replace any existing character.
1888 * Caller must have prepared for undo.
1889 * For multi-byte characters we get the whole character, the caller must
1890 * convert bytes to a character.
1896 #if defined(FEAT_MBYTE) || defined(PROTO)
1897 char_u buf
[MB_MAXBYTES
];
1900 n
= (*mb_char2bytes
)(c
, buf
);
1902 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1903 * Happens for CTRL-Vu9900. */
1907 ins_char_bytes(buf
, n
);
1911 ins_char_bytes(buf
, charlen
)
1918 int newlen
; /* nr of bytes inserted */
1919 int oldlen
; /* nr of bytes deleted (0 when not replacing) */
1923 int linelen
; /* length of old line including NUL */
1925 linenr_T lnum
= curwin
->w_cursor
.lnum
;
1928 #ifdef FEAT_VIRTUALEDIT
1929 /* Break tabs if needed. */
1930 if (virtual_active() && curwin
->w_cursor
.coladd
> 0)
1931 coladvance_force(getviscol());
1934 col
= curwin
->w_cursor
.col
;
1935 oldp
= ml_get(lnum
);
1936 linelen
= (int)STRLEN(oldp
) + 1;
1938 /* The lengths default to the values for when not replacing. */
1946 if (State
& REPLACE_FLAG
)
1948 #ifdef FEAT_VREPLACE
1949 if (State
& VREPLACE_FLAG
)
1951 colnr_T new_vcol
= 0; /* init for GCC */
1959 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1960 * Returns the old value of list, so when finished,
1961 * curwin->w_p_list should be set back to this.
1963 old_list
= curwin
->w_p_list
;
1964 if (old_list
&& vim_strchr(p_cpo
, CPO_LISTWM
) == NULL
)
1965 curwin
->w_p_list
= FALSE
;
1968 * In virtual replace mode each character may replace one or more
1969 * characters (zero if it's a TAB). Count the number of bytes to
1970 * be deleted to make room for the new character, counting screen
1971 * cells. May result in adding spaces to fill a gap.
1973 getvcol(curwin
, &curwin
->w_cursor
, NULL
, &vcol
, NULL
);
1978 new_vcol
= vcol
+ chartabsize(buf
, vcol
);
1979 while (oldp
[col
+ oldlen
] != NUL
&& vcol
< new_vcol
)
1981 vcol
+= chartabsize(oldp
+ col
+ oldlen
, vcol
);
1982 /* Don't need to remove a TAB that takes us to the right
1984 if (vcol
> new_vcol
&& oldp
[col
+ oldlen
] == TAB
)
1987 oldlen
+= (*mb_ptr2len
)(oldp
+ col
+ oldlen
);
1991 /* Deleted a bit too much, insert spaces. */
1992 if (vcol
> new_vcol
)
1993 newlen
+= vcol
- new_vcol
;
1995 curwin
->w_p_list
= old_list
;
1999 if (oldp
[col
] != NUL
)
2001 /* normal replace */
2003 oldlen
= (*mb_ptr2len
)(oldp
+ col
);
2010 /* Push the replaced bytes onto the replace stack, so that they can be
2011 * put back when BS is used. The bytes of a multi-byte character are
2012 * done the other way around, so that the first byte is popped off
2013 * first (it tells the byte length of the character). */
2015 for (i
= 0; i
< oldlen
; ++i
)
2018 l
= (*mb_ptr2len
)(oldp
+ col
+ i
) - 1;
2019 for (j
= l
; j
>= 0; --j
)
2020 replace_push(oldp
[col
+ i
+ j
]);
2023 replace_push(oldp
[col
+ i
]);
2028 newp
= alloc_check((unsigned)(linelen
+ newlen
- oldlen
));
2032 /* Copy bytes before the cursor. */
2034 mch_memmove(newp
, oldp
, (size_t)col
);
2036 /* Copy bytes after the changed character(s). */
2038 mch_memmove(p
+ newlen
, oldp
+ col
+ oldlen
,
2039 (size_t)(linelen
- col
- oldlen
));
2041 /* Insert or overwrite the new character. */
2043 mch_memmove(p
, buf
, charlen
);
2050 /* Fill with spaces when necessary. */
2054 /* Replace the line in the buffer. */
2055 ml_replace(lnum
, newp
, FALSE
);
2057 /* mark the buffer as changed and prepare for displaying */
2058 changed_bytes(lnum
, col
);
2061 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2062 * show the match for right parens and braces.
2064 if (p_sm
&& (State
& INSERT
)
2069 #ifdef FEAT_INS_EXPAND
2070 && !ins_compl_active()
2075 #ifdef FEAT_RIGHTLEFT
2076 if (!p_ri
|| (State
& REPLACE_FLAG
))
2079 /* Normal insert: move cursor right */
2081 curwin
->w_cursor
.col
+= charlen
;
2083 ++curwin
->w_cursor
.col
;
2087 * TODO: should try to update w_row here, to avoid recomputing it later.
2092 * Insert a string at the cursor position.
2093 * Note: Does NOT handle Replace mode.
2094 * Caller must have prepared for undo.
2100 char_u
*oldp
, *newp
;
2101 int newlen
= (int)STRLEN(s
);
2104 linenr_T lnum
= curwin
->w_cursor
.lnum
;
2106 #ifdef FEAT_VIRTUALEDIT
2107 if (virtual_active() && curwin
->w_cursor
.coladd
> 0)
2108 coladvance_force(getviscol());
2111 col
= curwin
->w_cursor
.col
;
2112 oldp
= ml_get(lnum
);
2113 oldlen
= (int)STRLEN(oldp
);
2115 newp
= alloc_check((unsigned)(oldlen
+ newlen
+ 1));
2119 mch_memmove(newp
, oldp
, (size_t)col
);
2120 mch_memmove(newp
+ col
, s
, (size_t)newlen
);
2121 mch_memmove(newp
+ col
+ newlen
, oldp
+ col
, (size_t)(oldlen
- col
+ 1));
2122 ml_replace(lnum
, newp
, FALSE
);
2123 changed_bytes(lnum
, col
);
2124 curwin
->w_cursor
.col
+= newlen
;
2128 * Delete one character under the cursor.
2129 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2130 * Caller must have prepared for undo.
2132 * return FAIL for failure, OK otherwise
2141 /* Make sure the cursor is at the start of a character. */
2143 if (*ml_get_cursor() == NUL
)
2145 return del_chars(1L, fixpos
);
2148 return del_bytes(1L, fixpos
, TRUE
);
2151 #if defined(FEAT_MBYTE) || defined(PROTO)
2153 * Like del_bytes(), but delete characters instead of bytes.
2156 del_chars(count
, fixpos
)
2165 p
= ml_get_cursor();
2166 for (i
= 0; i
< count
&& *p
!= NUL
; ++i
)
2168 l
= (*mb_ptr2len
)(p
);
2172 return del_bytes(bytes
, fixpos
, TRUE
);
2177 * Delete "count" bytes under the cursor.
2178 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2179 * Caller must have prepared for undo.
2181 * return FAIL for failure, OK otherwise
2185 del_bytes(count
, fixpos_arg
, use_delcombine
)
2188 int use_delcombine
; /* 'delcombine' option applies */
2190 char_u
*oldp
, *newp
;
2192 linenr_T lnum
= curwin
->w_cursor
.lnum
;
2193 colnr_T col
= curwin
->w_cursor
.col
;
2196 int fixpos
= fixpos_arg
;
2198 oldp
= ml_get(lnum
);
2199 oldlen
= (int)STRLEN(oldp
);
2202 * Can't do anything when the cursor is on the NUL after the line.
2208 /* If 'delcombine' is set and deleting (less than) one character, only
2209 * delete the last combining character. */
2210 if (p_deco
&& use_delcombine
&& enc_utf8
2211 && utfc_ptr2len(oldp
+ col
) >= count
)
2216 (void)utfc_ptr2char(oldp
+ col
, cc
);
2219 /* Find the last composing char, there can be several. */
2224 count
= utf_ptr2len(oldp
+ n
);
2226 } while (UTF_COMPOSINGLIKE(oldp
+ col
, oldp
+ n
));
2233 * When count is too big, reduce it.
2235 movelen
= (long)oldlen
- (long)col
- count
+ 1; /* includes trailing NUL */
2239 * If we just took off the last character of a non-blank line, and
2240 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2241 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2243 if (col
> 0 && fixpos
&& restart_edit
== 0
2244 #ifdef FEAT_VIRTUALEDIT
2245 && (ve_flags
& VE_ONEMORE
) == 0
2249 --curwin
->w_cursor
.col
;
2250 #ifdef FEAT_VIRTUALEDIT
2251 curwin
->w_cursor
.coladd
= 0;
2255 curwin
->w_cursor
.col
-=
2256 (*mb_head_off
)(oldp
, oldp
+ curwin
->w_cursor
.col
);
2259 count
= oldlen
- col
;
2264 * If the old line has been allocated the deletion can be done in the
2265 * existing line. Otherwise a new line has to be allocated
2267 was_alloced
= ml_line_alloced(); /* check if oldp was allocated */
2268 #ifdef FEAT_NETBEANS_INTG
2269 if (was_alloced
&& usingNetbeans
)
2270 netbeans_removed(curbuf
, lnum
, col
, count
);
2271 /* else is handled by ml_replace() */
2274 newp
= oldp
; /* use same allocated memory */
2276 { /* need to allocate a new line */
2277 newp
= alloc((unsigned)(oldlen
+ 1 - count
));
2280 mch_memmove(newp
, oldp
, (size_t)col
);
2282 mch_memmove(newp
+ col
, oldp
+ col
+ count
, (size_t)movelen
);
2284 ml_replace(lnum
, newp
, FALSE
);
2286 /* mark the buffer as changed and prepare for displaying */
2287 changed_bytes(lnum
, curwin
->w_cursor
.col
);
2293 * Delete from cursor to end of line.
2294 * Caller must have prepared for undo.
2296 * return FAIL for failure, OK otherwise
2299 truncate_line(fixpos
)
2300 int fixpos
; /* if TRUE fix the cursor position when done */
2303 linenr_T lnum
= curwin
->w_cursor
.lnum
;
2304 colnr_T col
= curwin
->w_cursor
.col
;
2307 newp
= vim_strsave((char_u
*)"");
2309 newp
= vim_strnsave(ml_get(lnum
), col
);
2314 ml_replace(lnum
, newp
, FALSE
);
2316 /* mark the buffer as changed and prepare for displaying */
2317 changed_bytes(lnum
, curwin
->w_cursor
.col
);
2320 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2322 if (fixpos
&& curwin
->w_cursor
.col
> 0)
2323 --curwin
->w_cursor
.col
;
2329 * Delete "nlines" lines at the cursor.
2330 * Saves the lines for undo first if "undo" is TRUE.
2333 del_lines(nlines
, undo
)
2334 long nlines
; /* number of lines to delete */
2335 int undo
; /* if TRUE, prepare for undo */
2342 /* save the deleted lines for undo */
2343 if (undo
&& u_savedel(curwin
->w_cursor
.lnum
, nlines
) == FAIL
)
2346 for (n
= 0; n
< nlines
; )
2348 if (curbuf
->b_ml
.ml_flags
& ML_EMPTY
) /* nothing to delete */
2351 ml_delete(curwin
->w_cursor
.lnum
, TRUE
);
2354 /* If we delete the last line in the file, stop */
2355 if (curwin
->w_cursor
.lnum
> curbuf
->b_ml
.ml_line_count
)
2358 /* adjust marks, mark the buffer as changed and prepare for displaying */
2359 deleted_lines_mark(curwin
->w_cursor
.lnum
, n
);
2361 curwin
->w_cursor
.col
= 0;
2362 check_cursor_lnum();
2369 char_u
*ptr
= ml_get_pos(pos
);
2373 return (*mb_ptr2char
)(ptr
);
2383 return (*mb_ptr2char
)(ml_get_cursor());
2385 return (int)*ml_get_cursor();
2389 * Write a character at the current cursor position.
2390 * It is directly written into the block.
2396 *(ml_get_buf(curbuf
, curwin
->w_cursor
.lnum
, TRUE
)
2397 + curwin
->w_cursor
.col
) = c
;
2400 #if 0 /* not used */
2402 * Put *pos at end of current buffer
2410 pos
->lnum
= curbuf
->b_ml
.ml_line_count
;
2412 p
= ml_get(pos
->lnum
);
2419 * When extra == 0: Return TRUE if the cursor is before or on the first
2420 * non-blank in the line.
2421 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2431 for (col
= 0, ptr
= ml_get_curline(); vim_iswhite(*ptr
); ++col
)
2433 if (col
>= curwin
->w_cursor
.col
+ extra
)
2440 * Skip to next part of an option argument: Skip space and comma.
2443 skip_to_option_part(p
)
2454 * changed() is called when something in the current buffer is changed.
2456 * Most often called through changed_bytes() and changed_lines(), which also
2457 * mark the area of the display to be redrawn.
2462 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2463 /* The text of the preediting area is inserted, but this doesn't
2464 * mean a change of the buffer yet. That is delayed until the
2465 * text is committed. (this means preedit becomes empty) */
2466 if (im_is_preediting() && !xim_changed_while_preediting
)
2468 xim_changed_while_preediting
= FALSE
;
2471 if (!curbuf
->b_changed
)
2473 int save_msg_scroll
= msg_scroll
;
2475 /* Give a warning about changing a read-only file. This may also
2476 * check-out the file, thus change "curbuf"! */
2479 /* Create a swap file if that is wanted.
2480 * Don't do this for "nofile" and "nowrite" buffer types. */
2481 if (curbuf
->b_may_swap
2482 #ifdef FEAT_QUICKFIX
2483 && !bt_dontwrite(curbuf
)
2487 ml_open_file(curbuf
);
2489 /* The ml_open_file() can cause an ATTENTION message.
2490 * Wait two seconds, to make sure the user reads this unexpected
2491 * message. Since we could be anywhere, call wait_return() now,
2492 * and don't let the emsg() set msg_scroll. */
2493 if (need_wait_return
&& emsg_silent
== 0)
2496 ui_delay(2000L, TRUE
);
2498 msg_scroll
= save_msg_scroll
;
2501 curbuf
->b_changed
= TRUE
;
2502 ml_setflags(curbuf
);
2504 check_status(curbuf
);
2505 redraw_tabline
= TRUE
;
2508 need_maketitle
= TRUE
; /* set window title later */
2511 ++curbuf
->b_changedtick
;
2514 static void changedOneline
__ARGS((buf_T
*buf
, linenr_T lnum
));
2515 static void changed_lines_buf
__ARGS((buf_T
*buf
, linenr_T lnum
, linenr_T lnume
, long xtra
));
2516 static void changed_common
__ARGS((linenr_T lnum
, colnr_T col
, linenr_T lnume
, long xtra
));
2519 * Changed bytes within a single line for the current buffer.
2520 * - marks the windows on this buffer to be redisplayed
2521 * - marks the buffer changed by calling changed()
2522 * - invalidates cached values
2525 changed_bytes(lnum
, col
)
2529 changedOneline(curbuf
, lnum
);
2530 changed_common(lnum
, col
, lnum
+ 1, 0L);
2533 /* Diff highlighting in other diff windows may need to be updated too. */
2534 if (curwin
->w_p_diff
)
2539 for (wp
= firstwin
; wp
!= NULL
; wp
= wp
->w_next
)
2540 if (wp
->w_p_diff
&& wp
!= curwin
)
2542 redraw_win_later(wp
, VALID
);
2543 wlnum
= diff_lnum_win(lnum
, wp
);
2545 changedOneline(wp
->w_buffer
, wlnum
);
2552 changedOneline(buf
, lnum
)
2558 /* find the maximum area that must be redisplayed */
2559 if (lnum
< buf
->b_mod_top
)
2560 buf
->b_mod_top
= lnum
;
2561 else if (lnum
>= buf
->b_mod_bot
)
2562 buf
->b_mod_bot
= lnum
+ 1;
2566 /* set the area that must be redisplayed to one line */
2567 buf
->b_mod_set
= TRUE
;
2568 buf
->b_mod_top
= lnum
;
2569 buf
->b_mod_bot
= lnum
+ 1;
2570 buf
->b_mod_xlines
= 0;
2575 * Appended "count" lines below line "lnum" in the current buffer.
2576 * Must be called AFTER the change and after mark_adjust().
2577 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2580 appended_lines(lnum
, count
)
2584 changed_lines(lnum
+ 1, 0, lnum
+ 1, count
);
2588 * Like appended_lines(), but adjust marks first.
2591 appended_lines_mark(lnum
, count
)
2595 mark_adjust(lnum
+ 1, (linenr_T
)MAXLNUM
, count
, 0L);
2596 changed_lines(lnum
+ 1, 0, lnum
+ 1, count
);
2600 * Deleted "count" lines at line "lnum" in the current buffer.
2601 * Must be called AFTER the change and after mark_adjust().
2602 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2605 deleted_lines(lnum
, count
)
2609 changed_lines(lnum
, 0, lnum
+ count
, -count
);
2613 * Like deleted_lines(), but adjust marks first.
2616 deleted_lines_mark(lnum
, count
)
2620 mark_adjust(lnum
, (linenr_T
)(lnum
+ count
- 1), (long)MAXLNUM
, -count
);
2621 changed_lines(lnum
, 0, lnum
+ count
, -count
);
2625 * Changed lines for the current buffer.
2626 * Must be called AFTER the change and after mark_adjust().
2627 * - mark the buffer changed by calling changed()
2628 * - mark the windows on this buffer to be redisplayed
2629 * - invalidate cached values
2630 * "lnum" is the first line that needs displaying, "lnume" the first line
2631 * below the changed lines (BEFORE the change).
2632 * When only inserting lines, "lnum" and "lnume" are equal.
2633 * Takes care of calling changed() and updating b_mod_*.
2636 changed_lines(lnum
, col
, lnume
, xtra
)
2637 linenr_T lnum
; /* first line with change */
2638 colnr_T col
; /* column in first line with change */
2639 linenr_T lnume
; /* line below last changed line */
2640 long xtra
; /* number of extra lines (negative when deleting) */
2642 changed_lines_buf(curbuf
, lnum
, lnume
, xtra
);
2645 if (xtra
== 0 && curwin
->w_p_diff
)
2647 /* When the number of lines doesn't change then mark_adjust() isn't
2648 * called and other diff buffers still need to be marked for
2653 for (wp
= firstwin
; wp
!= NULL
; wp
= wp
->w_next
)
2654 if (wp
->w_p_diff
&& wp
!= curwin
)
2656 redraw_win_later(wp
, VALID
);
2657 wlnum
= diff_lnum_win(lnum
, wp
);
2659 changed_lines_buf(wp
->w_buffer
, wlnum
,
2660 lnume
- lnum
+ wlnum
, 0L);
2665 changed_common(lnum
, col
, lnume
, xtra
);
2669 changed_lines_buf(buf
, lnum
, lnume
, xtra
)
2671 linenr_T lnum
; /* first line with change */
2672 linenr_T lnume
; /* line below last changed line */
2673 long xtra
; /* number of extra lines (negative when deleting) */
2677 /* find the maximum area that must be redisplayed */
2678 if (lnum
< buf
->b_mod_top
)
2679 buf
->b_mod_top
= lnum
;
2680 if (lnum
< buf
->b_mod_bot
)
2682 /* adjust old bot position for xtra lines */
2683 buf
->b_mod_bot
+= xtra
;
2684 if (buf
->b_mod_bot
< lnum
)
2685 buf
->b_mod_bot
= lnum
;
2687 if (lnume
+ xtra
> buf
->b_mod_bot
)
2688 buf
->b_mod_bot
= lnume
+ xtra
;
2689 buf
->b_mod_xlines
+= xtra
;
2693 /* set the area that must be redisplayed */
2694 buf
->b_mod_set
= TRUE
;
2695 buf
->b_mod_top
= lnum
;
2696 buf
->b_mod_bot
= lnume
+ xtra
;
2697 buf
->b_mod_xlines
= xtra
;
2702 changed_common(lnum
, col
, lnume
, xtra
)
2710 #ifdef FEAT_JUMPLIST
2716 /* mark the buffer as modified */
2719 /* set the '. mark */
2720 if (!cmdmod
.keepjumps
)
2722 curbuf
->b_last_change
.lnum
= lnum
;
2723 curbuf
->b_last_change
.col
= col
;
2725 #ifdef FEAT_JUMPLIST
2726 /* Create a new entry if a new undo-able change was started or we
2727 * don't have an entry yet. */
2728 if (curbuf
->b_new_change
|| curbuf
->b_changelistlen
== 0)
2730 if (curbuf
->b_changelistlen
== 0)
2734 /* Don't create a new entry when the line number is the same
2735 * as the last one and the column is not too far away. Avoids
2736 * creating many entries for typing "xxxxx". */
2737 p
= &curbuf
->b_changelist
[curbuf
->b_changelistlen
- 1];
2738 if (p
->lnum
!= lnum
)
2742 cols
= comp_textwidth(FALSE
);
2745 add
= (p
->col
+ cols
< col
|| col
+ cols
< p
->col
);
2750 /* This is the first of a new sequence of undo-able changes
2751 * and it's at some distance of the last change. Use a new
2752 * position in the changelist. */
2753 curbuf
->b_new_change
= FALSE
;
2755 if (curbuf
->b_changelistlen
== JUMPLISTSIZE
)
2757 /* changelist is full: remove oldest entry */
2758 curbuf
->b_changelistlen
= JUMPLISTSIZE
- 1;
2759 mch_memmove(curbuf
->b_changelist
, curbuf
->b_changelist
+ 1,
2760 sizeof(pos_T
) * (JUMPLISTSIZE
- 1));
2763 /* Correct position in changelist for other windows on
2765 if (wp
->w_buffer
== curbuf
&& wp
->w_changelistidx
> 0)
2766 --wp
->w_changelistidx
;
2771 /* For other windows, if the position in the changelist is
2772 * at the end it stays at the end. */
2773 if (wp
->w_buffer
== curbuf
2774 && wp
->w_changelistidx
== curbuf
->b_changelistlen
)
2775 ++wp
->w_changelistidx
;
2777 ++curbuf
->b_changelistlen
;
2780 curbuf
->b_changelist
[curbuf
->b_changelistlen
- 1] =
2781 curbuf
->b_last_change
;
2782 /* The current window is always after the last change, so that "g,"
2783 * takes you back to it. */
2784 curwin
->w_changelistidx
= curbuf
->b_changelistlen
;
2790 if (wp
->w_buffer
== curbuf
)
2792 /* Mark this window to be redrawn later. */
2793 if (wp
->w_redr_type
< VALID
)
2794 wp
->w_redr_type
= VALID
;
2796 /* Check if a change in the buffer has invalidated the cached
2797 * values for the cursor. */
2800 * Update the folds for this window. Can't postpone this, because
2801 * a following operator might work on the whole fold: ">>dd".
2803 foldUpdate(wp
, lnum
, lnume
+ xtra
- 1);
2805 /* The change may cause lines above or below the change to become
2806 * included in a fold. Set lnum/lnume to the first/last line that
2807 * might be displayed differently.
2808 * Set w_cline_folded here as an efficient way to update it when
2809 * inserting lines just above a closed fold. */
2810 i
= hasFoldingWin(wp
, lnum
, &lnum
, NULL
, FALSE
, NULL
);
2811 if (wp
->w_cursor
.lnum
== lnum
)
2812 wp
->w_cline_folded
= i
;
2813 i
= hasFoldingWin(wp
, lnume
, NULL
, &lnume
, FALSE
, NULL
);
2814 if (wp
->w_cursor
.lnum
== lnume
)
2815 wp
->w_cline_folded
= i
;
2817 /* If the changed line is in a range of previously folded lines,
2818 * compare with the first line in that range. */
2819 if (wp
->w_cursor
.lnum
<= lnum
)
2821 i
= find_wl_entry(wp
, lnum
);
2822 if (i
>= 0 && wp
->w_cursor
.lnum
> wp
->w_lines
[i
].wl_lnum
)
2823 changed_line_abv_curs_win(wp
);
2827 if (wp
->w_cursor
.lnum
> lnum
)
2828 changed_line_abv_curs_win(wp
);
2829 else if (wp
->w_cursor
.lnum
== lnum
&& wp
->w_cursor
.col
>= col
)
2830 changed_cline_bef_curs_win(wp
);
2831 if (wp
->w_botline
>= lnum
)
2833 /* Assume that botline doesn't change (inserted lines make
2834 * other lines scroll down below botline). */
2835 approximate_botline_win(wp
);
2838 /* Check if any w_lines[] entries have become invalid.
2839 * For entries below the change: Correct the lnums for
2840 * inserted/deleted lines. Makes it possible to stop displaying
2841 * after the change. */
2842 for (i
= 0; i
< wp
->w_lines_valid
; ++i
)
2843 if (wp
->w_lines
[i
].wl_valid
)
2845 if (wp
->w_lines
[i
].wl_lnum
>= lnum
)
2847 if (wp
->w_lines
[i
].wl_lnum
< lnume
)
2849 /* line included in change */
2850 wp
->w_lines
[i
].wl_valid
= FALSE
;
2854 /* line below change */
2855 wp
->w_lines
[i
].wl_lnum
+= xtra
;
2857 wp
->w_lines
[i
].wl_lastlnum
+= xtra
;
2862 else if (wp
->w_lines
[i
].wl_lastlnum
>= lnum
)
2864 /* change somewhere inside this range of folded lines,
2865 * may need to be redrawn */
2866 wp
->w_lines
[i
].wl_valid
= FALSE
;
2873 /* Call update_screen() later, which checks out what needs to be redrawn,
2874 * since it notices b_mod_set and then uses b_mod_*. */
2875 if (must_redraw
< VALID
)
2876 must_redraw
= VALID
;
2879 /* when the cursor line is changed always trigger CursorMoved */
2880 if (lnum
<= curwin
->w_cursor
.lnum
2881 && lnume
+ (xtra
< 0 ? -xtra
: xtra
) > curwin
->w_cursor
.lnum
)
2882 last_cursormoved
.lnum
= 0;
2887 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2892 int ff
; /* also reset 'fileformat' */
2894 if (buf
->b_changed
|| (ff
&& file_ff_differs(buf
)))
2902 redraw_tabline
= TRUE
;
2905 need_maketitle
= TRUE
; /* set window title later */
2908 ++buf
->b_changedtick
;
2909 #ifdef FEAT_NETBEANS_INTG
2910 netbeans_unmodified(buf
);
2914 #if defined(FEAT_WINDOWS) || defined(PROTO)
2916 * check_status: called when the status bars for the buffer 'buf'
2917 * need to be updated
2925 for (wp
= firstwin
; wp
!= NULL
; wp
= wp
->w_next
)
2926 if (wp
->w_buffer
== buf
&& wp
->w_status_height
)
2928 wp
->w_redr_status
= TRUE
;
2929 if (must_redraw
< VALID
)
2930 must_redraw
= VALID
;
2936 * If the file is readonly, give a warning message with the first change.
2937 * Don't do this for autocommands.
2938 * Don't use emsg(), because it flushes the macro buffer.
2939 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
2944 int col
; /* column for message; non-zero when in insert
2945 mode and 'showmode' is on */
2947 if (curbuf
->b_did_warn
== FALSE
2948 && curbufIsChanged() == 0
2956 apply_autocmds(EVENT_FILECHANGEDRO
, NULL
, NULL
, FALSE
, curbuf
);
2958 if (!curbuf
->b_p_ro
)
2962 * Do what msg() does, but with a column offset if the warning should
2963 * be after the mode message.
2966 if (msg_row
== Rows
- 1)
2968 msg_source(hl_attr(HLF_W
));
2969 MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
2970 hl_attr(HLF_W
) | MSG_HIST
);
2973 if (msg_silent
== 0 && !silent_mode
)
2976 ui_delay(1000L, TRUE
); /* give the user time to think about it */
2978 curbuf
->b_did_warn
= TRUE
;
2979 redraw_cmdline
= FALSE
; /* don't redraw and erase the message */
2980 if (msg_row
< Rows
- 1)
2986 * Ask for a reply from the user, a 'y' or a 'n'.
2987 * No other characters are accepted, the message is repeated until a valid
2988 * reply is entered or CTRL-C is hit.
2989 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
2990 * from any buffers but directly from the user.
2992 * return the 'y' or 'n'
2995 ask_yesno(str
, direct
)
3000 int save_State
= State
;
3002 if (exiting
) /* put terminal in raw mode for this question */
3003 settmode(TMODE_RAW
);
3005 #ifdef USE_ON_FLY_SCROLL
3006 dont_scroll
= TRUE
; /* disallow scrolling here */
3008 State
= CONFIRM
; /* mouse behaves like with :confirm */
3010 setmouse(); /* disables mouse for xterm */
3013 ++allow_keys
; /* no mapping here, but recognize keys */
3015 while (r
!= 'y' && r
!= 'n')
3017 /* same highlighting as for wait_return */
3018 smsg_attr(hl_attr(HLF_R
), (char_u
*)"%s (y/n)?", str
);
3020 r
= get_keystroke();
3023 if (r
== Ctrl_C
|| r
== ESC
)
3025 msg_putchar(r
); /* show what you typed */
3040 * Get a key stroke directly from the user.
3041 * Ignores mouse clicks and scrollbar events, except a click for the left
3042 * button (used at the more prompt).
3043 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3044 * Disadvantage: typeahead is ignored.
3045 * Translates the interrupt character for unix to ESC.
3051 char_u buf
[CBUFLEN
];
3054 int save_mapped_ctrl_c
= mapped_ctrl_c
;
3057 mapped_ctrl_c
= FALSE
; /* mappings are not used here */
3063 /* First time: blocking wait. Second time: wait up to 100ms for a
3064 * terminal code to complete. Leave some room for check_termcode() to
3065 * insert a key code into (max 5 chars plus NUL). And
3066 * fix_input_buffer() can triple the number of bytes. */
3067 n
= ui_inchar(buf
+ len
, (CBUFLEN
- 6 - len
) / 3,
3068 len
== 0 ? -1L : 100L, 0);
3071 /* Replace zero and CSI by a special key code. */
3072 n
= fix_input_buffer(buf
+ len
, n
, FALSE
);
3077 ++waited
; /* keep track of the waiting time */
3079 /* Incomplete termcode and not timed out yet: get more characters */
3080 if ((n
= check_termcode(1, buf
, len
)) < 0
3081 && (!p_ttimeout
|| waited
* 100L < (p_ttm
< 0 ? p_tm
: p_ttm
)))
3084 /* found a termcode: adjust length */
3087 if (len
== 0) /* nothing typed yet */
3090 /* Handle modifier and/or special key code. */
3094 n
= TO_SPECIAL(buf
[1], buf
[2]);
3095 if (buf
[1] == KS_MODIFIER
3098 || n
== K_LEFTMOUSE_NM
3100 || n
== K_LEFTRELEASE
3101 || n
== K_LEFTRELEASE_NM
3102 || n
== K_MIDDLEMOUSE
3103 || n
== K_MIDDLEDRAG
3104 || n
== K_MIDDLERELEASE
3105 || n
== K_RIGHTMOUSE
3107 || n
== K_RIGHTRELEASE
3117 || n
== K_VER_SCROLLBAR
3118 || n
== K_HOR_SCROLLBAR
3123 if (buf
[1] == KS_MODIFIER
)
3127 mch_memmove(buf
, buf
+ 3, (size_t)len
);
3135 if (MB_BYTE2LEN(n
) > len
)
3136 continue; /* more bytes to get */
3137 buf
[len
>= CBUFLEN
? CBUFLEN
- 1 : len
] = NUL
;
3138 n
= (*mb_ptr2char
)(buf
);
3148 mapped_ctrl_c
= save_mapped_ctrl_c
;
3153 * Get a number from the user.
3154 * When "mouse_used" is not NULL allow using the mouse.
3157 get_number(colon
, mouse_used
)
3158 int colon
; /* allow colon to abort */
3165 if (mouse_used
!= NULL
)
3166 *mouse_used
= FALSE
;
3168 /* When not printing messages, the user won't know what to type, return a
3169 * zero (as if CR was hit). */
3170 if (msg_silent
!= 0)
3173 #ifdef USE_ON_FLY_SCROLL
3174 dont_scroll
= TRUE
; /* disallow scrolling here */
3177 ++allow_keys
; /* no mapping here, but recognize keys */
3180 windgoto(msg_row
, msg_col
);
3184 n
= n
* 10 + c
- '0';
3188 else if (c
== K_DEL
|| c
== K_KDEL
|| c
== K_BS
|| c
== Ctrl_H
)
3198 else if (mouse_used
!= NULL
&& c
== K_LEFTMOUSE
)
3205 else if (n
== 0 && c
== ':' && colon
)
3207 stuffcharReadbuff(':');
3209 cmdline_row
= msg_row
;
3210 skip_redraw
= TRUE
; /* skip redraw once */
3214 else if (c
== CAR
|| c
== NL
|| c
== Ctrl_C
|| c
== ESC
)
3223 * Ask the user to enter a number.
3224 * When "mouse_used" is not NULL allow using the mouse and in that case return
3228 prompt_for_number(mouse_used
)
3232 int save_cmdline_row
;
3235 /* When using ":silent" assume that <CR> was entered. */
3236 if (mouse_used
!= NULL
)
3237 MSG_PUTS(_("Type number or click with mouse (<Enter> cancels): "));
3239 MSG_PUTS(_("Choice number (<Enter> cancels): "));
3241 /* Set the state such that text can be selected/copied/pasted and we still
3242 * get mouse events. */
3243 save_cmdline_row
= cmdline_row
;
3248 i
= get_number(TRUE
, mouse_used
);
3251 /* don't call wait_return() now */
3252 /* msg_putchar('\n'); */
3253 cmdline_row
= msg_row
- 1;
3254 need_wait_return
= FALSE
;
3258 cmdline_row
= save_cmdline_row
;
3270 if (global_busy
/* no messages now, wait until global is finished */
3271 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3274 /* We don't want to overwrite another important message, but do overwrite
3275 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3276 * then "put" reports the last action. */
3277 if (keep_msg
!= NULL
&& !keep_msg_more
)
3290 STRCPY(msg_buf
, _("1 more line"));
3292 STRCPY(msg_buf
, _("1 line less"));
3297 sprintf((char *)msg_buf
, _("%ld more lines"), pn
);
3299 sprintf((char *)msg_buf
, _("%ld fewer lines"), pn
);
3302 STRCAT(msg_buf
, _(" (Interrupted)"));
3305 set_keep_msg(msg_buf
, 0);
3306 keep_msg_more
= TRUE
;
3312 * flush map and typeahead buffers and give a warning for an error
3317 if (emsg_silent
== 0)
3319 flush_buffers(FALSE
);
3325 * give a warning for an error
3330 if (emsg_silent
== 0)
3334 /* While the GUI is starting up the termcap is set for the GUI
3335 * but the output still goes to a terminal. */
3336 && !(gui
.in_use
&& gui
.starting
)
3346 * The number of beeps outputted is reduced to avoid having to wait
3347 * for all the beeps to finish. This is only a problem on systems
3348 * where the beeps don't overlap.
3350 if (beep_count
== 0 || beep_count
== 10)
3362 /* When 'verbose' is set and we are sourcing a script or executing a
3363 * function give the user a hint where the beep comes from. */
3364 if (vim_strchr(p_debug
, 'e') != NULL
)
3366 msg_source(hl_attr(HLF_W
));
3367 msg_attr((char_u
*)_("Beep!"), hl_attr(HLF_W
));
3373 * To get the "real" home directory:
3374 * - get value of $HOME
3376 * - go to that directory
3377 * - do mch_dirname() to get the real name of that directory.
3378 * This also works with mounts and links.
3379 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3381 static char_u
*homedir
= NULL
;
3388 /* In case we are called a second time (when 'encoding' changes). */
3393 var
= mch_getenv((char_u
*)"SYS$LOGIN");
3395 var
= mch_getenv((char_u
*)"HOME");
3398 if (var
!= NULL
&& *var
== NUL
) /* empty is same as not set */
3403 * Weird but true: $HOME may contain an indirect reference to another
3404 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3405 * when $HOME is being set.
3407 if (var
!= NULL
&& *var
== '%')
3412 p
= vim_strchr(var
+ 1, '%');
3415 vim_strncpy(NameBuff
, var
+ 1, p
- (var
+ 1));
3416 exp
= mch_getenv(NameBuff
);
3417 if (exp
!= NULL
&& *exp
!= NUL
3418 && STRLEN(exp
) + STRLEN(p
) < MAXPATHL
)
3420 vim_snprintf((char *)NameBuff
, MAXPATHL
, "%s%s", exp
, p
+ 1);
3422 /* Also set $HOME, it's needed for _viminfo. */
3423 vim_setenv((char_u
*)"HOME", NameBuff
);
3429 * Typically, $HOME is not defined on Windows, unless the user has
3430 * specifically defined it for Vim's sake. However, on Windows NT
3431 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3432 * each user. Try constructing $HOME from these.
3436 char_u
*homedrive
, *homepath
;
3438 homedrive
= mch_getenv((char_u
*)"HOMEDRIVE");
3439 homepath
= mch_getenv((char_u
*)"HOMEPATH");
3440 if (homedrive
!= NULL
&& homepath
!= NULL
3441 && STRLEN(homedrive
) + STRLEN(homepath
) < MAXPATHL
)
3443 sprintf((char *)NameBuff
, "%s%s", homedrive
, homepath
);
3444 if (NameBuff
[0] != NUL
)
3447 /* Also set $HOME, it's needed for _viminfo. */
3448 vim_setenv((char_u
*)"HOME", NameBuff
);
3453 # if defined(FEAT_MBYTE)
3454 if (enc_utf8
&& var
!= NULL
)
3459 /* Convert from active codepage to UTF-8. Other conversions are
3460 * not done, because they would fail for non-ASCII characters. */
3461 acp_to_enc(var
, (int)STRLEN(var
), &pp
, &len
);
3471 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3473 * Default home dir is C:/
3474 * Best assumption we can make in such a situation.
3483 * Change to the directory and get the actual path. This resolves
3484 * links. Don't do it when we can't return.
3486 if (mch_dirname(NameBuff
, MAXPATHL
) == OK
3487 && mch_chdir((char *)NameBuff
) == 0)
3489 if (!mch_chdir((char *)var
) && mch_dirname(IObuff
, IOSIZE
) == OK
)
3491 if (mch_chdir((char *)NameBuff
) != 0)
3492 EMSG(_(e_prev_dir
));
3495 homedir
= vim_strsave(var
);
3499 #if defined(EXITFREE) || defined(PROTO)
3508 * Expand environment variable with path name.
3509 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3510 * Skips over "\ ", "\~" and "\$".
3511 * If anything fails no expansion is done and dst equals src.
3514 expand_env(src
, dst
, dstlen
)
3515 char_u
*src
; /* input string e.g. "$HOME/vim.hlp" */
3516 char_u
*dst
; /* where to put the result */
3517 int dstlen
; /* maximum length of the result */
3519 expand_env_esc(src
, dst
, dstlen
, FALSE
, NULL
);
3523 expand_env_esc(srcp
, dst
, dstlen
, esc
, startstr
)
3524 char_u
*srcp
; /* input string e.g. "$HOME/vim.hlp" */
3525 char_u
*dst
; /* where to put the result */
3526 int dstlen
; /* maximum length of the result */
3527 int esc
; /* escape spaces in expanded variables */
3528 char_u
*startstr
; /* start again after this (can be NULL) */
3535 int mustfree
; /* var was allocated, need to free it later */
3536 int at_start
= TRUE
; /* at start of a name */
3537 int startstr_len
= 0;
3539 if (startstr
!= NULL
)
3540 startstr_len
= (int)STRLEN(startstr
);
3542 src
= skipwhite(srcp
);
3543 --dstlen
; /* leave one char space for "\," */
3544 while (*src
&& dstlen
> 0)
3552 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3555 || (*src
== '~' && at_start
))
3560 * The variable name is copied into dst temporarily, because it may
3561 * be a string in read-only memory and a NUL needs to be appended.
3563 if (*src
!= '~') /* environment var */
3570 /* Unix has ${var-name} type environment vars */
3571 if (*tail
== '{' && !vim_isIDc('{'))
3573 tail
++; /* ignore '{' */
3574 while (c
-- > 0 && *tail
&& *tail
!= '}')
3580 while (c
-- > 0 && *tail
!= NUL
&& ((vim_isIDc(*tail
))
3581 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3582 || (*src
== '%' && *tail
!= '%')
3586 #ifdef OS2 /* env vars only in uppercase */
3587 *var
++ = TOUPPER_LOC(*tail
);
3588 tail
++; /* toupper() may be a macro! */
3595 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3597 if (src
[1] == '{' && *tail
!= '}')
3599 if (*src
== '%' && *tail
!= '%')
3612 var
= vim_getenv(dst
, &mustfree
);
3613 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3617 /* home directory */
3618 else if ( src
[1] == NUL
3619 || vim_ispathsep(src
[1])
3620 || vim_strchr((char_u
*)" ,\t\n", src
[1]) != NULL
)
3625 else /* user directory */
3627 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3629 * Copy ~user to dst[], so we can put a NUL after it.
3636 && vim_isfilec(*tail
)
3637 && !vim_ispathsep(*tail
))
3642 * If the system supports getpwnam(), use it.
3643 * Otherwise, or if getpwnam() fails, the shell is used to
3644 * expand ~user. This is slower and may fail if the shell
3645 * does not support ~user (old versions of /bin/sh).
3647 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3651 /* Note: memory allocated by getpwnam() is never freed.
3652 * Calling endpwent() apparently doesn't help. */
3653 pw
= getpwnam((char *)dst
+ 1);
3655 var
= (char_u
*)pw
->pw_dir
;
3665 xpc
.xp_context
= EXPAND_FILES
;
3666 var
= ExpandOne(&xpc
, dst
, NULL
,
3667 WILD_ADD_SLASH
|WILD_SILENT
, WILD_EXPAND_FREE
);
3671 # else /* !UNIX, thus VMS */
3673 * USER_HOME is a comma-separated list of
3674 * directories to search for the user account in.
3677 char_u test
[MAXPATHL
], paths
[MAXPATHL
];
3678 char_u
*path
, *next_path
, *ptr
;
3681 STRCPY(paths
, USER_HOME
);
3685 for (path
= next_path
; *next_path
&& *next_path
!= ',';
3691 STRCAT(test
, dst
+ 1);
3692 if (mch_stat(test
, &st
) == 0)
3694 var
= alloc(STRLEN(test
) + 1);
3703 /* cannot expand user's home directory, so don't try */
3705 tail
= (char_u
*)""; /* for gcc */
3706 #endif /* UNIX || VMS */
3709 #ifdef BACKSLASH_IN_FILENAME
3710 /* If 'shellslash' is set change backslashes to forward slashes.
3711 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3712 if (p_ssl
&& var
!= NULL
&& vim_strchr(var
, '\\') != NULL
)
3714 char_u
*p
= vim_strsave(var
);
3727 /* If "var" contains white space, escape it with a backslash.
3728 * Required for ":e ~/tt" when $HOME includes a space. */
3729 if (esc
&& var
!= NULL
&& vim_strpbrk(var
, (char_u
*)" \t") != NULL
)
3731 char_u
*p
= vim_strsave_escaped(var
, (char_u
*)" \t");
3742 if (var
!= NULL
&& *var
!= NUL
3743 && (STRLEN(var
) + STRLEN(tail
) + 1 < (unsigned)dstlen
))
3746 dstlen
-= (int)STRLEN(var
);
3747 c
= (int)STRLEN(var
);
3748 /* if var[] ends in a path separator and tail[] starts
3749 * with it, skip a character */
3750 if (*var
!= NUL
&& after_pathsep(dst
, dst
+ c
)
3751 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3754 && vim_ispathsep(*tail
))
3764 if (copy_char
) /* copy at least one char */
3767 * Recognize the start of a new name, for '~'.
3770 if (src
[0] == '\\' && src
[1] != NUL
)
3775 else if (src
[0] == ' ' || src
[0] == ',')
3780 if (startstr
!= NULL
&& src
- startstr_len
>= srcp
3781 && STRNCMP(src
- startstr_len
, startstr
, startstr_len
) == 0)
3789 * Vim's version of getenv().
3790 * Special handling of $HOME, $VIM and $VIMRUNTIME.
3791 * Also does ACP to 'enc' conversion for Win32.
3794 vim_getenv(name
, mustfree
)
3796 int *mustfree
; /* set to TRUE when returned is allocated */
3802 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3803 /* use "C:/" when $HOME is not set */
3804 if (STRCMP(name
, "HOME") == 0)
3808 p
= mch_getenv(name
);
3809 if (p
!= NULL
&& *p
== NUL
) /* empty is the same as not set */
3814 #if defined(FEAT_MBYTE) && defined(WIN3264)
3820 /* Convert from active codepage to UTF-8. Other conversions are
3821 * not done, because they would fail for non-ASCII characters. */
3822 acp_to_enc(p
, (int)STRLEN(p
), &pp
, &len
);
3833 vimruntime
= (STRCMP(name
, "VIMRUNTIME") == 0);
3834 if (!vimruntime
&& STRCMP(name
, "VIM") != 0)
3838 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3839 * Don't do this when default_vimruntime_dir is non-empty.
3843 && *default_vimruntime_dir
== NUL
3847 p
= mch_getenv((char_u
*)"VIM");
3848 if (p
!= NULL
&& *p
== NUL
) /* empty is the same as not set */
3852 p
= vim_version_dir(p
);
3856 p
= mch_getenv((char_u
*)"VIM");
3858 #if defined(FEAT_MBYTE) && defined(WIN3264)
3864 /* Convert from active codepage to UTF-8. Other conversions
3865 * are not done, because they would fail for non-ASCII
3867 acp_to_enc(p
, (int)STRLEN(p
), &pp
, &len
);
3881 * When expanding $VIM or $VIMRUNTIME fails, try using:
3882 * - the directory name from 'helpfile' (unless it contains '$')
3883 * - the executable name from argv[0]
3887 if (p_hf
!= NULL
&& vim_strchr(p_hf
, '$') == NULL
)
3891 * Use the name of the executable, obtained from argv[0].
3898 /* remove the file name */
3901 /* remove "doc/" from 'helpfile', if present */
3903 pend
= remove_tail(p
, pend
, (char_u
*)"doc");
3907 /* remove "MacOS" from exe_name and add "Resources/vim" */
3913 pend1
= remove_tail(p
, pend
, (char_u
*)"MacOS");
3916 pnew
= alloc((unsigned)(pend1
- p
) + 15);
3919 STRNCPY(pnew
, p
, (pend1
- p
));
3920 STRCPY(pnew
+ (pend1
- p
), "Resources/vim");
3922 pend
= p
+ STRLEN(p
);
3927 /* remove "src/" from exe_name, if present */
3929 pend
= remove_tail(p
, pend
, (char_u
*)"src");
3932 /* for $VIM, remove "runtime/" or "vim54/", if present */
3935 pend
= remove_tail(p
, pend
, (char_u
*)RUNTIME_DIRNAME
);
3936 pend
= remove_tail(p
, pend
, (char_u
*)VIM_VERSION_NODOT
);
3939 /* remove trailing path separator */
3940 #ifndef MACOS_CLASSIC
3941 /* With MacOS path (with colons) the final colon is required */
3942 /* to avoid confusion between absoulute and relative path */
3943 if (pend
> p
&& after_pathsep(p
, pend
))
3948 if (p
== exe_name
|| p
== p_hf
)
3950 /* check that the result is a directory name */
3951 p
= vim_strnsave(p
, (int)(pend
- p
));
3953 if (p
!= NULL
&& !mch_isdir(p
))
3961 /* may add "/vim54" or "/runtime" if it exists */
3962 if (vimruntime
&& (pend
= vim_version_dir(p
)) != NULL
)
3974 /* When there is a pathdef.c file we can use default_vim_dir and
3975 * default_vimruntime_dir */
3978 /* Only use default_vimruntime_dir when it is not empty */
3979 if (vimruntime
&& *default_vimruntime_dir
!= NUL
)
3981 p
= default_vimruntime_dir
;
3984 else if (*default_vim_dir
!= NUL
)
3986 if (vimruntime
&& (p
= vim_version_dir(default_vim_dir
)) != NULL
)
3990 p
= default_vim_dir
;
3998 * Set the environment variable, so that the new value can be found fast
3999 * next time, and others can also use it (e.g. Perl).
4005 vim_setenv((char_u
*)"VIMRUNTIME", p
);
4006 didset_vimruntime
= TRUE
;
4009 char_u
*buf
= concat_str(p
, (char_u
*)"/lang");
4013 bindtextdomain(VIMPACKAGE
, (char *)buf
);
4021 vim_setenv((char_u
*)"VIM", p
);
4029 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4030 * Return NULL if not, return its name in allocated memory otherwise.
4033 vim_version_dir(vimdir
)
4038 if (vimdir
== NULL
|| *vimdir
== NUL
)
4040 p
= concat_fnames(vimdir
, (char_u
*)VIM_VERSION_NODOT
, TRUE
);
4041 if (p
!= NULL
&& mch_isdir(p
))
4044 p
= concat_fnames(vimdir
, (char_u
*)RUNTIME_DIRNAME
, TRUE
);
4045 if (p
!= NULL
&& mch_isdir(p
))
4052 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4053 * the length of "name/". Otherwise return "pend".
4056 remove_tail(p
, pend
, name
)
4061 int len
= (int)STRLEN(name
) + 1;
4062 char_u
*newend
= pend
- len
;
4065 && fnamencmp(newend
, name
, len
- 1) == 0
4066 && (newend
== p
|| after_pathsep(p
, newend
)))
4072 * Call expand_env() and store the result in an allocated string.
4073 * This is not very memory efficient, this expects the result to be freed
4077 expand_env_save(src
)
4082 p
= alloc(MAXPATHL
);
4084 expand_env(src
, p
, MAXPATHL
);
4089 * Our portable version of setenv.
4092 vim_setenv(name
, val
)
4097 mch_setenv((char *)name
, (char *)val
, 1);
4102 * Putenv does not copy the string, it has to remain
4103 * valid. The allocated memory will never be freed.
4105 envbuf
= alloc((unsigned)(STRLEN(name
) + STRLEN(val
) + 2));
4108 sprintf((char *)envbuf
, "%s=%s", name
, val
);
4109 putenv((char *)envbuf
);
4114 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4116 * Function given to ExpandGeneric() to obtain an environment variable name.
4120 get_env_name(xp
, idx
)
4124 # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4126 * No environ[] on the Amiga and on the Mac (using MPW).
4131 /* Borland C++ 5.2 has this in a header file. */
4132 extern char **environ
;
4134 # define ENVNAMELEN 100
4135 static char_u name
[ENVNAMELEN
];
4139 str
= (char_u
*)environ
[idx
];
4143 for (n
= 0; n
< ENVNAMELEN
- 1; ++n
)
4145 if (str
[n
] == '=' || str
[n
] == NUL
)
4156 * Replace home directory by "~" in each space or comma separated file name in
4158 * If anything fails (except when out of space) dst equals src.
4161 home_replace(buf
, src
, dst
, dstlen
, one
)
4162 buf_T
*buf
; /* when not NULL, check for help files */
4163 char_u
*src
; /* input file name */
4164 char_u
*dst
; /* where to put the result */
4165 int dstlen
; /* maximum length of the result */
4166 int one
; /* if TRUE, only replace one file name, include
4167 spaces and commas in the file name. */
4169 size_t dirlen
= 0, envlen
= 0;
4171 char_u
*homedir_env
;
4181 * If the file is a help file, remove the path completely.
4183 if (buf
!= NULL
&& buf
->b_help
)
4185 STRCPY(dst
, gettail(src
));
4190 * We check both the value of the $HOME environment variable and the
4191 * "real" home directory.
4193 if (homedir
!= NULL
)
4194 dirlen
= STRLEN(homedir
);
4197 homedir_env
= mch_getenv((char_u
*)"SYS$LOGIN");
4199 homedir_env
= mch_getenv((char_u
*)"HOME");
4202 if (homedir_env
!= NULL
&& *homedir_env
== NUL
)
4204 if (homedir_env
!= NULL
)
4205 envlen
= STRLEN(homedir_env
);
4208 src
= skipwhite(src
);
4209 while (*src
&& dstlen
> 0)
4212 * Here we are at the beginning of a file name.
4213 * First, check to see if the beginning of the file name matches
4214 * $HOME or the "real" home directory. Check that there is a '/'
4215 * after the match (so that if e.g. the file is "/home/pieter/bla",
4216 * and the home directory is "/home/piet", the file does not end up
4217 * as "~er/bla" (which would seem to indicate the file "bla" in user
4218 * er's home directory)).
4225 && fnamencmp(src
, p
, len
) == 0
4226 && (vim_ispathsep(src
[len
])
4227 || (!one
&& (src
[len
] == ',' || src
[len
] == ' '))
4228 || src
[len
] == NUL
))
4235 * If it's just the home directory, add "/".
4237 if (!vim_ispathsep(src
[0]) && --dstlen
> 0)
4241 if (p
== homedir_env
)
4247 /* if (!one) skip to separator: space or comma */
4248 while (*src
&& (one
|| (*src
!= ',' && *src
!= ' ')) && --dstlen
> 0)
4250 /* skip separator */
4251 while ((*src
== ' ' || *src
== ',') && --dstlen
> 0)
4254 /* if (dstlen == 0) out of space, what to do??? */
4260 * Like home_replace, store the replaced string in allocated memory.
4261 * When something fails, NULL is returned.
4264 home_replace_save(buf
, src
)
4265 buf_T
*buf
; /* when not NULL, check for help files */
4266 char_u
*src
; /* input file name */
4271 len
= 3; /* space for "~/" and trailing NUL */
4272 if (src
!= NULL
) /* just in case */
4273 len
+= (unsigned)STRLEN(src
);
4276 home_replace(buf
, src
, dst
, len
, TRUE
);
4281 * Compare two file names and return:
4282 * FPC_SAME if they both exist and are the same file.
4283 * FPC_SAMEX if they both don't exist and have the same file name.
4284 * FPC_DIFF if they both exist and are different files.
4285 * FPC_NOTX if they both don't exist.
4286 * FPC_DIFFX if one of them doesn't exist.
4287 * For the first name environment variables are expanded
4290 fullpathcmp(s1
, s2
, checkname
)
4292 int checkname
; /* when both don't exist, check file names */
4295 char_u exp1
[MAXPATHL
];
4296 char_u full1
[MAXPATHL
];
4297 char_u full2
[MAXPATHL
];
4298 struct stat st1
, st2
;
4301 expand_env(s1
, exp1
, MAXPATHL
);
4302 r1
= mch_stat((char *)exp1
, &st1
);
4303 r2
= mch_stat((char *)s2
, &st2
);
4304 if (r1
!= 0 && r2
!= 0)
4306 /* if mch_stat() doesn't work, may compare the names */
4309 if (fnamecmp(exp1
, s2
) == 0)
4311 r1
= vim_FullName(exp1
, full1
, MAXPATHL
, FALSE
);
4312 r2
= vim_FullName(s2
, full2
, MAXPATHL
, FALSE
);
4313 if (r1
== OK
&& r2
== OK
&& fnamecmp(full1
, full2
) == 0)
4318 if (r1
!= 0 || r2
!= 0)
4320 if (st1
.st_dev
== st2
.st_dev
&& st1
.st_ino
== st2
.st_ino
)
4324 char_u
*exp1
; /* expanded s1 */
4325 char_u
*full1
; /* full path of s1 */
4326 char_u
*full2
; /* full path of s2 */
4327 int retval
= FPC_DIFF
;
4330 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4331 if ((exp1
= alloc(MAXPATHL
* 3)) != NULL
)
4333 full1
= exp1
+ MAXPATHL
;
4334 full2
= full1
+ MAXPATHL
;
4336 expand_env(s1
, exp1
, MAXPATHL
);
4337 r1
= vim_FullName(exp1
, full1
, MAXPATHL
, FALSE
);
4338 r2
= vim_FullName(s2
, full2
, MAXPATHL
, FALSE
);
4340 /* If vim_FullName() fails, the file probably doesn't exist. */
4341 if (r1
!= OK
&& r2
!= OK
)
4343 if (checkname
&& fnamecmp(exp1
, s2
) == 0)
4348 else if (r1
!= OK
|| r2
!= OK
)
4350 else if (fnamecmp(full1
, full2
))
4361 * Get the tail of a path: the file name.
4362 * Fail safe: never returns NULL.
4371 return (char_u
*)"";
4372 for (p1
= p2
= fname
; *p2
; ) /* find last part of path */
4374 if (vim_ispathsep(*p2
))
4382 * Get pointer to tail of "fname", including path separators. Putting a NUL
4383 * here leaves the directory name. Takes care of "c:/" and "//".
4384 * Always returns a valid pointer.
4393 p
= get_past_head(fname
); /* don't remove the '/' from "c:/file" */
4395 while (t
> p
&& after_pathsep(fname
, t
))
4398 /* path separator is part of the path */
4405 * get the next path component (just after the next path separator).
4411 while (*fname
&& !vim_ispathsep(*fname
))
4419 * Get a pointer to one character past the head of a path name.
4420 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4421 * If there is no head, path is returned.
4429 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4431 if (isalpha(path
[0]) && path
[1] == ':')
4437 /* may skip "label:" */
4438 retval
= vim_strchr(path
, ':');
4446 while (vim_ispathsep(*retval
))
4453 * return TRUE if 'c' is a path separator.
4460 return (c
== '.' || c
== ':');
4463 return (c
== '/'); /* UNIX has ':' inside file names */
4465 # ifdef BACKSLASH_IN_FILENAME
4466 return (c
== ':' || c
== '/' || c
== '\\');
4469 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4470 return (c
== ':' || c
== '[' || c
== ']' || c
== '/'
4471 || c
== '<' || c
== '>' || c
== '"' );
4473 return (c
== ':' || c
== '/');
4477 #endif /* RISC OS */
4480 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
4482 * return TRUE if 'c' is a path list separator.
4485 vim_ispathlistsep(c
)
4491 return (c
== ';'); /* might not be right for every system... */
4496 #if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4497 || defined(FEAT_EVAL) || defined(PROTO)
4499 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4500 * It's done in-place.
4506 char_u
*tail
, *s
, *d
;
4509 tail
= gettail(str
);
4511 for (s
= str
; ; ++s
)
4513 if (s
>= tail
) /* copy the whole tail */
4519 else if (vim_ispathsep(*s
)) /* copy '/' and next char */
4526 *d
++ = *s
; /* copy next char */
4527 if (*s
!= '~' && *s
!= '.') /* and leading "~" and "." */
4532 int l
= mb_ptr2len(s
);
4544 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4545 * Also returns TRUE if there is no directory name.
4546 * "fname" must be writable!.
4549 dir_of_file_exists(fname
)
4556 p
= gettail_sep(fname
);
4561 retval
= mch_isdir(fname
);
4566 #if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4569 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4575 return vim_fnamencmp(x
, y
, MAXPATHL
);
4579 vim_fnamencmp(x
, y
, len
)
4583 while (len
> 0 && *x
&& *y
)
4585 if (TOLOWER_LOC(*x
) != TOLOWER_LOC(*y
)
4586 && !(*x
== '/' && *y
== '\\')
4587 && !(*x
== '\\' && *y
== '/'))
4600 * Concatenate file names fname1 and fname2 into allocated memory.
4601 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
4604 concat_fnames(fname1
, fname2
, sep
)
4611 dest
= alloc((unsigned)(STRLEN(fname1
) + STRLEN(fname2
) + 3));
4614 STRCPY(dest
, fname1
);
4617 STRCAT(dest
, fname2
);
4622 #if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4624 * Concatenate two strings and return the result in allocated memory.
4625 * Returns NULL when out of memory.
4628 concat_str(str1
, str2
)
4633 size_t l
= STRLEN(str1
);
4635 dest
= alloc((unsigned)(l
+ STRLEN(str2
) + 1L));
4639 STRCPY(dest
+ l
, str2
);
4646 * Add a path separator to a file name, unless it already ends in a path
4653 if (*p
!= NUL
&& !after_pathsep(p
, p
+ STRLEN(p
)))
4654 STRCAT(p
, PATHSEPSTR
);
4658 * FullName_save - Make an allocated copy of a full file name.
4659 * Returns NULL when out of memory.
4662 FullName_save(fname
, force
)
4664 int force
; /* force expansion, even when it already looks
4665 like a full path name */
4668 char_u
*new_fname
= NULL
;
4673 buf
= alloc((unsigned)MAXPATHL
);
4676 if (vim_FullName(fname
, buf
, MAXPATHL
, force
) != FAIL
)
4677 new_fname
= vim_strsave(buf
);
4679 new_fname
= vim_strsave(fname
);
4685 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4687 static char_u
*skip_string
__ARGS((char_u
*p
));
4690 * Find the start of a comment, not knowing if we are in a comment right now.
4691 * Search starts at w_cursor.lnum and goes backwards.
4694 find_start_comment(ind_maxcomment
) /* XXX */
4700 int cur_maxcomment
= ind_maxcomment
;
4704 pos
= findmatchlimit(NULL
, '*', FM_BACKWARD
, cur_maxcomment
);
4709 * Check if the comment start we found is inside a string.
4710 * If it is then restrict the search to below this line and try again.
4712 line
= ml_get(pos
->lnum
);
4713 for (p
= line
; *p
&& (unsigned)(p
- line
) < pos
->col
; ++p
)
4715 if ((unsigned)(p
- line
) <= pos
->col
)
4717 cur_maxcomment
= curwin
->w_cursor
.lnum
- pos
->lnum
- 1;
4718 if (cur_maxcomment
<= 0)
4728 * Skip to the end of a "string" and a 'c' character.
4729 * If there is no string or character, return argument unmodified.
4738 * We loop, because strings may be concatenated: "date""time".
4742 if (p
[0] == '\'') /* 'c' or '\n' or '\000' */
4744 if (!p
[1]) /* ' at end of line */
4747 if (p
[1] == '\\') /* '\n' or '\000' */
4750 while (vim_isdigit(p
[i
- 1])) /* '\000' */
4753 if (p
[i
] == '\'') /* check for trailing ' */
4759 else if (p
[0] == '"') /* start of string */
4761 for (++p
; p
[0]; ++p
)
4763 if (p
[0] == '\\' && p
[1] != NUL
)
4765 else if (p
[0] == '"') /* end of string */
4771 break; /* no string found */
4774 --p
; /* backup from NUL */
4777 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
4779 #if defined(FEAT_CINDENT) || defined(PROTO)
4782 * Do C or expression indenting on the current line.
4788 if (*curbuf
->b_p_inde
!= NUL
)
4789 fixthisline(get_expr_indent
);
4792 fixthisline(get_c_indent
);
4796 * Functions for C-indenting.
4797 * Most of this originally comes from Eric Fischer.
4800 * Below "XXX" means that this function may unlock the current line.
4803 static char_u
*cin_skipcomment
__ARGS((char_u
*));
4804 static int cin_nocode
__ARGS((char_u
*));
4805 static pos_T
*find_line_comment
__ARGS((void));
4806 static int cin_islabel_skip
__ARGS((char_u
**));
4807 static int cin_isdefault
__ARGS((char_u
*));
4808 static char_u
*after_label
__ARGS((char_u
*l
));
4809 static int get_indent_nolabel
__ARGS((linenr_T lnum
));
4810 static int skip_label
__ARGS((linenr_T
, char_u
**pp
, int ind_maxcomment
));
4811 static int cin_first_id_amount
__ARGS((void));
4812 static int cin_get_equal_amount
__ARGS((linenr_T lnum
));
4813 static int cin_ispreproc
__ARGS((char_u
*));
4814 static int cin_ispreproc_cont
__ARGS((char_u
**pp
, linenr_T
*lnump
));
4815 static int cin_iscomment
__ARGS((char_u
*));
4816 static int cin_islinecomment
__ARGS((char_u
*));
4817 static int cin_isterminated
__ARGS((char_u
*, int, int));
4818 static int cin_isinit
__ARGS((void));
4819 static int cin_isfuncdecl
__ARGS((char_u
**, linenr_T
));
4820 static int cin_isif
__ARGS((char_u
*));
4821 static int cin_iselse
__ARGS((char_u
*));
4822 static int cin_isdo
__ARGS((char_u
*));
4823 static int cin_iswhileofdo
__ARGS((char_u
*, linenr_T
, int));
4824 static int cin_iswhileofdo_end
__ARGS((int terminated
, int ind_maxparen
, int ind_maxcomment
));
4825 static int cin_isbreak
__ARGS((char_u
*));
4826 static int cin_is_cpp_baseclass
__ARGS((colnr_T
*col
));
4827 static int get_baseclass_amount
__ARGS((int col
, int ind_maxparen
, int ind_maxcomment
, int ind_cpp_baseclass
));
4828 static int cin_ends_in
__ARGS((char_u
*, char_u
*, char_u
*));
4829 static int cin_skip2pos
__ARGS((pos_T
*trypos
));
4830 static pos_T
*find_start_brace
__ARGS((int));
4831 static pos_T
*find_match_paren
__ARGS((int, int));
4832 static int corr_ind_maxparen
__ARGS((int ind_maxparen
, pos_T
*startpos
));
4833 static int find_last_paren
__ARGS((char_u
*l
, int start
, int end
));
4834 static int find_match
__ARGS((int lookfor
, linenr_T ourscope
, int ind_maxparen
, int ind_maxcomment
));
4836 static int ind_hash_comment
= 0; /* # starts a comment */
4839 * Skip over white space and C comments within the line.
4840 * Also skip over Perl/shell comments if desired.
4852 /* Perl/shell # comment comment continues until eol. Require a space
4853 * before # to avoid recognizing $#array. */
4854 if (ind_hash_comment
!= 0 && s
!= prev_s
&& *s
== '#')
4862 if (*s
== '/') /* slash-slash comment continues till eol */
4869 for (++s
; *s
; ++s
) /* skip slash-star comment */
4870 if (s
[0] == '*' && s
[1] == '/')
4880 * Return TRUE if there there is no code at *s. White space and comments are
4881 * not considered code.
4887 return *cin_skipcomment(s
) == NUL
;
4891 * Check previous lines for a "//" line comment, skipping over blank lines.
4894 find_line_comment() /* XXX */
4900 pos
= curwin
->w_cursor
;
4901 while (--pos
.lnum
> 0)
4903 line
= ml_get(pos
.lnum
);
4904 p
= skipwhite(line
);
4905 if (cin_islinecomment(p
))
4907 pos
.col
= (int)(p
- line
);
4917 * Check if string matches "label:"; move to character after ':' if true.
4923 if (!vim_isIDc(**s
)) /* need at least one ID character */
4926 while (vim_isIDc(**s
))
4929 *s
= cin_skipcomment(*s
);
4931 /* "::" is not a label, it's C++ */
4932 return (**s
== ':' && *++*s
!= ':');
4936 * Recognize a label: "label:".
4937 * Note: curwin->w_cursor must be where we are looking for the label.
4940 cin_islabel(ind_maxcomment
) /* XXX */
4945 s
= cin_skipcomment(ml_get_curline());
4948 * Exclude "default" from labels, since it should be indented
4949 * like a switch label. Same for C++ scope declarations.
4951 if (cin_isdefault(s
))
4953 if (cin_isscopedecl(s
))
4956 if (cin_islabel_skip(&s
))
4959 * Only accept a label if the previous line is terminated or is a case
4966 cursor_save
= curwin
->w_cursor
;
4967 while (curwin
->w_cursor
.lnum
> 1)
4969 --curwin
->w_cursor
.lnum
;
4972 * If we're in a comment now, skip to the start of the comment.
4974 curwin
->w_cursor
.col
= 0;
4975 if ((trypos
= find_start_comment(ind_maxcomment
)) != NULL
) /* XXX */
4976 curwin
->w_cursor
= *trypos
;
4978 line
= ml_get_curline();
4979 if (cin_ispreproc(line
)) /* ignore #defines, #if, etc. */
4981 if (*(line
= cin_skipcomment(line
)) == NUL
)
4984 curwin
->w_cursor
= cursor_save
;
4985 if (cin_isterminated(line
, TRUE
, FALSE
)
4986 || cin_isscopedecl(line
)
4988 || (cin_islabel_skip(&line
) && cin_nocode(line
)))
4992 curwin
->w_cursor
= cursor_save
;
4993 return TRUE
; /* label at start of file??? */
4999 * Recognize structure initialization and enumerations.
5000 * Q&D-Implementation:
5001 * check for "=" at end or "[typedef] enum" at beginning of line.
5008 s
= cin_skipcomment(ml_get_curline());
5010 if (STRNCMP(s
, "typedef", 7) == 0 && !vim_isIDc(s
[7]))
5011 s
= cin_skipcomment(s
+ 7);
5013 if (STRNCMP(s
, "enum", 4) == 0 && !vim_isIDc(s
[4]))
5016 if (cin_ends_in(s
, (char_u
*)"=", (char_u
*)"{"))
5023 * Recognize a switch label: "case .*:" or "default:".
5029 s
= cin_skipcomment(s
);
5030 if (STRNCMP(s
, "case", 4) == 0 && !vim_isIDc(s
[4]))
5032 for (s
+= 4; *s
; ++s
)
5034 s
= cin_skipcomment(s
);
5037 if (s
[1] == ':') /* skip over "::" for C++ */
5042 if (*s
== '\'' && s
[1] && s
[2] == '\'')
5043 s
+= 2; /* skip over '.' */
5044 else if (*s
== '/' && (s
[1] == '*' || s
[1] == '/'))
5045 return FALSE
; /* stop at comment */
5047 return FALSE
; /* stop at string */
5052 if (cin_isdefault(s
))
5058 * Recognize a "default" switch label.
5064 return (STRNCMP(s
, "default", 7) == 0
5065 && *(s
= cin_skipcomment(s
+ 7)) == ':'
5070 * Recognize a "public/private/proctected" scope declaration label.
5078 s
= cin_skipcomment(s
);
5079 if (STRNCMP(s
, "public", 6) == 0)
5081 else if (STRNCMP(s
, "protected", 9) == 0)
5083 else if (STRNCMP(s
, "private", 7) == 0)
5087 return (*(s
= cin_skipcomment(s
+ i
)) == ':' && s
[1] != ':');
5091 * Return a pointer to the first non-empty non-comment character after a ':'.
5092 * Return NULL if not found.
5104 if (l
[1] == ':') /* skip over "::" for C++ */
5106 else if (!cin_iscase(l
+ 1))
5109 else if (*l
== '\'' && l
[1] && l
[2] == '\'')
5110 l
+= 2; /* skip over 'x' */
5114 l
= cin_skipcomment(l
+ 1);
5121 * Get indent of line "lnum", skipping a label.
5122 * Return 0 if there is nothing after the label.
5125 get_indent_nolabel(lnum
) /* XXX */
5138 fp
.col
= (colnr_T
)(p
- l
);
5140 getvcol(curwin
, &fp
, &col
, NULL
, NULL
);
5145 * Find indent for line "lnum", ignoring any case or jump label.
5146 * Also return a pointer to the text (after the label) in "pp".
5147 * label: if (asdf && asdfasdf)
5151 skip_label(lnum
, pp
, ind_maxcomment
)
5160 cursor_save
= curwin
->w_cursor
;
5161 curwin
->w_cursor
.lnum
= lnum
;
5162 l
= ml_get_curline();
5164 if (cin_iscase(l
) || cin_isscopedecl(l
) || cin_islabel(ind_maxcomment
))
5166 amount
= get_indent_nolabel(lnum
);
5167 l
= after_label(ml_get_curline());
5168 if (l
== NULL
) /* just in case */
5169 l
= ml_get_curline();
5173 amount
= get_indent();
5174 l
= ml_get_curline();
5178 curwin
->w_cursor
= cursor_save
;
5183 * Return the indent of the first variable name after a type in a declaration.
5184 * int a, indent of "a"
5185 * static struct foo b, indent of "b"
5186 * enum bla c, indent of "c"
5187 * Returns zero when it doesn't look like a declaration.
5190 cin_first_id_amount()
5192 char_u
*line
, *p
, *s
;
5197 line
= ml_get_curline();
5198 p
= skipwhite(line
);
5199 len
= (int)(skiptowhite(p
) - p
);
5200 if (len
== 6 && STRNCMP(p
, "static", 6) == 0)
5202 p
= skipwhite(p
+ 6);
5203 len
= (int)(skiptowhite(p
) - p
);
5205 if (len
== 6 && STRNCMP(p
, "struct", 6) == 0)
5206 p
= skipwhite(p
+ 6);
5207 else if (len
== 4 && STRNCMP(p
, "enum", 4) == 0)
5208 p
= skipwhite(p
+ 4);
5209 else if ((len
== 8 && STRNCMP(p
, "unsigned", 8) == 0)
5210 || (len
== 6 && STRNCMP(p
, "signed", 6) == 0))
5212 s
= skipwhite(p
+ len
);
5213 if ((STRNCMP(s
, "int", 3) == 0 && vim_iswhite(s
[3]))
5214 || (STRNCMP(s
, "long", 4) == 0 && vim_iswhite(s
[4]))
5215 || (STRNCMP(s
, "short", 5) == 0 && vim_iswhite(s
[5]))
5216 || (STRNCMP(s
, "char", 4) == 0 && vim_iswhite(s
[4])))
5219 for (len
= 0; vim_isIDc(p
[len
]); ++len
)
5221 if (len
== 0 || !vim_iswhite(p
[len
]) || cin_nocode(p
))
5224 p
= skipwhite(p
+ len
);
5225 fp
.lnum
= curwin
->w_cursor
.lnum
;
5226 fp
.col
= (colnr_T
)(p
- line
);
5227 getvcol(curwin
, &fp
, &col
, NULL
, NULL
);
5232 * Return the indent of the first non-blank after an equal sign.
5233 * char *foo = "here";
5234 * Return zero if no (useful) equal sign found.
5235 * Return -1 if the line above "lnum" ends in a backslash.
5241 cin_get_equal_amount(lnum
)
5251 line
= ml_get(lnum
- 1);
5252 if (*line
!= NUL
&& line
[STRLEN(line
) - 1] == '\\')
5256 line
= s
= ml_get(lnum
);
5257 while (*s
!= NUL
&& vim_strchr((char_u
*)"=;{}\"'", *s
) == NULL
)
5259 if (cin_iscomment(s
)) /* ignore comments */
5260 s
= cin_skipcomment(s
);
5267 s
= skipwhite(s
+ 1);
5271 if (*s
== '"') /* nice alignment for continued strings */
5275 fp
.col
= (colnr_T
)(s
- line
);
5276 getvcol(curwin
, &fp
, &col
, NULL
, NULL
);
5281 * Recognize a preprocessor statement: Any line that starts with '#'.
5294 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5295 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5296 * start and return the line in "*pp".
5299 cin_ispreproc_cont(pp
, lnump
)
5304 linenr_T lnum
= *lnump
;
5309 if (cin_ispreproc(line
))
5317 line
= ml_get(--lnum
);
5318 if (*line
== NUL
|| line
[STRLEN(line
) - 1] != '\\')
5323 *pp
= ml_get(*lnump
);
5328 * Recognize the start of a C or C++ comment.
5334 return (p
[0] == '/' && (p
[1] == '*' || p
[1] == '/'));
5338 * Recognize the start of a "//" comment.
5341 cin_islinecomment(p
)
5344 return (p
[0] == '/' && p
[1] == '/');
5348 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5349 * Don't consider "} else" a terminated line.
5350 * Return the character terminating the line (ending char's have precedence if
5351 * both apply in order to determine initializations).
5354 cin_isterminated(s
, incl_open
, incl_comma
)
5356 int incl_open
; /* include '{' at the end as terminator */
5357 int incl_comma
; /* recognize a trailing comma */
5359 char_u found_start
= 0;
5361 s
= cin_skipcomment(s
);
5363 if (*s
== '{' || (*s
== '}' && !cin_iselse(s
)))
5368 /* skip over comments, "" strings and 'c'haracters */
5369 s
= skip_string(cin_skipcomment(s
));
5370 if ((*s
== ';' || (incl_open
&& *s
== '{') || *s
== '}'
5371 || (incl_comma
&& *s
== ','))
5372 && cin_nocode(s
+ 1))
5382 * Recognize the basic picture of a function declaration -- it needs to
5383 * have an open paren somewhere and a close paren at the end of the line and
5384 * no semicolons anywhere.
5385 * When a line ends in a comma we continue looking in the next line.
5386 * "sp" points to a string with the line. When looking at other lines it must
5387 * be restored to the line. When it's NULL fetch lines here.
5388 * "lnum" is where we start looking.
5391 cin_isfuncdecl(sp
, first_lnum
)
5393 linenr_T first_lnum
;
5396 linenr_T lnum
= first_lnum
;
5404 while (*s
&& *s
!= '(' && *s
!= ';' && *s
!= '\'' && *s
!= '"')
5406 if (cin_iscomment(s
)) /* ignore comments */
5407 s
= cin_skipcomment(s
);
5412 return FALSE
; /* ';', ' or " before any () or no '(' */
5414 while (*s
&& *s
!= ';' && *s
!= '\'' && *s
!= '"')
5416 if (*s
== ')' && cin_nocode(s
+ 1))
5418 /* ')' at the end: may have found a match
5419 * Check for he previous line not to end in a backslash:
5420 * #if defined(x) && \
5423 lnum
= first_lnum
- 1;
5425 if (*s
== NUL
|| s
[STRLEN(s
) - 1] != '\\')
5429 if (*s
== ',' && cin_nocode(s
+ 1))
5431 /* ',' at the end: continue looking in the next line */
5432 if (lnum
>= curbuf
->b_ml
.ml_line_count
)
5437 else if (cin_iscomment(s
)) /* ignore comments */
5438 s
= cin_skipcomment(s
);
5444 if (lnum
!= first_lnum
&& sp
!= NULL
)
5445 *sp
= ml_get(first_lnum
);
5454 return (STRNCMP(p
, "if", 2) == 0 && !vim_isIDc(p
[2]));
5461 if (*p
== '}') /* accept "} else" */
5462 p
= cin_skipcomment(p
+ 1);
5463 return (STRNCMP(p
, "else", 4) == 0 && !vim_isIDc(p
[4]));
5470 return (STRNCMP(p
, "do", 2) == 0 && !vim_isIDc(p
[2]));
5474 * Check if this is a "while" that should have a matching "do".
5475 * We only accept a "while (condition) ;", with only white space between the
5476 * ')' and ';'. The condition may be spread over several lines.
5479 cin_iswhileofdo(p
, lnum
, ind_maxparen
) /* XXX */
5488 p
= cin_skipcomment(p
);
5489 if (*p
== '}') /* accept "} while (cond);" */
5490 p
= cin_skipcomment(p
+ 1);
5491 if (STRNCMP(p
, "while", 5) == 0 && !vim_isIDc(p
[5]))
5493 cursor_save
= curwin
->w_cursor
;
5494 curwin
->w_cursor
.lnum
= lnum
;
5495 curwin
->w_cursor
.col
= 0;
5496 p
= ml_get_curline();
5497 while (*p
&& *p
!= 'w') /* skip any '}', until the 'w' of the "while" */
5500 ++curwin
->w_cursor
.col
;
5502 if ((trypos
= findmatchlimit(NULL
, 0, 0, ind_maxparen
)) != NULL
5503 && *cin_skipcomment(ml_get_pos(trypos
) + 1) == ';')
5505 curwin
->w_cursor
= cursor_save
;
5511 * Return TRUE if we are at the end of a do-while.
5516 * Adjust the cursor to the line with "while".
5519 cin_iswhileofdo_end(terminated
, ind_maxparen
, ind_maxcomment
)
5530 if (terminated
!= ';') /* there must be a ';' at the end */
5533 p
= line
= ml_get_curline();
5536 p
= cin_skipcomment(p
);
5539 s
= skipwhite(p
+ 1);
5540 if (*s
== ';' && cin_nocode(s
+ 1))
5542 /* Found ");" at end of the line, now check there is "while"
5543 * before the matching '('. XXX */
5544 i
= (int)(p
- line
);
5545 curwin
->w_cursor
.col
= i
;
5546 trypos
= find_match_paren(ind_maxparen
, ind_maxcomment
);
5549 s
= cin_skipcomment(ml_get(trypos
->lnum
));
5550 if (*s
== '}') /* accept "} while (cond);" */
5551 s
= cin_skipcomment(s
+ 1);
5552 if (STRNCMP(s
, "while", 5) == 0 && !vim_isIDc(s
[5]))
5554 curwin
->w_cursor
.lnum
= trypos
->lnum
;
5559 /* Searching may have made "line" invalid, get it again. */
5560 line
= ml_get_curline();
5574 return (STRNCMP(p
, "break", 5) == 0 && !vim_isIDc(p
[5]));
5578 * Find the position of a C++ base-class declaration or
5579 * constructor-initialization. eg:
5582 * baseClass <-- here
5583 * class MyClass : public baseClass,
5584 * anotherBaseClass <-- here (should probably lineup ??)
5585 * MyClass::MyClass(...) :
5586 * baseClass(...) <-- here (constructor-initialization)
5588 * This is a lot of guessing. Watch out for "cond ? func() : foo".
5591 cin_is_cpp_baseclass(col
)
5592 colnr_T
*col
; /* return: column to align with */
5595 int class_or_struct
, lookfor_ctor_init
, cpp_base_class
;
5596 linenr_T lnum
= curwin
->w_cursor
.lnum
;
5597 char_u
*line
= ml_get_curline();
5601 s
= skipwhite(line
);
5602 if (*s
== '#') /* skip #define FOO x ? (x) : x */
5604 s
= cin_skipcomment(s
);
5608 cpp_base_class
= lookfor_ctor_init
= class_or_struct
= FALSE
;
5610 /* Search for a line starting with '#', empty, ending in ';' or containing
5611 * '{' or '}' and start below it. This handles the following situations:
5618 * Foo::Foo (int one, int two)
5625 line
= ml_get(lnum
- 1);
5626 s
= skipwhite(line
);
5627 if (*s
== '#' || *s
== NUL
)
5631 s
= cin_skipcomment(s
);
5632 if (*s
== '{' || *s
== '}'
5633 || (*s
== ';' && cin_nocode(s
+ 1)))
5643 line
= ml_get(lnum
);
5644 s
= cin_skipcomment(line
);
5649 if (lnum
== curwin
->w_cursor
.lnum
)
5651 /* Continue in the cursor line. */
5652 line
= ml_get(++lnum
);
5653 s
= cin_skipcomment(line
);
5662 /* skip double colon. It can't be a constructor
5663 * initialization any more */
5664 lookfor_ctor_init
= FALSE
;
5665 s
= cin_skipcomment(s
+ 2);
5667 else if (lookfor_ctor_init
|| class_or_struct
)
5669 /* we have something found, that looks like the start of
5670 * cpp-base-class-declaration or contructor-initialization */
5671 cpp_base_class
= TRUE
;
5672 lookfor_ctor_init
= class_or_struct
= FALSE
;
5674 s
= cin_skipcomment(s
+ 1);
5677 s
= cin_skipcomment(s
+ 1);
5679 else if ((STRNCMP(s
, "class", 5) == 0 && !vim_isIDc(s
[5]))
5680 || (STRNCMP(s
, "struct", 6) == 0 && !vim_isIDc(s
[6])))
5682 class_or_struct
= TRUE
;
5683 lookfor_ctor_init
= FALSE
;
5686 s
= cin_skipcomment(s
+ 5);
5688 s
= cin_skipcomment(s
+ 6);
5692 if (s
[0] == '{' || s
[0] == '}' || s
[0] == ';')
5694 cpp_base_class
= lookfor_ctor_init
= class_or_struct
= FALSE
;
5696 else if (s
[0] == ')')
5698 /* Constructor-initialization is assumed if we come across
5699 * something like "):" */
5700 class_or_struct
= FALSE
;
5701 lookfor_ctor_init
= TRUE
;
5703 else if (s
[0] == '?')
5705 /* Avoid seeing '() :' after '?' as constructor init. */
5708 else if (!vim_isIDc(s
[0]))
5710 /* if it is not an identifier, we are wrong */
5711 class_or_struct
= FALSE
;
5712 lookfor_ctor_init
= FALSE
;
5716 /* it can't be a constructor-initialization any more */
5717 lookfor_ctor_init
= FALSE
;
5719 /* the first statement starts here: lineup with this one... */
5721 *col
= (colnr_T
)(s
- line
);
5724 /* When the line ends in a comma don't align with it. */
5725 if (lnum
== curwin
->w_cursor
.lnum
&& *s
== ',' && cin_nocode(s
+ 1))
5728 s
= cin_skipcomment(s
+ 1);
5732 return cpp_base_class
;
5736 get_baseclass_amount(col
, ind_maxparen
, ind_maxcomment
, ind_cpp_baseclass
)
5740 int ind_cpp_baseclass
;
5748 amount
= get_indent();
5749 if (find_last_paren(ml_get_curline(), '(', ')')
5750 && (trypos
= find_match_paren(ind_maxparen
,
5751 ind_maxcomment
)) != NULL
)
5752 amount
= get_indent_lnum(trypos
->lnum
); /* XXX */
5753 if (!cin_ends_in(ml_get_curline(), (char_u
*)",", NULL
))
5754 amount
+= ind_cpp_baseclass
;
5758 curwin
->w_cursor
.col
= col
;
5759 getvcol(curwin
, &curwin
->w_cursor
, &vcol
, NULL
, NULL
);
5762 if (amount
< ind_cpp_baseclass
)
5763 amount
= ind_cpp_baseclass
;
5768 * Return TRUE if string "s" ends with the string "find", possibly followed by
5769 * white space and comments. Skip strings and comments.
5770 * Ignore "ignore" after "find" if it's not NULL.
5773 cin_ends_in(s
, find
, ignore
)
5780 int len
= (int)STRLEN(find
);
5784 p
= cin_skipcomment(p
);
5785 if (STRNCMP(p
, find
, len
) == 0)
5787 r
= skipwhite(p
+ len
);
5788 if (ignore
!= NULL
&& STRNCMP(r
, ignore
, STRLEN(ignore
)) == 0)
5789 r
= skipwhite(r
+ STRLEN(ignore
));
5800 * Skip strings, chars and comments until at or past "trypos".
5801 * Return the column found.
5804 cin_skip2pos(trypos
)
5810 p
= line
= ml_get(trypos
->lnum
);
5811 while (*p
&& (colnr_T
)(p
- line
) < trypos
->col
)
5813 if (cin_iscomment(p
))
5814 p
= cin_skipcomment(p
);
5821 return (int)(p
- line
);
5825 * Find the '{' at the start of the block we are in.
5826 * Return NULL if no match found.
5827 * Ignore a '{' that is in a comment, makes indenting the next three lines
5834 find_start_brace(ind_maxcomment
) /* XXX */
5840 static pos_T pos_copy
;
5842 cursor_save
= curwin
->w_cursor
;
5843 while ((trypos
= findmatchlimit(NULL
, '{', FM_BLOCKSTOP
, 0)) != NULL
)
5845 pos_copy
= *trypos
; /* copy pos_T, next findmatch will change it */
5847 curwin
->w_cursor
= *trypos
;
5849 /* ignore the { if it's in a // or / * * / comment */
5850 if ((colnr_T
)cin_skip2pos(trypos
) == trypos
->col
5851 && (pos
= find_start_comment(ind_maxcomment
)) == NULL
) /* XXX */
5854 curwin
->w_cursor
.lnum
= pos
->lnum
;
5856 curwin
->w_cursor
= cursor_save
;
5861 * Find the matching '(', failing if it is in a comment.
5862 * Return NULL of no match found.
5865 find_match_paren(ind_maxparen
, ind_maxcomment
) /* XXX */
5871 static pos_T pos_copy
;
5873 cursor_save
= curwin
->w_cursor
;
5874 if ((trypos
= findmatchlimit(NULL
, '(', 0, ind_maxparen
)) != NULL
)
5876 /* check if the ( is in a // comment */
5877 if ((colnr_T
)cin_skip2pos(trypos
) > trypos
->col
)
5881 pos_copy
= *trypos
; /* copy trypos, findmatch will change it */
5883 curwin
->w_cursor
= *trypos
;
5884 if (find_start_comment(ind_maxcomment
) != NULL
) /* XXX */
5888 curwin
->w_cursor
= cursor_save
;
5893 * Return ind_maxparen corrected for the difference in line number between the
5894 * cursor position and "startpos". This makes sure that searching for a
5895 * matching paren above the cursor line doesn't find a match because of
5896 * looking a few lines further.
5899 corr_ind_maxparen(ind_maxparen
, startpos
)
5903 long n
= (long)startpos
->lnum
- (long)curwin
->w_cursor
.lnum
;
5905 if (n
> 0 && n
< ind_maxparen
/ 2)
5906 return ind_maxparen
- (int)n
;
5907 return ind_maxparen
;
5911 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5915 find_last_paren(l
, start
, end
)
5923 curwin
->w_cursor
.col
= 0; /* default is start of line */
5925 for (i
= 0; l
[i
]; i
++)
5927 i
= (int)(cin_skipcomment(l
+ i
) - l
); /* ignore parens in comments */
5928 i
= (int)(skip_string(l
+ i
) - l
); /* ignore parens in quotes */
5931 else if (l
[i
] == end
)
5937 curwin
->w_cursor
.col
= i
;
5949 * spaces from a block's opening brace the prevailing indent for that
5952 int ind_level
= curbuf
->b_p_sw
;
5955 * spaces from the edge of the line an open brace that's at the end of a
5956 * line is imagined to be.
5958 int ind_open_imag
= 0;
5961 * spaces from the prevailing indent for a line that is not precededof by
5964 int ind_no_brace
= 0;
5967 * column where the first { of a function should be located }
5969 int ind_first_open
= 0;
5972 * spaces from the prevailing indent a leftmost open brace should be
5975 int ind_open_extra
= 0;
5978 * spaces from the matching open brace (real location for one at the left
5979 * edge; imaginary location from one that ends a line) the matching close
5980 * brace should be located
5982 int ind_close_extra
= 0;
5985 * spaces from the edge of the line an open brace sitting in the leftmost
5986 * column is imagined to be
5988 int ind_open_left_imag
= 0;
5991 * spaces from the switch() indent a "case xx" label should be located
5993 int ind_case
= curbuf
->b_p_sw
;
5996 * spaces from the "case xx:" code after a switch() should be located
5998 int ind_case_code
= curbuf
->b_p_sw
;
6001 * lineup break at end of case in switch() with case label
6003 int ind_case_break
= 0;
6006 * spaces from the class declaration indent a scope declaration label
6009 int ind_scopedecl
= curbuf
->b_p_sw
;
6012 * spaces from the scope declaration label code should be located
6014 int ind_scopedecl_code
= curbuf
->b_p_sw
;
6017 * amount K&R-style parameters should be indented
6019 int ind_param
= curbuf
->b_p_sw
;
6022 * amount a function type spec should be indented
6024 int ind_func_type
= curbuf
->b_p_sw
;
6027 * amount a cpp base class declaration or constructor initialization
6028 * should be indented
6030 int ind_cpp_baseclass
= curbuf
->b_p_sw
;
6033 * additional spaces beyond the prevailing indent a continuation line
6036 int ind_continuation
= curbuf
->b_p_sw
;
6039 * spaces from the indent of the line with an unclosed parentheses
6041 int ind_unclosed
= curbuf
->b_p_sw
* 2;
6044 * spaces from the indent of the line with an unclosed parentheses, which
6045 * itself is also unclosed
6047 int ind_unclosed2
= curbuf
->b_p_sw
;
6050 * suppress ignoring spaces from the indent of a line starting with an
6051 * unclosed parentheses.
6053 int ind_unclosed_noignore
= 0;
6056 * If the opening paren is the last nonwhite character on the line, and
6057 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6058 * context (for very long lines).
6060 int ind_unclosed_wrapped
= 0;
6063 * suppress ignoring white space when lining up with the character after
6064 * an unclosed parentheses.
6066 int ind_unclosed_whiteok
= 0;
6069 * indent a closing parentheses under the line start of the matching
6070 * opening parentheses.
6072 int ind_matching_paren
= 0;
6075 * indent a closing parentheses under the previous line.
6077 int ind_paren_prev
= 0;
6080 * Extra indent for comments.
6082 int ind_comment
= 0;
6085 * spaces from the comment opener when there is nothing after it.
6087 int ind_in_comment
= 3;
6090 * boolean: if non-zero, use ind_in_comment even if there is something
6091 * after the comment opener.
6093 int ind_in_comment2
= 0;
6096 * max lines to search for an open paren
6098 int ind_maxparen
= 20;
6101 * max lines to search for an open comment
6103 int ind_maxcomment
= 70;
6106 * handle braces for java code
6111 * handle blocked cases correctly
6113 int ind_keep_case_label
= 0;
6118 int cur_amount
= MAXCOL
;
6123 pos_T
*tryposBrace
= NULL
;
6124 pos_T our_paren_pos
;
6127 #define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
6128 #define BRACE_AT_START 2 /* '{' is at start of line */
6129 #define BRACE_AT_END 3 /* '{' is at end of line */
6135 #define LOOKFOR_INITIAL 0
6136 #define LOOKFOR_IF 1
6137 #define LOOKFOR_DO 2
6138 #define LOOKFOR_CASE 3
6139 #define LOOKFOR_ANY 4
6140 #define LOOKFOR_TERM 5
6141 #define LOOKFOR_UNTERM 6
6142 #define LOOKFOR_SCOPEDECL 7
6143 #define LOOKFOR_NOBREAK 8
6144 #define LOOKFOR_CPP_BASECLASS 9
6145 #define LOOKFOR_ENUM_OR_INIT 10
6150 int fraction
= 0; /* init for GCC */
6155 int cont_amount
= 0; /* amount for continuation line */
6157 for (options
= curbuf
->b_p_cino
; *options
; )
6160 if (*options
== '-')
6162 n
= getdigits(&options
);
6164 if (*options
== '.') /* ".5s" means a fraction */
6166 fraction
= atol((char *)++options
);
6167 while (VIM_ISDIGIT(*options
))
6176 if (*options
== 's') /* "2s" means two times 'shiftwidth' */
6178 if (n
== 0 && fraction
== 0)
6179 n
= curbuf
->b_p_sw
; /* just "s" is one 'shiftwidth' */
6182 n
*= curbuf
->b_p_sw
;
6184 n
+= (curbuf
->b_p_sw
* fraction
+ divider
/ 2) / divider
;
6190 /* When adding an entry here, also update the default 'cinoptions' in
6191 * doc/indent.txt, and add explanation for it! */
6194 case '>': ind_level
= n
; break;
6195 case 'e': ind_open_imag
= n
; break;
6196 case 'n': ind_no_brace
= n
; break;
6197 case 'f': ind_first_open
= n
; break;
6198 case '{': ind_open_extra
= n
; break;
6199 case '}': ind_close_extra
= n
; break;
6200 case '^': ind_open_left_imag
= n
; break;
6201 case ':': ind_case
= n
; break;
6202 case '=': ind_case_code
= n
; break;
6203 case 'b': ind_case_break
= n
; break;
6204 case 'p': ind_param
= n
; break;
6205 case 't': ind_func_type
= n
; break;
6206 case '/': ind_comment
= n
; break;
6207 case 'c': ind_in_comment
= n
; break;
6208 case 'C': ind_in_comment2
= n
; break;
6209 case 'i': ind_cpp_baseclass
= n
; break;
6210 case '+': ind_continuation
= n
; break;
6211 case '(': ind_unclosed
= n
; break;
6212 case 'u': ind_unclosed2
= n
; break;
6213 case 'U': ind_unclosed_noignore
= n
; break;
6214 case 'W': ind_unclosed_wrapped
= n
; break;
6215 case 'w': ind_unclosed_whiteok
= n
; break;
6216 case 'm': ind_matching_paren
= n
; break;
6217 case 'M': ind_paren_prev
= n
; break;
6218 case ')': ind_maxparen
= n
; break;
6219 case '*': ind_maxcomment
= n
; break;
6220 case 'g': ind_scopedecl
= n
; break;
6221 case 'h': ind_scopedecl_code
= n
; break;
6222 case 'j': ind_java
= n
; break;
6223 case 'l': ind_keep_case_label
= n
; break;
6224 case '#': ind_hash_comment
= n
; break;
6228 /* remember where the cursor was when we started */
6229 cur_curpos
= curwin
->w_cursor
;
6231 /* Get a copy of the current contents of the line.
6232 * This is required, because only the most recent line obtained with
6233 * ml_get is valid! */
6234 linecopy
= vim_strsave(ml_get(cur_curpos
.lnum
));
6235 if (linecopy
== NULL
)
6239 * In insert mode and the cursor is on a ')' truncate the line at the
6240 * cursor position. We don't want to line up with the matching '(' when
6241 * inserting new stuff.
6242 * For unknown reasons the cursor might be past the end of the line, thus
6245 if ((State
& INSERT
)
6246 && curwin
->w_cursor
.col
< STRLEN(linecopy
)
6247 && linecopy
[curwin
->w_cursor
.col
] == ')')
6248 linecopy
[curwin
->w_cursor
.col
] = NUL
;
6250 theline
= skipwhite(linecopy
);
6252 /* move the cursor to the start of the line */
6254 curwin
->w_cursor
.col
= 0;
6257 * #defines and so on always go at the left when included in 'cinkeys'.
6259 if (*theline
== '#' && (*linecopy
== '#' || in_cinkeys('#', ' ', TRUE
)))
6265 * Is it a non-case label? Then that goes at the left margin too.
6267 else if (cin_islabel(ind_maxcomment
)) /* XXX */
6273 * If we're inside a "//" comment and there is a "//" comment in a
6274 * previous line, lineup with that one.
6276 else if (cin_islinecomment(theline
)
6277 && (trypos
= find_line_comment()) != NULL
) /* XXX */
6279 /* find how indented the line beginning the comment is */
6280 getvcol(curwin
, trypos
, &col
, NULL
, NULL
);
6285 * If we're inside a comment and not looking at the start of the
6286 * comment, try using the 'comments' option.
6288 else if (!cin_iscomment(theline
)
6289 && (trypos
= find_start_comment(ind_maxcomment
)) != NULL
) /* XXX */
6291 int lead_start_len
= 2;
6292 int lead_middle_len
= 1;
6293 char_u lead_start
[COM_MAX_LEN
]; /* start-comment string */
6294 char_u lead_middle
[COM_MAX_LEN
]; /* middle-comment string */
6295 char_u lead_end
[COM_MAX_LEN
]; /* end-comment string */
6297 int start_align
= 0;
6301 /* find how indented the line beginning the comment is */
6302 getvcol(curwin
, trypos
, &col
, NULL
, NULL
);
6305 p
= curbuf
->b_p_com
;
6312 while (*p
!= NUL
&& *p
!= ':')
6314 if (*p
== COM_START
|| *p
== COM_END
|| *p
== COM_MIDDLE
)
6316 else if (*p
== COM_LEFT
|| *p
== COM_RIGHT
)
6318 else if (VIM_ISDIGIT(*p
) || *p
== '-')
6319 off
= getdigits(&p
);
6326 (void)copy_option_part(&p
, lead_end
, COM_MAX_LEN
, ",");
6327 if (what
== COM_START
)
6329 STRCPY(lead_start
, lead_end
);
6330 lead_start_len
= (int)STRLEN(lead_start
);
6332 start_align
= align
;
6334 else if (what
== COM_MIDDLE
)
6336 STRCPY(lead_middle
, lead_end
);
6337 lead_middle_len
= (int)STRLEN(lead_middle
);
6339 else if (what
== COM_END
)
6341 /* If our line starts with the middle comment string, line it
6342 * up with the comment opener per the 'comments' option. */
6343 if (STRNCMP(theline
, lead_middle
, lead_middle_len
) == 0
6344 && STRNCMP(theline
, lead_end
, STRLEN(lead_end
)) != 0)
6347 if (curwin
->w_cursor
.lnum
> 1)
6349 /* If the start comment string matches in the previous
6350 * line, use the indent of that line pluss offset. If
6351 * the middle comment string matches in the previous
6352 * line, use the indent of that line. XXX */
6353 look
= skipwhite(ml_get(curwin
->w_cursor
.lnum
- 1));
6354 if (STRNCMP(look
, lead_start
, lead_start_len
) == 0)
6355 amount
= get_indent_lnum(curwin
->w_cursor
.lnum
- 1);
6356 else if (STRNCMP(look
, lead_middle
,
6357 lead_middle_len
) == 0)
6359 amount
= get_indent_lnum(curwin
->w_cursor
.lnum
- 1);
6362 /* If the start comment string doesn't match with the
6363 * start of the comment, skip this entry. XXX */
6364 else if (STRNCMP(ml_get(trypos
->lnum
) + trypos
->col
,
6365 lead_start
, lead_start_len
) != 0)
6369 amount
+= start_off
;
6370 else if (start_align
== COM_RIGHT
)
6371 amount
+= vim_strsize(lead_start
)
6372 - vim_strsize(lead_middle
);
6376 /* If our line starts with the end comment string, line it up
6377 * with the middle comment */
6378 if (STRNCMP(theline
, lead_middle
, lead_middle_len
) != 0
6379 && STRNCMP(theline
, lead_end
, STRLEN(lead_end
)) == 0)
6381 amount
= get_indent_lnum(curwin
->w_cursor
.lnum
- 1);
6385 else if (align
== COM_RIGHT
)
6386 amount
+= vim_strsize(lead_start
)
6387 - vim_strsize(lead_middle
);
6394 /* If our line starts with an asterisk, line up with the
6395 * asterisk in the comment opener; otherwise, line up
6396 * with the first character of the comment text.
6400 else if (theline
[0] == '*')
6405 * If we are more than one line away from the comment opener, take
6406 * the indent of the previous non-empty line. If 'cino' has "CO"
6407 * and we are just below the comment opener and there are any
6408 * white characters after it line up with the text after it;
6409 * otherwise, add the amount specified by "c" in 'cino'
6412 for (lnum
= cur_curpos
.lnum
- 1; lnum
> trypos
->lnum
; --lnum
)
6414 if (linewhite(lnum
)) /* skip blank lines */
6416 amount
= get_indent_lnum(lnum
); /* XXX */
6419 if (amount
== -1) /* use the comment opener */
6421 if (!ind_in_comment2
)
6423 start
= ml_get(trypos
->lnum
);
6424 look
= start
+ trypos
->col
+ 2; /* skip / and * */
6425 if (*look
!= NUL
) /* if something after it */
6426 trypos
->col
= (colnr_T
)(skipwhite(look
) - start
);
6428 getvcol(curwin
, trypos
, &col
, NULL
, NULL
);
6430 if (ind_in_comment2
|| *look
== NUL
)
6431 amount
+= ind_in_comment
;
6437 * Are we inside parentheses or braces?
6439 else if (((trypos
= find_match_paren(ind_maxparen
, ind_maxcomment
)) != NULL
6441 || (tryposBrace
= find_start_brace(ind_maxcomment
)) != NULL
6444 if (trypos
!= NULL
&& tryposBrace
!= NULL
)
6446 /* Both an unmatched '(' and '{' is found. Use the one which is
6447 * closer to the current cursor position, set the other to NULL. */
6448 if (trypos
->lnum
!= tryposBrace
->lnum
6449 ? trypos
->lnum
< tryposBrace
->lnum
6450 : trypos
->col
< tryposBrace
->col
)
6459 * If the matching paren is more than one line away, use the indent of
6460 * a previous non-empty line that matches the same paren.
6462 if (theline
[0] == ')' && ind_paren_prev
)
6464 /* Line up with the start of the matching paren line. */
6465 amount
= get_indent_lnum(curwin
->w_cursor
.lnum
- 1); /* XXX */
6470 our_paren_pos
= *trypos
;
6471 for (lnum
= cur_curpos
.lnum
- 1; lnum
> our_paren_pos
.lnum
; --lnum
)
6473 l
= skipwhite(ml_get(lnum
));
6474 if (cin_nocode(l
)) /* skip comment lines */
6476 if (cin_ispreproc_cont(&l
, &lnum
))
6477 continue; /* ignore #define, #if, etc. */
6478 curwin
->w_cursor
.lnum
= lnum
;
6480 /* Skip a comment. XXX */
6481 if ((trypos
= find_start_comment(ind_maxcomment
)) != NULL
)
6483 lnum
= trypos
->lnum
+ 1;
6488 if ((trypos
= find_match_paren(
6489 corr_ind_maxparen(ind_maxparen
, &cur_curpos
),
6490 ind_maxcomment
)) != NULL
6491 && trypos
->lnum
== our_paren_pos
.lnum
6492 && trypos
->col
== our_paren_pos
.col
)
6494 amount
= get_indent_lnum(lnum
); /* XXX */
6496 if (theline
[0] == ')')
6498 if (our_paren_pos
.lnum
!= lnum
6499 && cur_amount
> amount
)
6500 cur_amount
= amount
;
6509 * Line up with line where the matching paren is. XXX
6510 * If the line starts with a '(' or the indent for unclosed
6511 * parentheses is zero, line up with the unclosed parentheses.
6515 int ignore_paren_col
= 0;
6517 amount
= skip_label(our_paren_pos
.lnum
, &look
, ind_maxcomment
);
6518 look
= skipwhite(look
);
6521 linenr_T save_lnum
= curwin
->w_cursor
.lnum
;
6525 /* Ignore a '(' in front of the line that has a match before
6526 * our matching '('. */
6527 curwin
->w_cursor
.lnum
= our_paren_pos
.lnum
;
6528 line
= ml_get_curline();
6529 look_col
= (int)(look
- line
);
6530 curwin
->w_cursor
.col
= look_col
+ 1;
6531 if ((trypos
= findmatchlimit(NULL
, ')', 0, ind_maxparen
))
6533 && trypos
->lnum
== our_paren_pos
.lnum
6534 && trypos
->col
< our_paren_pos
.col
)
6535 ignore_paren_col
= trypos
->col
+ 1;
6537 curwin
->w_cursor
.lnum
= save_lnum
;
6538 look
= ml_get(our_paren_pos
.lnum
) + look_col
;
6540 if (theline
[0] == ')' || ind_unclosed
== 0
6541 || (!ind_unclosed_noignore
&& *look
== '('
6542 && ignore_paren_col
== 0))
6545 * If we're looking at a close paren, line up right there;
6546 * otherwise, line up with the next (non-white) character.
6547 * When ind_unclosed_wrapped is set and the matching paren is
6548 * the last nonwhite character of the line, use either the
6549 * indent of the current line or the indentation of the next
6550 * outer paren and add ind_unclosed_wrapped (for very long
6553 if (theline
[0] != ')')
6555 cur_amount
= MAXCOL
;
6556 l
= ml_get(our_paren_pos
.lnum
);
6557 if (ind_unclosed_wrapped
6558 && cin_ends_in(l
, (char_u
*)"(", NULL
))
6560 /* look for opening unmatched paren, indent one level
6561 * for each additional level */
6563 for (col
= 0; col
< our_paren_pos
.col
; ++col
)
6572 case '}': if (n
> 1)
6578 our_paren_pos
.col
= 0;
6579 amount
+= n
* ind_unclosed_wrapped
;
6581 else if (ind_unclosed_whiteok
)
6582 our_paren_pos
.col
++;
6585 col
= our_paren_pos
.col
+ 1;
6586 while (vim_iswhite(l
[col
]))
6588 if (l
[col
] != NUL
) /* In case of trailing space */
6589 our_paren_pos
.col
= col
;
6591 our_paren_pos
.col
++;
6596 * Find how indented the paren is, or the character after it
6597 * if we did the above "if".
6599 if (our_paren_pos
.col
> 0)
6601 getvcol(curwin
, &our_paren_pos
, &col
, NULL
, NULL
);
6602 if (cur_amount
> (int)col
)
6607 if (theline
[0] == ')' && ind_matching_paren
)
6609 /* Line up with the start of the matching paren line. */
6611 else if (ind_unclosed
== 0 || (!ind_unclosed_noignore
6612 && *look
== '(' && ignore_paren_col
== 0))
6614 if (cur_amount
!= MAXCOL
)
6615 amount
= cur_amount
;
6619 /* Add ind_unclosed2 for each '(' before our matching one, but
6620 * ignore (void) before the line (ignore_paren_col). */
6621 col
= our_paren_pos
.col
;
6622 while ((int)our_paren_pos
.col
> ignore_paren_col
)
6624 --our_paren_pos
.col
;
6625 switch (*ml_get_pos(&our_paren_pos
))
6627 case '(': amount
+= ind_unclosed2
;
6628 col
= our_paren_pos
.col
;
6630 case ')': amount
-= ind_unclosed2
;
6636 /* Use ind_unclosed once, when the first '(' is not inside
6639 amount
+= ind_unclosed
;
6642 curwin
->w_cursor
.lnum
= our_paren_pos
.lnum
;
6643 curwin
->w_cursor
.col
= col
;
6644 if ((trypos
= find_match_paren(ind_maxparen
,
6645 ind_maxcomment
)) != NULL
)
6646 amount
+= ind_unclosed2
;
6648 amount
+= ind_unclosed
;
6651 * For a line starting with ')' use the minimum of the two
6652 * positions, to avoid giving it more indent than the previous
6654 * func_long_name( if (x
6656 * ) ^ not here ) ^ not here
6658 if (cur_amount
< amount
)
6659 amount
= cur_amount
;
6663 /* add extra indent for a comment */
6664 if (cin_iscomment(theline
))
6665 amount
+= ind_comment
;
6669 * Are we at least inside braces, then?
6673 trypos
= tryposBrace
;
6675 ourscope
= trypos
->lnum
;
6676 start
= ml_get(ourscope
);
6679 * Now figure out how indented the line is in general.
6680 * If the brace was at the start of the line, we use that;
6681 * otherwise, check out the indentation of the line as
6682 * a whole and then add the "imaginary indent" to that.
6684 look
= skipwhite(start
);
6687 getvcol(curwin
, trypos
, &col
, NULL
, NULL
);
6690 start_brace
= BRACE_IN_COL0
;
6692 start_brace
= BRACE_AT_START
;
6697 * that opening brace might have been on a continuation
6698 * line. if so, find the start of the line.
6700 curwin
->w_cursor
.lnum
= ourscope
;
6703 * position the cursor over the rightmost paren, so that
6704 * matching it will take us back to the start of the line.
6707 if (find_last_paren(start
, '(', ')')
6708 && (trypos
= find_match_paren(ind_maxparen
,
6709 ind_maxcomment
)) != NULL
)
6710 lnum
= trypos
->lnum
;
6713 * It could have been something like
6714 * case 1: if (asdf &&
6718 if (ind_keep_case_label
&& cin_iscase(skipwhite(ml_get_curline())))
6719 amount
= get_indent();
6721 amount
= skip_label(lnum
, &l
, ind_maxcomment
);
6723 start_brace
= BRACE_AT_END
;
6727 * if we're looking at a closing brace, that's where
6728 * we want to be. otherwise, add the amount of room
6729 * that an indent is supposed to be.
6731 if (theline
[0] == '}')
6734 * they may want closing braces to line up with something
6735 * other than the open brace. indulge them, if so.
6737 amount
+= ind_close_extra
;
6742 * If we're looking at an "else", try to find an "if"
6744 * If we're looking at a "while", try to find a "do"
6747 lookfor
= LOOKFOR_INITIAL
;
6748 if (cin_iselse(theline
))
6749 lookfor
= LOOKFOR_IF
;
6750 else if (cin_iswhileofdo(theline
, cur_curpos
.lnum
, ind_maxparen
))
6752 lookfor
= LOOKFOR_DO
;
6753 if (lookfor
!= LOOKFOR_INITIAL
)
6755 curwin
->w_cursor
.lnum
= cur_curpos
.lnum
;
6756 if (find_match(lookfor
, ourscope
, ind_maxparen
,
6757 ind_maxcomment
) == OK
)
6759 amount
= get_indent(); /* XXX */
6765 * We get here if we are not on an "while-of-do" or "else" (or
6766 * failed to find a matching "if").
6767 * Search backwards for something to line up with.
6768 * First set amount for when we don't find anything.
6772 * if the '{' is _really_ at the left margin, use the imaginary
6773 * location of a left-margin brace. Otherwise, correct the
6774 * location for ind_open_extra.
6777 if (start_brace
== BRACE_IN_COL0
) /* '{' is in column 0 */
6779 amount
= ind_open_left_imag
;
6783 if (start_brace
== BRACE_AT_END
) /* '{' is at end of line */
6784 amount
+= ind_open_imag
;
6787 /* Compensate for adding ind_open_extra later. */
6788 amount
-= ind_open_extra
;
6794 lookfor_break
= FALSE
;
6796 if (cin_iscase(theline
)) /* it's a switch() label */
6798 lookfor
= LOOKFOR_CASE
; /* find a previous switch() label */
6801 else if (cin_isscopedecl(theline
)) /* private:, ... */
6803 lookfor
= LOOKFOR_SCOPEDECL
; /* class decl is this block */
6804 amount
+= ind_scopedecl
;
6808 if (ind_case_break
&& cin_isbreak(theline
)) /* break; ... */
6809 lookfor_break
= TRUE
;
6811 lookfor
= LOOKFOR_INITIAL
;
6812 amount
+= ind_level
; /* ind_level from start of block */
6814 scope_amount
= amount
;
6818 * Search backwards. If we find something we recognize, line up
6821 * if we're looking at an open brace, indent
6822 * the usual amount relative to the conditional
6823 * that opens the block.
6825 curwin
->w_cursor
= cur_curpos
;
6828 curwin
->w_cursor
.lnum
--;
6829 curwin
->w_cursor
.col
= 0;
6832 * If we went all the way back to the start of our scope, line
6835 if (curwin
->w_cursor
.lnum
<= ourscope
)
6837 /* we reached end of scope:
6838 * if looking for a enum or structure initialization
6840 * if it is an initializer (enum xxx or xxx =), then
6841 * don't add ind_continuation, otherwise it is a variable
6844 * here; <-- add ind_continuation
6846 if (lookfor
== LOOKFOR_ENUM_OR_INIT
)
6848 if (curwin
->w_cursor
.lnum
== 0
6849 || curwin
->w_cursor
.lnum
6850 < ourscope
- ind_maxparen
)
6852 /* nothing found (abuse ind_maxparen as limit)
6853 * assume terminated line (i.e. a variable
6854 * initialization) */
6855 if (cont_amount
> 0)
6856 amount
= cont_amount
;
6858 amount
+= ind_continuation
;
6862 l
= ml_get_curline();
6865 * If we're in a comment now, skip to the start of the
6868 trypos
= find_start_comment(ind_maxcomment
);
6871 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
6876 * Skip preprocessor directives and blank lines.
6878 if (cin_ispreproc_cont(&l
, &curwin
->w_cursor
.lnum
))
6884 terminated
= cin_isterminated(l
, FALSE
, TRUE
);
6887 * If we are at top level and the line looks like a
6888 * function declaration, we are done
6889 * (it's a variable declaration).
6891 if (start_brace
!= BRACE_IN_COL0
6892 || !cin_isfuncdecl(&l
, curwin
->w_cursor
.lnum
))
6894 /* if the line is terminated with another ','
6895 * it is a continued variable initialization.
6896 * don't add extra indent.
6897 * TODO: does not work, if a function
6898 * declaration is split over multiple lines:
6899 * cin_isfuncdecl returns FALSE then.
6901 if (terminated
== ',')
6904 /* if it es a enum declaration or an assignment,
6907 if (terminated
!= ';' && cin_isinit())
6910 /* nothing useful found */
6911 if (terminated
== 0 || terminated
== '{')
6915 if (terminated
!= ';')
6917 /* Skip parens and braces. Position the cursor
6918 * over the rightmost paren, so that matching it
6919 * will take us back to the start of the line.
6922 if (find_last_paren(l
, '(', ')'))
6923 trypos
= find_match_paren(ind_maxparen
,
6926 if (trypos
== NULL
&& find_last_paren(l
, '{', '}'))
6927 trypos
= find_start_brace(ind_maxcomment
);
6931 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
6936 /* it's a variable declaration, add indentation
6941 if (cont_amount
> 0)
6942 amount
= cont_amount
;
6944 amount
+= ind_continuation
;
6946 else if (lookfor
== LOOKFOR_UNTERM
)
6948 if (cont_amount
> 0)
6949 amount
= cont_amount
;
6951 amount
+= ind_continuation
;
6953 else if (lookfor
!= LOOKFOR_TERM
6954 && lookfor
!= LOOKFOR_CPP_BASECLASS
)
6956 amount
= scope_amount
;
6957 if (theline
[0] == '{')
6958 amount
+= ind_open_extra
;
6964 * If we're in a comment now, skip to the start of the comment.
6966 if ((trypos
= find_start_comment(ind_maxcomment
)) != NULL
)
6968 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
6972 l
= ml_get_curline();
6975 * If this is a switch() label, may line up relative to that.
6976 * If this is a C++ scope declaration, do the same.
6978 iscase
= cin_iscase(l
);
6979 if (iscase
|| cin_isscopedecl(l
))
6981 /* we are only looking for cpp base class
6982 * declaration/initialization any longer */
6983 if (lookfor
== LOOKFOR_CPP_BASECLASS
)
6986 /* When looking for a "do" we are not interested in
6993 * c = 99 + <- this indent plus continuation
6996 if (lookfor
== LOOKFOR_UNTERM
6997 || lookfor
== LOOKFOR_ENUM_OR_INIT
)
6999 if (cont_amount
> 0)
7000 amount
= cont_amount
;
7002 amount
+= ind_continuation
;
7007 * case xx: <- line up with this case
7011 if ( (iscase
&& lookfor
== LOOKFOR_CASE
)
7012 || (iscase
&& lookfor_break
)
7013 || (!iscase
&& lookfor
== LOOKFOR_SCOPEDECL
))
7016 * Check that this case label is not for another
7019 if ((trypos
= find_start_brace(ind_maxcomment
)) ==
7020 NULL
|| trypos
->lnum
== ourscope
)
7022 amount
= get_indent(); /* XXX */
7028 n
= get_indent_nolabel(curwin
->w_cursor
.lnum
); /* XXX */
7031 * case xx: if (cond) <- line up with this if
7036 * if (cond) <- line up with this line
7040 if (lookfor
== LOOKFOR_TERM
)
7050 * case xx: x = x + 1; <- line up with this x
7053 * case xx: if (cond) <- line up with this if
7059 l
= after_label(ml_get_curline());
7060 if (l
!= NULL
&& cin_is_cinword(l
))
7062 if (theline
[0] == '{')
7063 amount
+= ind_open_extra
;
7065 amount
+= ind_level
+ ind_no_brace
;
7071 * Try to get the indent of a statement before the switch
7072 * label. If nothing is found, line up relative to the
7074 * break; <- may line up with this line
7078 scope_amount
= get_indent() + (iscase
/* XXX */
7079 ? ind_case_code
: ind_scopedecl_code
);
7080 lookfor
= ind_case_break
? LOOKFOR_NOBREAK
: LOOKFOR_ANY
;
7085 * Looking for a switch() label or C++ scope declaration,
7086 * ignore other lines, skip {}-blocks.
7088 if (lookfor
== LOOKFOR_CASE
|| lookfor
== LOOKFOR_SCOPEDECL
)
7090 if (find_last_paren(l
, '{', '}') && (trypos
=
7091 find_start_brace(ind_maxcomment
)) != NULL
)
7092 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
7097 * Ignore jump labels with nothing after them.
7099 if (cin_islabel(ind_maxcomment
))
7101 l
= after_label(ml_get_curline());
7102 if (l
== NULL
|| cin_nocode(l
))
7107 * Ignore #defines, #if, etc.
7108 * Ignore comment and empty lines.
7109 * (need to get the line again, cin_islabel() may have
7112 l
= ml_get_curline();
7113 if (cin_ispreproc_cont(&l
, &curwin
->w_cursor
.lnum
)
7118 * Are we at the start of a cpp base class declaration or
7119 * constructor initialization?
7122 if (lookfor
!= LOOKFOR_TERM
&& ind_cpp_baseclass
> 0)
7124 n
= cin_is_cpp_baseclass(&col
);
7125 l
= ml_get_curline();
7129 if (lookfor
== LOOKFOR_UNTERM
)
7131 if (cont_amount
> 0)
7132 amount
= cont_amount
;
7134 amount
+= ind_continuation
;
7136 else if (theline
[0] == '{')
7138 /* Need to find start of the declaration. */
7139 lookfor
= LOOKFOR_UNTERM
;
7140 ind_continuation
= 0;
7145 amount
= get_baseclass_amount(col
, ind_maxparen
,
7146 ind_maxcomment
, ind_cpp_baseclass
);
7149 else if (lookfor
== LOOKFOR_CPP_BASECLASS
)
7151 /* only look, whether there is a cpp base class
7152 * declaration or initialization before the opening brace.
7154 if (cin_isterminated(l
, TRUE
, FALSE
))
7161 * What happens next depends on the line being terminated.
7162 * If terminated with a ',' only consider it terminating if
7163 * there is another unterminated statement behind, eg:
7167 * Otherwise check whether it is a enumeration or structure
7168 * initialisation (not indented) or a variable declaration
7171 terminated
= cin_isterminated(l
, FALSE
, TRUE
);
7173 if (terminated
== 0 || (lookfor
!= LOOKFOR_UNTERM
7174 && terminated
== ','))
7177 * if we're in the middle of a paren thing,
7178 * go back to the line that starts it so
7179 * we can get the right prevailing indent
7184 * position the cursor over the rightmost paren, so that
7185 * matching it will take us back to the start of the line.
7187 (void)find_last_paren(l
, '(', ')');
7188 trypos
= find_match_paren(
7189 corr_ind_maxparen(ind_maxparen
, &cur_curpos
),
7193 * If we are looking for ',', we also look for matching
7196 if (trypos
== NULL
&& terminated
== ','
7197 && find_last_paren(l
, '{', '}'))
7198 trypos
= find_start_brace(ind_maxcomment
);
7203 * Check if we are on a case label now. This is
7205 * case xx: if ( asdf &&
7208 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7209 l
= ml_get_curline();
7210 if (cin_iscase(l
) || cin_isscopedecl(l
))
7212 ++curwin
->w_cursor
.lnum
;
7218 * Skip over continuation lines to find the one to get the
7220 * char *usethis = "bla\
7224 if (terminated
== ',')
7226 while (curwin
->w_cursor
.lnum
> 1)
7228 l
= ml_get(curwin
->w_cursor
.lnum
- 1);
7229 if (*l
== NUL
|| l
[STRLEN(l
) - 1] != '\\')
7231 --curwin
->w_cursor
.lnum
;
7236 * Get indent and pointer to text for current line,
7237 * ignoring any jump label. XXX
7239 cur_amount
= skip_label(curwin
->w_cursor
.lnum
,
7240 &l
, ind_maxcomment
);
7243 * If this is just above the line we are indenting, and it
7244 * starts with a '{', line it up with this line.
7249 if (terminated
!= ',' && lookfor
!= LOOKFOR_TERM
7250 && theline
[0] == '{')
7252 amount
= cur_amount
;
7254 * Only add ind_open_extra when the current line
7255 * doesn't start with a '{', which must have a match
7256 * in the same line (scope is the same). Probably:
7260 if (*skipwhite(l
) != '{')
7261 amount
+= ind_open_extra
;
7263 if (ind_cpp_baseclass
)
7265 /* have to look back, whether it is a cpp base
7266 * class declaration or initialization */
7267 lookfor
= LOOKFOR_CPP_BASECLASS
;
7274 * Check if we are after an "if", "while", etc.
7275 * Also allow " } else".
7277 if (cin_is_cinword(l
) || cin_iselse(skipwhite(l
)))
7280 * Found an unterminated line after an if (), line up
7281 * with the last one.
7286 if (lookfor
== LOOKFOR_UNTERM
7287 || lookfor
== LOOKFOR_ENUM_OR_INIT
)
7289 if (cont_amount
> 0)
7290 amount
= cont_amount
;
7292 amount
+= ind_continuation
;
7297 * If this is just above the line we are indenting, we
7301 * Otherwise this indent can be used when the line
7302 * before this is terminated.
7309 amount
= cur_amount
;
7310 if (theline
[0] == '{')
7311 amount
+= ind_open_extra
;
7312 if (lookfor
!= LOOKFOR_TERM
)
7314 amount
+= ind_level
+ ind_no_brace
;
7319 * Special trick: when expecting the while () after a
7320 * do, line up with the while()
7325 l
= skipwhite(ml_get_curline());
7328 if (whilelevel
== 0)
7334 * When searching for a terminated line, don't use the
7335 * one between the "if" and the "else".
7336 * Need to use the scope of this "else". XXX
7337 * If whilelevel != 0 continue looking for a "do {".
7341 && ((trypos
= find_start_brace(ind_maxcomment
))
7343 || find_match(LOOKFOR_IF
, trypos
->lnum
,
7344 ind_maxparen
, ind_maxcomment
) == FAIL
))
7349 * If we're below an unterminated line that is not an
7350 * "if" or something, we may line up with this line or
7351 * add something for a continuation line, depending on
7352 * the line before this one.
7357 * Found two unterminated lines on a row, line up with
7363 if (lookfor
== LOOKFOR_UNTERM
)
7365 /* When line ends in a comma add extra indent */
7366 if (terminated
== ',')
7367 amount
+= ind_continuation
;
7371 if (lookfor
== LOOKFOR_ENUM_OR_INIT
)
7373 /* Found two lines ending in ',', lineup with the
7374 * lowest one, but check for cpp base class
7375 * declaration/initialization, if it is an
7376 * opening brace or we are looking just for
7377 * enumerations/initializations. */
7378 if (terminated
== ',')
7380 if (ind_cpp_baseclass
== 0)
7383 lookfor
= LOOKFOR_CPP_BASECLASS
;
7387 /* Ignore unterminated lines in between, but
7389 if (amount
> cur_amount
)
7390 amount
= cur_amount
;
7395 * Found first unterminated line on a row, may
7396 * line up with this line, remember its indent
7400 amount
= cur_amount
;
7403 * If previous line ends in ',', check whether we
7404 * are in an initialization or enum
7409 * or a normal possible continuation line.
7410 * but only, of no other statement has been found
7413 if (lookfor
== LOOKFOR_INITIAL
&& terminated
== ',')
7415 lookfor
= LOOKFOR_ENUM_OR_INIT
;
7416 cont_amount
= cin_first_id_amount();
7420 if (lookfor
== LOOKFOR_INITIAL
7422 && l
[STRLEN(l
) - 1] == '\\')
7424 cont_amount
= cin_get_equal_amount(
7425 curwin
->w_cursor
.lnum
);
7426 if (lookfor
!= LOOKFOR_TERM
)
7427 lookfor
= LOOKFOR_UNTERM
;
7434 * Check if we are after a while (cond);
7435 * If so: Ignore until the matching "do".
7438 else if (cin_iswhileofdo_end(terminated
, ind_maxparen
,
7442 * Found an unterminated line after a while ();, line up
7443 * with the last one.
7445 * 100 + <- line up with this one
7448 if (lookfor
== LOOKFOR_UNTERM
7449 || lookfor
== LOOKFOR_ENUM_OR_INIT
)
7451 if (cont_amount
> 0)
7452 amount
= cont_amount
;
7454 amount
+= ind_continuation
;
7458 if (whilelevel
== 0)
7460 lookfor
= LOOKFOR_TERM
;
7461 amount
= get_indent(); /* XXX */
7462 if (theline
[0] == '{')
7463 amount
+= ind_open_extra
;
7469 * We are after a "normal" statement.
7470 * If we had another statement we can stop now and use the
7471 * indent of that other statement.
7472 * Otherwise the indent of the current statement may be used,
7473 * search backwards for the next "normal" statement.
7478 * Skip single break line, if before a switch label. It
7479 * may be lined up with the case label.
7481 if (lookfor
== LOOKFOR_NOBREAK
7482 && cin_isbreak(skipwhite(ml_get_curline())))
7484 lookfor
= LOOKFOR_ANY
;
7489 * Handle "do {" line.
7493 l
= cin_skipcomment(ml_get_curline());
7496 amount
= get_indent(); /* XXX */
7503 * Found a terminated line above an unterminated line. Add
7504 * the amount for a continuation line.
7513 if (lookfor
== LOOKFOR_UNTERM
7514 || lookfor
== LOOKFOR_ENUM_OR_INIT
)
7516 if (cont_amount
> 0)
7517 amount
= cont_amount
;
7519 amount
+= ind_continuation
;
7524 * Found a terminated line above a terminated line or "if"
7525 * etc. line. Use the amount of the line below us.
7528 * while (asdf) ->here;
7532 if (lookfor
== LOOKFOR_TERM
)
7534 if (!lookfor_break
&& whilelevel
== 0)
7539 * First line above the one we're indenting is terminated.
7540 * To know what needs to be done look further backward for
7541 * a terminated line.
7546 * position the cursor over the rightmost paren, so
7547 * that matching it will take us back to the start of
7548 * the line. Helps for:
7554 l
= ml_get_curline();
7555 if (find_last_paren(l
, '(', ')')
7556 && (trypos
= find_match_paren(ind_maxparen
,
7557 ind_maxcomment
)) != NULL
)
7560 * Check if we are on a case label now. This is
7562 * case xx: if ( asdf &&
7565 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7566 l
= ml_get_curline();
7567 if (cin_iscase(l
) || cin_isscopedecl(l
))
7569 ++curwin
->w_cursor
.lnum
;
7574 /* When aligning with the case statement, don't align
7575 * with a statement after it.
7576 * case 1: { <-- don't use this { position
7583 iscase
= (ind_keep_case_label
&& cin_iscase(l
));
7586 * Get indent and pointer to text for current line,
7587 * ignoring any jump label.
7589 amount
= skip_label(curwin
->w_cursor
.lnum
,
7590 &l
, ind_maxcomment
);
7592 if (theline
[0] == '{')
7593 amount
+= ind_open_extra
;
7594 /* See remark above: "Only add ind_open_extra.." */
7597 amount
-= ind_open_extra
;
7598 lookfor
= iscase
? LOOKFOR_ANY
: LOOKFOR_TERM
;
7601 * When a terminated line starts with "else" skip to
7602 * the matching "if":
7605 * Need to use the scope of this "else". XXX
7606 * If whilelevel != 0 continue looking for a "do {".
7608 if (lookfor
== LOOKFOR_TERM
7613 if ((trypos
= find_start_brace(ind_maxcomment
))
7615 || find_match(LOOKFOR_IF
, trypos
->lnum
,
7616 ind_maxparen
, ind_maxcomment
) == FAIL
)
7622 * If we're at the end of a block, skip to the start of
7625 curwin
->w_cursor
.col
= 0;
7626 if (*cin_skipcomment(l
) == '}'
7627 && (trypos
= find_start_brace(ind_maxcomment
))
7630 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7631 /* if not "else {" check for terminated again */
7632 /* but skip block for "} else {" */
7633 l
= cin_skipcomment(ml_get_curline());
7634 if (*l
== '}' || !cin_iselse(l
))
7636 ++curwin
->w_cursor
.lnum
;
7644 /* add extra indent for a comment */
7645 if (cin_iscomment(theline
))
7646 amount
+= ind_comment
;
7650 * ok -- we're not inside any sort of structure at all!
7652 * this means we're at the top level, and everything should
7653 * basically just match where the previous line is, except
7654 * for the lines immediately following a function declaration,
7655 * which are K&R-style parameters and need to be indented.
7660 * if our line starts with an open brace, forget about any
7661 * prevailing indent and make sure it looks like the start
7665 if (theline
[0] == '{')
7667 amount
= ind_first_open
;
7671 * If the NEXT line is a function declaration, the current
7672 * line needs to be indented as a function type spec.
7673 * Don't do this if the current line looks like a comment
7674 * or if the current line is terminated, ie. ends in ';'.
7676 else if (cur_curpos
.lnum
< curbuf
->b_ml
.ml_line_count
7677 && !cin_nocode(theline
)
7678 && !cin_ends_in(theline
, (char_u
*)":", NULL
)
7679 && !cin_ends_in(theline
, (char_u
*)",", NULL
)
7680 && cin_isfuncdecl(NULL
, cur_curpos
.lnum
+ 1)
7681 && !cin_isterminated(theline
, FALSE
, TRUE
))
7683 amount
= ind_func_type
;
7688 curwin
->w_cursor
= cur_curpos
;
7690 /* search backwards until we find something we recognize */
7692 while (curwin
->w_cursor
.lnum
> 1)
7694 curwin
->w_cursor
.lnum
--;
7695 curwin
->w_cursor
.col
= 0;
7697 l
= ml_get_curline();
7700 * If we're in a comment now, skip to the start of the comment.
7702 if ((trypos
= find_start_comment(ind_maxcomment
)) != NULL
)
7704 curwin
->w_cursor
.lnum
= trypos
->lnum
+ 1;
7709 * Are we at the start of a cpp base class declaration or
7710 * constructor initialization?
7713 if (ind_cpp_baseclass
!= 0 && theline
[0] != '{')
7715 n
= cin_is_cpp_baseclass(&col
);
7716 l
= ml_get_curline();
7721 amount
= get_baseclass_amount(col
, ind_maxparen
,
7722 ind_maxcomment
, ind_cpp_baseclass
);
7727 * Skip preprocessor directives and blank lines.
7729 if (cin_ispreproc_cont(&l
, &curwin
->w_cursor
.lnum
))
7736 * If the previous line ends in ',', use one level of
7740 * do this before checking for '}' in case of eg.
7748 if (cin_ends_in(l
, (char_u
*)",", NULL
)
7749 || (*l
!= NUL
&& (n
= l
[STRLEN(l
) - 1]) == '\\'))
7751 /* take us back to opening paren */
7752 if (find_last_paren(l
, '(', ')')
7753 && (trypos
= find_match_paren(ind_maxparen
,
7754 ind_maxcomment
)) != NULL
)
7755 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7757 /* For a line ending in ',' that is a continuation line go
7758 * back to the first line with a backslash:
7763 while (n
== 0 && curwin
->w_cursor
.lnum
> 1)
7765 l
= ml_get(curwin
->w_cursor
.lnum
- 1);
7766 if (*l
== NUL
|| l
[STRLEN(l
) - 1] != '\\')
7768 --curwin
->w_cursor
.lnum
;
7771 amount
= get_indent(); /* XXX */
7774 amount
= cin_first_id_amount();
7776 amount
= ind_continuation
;
7781 * If the line looks like a function declaration, and we're
7782 * not in a comment, put it the left margin.
7784 if (cin_isfuncdecl(NULL
, cur_curpos
.lnum
)) /* XXX */
7786 l
= ml_get_curline();
7789 * Finding the closing '}' of a previous function. Put
7790 * current line at the left margin. For when 'cino' has "fs".
7792 if (*skipwhite(l
) == '}')
7796 * If the previous line ends on '};' (maybe followed by
7797 * comments) align at column 0. For example:
7798 * char *string_array[] = { "foo",
7799 * / * x * / "b};ar" }; / * foobar * /
7801 if (cin_ends_in(l
, (char_u
*)"};", NULL
))
7805 * If the PREVIOUS line is a function declaration, the current
7806 * line (and the ones that follow) needs to be indented as
7809 if (cin_isfuncdecl(&l
, curwin
->w_cursor
.lnum
))
7816 * If the previous line ends in ';' and the line before the
7817 * previous line ends in ',' or '\', ident to column zero:
7822 if (cin_ends_in(l
, (char_u
*)";", NULL
))
7824 l
= ml_get(curwin
->w_cursor
.lnum
- 1);
7825 if (cin_ends_in(l
, (char_u
*)",", NULL
)
7826 || (*l
!= NUL
&& l
[STRLEN(l
) - 1] == '\\'))
7828 l
= ml_get_curline();
7832 * Doesn't look like anything interesting -- so just
7833 * use the indent of this line.
7835 * Position the cursor over the rightmost paren, so that
7836 * matching it will take us back to the start of the line.
7838 find_last_paren(l
, '(', ')');
7840 if ((trypos
= find_match_paren(ind_maxparen
,
7841 ind_maxcomment
)) != NULL
)
7842 curwin
->w_cursor
.lnum
= trypos
->lnum
;
7843 amount
= get_indent(); /* XXX */
7847 /* add extra indent for a comment */
7848 if (cin_iscomment(theline
))
7849 amount
+= ind_comment
;
7851 /* add extra indent if the previous line ended in a backslash:
7854 * char *foo = "asdf\
7857 if (cur_curpos
.lnum
> 1)
7859 l
= ml_get(cur_curpos
.lnum
- 1);
7860 if (*l
!= NUL
&& l
[STRLEN(l
) - 1] == '\\')
7862 cur_amount
= cin_get_equal_amount(cur_curpos
.lnum
- 1);
7864 amount
= cur_amount
;
7865 else if (cur_amount
== 0)
7866 amount
+= ind_continuation
;
7873 /* put the cursor back where it belongs */
7874 curwin
->w_cursor
= cur_curpos
;
7884 find_match(lookfor
, ourscope
, ind_maxparen
, ind_maxcomment
)
7896 if (lookfor
== LOOKFOR_IF
)
7907 curwin
->w_cursor
.col
= 0;
7909 while (curwin
->w_cursor
.lnum
> ourscope
+ 1)
7911 curwin
->w_cursor
.lnum
--;
7912 curwin
->w_cursor
.col
= 0;
7914 look
= cin_skipcomment(ml_get_curline());
7915 if (cin_iselse(look
)
7917 || cin_isdo(look
) /* XXX */
7918 || cin_iswhileofdo(look
, curwin
->w_cursor
.lnum
, ind_maxparen
))
7921 * if we've gone outside the braces entirely,
7922 * we must be out of scope...
7924 theirscope
= find_start_brace(ind_maxcomment
); /* XXX */
7925 if (theirscope
== NULL
)
7929 * and if the brace enclosing this is further
7930 * back than the one enclosing the else, we're
7933 if (theirscope
->lnum
< ourscope
)
7937 * and if they're enclosed in a *deeper* brace,
7938 * then we can ignore it because it's in a
7939 * different scope...
7941 if (theirscope
->lnum
> ourscope
)
7945 * if it was an "else" (that's not an "else if")
7946 * then we need to go back to another if, so
7947 * increment elselevel
7949 look
= cin_skipcomment(ml_get_curline());
7950 if (cin_iselse(look
))
7952 mightbeif
= cin_skipcomment(look
+ 4);
7953 if (!cin_isif(mightbeif
))
7959 * if it was a "while" then we need to go back to
7960 * another "do", so increment whilelevel. XXX
7962 if (cin_iswhileofdo(look
, curwin
->w_cursor
.lnum
, ind_maxparen
))
7968 /* If it's an "if" decrement elselevel */
7969 look
= cin_skipcomment(ml_get_curline());
7974 * When looking for an "if" ignore "while"s that
7977 if (elselevel
== 0 && lookfor
== LOOKFOR_IF
)
7981 /* If it's a "do" decrement whilelevel */
7986 * if we've used up all the elses, then
7987 * this must be the if that we want!
7988 * match the indent level of that if.
7990 if (elselevel
<= 0 && whilelevel
<= 0)
7999 # if defined(FEAT_EVAL) || defined(PROTO)
8001 * Get indent level from 'indentexpr'.
8009 int use_sandbox
= was_set_insecurely((char_u
*)"indentexpr",
8012 pos
= curwin
->w_cursor
;
8013 set_vim_var_nr(VV_LNUM
, curwin
->w_cursor
.lnum
);
8017 indent
= eval_to_number(curbuf
->b_p_inde
);
8022 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8023 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8027 curwin
->w_cursor
= pos
;
8031 /* If there is an error, just keep the current indent. */
8033 indent
= get_indent();
8039 #endif /* FEAT_CINDENT */
8041 #if defined(FEAT_LISP) || defined(PROTO)
8043 static int lisp_match
__ARGS((char_u
*p
));
8051 char_u
*word
= p_lispwords
;
8053 while (*word
!= NUL
)
8055 (void)copy_option_part(&word
, buf
, LSIZE
, ",");
8056 len
= (int)STRLEN(buf
);
8057 if (STRNCMP(buf
, p
, len
) == 0 && p
[len
] == ' ')
8064 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8065 * The incompatible newer method is quite a bit better at indenting
8066 * code in lisp-like languages than the traditional one; it's still
8067 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8070 * Findmatch() should be adapted for lisp, also to make showmatch
8071 * work correctly: now (v5.3) it seems all C/C++ oriented:
8072 * - it does not recognize the #\( and #\) notations as character literals
8073 * - it doesn't know about comments starting with a semicolon
8074 * - it incorrectly interprets '(' as a character literal
8075 * All this messes up get_lisp_indent in some rare cases.
8076 * Update from Sergey Khorev:
8077 * I tried to fix the first two issues.
8082 pos_T
*pos
, realpos
, paren
;
8087 int parencount
, quotecount
;
8090 /* Set vi_lisp to use the vi-compatible method */
8091 vi_lisp
= (vim_strchr(p_cpo
, CPO_LISP
) != NULL
);
8093 realpos
= curwin
->w_cursor
;
8094 curwin
->w_cursor
.col
= 0;
8096 if ((pos
= findmatch(NULL
, '(')) == NULL
)
8097 pos
= findmatch(NULL
, '[');
8101 pos
= findmatch(NULL
, '[');
8102 if (pos
== NULL
|| ltp(pos
, &paren
))
8107 /* Extra trick: Take the indent of the first previous non-white
8108 * line that is at the same () level. */
8112 while (--curwin
->w_cursor
.lnum
>= pos
->lnum
)
8114 if (linewhite(curwin
->w_cursor
.lnum
))
8116 for (that
= ml_get_curline(); *that
!= NUL
; ++that
)
8120 while (*(that
+ 1) != NUL
)
8126 if (*(that
+ 1) != NUL
)
8130 if (*that
== '"' && *(that
+ 1) != NUL
)
8132 while (*++that
&& *that
!= '"')
8134 /* skipping escaped characters in the string */
8147 if (*that
== '(' || *that
== '[')
8149 else if (*that
== ')' || *that
== ']')
8152 if (parencount
== 0)
8154 amount
= get_indent();
8161 curwin
->w_cursor
.lnum
= pos
->lnum
;
8162 curwin
->w_cursor
.col
= pos
->col
;
8165 that
= ml_get_curline();
8167 if (vi_lisp
&& get_indent() == 0)
8172 while (*that
&& col
)
8174 amount
+= lbr_chartabsize_adv(&that
, (colnr_T
)amount
);
8179 * Some keywords require "body" indenting rules (the
8180 * non-standard-lisp ones are Scheme special forms):
8182 * (let ((a 1)) instead (let ((a 1))
8186 if (!vi_lisp
&& (*that
== '(' || *that
== '[')
8187 && lisp_match(that
+ 1))
8195 while (vim_iswhite(*that
))
8197 amount
+= lbr_chartabsize(that
, (colnr_T
)amount
);
8201 if (*that
&& *that
!= ';') /* not a comment line */
8203 /* test *that != '(' to accomodate first let/do
8204 * argument if it is more than one line */
8205 if (!vi_lisp
&& *that
!= '(' && *that
!= '[')
8215 && (*that
< '0' || *that
> '9')))
8218 && (!vim_iswhite(*that
)
8221 && (!((*that
== '(' || *that
== '[')
8227 quotecount
= !quotecount
;
8228 if ((*that
== '(' || *that
== '[')
8231 if ((*that
== ')' || *that
== ']')
8234 if (*that
== '\\' && *(that
+1) != NUL
)
8235 amount
+= lbr_chartabsize_adv(&that
,
8237 amount
+= lbr_chartabsize_adv(&that
,
8241 while (vim_iswhite(*that
))
8243 amount
+= lbr_chartabsize(that
, (colnr_T
)amount
);
8246 if (!*that
|| *that
== ';')
8254 amount
= 0; /* no matching '(' or '[' found, use zero indent */
8256 curwin
->w_cursor
= realpos
;
8260 #endif /* FEAT_LISP */
8265 #if defined(SIGHUP) && defined(SIG_IGN)
8266 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8267 * makes Vim exit and then handling SIGHUP causes various reentrance
8269 signal(SIGHUP
, SIG_IGN
);
8276 out_trash(); /* trash any pending output */
8281 windgoto((int)Rows
- 1, 0);
8284 * Switch terminal mode back now, so messages end up on the "normal"
8285 * screen (if there are two screens).
8287 settmode(TMODE_COOK
);
8289 if (can_end_termcap_mode(FALSE
) == TRUE
)
8297 * Preserve files and exit.
8298 * When called IObuff must contain a message.
8307 /* Setting this will prevent free() calls. That avoids calling free()
8308 * recursively when free() was invoked with a bad pointer. */
8309 really_exiting
= TRUE
;
8312 screen_start(); /* don't know where cursor is now */
8315 ml_close_notmod(); /* close all not-modified buffers */
8317 for (buf
= firstbuf
; buf
!= NULL
; buf
= buf
->b_next
)
8319 if (buf
->b_ml
.ml_mfp
!= NULL
&& buf
->b_ml
.ml_mfp
->mf_fname
!= NULL
)
8321 OUT_STR(_("Vim: preserving files...\n"));
8322 screen_start(); /* don't know where cursor is now */
8324 ml_sync_all(FALSE
, FALSE
); /* preserve all swap files */
8329 ml_close_all(FALSE
); /* close all memfiles, without deleting */
8331 OUT_STR(_("Vim: Finished.\n"));
8337 * return TRUE if "fname" exists.
8345 if (mch_stat((char *)fname
, &st
))
8351 * Check for CTRL-C pressed, but only once in a while.
8352 * Should be used instead of ui_breakcheck() for functions that check for
8353 * each line in the file. Calling ui_breakcheck() each time takes too much
8354 * time, because it can be a system call.
8357 #ifndef BREAKCHECK_SKIP
8358 # ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8359 # define BREAKCHECK_SKIP 200
8361 # define BREAKCHECK_SKIP 32
8365 static int breakcheck_count
= 0;
8370 if (++breakcheck_count
>= BREAKCHECK_SKIP
)
8372 breakcheck_count
= 0;
8378 * Like line_breakcheck() but check 10 times less often.
8383 if (++breakcheck_count
>= BREAKCHECK_SKIP
* 10)
8385 breakcheck_count
= 0;
8391 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8393 * Returns OK or FAIL.
8396 expand_wildcards(num_pat
, pat
, num_file
, file
, flags
)
8397 int num_pat
; /* number of input patterns */
8398 char_u
**pat
; /* array of input patterns */
8399 int *num_file
; /* resulting number of files */
8400 char_u
***file
; /* array of resulting files */
8401 int flags
; /* EW_DIR, etc. */
8406 int non_suf_match
; /* number without matching suffix */
8408 retval
= gen_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
);
8410 /* When keeping all matches, return here */
8411 if (flags
& EW_KEEPALL
)
8416 * Remove names that match 'wildignore'.
8422 /* check all files in (*file)[] */
8423 for (i
= 0; i
< *num_file
; ++i
)
8425 ffname
= FullName_save((*file
)[i
], FALSE
);
8426 if (ffname
== NULL
) /* out of memory */
8429 vms_remove_version(ffname
);
8431 if (match_file_list(p_wig
, (*file
)[i
], ffname
))
8433 /* remove this matching file from the list */
8434 vim_free((*file
)[i
]);
8435 for (j
= i
; j
+ 1 < *num_file
; ++j
)
8436 (*file
)[j
] = (*file
)[j
+ 1];
8446 * Move the names where 'suffixes' match to the end.
8451 for (i
= 0; i
< *num_file
; ++i
)
8453 if (!match_suffix((*file
)[i
]))
8456 * Move the name without matching suffix to the front
8460 for (j
= i
; j
> non_suf_match
; --j
)
8461 (*file
)[j
] = (*file
)[j
- 1];
8462 (*file
)[non_suf_match
++] = p
;
8471 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8477 int fnamelen
, setsuflen
;
8479 #define MAXSUFLEN 30 /* maximum length of a file suffix */
8480 char_u suf_buf
[MAXSUFLEN
];
8482 fnamelen
= (int)STRLEN(fname
);
8484 for (setsuf
= p_su
; *setsuf
; )
8486 setsuflen
= copy_option_part(&setsuf
, suf_buf
, MAXSUFLEN
, ".,");
8487 if (fnamelen
>= setsuflen
8488 && fnamencmp(suf_buf
, fname
+ fnamelen
- setsuflen
,
8489 (size_t)setsuflen
) == 0)
8493 return (setsuflen
!= 0);
8496 #if !defined(NO_EXPANDPATH) || defined(PROTO)
8498 # ifdef VIM_BACKTICK
8499 static int vim_backtick
__ARGS((char_u
*p
));
8500 static int expand_backtick
__ARGS((garray_T
*gap
, char_u
*pat
, int flags
));
8503 # if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8505 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8506 * it's shared between these systems.
8508 # if defined(DJGPP) || defined(PROTO)
8509 # define _cdecl /* DJGPP doesn't have this */
8511 # ifdef __BORLANDC__
8512 # define _cdecl _RTLENTRYF
8517 * comparison function for qsort in dos_expandpath()
8520 pstrcmp(const void *a
, const void *b
)
8522 return (pathcmp(*(char **)a
, *(char **)b
, -1));
8532 if (USE_LONG_FNAME
) /* don't lower case on Windows 95/NT systems */
8538 *d
++ = TOLOWER_LOC(*s
++);
8544 * Recursively expand one path component into all matching files and/or
8545 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8546 * Return the number of matches found.
8547 * "path" has backslashes before chars that are not to be expanded, starting
8548 * at "path[wildoff]".
8549 * Return the number of matches found.
8550 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
8557 int flags
, /* EW_* flags */
8558 int didstar
) /* expanded "**" once already */
8563 int start_len
= gap
->ga_len
;
8565 regmatch_T regmatch
;
8566 int starts_with_dot
;
8569 int starstar
= FALSE
;
8570 static int stardepth
= 0; /* depth for "**" expansion */
8573 HANDLE hFind
= (HANDLE
)0;
8575 WIN32_FIND_DATAW wfb
;
8576 WCHAR
*wn
= NULL
; /* UCS-2 name, NULL when not used. */
8584 /* Expanding "**" may take a long time, check for CTRL-C. */
8592 /* make room for file name */
8593 buf
= alloc((int)STRLEN(path
) + BASENAMELEN
+ 5);
8598 * Find the first part in the path name that contains a wildcard or a ~1.
8599 * Copy it into buf, including the preceding characters.
8605 while (*path_end
!= NUL
)
8607 /* May ignore a wildcard that has a backslash before it; it will
8608 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8609 if (path_end
>= path
+ wildoff
&& rem_backslash(path_end
))
8611 else if (*path_end
== '\\' || *path_end
== ':' || *path_end
== '/')
8617 else if (path_end
>= path
+ wildoff
8618 && vim_strchr((char_u
*)"*?[~", *path_end
) != NULL
)
8623 len
= (*mb_ptr2len
)(path_end
);
8624 STRNCPY(p
, path_end
, len
);
8635 /* now we have one wildcard component between s and e */
8636 /* Remove backslashes between "wildoff" and the start of the wildcard
8638 for (p
= buf
+ wildoff
; p
< s
; ++p
)
8639 if (rem_backslash(p
))
8641 mch_memmove(p
, p
+ 1, STRLEN(p
));
8646 /* Check for "**" between "s" and "e". */
8647 for (p
= s
; p
< e
; ++p
)
8648 if (p
[0] == '*' && p
[1] == '*')
8651 starts_with_dot
= (*s
== '.');
8652 pat
= file_pat_to_reg_pat(s
, e
, NULL
, FALSE
);
8659 /* compile the regexp into a program */
8660 regmatch
.rm_ic
= TRUE
; /* Always ignore case */
8661 regmatch
.regprog
= vim_regcomp(pat
, RE_MAGIC
);
8664 if (regmatch
.regprog
== NULL
)
8670 /* remember the pattern or file name being looked for */
8671 matchname
= vim_strsave(s
);
8673 /* If "**" is by itself, this is the first time we encounter it and more
8674 * is following then find matches without any directory. */
8675 if (!didstar
&& stardepth
< 100 && starstar
&& e
- s
== 2
8676 && *path_end
== '/')
8678 STRCPY(s
, path_end
+ 1);
8680 (void)dos_expandpath(gap
, buf
, (int)(s
- buf
), flags
, TRUE
);
8684 /* Scan all files in the directory with "dir/ *.*" */
8688 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
8690 /* The active codepage differs from 'encoding'. Attempt using the
8691 * wide function. If it fails because it is not implemented fall back
8692 * to the non-wide version (for Windows 98) */
8693 wn
= enc_to_ucs2(buf
, NULL
);
8696 hFind
= FindFirstFileW(wn
, &wfb
);
8697 if (hFind
== INVALID_HANDLE_VALUE
8698 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED
)
8708 hFind
= FindFirstFile(buf
, &fb
);
8709 ok
= (hFind
!= INVALID_HANDLE_VALUE
);
8711 /* If we are expanding wildcards we try both files and directories */
8712 ok
= (findfirst((char *)buf
, &fb
,
8713 (*path_end
!= NUL
|| (flags
& EW_DIR
)) ? FA_DIREC
: 0) == 0);
8721 p
= ucs2_to_enc(wfb
.cFileName
, NULL
); /* p is allocated here */
8724 p
= (char_u
*)fb
.cFileName
;
8726 p
= (char_u
*)fb
.ff_name
;
8728 /* Ignore entries starting with a dot, unless when asked for. Accept
8729 * all entries found with "matchname". */
8730 if ((p
[0] != '.' || starts_with_dot
)
8731 && (matchname
== NULL
8732 || vim_regexec(®match
, p
, (colnr_T
)0)))
8739 len
= (int)STRLEN(buf
);
8741 if (starstar
&& stardepth
< 100)
8743 /* For "**" in the pattern first go deeper in the tree to
8745 STRCPY(buf
+ len
, "/**");
8746 STRCPY(buf
+ len
+ 3, path_end
);
8748 (void)dos_expandpath(gap
, buf
, len
+ 1, flags
, TRUE
);
8752 STRCPY(buf
+ len
, path_end
);
8753 if (mch_has_exp_wildcard(path_end
))
8755 /* need to expand another component of the path */
8756 /* remove backslashes for the remaining components only */
8757 (void)dos_expandpath(gap
, buf
, len
+ 1, flags
, FALSE
);
8761 /* no more wildcards, check if there is a match */
8762 /* remove backslashes for the remaining components only */
8764 backslash_halve(buf
+ len
+ 1);
8765 if (mch_getperm(buf
) >= 0) /* add existing file */
8766 addfile(gap
, buf
, flags
);
8775 ok
= FindNextFileW(hFind
, &wfb
);
8779 ok
= FindNextFile(hFind
, &fb
);
8781 ok
= (findnext(&fb
) == 0);
8784 /* If no more matches and no match was used, try expanding the name
8785 * itself. Finds the long name of a short filename. */
8786 if (!ok
&& matchname
!= NULL
&& gap
->ga_len
== start_len
)
8788 STRCPY(s
, matchname
);
8795 wn
= enc_to_ucs2(buf
, NULL
);
8797 hFind
= FindFirstFileW(wn
, &wfb
);
8801 hFind
= FindFirstFile(buf
, &fb
);
8802 ok
= (hFind
!= INVALID_HANDLE_VALUE
);
8804 ok
= (findfirst((char *)buf
, &fb
,
8805 (*path_end
!= NUL
|| (flags
& EW_DIR
)) ? FA_DIREC
: 0) == 0);
8807 vim_free(matchname
);
8819 vim_free(regmatch
.regprog
);
8820 vim_free(matchname
);
8822 matches
= gap
->ga_len
- start_len
;
8824 qsort(((char_u
**)gap
->ga_data
) + start_len
, (size_t)matches
,
8825 sizeof(char_u
*), pstrcmp
);
8833 int flags
) /* EW_* flags */
8835 return dos_expandpath(gap
, path
, 0, flags
, FALSE
);
8837 # endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8839 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8842 * Unix style wildcard expansion code.
8843 * It's here because it's used both for Unix and Mac.
8845 static int pstrcmp
__ARGS((const void *, const void *));
8851 return (pathcmp(*(char **)a
, *(char **)b
, -1));
8855 * Recursively expand one path component into all matching files and/or
8856 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8857 * "path" has backslashes before chars that are not to be expanded, starting
8858 * at "path + wildoff".
8859 * Return the number of matches found.
8860 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8863 unix_expandpath(gap
, path
, wildoff
, flags
, didstar
)
8867 int flags
; /* EW_* flags */
8868 int didstar
; /* expanded "**" once already */
8873 int start_len
= gap
->ga_len
;
8875 regmatch_T regmatch
;
8876 int starts_with_dot
;
8879 int starstar
= FALSE
;
8880 static int stardepth
= 0; /* depth for "**" expansion */
8885 /* Expanding "**" may take a long time, check for CTRL-C. */
8893 /* make room for file name */
8894 buf
= alloc((int)STRLEN(path
) + BASENAMELEN
+ 5);
8899 * Find the first part in the path name that contains a wildcard.
8900 * Copy it into "buf", including the preceding characters.
8906 while (*path_end
!= NUL
)
8908 /* May ignore a wildcard that has a backslash before it; it will
8909 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8910 if (path_end
>= path
+ wildoff
&& rem_backslash(path_end
))
8912 else if (*path_end
== '/')
8918 else if (path_end
>= path
+ wildoff
8919 && vim_strchr((char_u
*)"*?[{~$", *path_end
) != NULL
)
8924 len
= (*mb_ptr2len
)(path_end
);
8925 STRNCPY(p
, path_end
, len
);
8936 /* now we have one wildcard component between "s" and "e" */
8937 /* Remove backslashes between "wildoff" and the start of the wildcard
8939 for (p
= buf
+ wildoff
; p
< s
; ++p
)
8940 if (rem_backslash(p
))
8942 mch_memmove(p
, p
+ 1, STRLEN(p
));
8947 /* Check for "**" between "s" and "e". */
8948 for (p
= s
; p
< e
; ++p
)
8949 if (p
[0] == '*' && p
[1] == '*')
8952 /* convert the file pattern to a regexp pattern */
8953 starts_with_dot
= (*s
== '.');
8954 pat
= file_pat_to_reg_pat(s
, e
, NULL
, FALSE
);
8961 /* compile the regexp into a program */
8962 #ifdef CASE_INSENSITIVE_FILENAME
8963 regmatch
.rm_ic
= TRUE
; /* Behave like Terminal.app */
8965 regmatch
.rm_ic
= FALSE
; /* Don't ever ignore case */
8967 regmatch
.regprog
= vim_regcomp(pat
, RE_MAGIC
);
8970 if (regmatch
.regprog
== NULL
)
8976 /* If "**" is by itself, this is the first time we encounter it and more
8977 * is following then find matches without any directory. */
8978 if (!didstar
&& stardepth
< 100 && starstar
&& e
- s
== 2
8979 && *path_end
== '/')
8981 STRCPY(s
, path_end
+ 1);
8983 (void)unix_expandpath(gap
, buf
, (int)(s
- buf
), flags
, TRUE
);
8987 /* open the directory for scanning */
8989 dirp
= opendir(*buf
== NUL
? "." : (char *)buf
);
8991 /* Find all matching entries */
8999 if ((dp
->d_name
[0] != '.' || starts_with_dot
)
9000 && vim_regexec(®match
, (char_u
*)dp
->d_name
, (colnr_T
)0))
9002 STRCPY(s
, dp
->d_name
);
9005 if (starstar
&& stardepth
< 100)
9007 /* For "**" in the pattern first go deeper in the tree to
9009 STRCPY(buf
+ len
, "/**");
9010 STRCPY(buf
+ len
+ 3, path_end
);
9012 (void)unix_expandpath(gap
, buf
, len
+ 1, flags
, TRUE
);
9016 STRCPY(buf
+ len
, path_end
);
9017 if (mch_has_exp_wildcard(path_end
)) /* handle more wildcards */
9019 /* need to expand another component of the path */
9020 /* remove backslashes for the remaining components only */
9021 (void)unix_expandpath(gap
, buf
, len
+ 1, flags
, FALSE
);
9025 /* no more wildcards, check if there is a match */
9026 /* remove backslashes for the remaining components only */
9027 if (*path_end
!= NUL
)
9028 backslash_halve(buf
+ len
+ 1);
9029 if (mch_getperm(buf
) >= 0) /* add existing file */
9031 #ifdef MACOS_CONVERT
9032 size_t precomp_len
= STRLEN(buf
)+1;
9033 char_u
*precomp_buf
=
9034 mac_precompose_path(buf
, precomp_len
, &precomp_len
);
9038 mch_memmove(buf
, precomp_buf
, precomp_len
);
9039 vim_free(precomp_buf
);
9042 addfile(gap
, buf
, flags
);
9052 vim_free(regmatch
.regprog
);
9054 matches
= gap
->ga_len
- start_len
;
9056 qsort(((char_u
**)gap
->ga_data
) + start_len
, matches
,
9057 sizeof(char_u
*), pstrcmp
);
9063 * Generic wildcard expansion code.
9065 * Characters in "pat" that should not be expanded must be preceded with a
9066 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9068 * Return FAIL when no single file was found. In this case "num_file" is not
9069 * set, and "file" may contain an error message.
9070 * Return OK when some files found. "num_file" is set to the number of
9071 * matches, "file" to the array of matches. Call FreeWild() later.
9074 gen_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
)
9075 int num_pat
; /* number of input patterns */
9076 char_u
**pat
; /* array of input patterns */
9077 int *num_file
; /* resulting number of files */
9078 char_u
***file
; /* array of resulting files */
9079 int flags
; /* EW_* flags */
9084 static int recursive
= FALSE
;
9088 * expand_env() is called to expand things like "~user". If this fails,
9089 * it calls ExpandOne(), which brings us back here. In this case, always
9090 * call the machine specific expansion function, if possible. Otherwise,
9094 #ifdef SPECIAL_WILDCHAR
9095 return mch_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
);
9100 #ifdef SPECIAL_WILDCHAR
9102 * If there are any special wildcard characters which we cannot handle
9103 * here, call machine specific function for all the expansion. This
9104 * avoids starting the shell for each argument separately.
9105 * For `=expr` do use the internal function.
9107 for (i
= 0; i
< num_pat
; i
++)
9109 if (vim_strpbrk(pat
[i
], (char_u
*)SPECIAL_WILDCHAR
) != NULL
9110 # ifdef VIM_BACKTICK
9111 && !(vim_backtick(pat
[i
]) && pat
[i
][1] == '=')
9114 return mch_expand_wildcards(num_pat
, pat
, num_file
, file
, flags
);
9121 * The matching file names are stored in a growarray. Init it empty.
9123 ga_init2(&ga
, (int)sizeof(char_u
*), 30);
9125 for (i
= 0; i
< num_pat
; ++i
)
9131 if (vim_backtick(p
))
9132 add_pat
= expand_backtick(&ga
, p
, flags
);
9137 * First expand environment variables, "~/" and "~user/".
9139 if (vim_strpbrk(p
, (char_u
*)"$~") != NULL
)
9141 p
= expand_env_save(p
);
9146 * On Unix, if expand_env() can't expand an environment
9147 * variable, use the shell to do that. Discard previously
9148 * found file names and start all over again.
9150 else if (vim_strpbrk(p
, (char_u
*)"$~") != NULL
)
9154 i
= mch_expand_wildcards(num_pat
, pat
, num_file
, file
,
9163 * If there are wildcards: Expand file names and add each match to
9164 * the list. If there is no match, and EW_NOTFOUND is given, add
9166 * If there are no wildcards: Add the file name if it exists or
9167 * when EW_NOTFOUND is given.
9169 if (mch_has_exp_wildcard(p
))
9170 add_pat
= mch_expandpath(&ga
, p
, flags
);
9173 if (add_pat
== -1 || (add_pat
== 0 && (flags
& EW_NOTFOUND
)))
9175 char_u
*t
= backslash_halve_save(p
);
9177 #if defined(MACOS_CLASSIC)
9180 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9181 * "vim c:/" work. */
9182 if (flags
& EW_NOTFOUND
)
9183 addfile(&ga
, t
, flags
| EW_DIR
| EW_FILE
);
9184 else if (mch_getperm(t
) >= 0)
9185 addfile(&ga
, t
, flags
);
9193 *num_file
= ga
.ga_len
;
9194 *file
= (ga
.ga_data
!= NULL
) ? (char_u
**)ga
.ga_data
: (char_u
**)"";
9198 return (ga
.ga_data
!= NULL
) ? OK
: FAIL
;
9201 # ifdef VIM_BACKTICK
9204 * Return TRUE if we can expand this backtick thing here.
9210 return (*p
== '`' && *(p
+ 1) != NUL
&& *(p
+ STRLEN(p
) - 1) == '`');
9214 * Expand an item in `backticks` by executing it as a command.
9215 * Currently only works when pat[] starts and ends with a `.
9216 * Returns number of file names found.
9219 expand_backtick(gap
, pat
, flags
)
9222 int flags
; /* EW_* flags */
9230 /* Create the command: lop off the backticks. */
9231 cmd
= vim_strnsave(pat
+ 1, (int)STRLEN(pat
) - 2);
9236 if (*cmd
== '=') /* `={expr}`: Expand expression */
9237 buffer
= eval_to_string(cmd
+ 1, &p
, TRUE
);
9240 buffer
= get_cmd_output(cmd
, NULL
,
9241 (flags
& EW_SILENT
) ? SHELL_SILENT
: 0);
9249 cmd
= skipwhite(cmd
); /* skip over white space */
9251 while (*p
!= NUL
&& *p
!= '\r' && *p
!= '\n') /* skip over entry */
9253 /* add an entry if it is not empty */
9258 addfile(gap
, cmd
, flags
);
9263 while (*cmd
!= NUL
&& (*cmd
== '\r' || *cmd
== '\n'))
9270 # endif /* VIM_BACKTICK */
9273 * Add a file to a file list. Accepted flags:
9274 * EW_DIR add directories
9276 * EW_EXEC add executable files
9277 * EW_NOTFOUND add even when it doesn't exist
9278 * EW_ADDSLASH add slash after directory name
9281 addfile(gap
, f
, flags
)
9283 char_u
*f
; /* filename */
9289 /* if the file/dir doesn't exist, may not add it */
9290 if (!(flags
& EW_NOTFOUND
) && mch_getperm(f
) < 0)
9293 #ifdef FNAME_ILLEGAL
9294 /* if the file/dir contains illegal characters, don't add it */
9295 if (vim_strpbrk(f
, (char_u
*)FNAME_ILLEGAL
) != NULL
)
9299 isdir
= mch_isdir(f
);
9300 if ((isdir
&& !(flags
& EW_DIR
)) || (!isdir
&& !(flags
& EW_FILE
)))
9303 /* If the file isn't executable, may not add it. Do accept directories. */
9304 if (!isdir
&& (flags
& EW_EXEC
) && !mch_can_exe(f
))
9307 /* Make room for another item in the file list. */
9308 if (ga_grow(gap
, 1) == FAIL
)
9311 p
= alloc((unsigned)(STRLEN(f
) + 1 + isdir
));
9316 #ifdef BACKSLASH_IN_FILENAME
9320 * Append a slash or backslash after directory names if none is present.
9322 #ifndef DONT_ADD_PATHSEP_TO_DIR
9323 if (isdir
&& (flags
& EW_ADDSLASH
))
9326 ((char_u
**)gap
->ga_data
)[gap
->ga_len
++] = p
;
9328 #endif /* !NO_EXPANDPATH */
9330 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9340 * Get the stdout of an external command.
9341 * Returns an allocated string, or NULL for error.
9344 get_cmd_output(cmd
, infile
, flags
)
9346 char_u
*infile
; /* optional input file name */
9347 int flags
; /* can be SHELL_SILENT */
9351 char_u
*buffer
= NULL
;
9356 if (check_restricted() || check_secure())
9359 /* get a name for the temp file */
9360 if ((tempname
= vim_tempname('o')) == NULL
)
9366 /* Add the redirection stuff */
9367 command
= make_filter_cmd(cmd
, infile
, tempname
);
9368 if (command
== NULL
)
9372 * Call the shell to execute the command (errors are ignored).
9373 * Don't check timestamps here.
9375 ++no_check_timestamps
;
9376 call_shell(command
, SHELL_DOOUT
| SHELL_EXPAND
| flags
);
9377 --no_check_timestamps
;
9382 * read the names from the file into memory
9385 /* created temporary file is not always readable as binary */
9386 fd
= mch_fopen((char *)tempname
, "r");
9388 fd
= mch_fopen((char *)tempname
, READBIN
);
9393 EMSG2(_(e_notopen
), tempname
);
9397 fseek(fd
, 0L, SEEK_END
);
9398 len
= ftell(fd
); /* get size of temp file */
9399 fseek(fd
, 0L, SEEK_SET
);
9401 buffer
= alloc(len
+ 1);
9403 i
= (int)fread((char *)buffer
, (size_t)1, (size_t)len
, fd
);
9405 mch_remove(tempname
);
9409 len
= i
; /* VMS doesn't give us what we asked for... */
9413 EMSG2(_(e_notread
), tempname
);
9418 buffer
[len
] = '\0'; /* make sure the buffer is terminated */
9427 * Free the list of files returned by expand_wildcards() or other expansion
9431 FreeWild(count
, files
)
9435 if (count
<= 0 || files
== NULL
)
9437 #if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9439 * Is this still OK for when other functions than expand_wildcards() have
9442 _fnexplodefree((char **)files
);
9445 vim_free(files
[count
]);
9451 * return TRUE when need to go to Insert mode because of 'insertmode'.
9452 * Don't do this when still processing a command or a mapping.
9453 * Don't do this when inside a ":normal" command.
9458 return (p_im
&& stuff_empty() && typebuf_typed());