Beware exceptions when processing input
[MacVim.git] / src / misc1.c
blob3fdcdecb191c560bb510fc7f3852940758c10f85
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.
8 */
11 * misc1.c: functions that didn't seem to fit elsewhere
14 #include "vim.h"
15 #include "version.h"
17 static char_u *vim_version_dir __ARGS((char_u *vimdir));
18 static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
19 static int copy_indent __ARGS((int size, char_u *src));
22 * Count the size (in window cells) of the indent in the current line.
24 int
25 get_indent()
27 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
31 * Count the size (in window cells) of the indent in line "lnum".
33 int
34 get_indent_lnum(lnum)
35 linenr_T lnum;
37 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
40 #if defined(FEAT_FOLDING) || defined(PROTO)
42 * Count the size (in window cells) of the indent in line "lnum" of buffer
43 * "buf".
45 int
46 get_indent_buf(buf, lnum)
47 buf_T *buf;
48 linenr_T lnum;
50 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
52 #endif
55 * count the size (in window cells) of the indent in line "ptr", with
56 * 'tabstop' at "ts"
58 int
59 get_indent_str(ptr, ts)
60 char_u *ptr;
61 int ts;
63 int count = 0;
65 for ( ; *ptr; ++ptr)
67 if (*ptr == TAB) /* count a tab for what it is worth */
68 count += ts - (count % ts);
69 else if (*ptr == ' ')
70 ++count; /* count a space for one */
71 else
72 break;
74 return count;
78 * Set the indent of the current line.
79 * Leaves the cursor on the first non-blank in the line.
80 * Caller must take care of undo.
81 * "flags":
82 * SIN_CHANGED: call changed_bytes() if the line was changed.
83 * SIN_INSERT: insert the indent in front of the line.
84 * SIN_UNDO: save line for undo before changing it.
85 * Returns TRUE if the line was changed.
87 int
88 set_indent(size, flags)
89 int size; /* measured in spaces */
90 int flags;
92 char_u *p;
93 char_u *newline;
94 char_u *oldline;
95 char_u *s;
96 int todo;
97 int ind_len; /* measured in characters */
98 int line_len;
99 int doit = FALSE;
100 int ind_done = 0; /* measured in spaces */
101 int tab_pad;
102 int retval = FALSE;
103 int orig_char_len = -1; /* number of initial whitespace chars when
104 'et' and 'pi' are both set */
107 * First check if there is anything to do and compute the number of
108 * characters needed for the indent.
110 todo = size;
111 ind_len = 0;
112 p = oldline = ml_get_curline();
114 /* Calculate the buffer size for the new indent, and check to see if it
115 * isn't already set */
117 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
118 * 'preserveindent' are set count the number of characters at the
119 * beginning of the line to be copied */
120 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
122 /* If 'preserveindent' is set then reuse as much as possible of
123 * the existing indent structure for the new indent */
124 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
126 ind_done = 0;
128 /* count as many characters as we can use */
129 while (todo > 0 && vim_iswhite(*p))
131 if (*p == TAB)
133 tab_pad = (int)curbuf->b_p_ts
134 - (ind_done % (int)curbuf->b_p_ts);
135 /* stop if this tab will overshoot the target */
136 if (todo < tab_pad)
137 break;
138 todo -= tab_pad;
139 ++ind_len;
140 ind_done += tab_pad;
142 else
144 --todo;
145 ++ind_len;
146 ++ind_done;
148 ++p;
151 /* Set initial number of whitespace chars to copy if we are
152 * preserving indent but expandtab is set */
153 if (curbuf->b_p_et)
154 orig_char_len = ind_len;
156 /* Fill to next tabstop with a tab, if possible */
157 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
158 if (todo >= tab_pad && orig_char_len == -1)
160 doit = TRUE;
161 todo -= tab_pad;
162 ++ind_len;
163 /* ind_done += tab_pad; */
167 /* count tabs required for indent */
168 while (todo >= (int)curbuf->b_p_ts)
170 if (*p != TAB)
171 doit = TRUE;
172 else
173 ++p;
174 todo -= (int)curbuf->b_p_ts;
175 ++ind_len;
176 /* ind_done += (int)curbuf->b_p_ts; */
179 /* count spaces required for indent */
180 while (todo > 0)
182 if (*p != ' ')
183 doit = TRUE;
184 else
185 ++p;
186 --todo;
187 ++ind_len;
188 /* ++ind_done; */
191 /* Return if the indent is OK already. */
192 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
193 return FALSE;
195 /* Allocate memory for the new line. */
196 if (flags & SIN_INSERT)
197 p = oldline;
198 else
199 p = skipwhite(p);
200 line_len = (int)STRLEN(p) + 1;
202 /* If 'preserveindent' and 'expandtab' are both set keep the original
203 * characters and allocate accordingly. We will fill the rest with spaces
204 * after the if (!curbuf->b_p_et) below. */
205 if (orig_char_len != -1)
207 newline = alloc(orig_char_len + size - ind_done + line_len);
208 if (newline == NULL)
209 return FALSE;
210 todo = size - ind_done;
211 ind_len = orig_char_len + todo; /* Set total length of indent in
212 * characters, which may have been
213 * undercounted until now */
214 p = oldline;
215 s = newline;
216 while (orig_char_len > 0)
218 *s++ = *p++;
219 orig_char_len--;
222 /* Skip over any additional white space (useful when newindent is less
223 * than old) */
224 while (vim_iswhite(*p))
225 ++p;
228 else
230 todo = size;
231 newline = alloc(ind_len + line_len);
232 if (newline == NULL)
233 return FALSE;
234 s = newline;
237 /* Put the characters in the new line. */
238 /* if 'expandtab' isn't set: use TABs */
239 if (!curbuf->b_p_et)
241 /* If 'preserveindent' is set then reuse as much as possible of
242 * the existing indent structure for the new indent */
243 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
245 p = oldline;
246 ind_done = 0;
248 while (todo > 0 && vim_iswhite(*p))
250 if (*p == TAB)
252 tab_pad = (int)curbuf->b_p_ts
253 - (ind_done % (int)curbuf->b_p_ts);
254 /* stop if this tab will overshoot the target */
255 if (todo < tab_pad)
256 break;
257 todo -= tab_pad;
258 ind_done += tab_pad;
260 else
262 --todo;
263 ++ind_done;
265 *s++ = *p++;
268 /* Fill to next tabstop with a tab, if possible */
269 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
270 if (todo >= tab_pad)
272 *s++ = TAB;
273 todo -= tab_pad;
276 p = skipwhite(p);
279 while (todo >= (int)curbuf->b_p_ts)
281 *s++ = TAB;
282 todo -= (int)curbuf->b_p_ts;
285 while (todo > 0)
287 *s++ = ' ';
288 --todo;
290 mch_memmove(s, p, (size_t)line_len);
292 /* Replace the line (unless undo fails). */
293 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
295 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
296 if (flags & SIN_CHANGED)
297 changed_bytes(curwin->w_cursor.lnum, 0);
298 /* Correct saved cursor position if it's after the indent. */
299 if (saved_cursor.lnum == curwin->w_cursor.lnum
300 && saved_cursor.col >= (colnr_T)(p - oldline))
301 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
302 retval = TRUE;
304 else
305 vim_free(newline);
307 curwin->w_cursor.col = ind_len;
308 return retval;
312 * Copy the indent from ptr to the current line (and fill to size)
313 * Leaves the cursor on the first non-blank in the line.
314 * Returns TRUE if the line was changed.
316 static int
317 copy_indent(size, src)
318 int size;
319 char_u *src;
321 char_u *p = NULL;
322 char_u *line = NULL;
323 char_u *s;
324 int todo;
325 int ind_len;
326 int line_len = 0;
327 int tab_pad;
328 int ind_done;
329 int round;
331 /* Round 1: compute the number of characters needed for the indent
332 * Round 2: copy the characters. */
333 for (round = 1; round <= 2; ++round)
335 todo = size;
336 ind_len = 0;
337 ind_done = 0;
338 s = src;
340 /* Count/copy the usable portion of the source line */
341 while (todo > 0 && vim_iswhite(*s))
343 if (*s == TAB)
345 tab_pad = (int)curbuf->b_p_ts
346 - (ind_done % (int)curbuf->b_p_ts);
347 /* Stop if this tab will overshoot the target */
348 if (todo < tab_pad)
349 break;
350 todo -= tab_pad;
351 ind_done += tab_pad;
353 else
355 --todo;
356 ++ind_done;
358 ++ind_len;
359 if (p != NULL)
360 *p++ = *s;
361 ++s;
364 /* Fill to next tabstop with a tab, if possible */
365 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
366 if (todo >= tab_pad)
368 todo -= tab_pad;
369 ++ind_len;
370 if (p != NULL)
371 *p++ = TAB;
374 /* Add tabs required for indent */
375 while (todo >= (int)curbuf->b_p_ts)
377 todo -= (int)curbuf->b_p_ts;
378 ++ind_len;
379 if (p != NULL)
380 *p++ = TAB;
383 /* Count/add spaces required for indent */
384 while (todo > 0)
386 --todo;
387 ++ind_len;
388 if (p != NULL)
389 *p++ = ' ';
392 if (p == NULL)
394 /* Allocate memory for the result: the copied indent, new indent
395 * and the rest of the line. */
396 line_len = (int)STRLEN(ml_get_curline()) + 1;
397 line = alloc(ind_len + line_len);
398 if (line == NULL)
399 return FALSE;
400 p = line;
404 /* Append the original line */
405 mch_memmove(p, ml_get_curline(), (size_t)line_len);
407 /* Replace the line */
408 ml_replace(curwin->w_cursor.lnum, line, FALSE);
410 /* Put the cursor after the indent. */
411 curwin->w_cursor.col = ind_len;
412 return TRUE;
416 * Return the indent of the current line after a number. Return -1 if no
417 * number was found. Used for 'n' in 'formatoptions': numbered list.
418 * Since a pattern is used it can actually handle more than numbers.
421 get_number_indent(lnum)
422 linenr_T lnum;
424 colnr_T col;
425 pos_T pos;
426 regmmatch_T regmatch;
428 if (lnum > curbuf->b_ml.ml_line_count)
429 return -1;
430 pos.lnum = 0;
431 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
432 if (regmatch.regprog != NULL)
434 regmatch.rmm_ic = FALSE;
435 regmatch.rmm_maxcol = 0;
436 if (vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
437 (colnr_T)0, NULL))
439 pos.lnum = regmatch.endpos[0].lnum + lnum;
440 pos.col = regmatch.endpos[0].col;
441 #ifdef FEAT_VIRTUALEDIT
442 pos.coladd = 0;
443 #endif
445 vim_free(regmatch.regprog);
448 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
449 return -1;
450 getvcol(curwin, &pos, &col, NULL, NULL);
451 return (int)col;
454 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
456 static int cin_is_cinword __ARGS((char_u *line));
459 * Return TRUE if the string "line" starts with a word from 'cinwords'.
461 static int
462 cin_is_cinword(line)
463 char_u *line;
465 char_u *cinw;
466 char_u *cinw_buf;
467 int cinw_len;
468 int retval = FALSE;
469 int len;
471 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
472 cinw_buf = alloc((unsigned)cinw_len);
473 if (cinw_buf != NULL)
475 line = skipwhite(line);
476 for (cinw = curbuf->b_p_cinw; *cinw; )
478 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
479 if (STRNCMP(line, cinw_buf, len) == 0
480 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
482 retval = TRUE;
483 break;
486 vim_free(cinw_buf);
488 return retval;
490 #endif
493 * open_line: Add a new line below or above the current line.
495 * For VREPLACE mode, we only add a new line when we get to the end of the
496 * file, otherwise we just start replacing the next line.
498 * Caller must take care of undo. Since VREPLACE may affect any number of
499 * lines however, it may call u_save_cursor() again when starting to change a
500 * new line.
501 * "flags": OPENLINE_DELSPACES delete spaces after cursor
502 * OPENLINE_DO_COM format comments
503 * OPENLINE_KEEPTRAIL keep trailing spaces
504 * OPENLINE_MARKFIX adjust mark positions after the line break
506 * Return TRUE for success, FALSE for failure
509 open_line(dir, flags, old_indent)
510 int dir; /* FORWARD or BACKWARD */
511 int flags;
512 int old_indent; /* indent for after ^^D in Insert mode */
514 char_u *saved_line; /* copy of the original line */
515 char_u *next_line = NULL; /* copy of the next line */
516 char_u *p_extra = NULL; /* what goes to next line */
517 int less_cols = 0; /* less columns for mark in new line */
518 int less_cols_off = 0; /* columns to skip for mark adjust */
519 pos_T old_cursor; /* old cursor position */
520 int newcol = 0; /* new cursor column */
521 int newindent = 0; /* auto-indent of the new line */
522 int n;
523 int trunc_line = FALSE; /* truncate current line afterwards */
524 int retval = FALSE; /* return value, default is FAIL */
525 #ifdef FEAT_COMMENTS
526 int extra_len = 0; /* length of p_extra string */
527 int lead_len; /* length of comment leader */
528 char_u *lead_flags; /* position in 'comments' for comment leader */
529 char_u *leader = NULL; /* copy of comment leader */
530 #endif
531 char_u *allocated = NULL; /* allocated memory */
532 #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
533 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
534 char_u *p;
535 #endif
536 int saved_char = NUL; /* init for GCC */
537 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
538 pos_T *pos;
539 #endif
540 #ifdef FEAT_SMARTINDENT
541 int do_si = (!p_paste && curbuf->b_p_si
542 # ifdef FEAT_CINDENT
543 && !curbuf->b_p_cin
544 # endif
546 int no_si = FALSE; /* reset did_si afterwards */
547 int first_char = NUL; /* init for GCC */
548 #endif
549 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
550 int vreplace_mode;
551 #endif
552 int did_append; /* appended a new line */
553 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
556 * make a copy of the current line so we can mess with it
558 saved_line = vim_strsave(ml_get_curline());
559 if (saved_line == NULL) /* out of memory! */
560 return FALSE;
562 #ifdef FEAT_VREPLACE
563 if (State & VREPLACE_FLAG)
566 * With VREPLACE we make a copy of the next line, which we will be
567 * starting to replace. First make the new line empty and let vim play
568 * with the indenting and comment leader to its heart's content. Then
569 * we grab what it ended up putting on the new line, put back the
570 * original line, and call ins_char() to put each new character onto
571 * the line, replacing what was there before and pushing the right
572 * stuff onto the replace stack. -- webb.
574 if (curwin->w_cursor.lnum < orig_line_count)
575 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
576 else
577 next_line = vim_strsave((char_u *)"");
578 if (next_line == NULL) /* out of memory! */
579 goto theend;
582 * In VREPLACE mode, a NL replaces the rest of the line, and starts
583 * replacing the next line, so push all of the characters left on the
584 * line onto the replace stack. We'll push any other characters that
585 * might be replaced at the start of the next line (due to autoindent
586 * etc) a bit later.
588 replace_push(NUL); /* Call twice because BS over NL expects it */
589 replace_push(NUL);
590 p = saved_line + curwin->w_cursor.col;
591 while (*p != NUL)
593 #ifdef FEAT_MBYTE
594 if (has_mbyte)
595 p += replace_push_mb(p);
596 else
597 #endif
598 replace_push(*p++);
600 saved_line[curwin->w_cursor.col] = NUL;
602 #endif
604 if ((State & INSERT)
605 #ifdef FEAT_VREPLACE
606 && !(State & VREPLACE_FLAG)
607 #endif
610 p_extra = saved_line + curwin->w_cursor.col;
611 #ifdef FEAT_SMARTINDENT
612 if (do_si) /* need first char after new line break */
614 p = skipwhite(p_extra);
615 first_char = *p;
617 #endif
618 #ifdef FEAT_COMMENTS
619 extra_len = (int)STRLEN(p_extra);
620 #endif
621 saved_char = *p_extra;
622 *p_extra = NUL;
625 u_clearline(); /* cannot do "U" command when adding lines */
626 #ifdef FEAT_SMARTINDENT
627 did_si = FALSE;
628 #endif
629 ai_col = 0;
632 * If we just did an auto-indent, then we didn't type anything on
633 * the prior line, and it should be truncated. Do this even if 'ai' is not
634 * set because automatically inserting a comment leader also sets did_ai.
636 if (dir == FORWARD && did_ai)
637 trunc_line = TRUE;
640 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
641 * indent to use for the new line.
643 if (curbuf->b_p_ai
644 #ifdef FEAT_SMARTINDENT
645 || do_si
646 #endif
650 * count white space on current line
652 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
653 if (newindent == 0)
654 newindent = old_indent; /* for ^^D command in insert mode */
656 #ifdef FEAT_SMARTINDENT
658 * Do smart indenting.
659 * In insert/replace mode (only when dir == FORWARD)
660 * we may move some text to the next line. If it starts with '{'
661 * don't add an indent. Fixes inserting a NL before '{' in line
662 * "if (condition) {"
664 if (!trunc_line && do_si && *saved_line != NUL
665 && (p_extra == NULL || first_char != '{'))
667 char_u *ptr;
668 char_u last_char;
670 old_cursor = curwin->w_cursor;
671 ptr = saved_line;
672 # ifdef FEAT_COMMENTS
673 if (flags & OPENLINE_DO_COM)
674 lead_len = get_leader_len(ptr, NULL, FALSE);
675 else
676 lead_len = 0;
677 # endif
678 if (dir == FORWARD)
681 * Skip preprocessor directives, unless they are
682 * recognised as comments.
684 if (
685 # ifdef FEAT_COMMENTS
686 lead_len == 0 &&
687 # endif
688 ptr[0] == '#')
690 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
691 ptr = ml_get(--curwin->w_cursor.lnum);
692 newindent = get_indent();
694 # ifdef FEAT_COMMENTS
695 if (flags & OPENLINE_DO_COM)
696 lead_len = get_leader_len(ptr, NULL, FALSE);
697 else
698 lead_len = 0;
699 if (lead_len > 0)
702 * This case gets the following right:
703 * \*
704 * * A comment (read '\' as '/').
705 * *\
706 * #define IN_THE_WAY
707 * This should line up here;
709 p = skipwhite(ptr);
710 if (p[0] == '/' && p[1] == '*')
711 p++;
712 if (p[0] == '*')
714 for (p++; *p; p++)
716 if (p[0] == '/' && p[-1] == '*')
719 * End of C comment, indent should line up
720 * with the line containing the start of
721 * the comment
723 curwin->w_cursor.col = (colnr_T)(p - ptr);
724 if ((pos = findmatch(NULL, NUL)) != NULL)
726 curwin->w_cursor.lnum = pos->lnum;
727 newindent = get_indent();
733 else /* Not a comment line */
734 # endif
736 /* Find last non-blank in line */
737 p = ptr + STRLEN(ptr) - 1;
738 while (p > ptr && vim_iswhite(*p))
739 --p;
740 last_char = *p;
743 * find the character just before the '{' or ';'
745 if (last_char == '{' || last_char == ';')
747 if (p > ptr)
748 --p;
749 while (p > ptr && vim_iswhite(*p))
750 --p;
753 * Try to catch lines that are split over multiple
754 * lines. eg:
755 * if (condition &&
756 * condition) {
757 * Should line up here!
760 if (*p == ')')
762 curwin->w_cursor.col = (colnr_T)(p - ptr);
763 if ((pos = findmatch(NULL, '(')) != NULL)
765 curwin->w_cursor.lnum = pos->lnum;
766 newindent = get_indent();
767 ptr = ml_get_curline();
771 * If last character is '{' do indent, without
772 * checking for "if" and the like.
774 if (last_char == '{')
776 did_si = TRUE; /* do indent */
777 no_si = TRUE; /* don't delete it when '{' typed */
780 * Look for "if" and the like, use 'cinwords'.
781 * Don't do this if the previous line ended in ';' or
782 * '}'.
784 else if (last_char != ';' && last_char != '}'
785 && cin_is_cinword(ptr))
786 did_si = TRUE;
789 else /* dir == BACKWARD */
792 * Skip preprocessor directives, unless they are
793 * recognised as comments.
795 if (
796 # ifdef FEAT_COMMENTS
797 lead_len == 0 &&
798 # endif
799 ptr[0] == '#')
801 int was_backslashed = FALSE;
803 while ((ptr[0] == '#' || was_backslashed) &&
804 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
806 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
807 was_backslashed = TRUE;
808 else
809 was_backslashed = FALSE;
810 ptr = ml_get(++curwin->w_cursor.lnum);
812 if (was_backslashed)
813 newindent = 0; /* Got to end of file */
814 else
815 newindent = get_indent();
817 p = skipwhite(ptr);
818 if (*p == '}') /* if line starts with '}': do indent */
819 did_si = TRUE;
820 else /* can delete indent when '{' typed */
821 can_si_back = TRUE;
823 curwin->w_cursor = old_cursor;
825 if (do_si)
826 can_si = TRUE;
827 #endif /* FEAT_SMARTINDENT */
829 did_ai = TRUE;
832 #ifdef FEAT_COMMENTS
834 * Find out if the current line starts with a comment leader.
835 * This may then be inserted in front of the new line.
837 end_comment_pending = NUL;
838 if (flags & OPENLINE_DO_COM)
839 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD);
840 else
841 lead_len = 0;
842 if (lead_len > 0)
844 char_u *lead_repl = NULL; /* replaces comment leader */
845 int lead_repl_len = 0; /* length of *lead_repl */
846 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
847 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
848 char_u *comment_end = NULL; /* where lead_end has been found */
849 int extra_space = FALSE; /* append extra space */
850 int current_flag;
851 int require_blank = FALSE; /* requires blank after middle */
852 char_u *p2;
855 * If the comment leader has the start, middle or end flag, it may not
856 * be used or may be replaced with the middle leader.
858 for (p = lead_flags; *p && *p != ':'; ++p)
860 if (*p == COM_BLANK)
862 require_blank = TRUE;
863 continue;
865 if (*p == COM_START || *p == COM_MIDDLE)
867 current_flag = *p;
868 if (*p == COM_START)
871 * Doing "O" on a start of comment does not insert leader.
873 if (dir == BACKWARD)
875 lead_len = 0;
876 break;
879 /* find start of middle part */
880 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
881 require_blank = FALSE;
885 * Isolate the strings of the middle and end leader.
887 while (*p && p[-1] != ':') /* find end of middle flags */
889 if (*p == COM_BLANK)
890 require_blank = TRUE;
891 ++p;
893 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
895 while (*p && p[-1] != ':') /* find end of end flags */
897 /* Check whether we allow automatic ending of comments */
898 if (*p == COM_AUTO_END)
899 end_comment_pending = -1; /* means we want to set it */
900 ++p;
902 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
904 if (end_comment_pending == -1) /* we can set it now */
905 end_comment_pending = lead_end[n - 1];
908 * If the end of the comment is in the same line, don't use
909 * the comment leader.
911 if (dir == FORWARD)
913 for (p = saved_line + lead_len; *p; ++p)
914 if (STRNCMP(p, lead_end, n) == 0)
916 comment_end = p;
917 lead_len = 0;
918 break;
923 * Doing "o" on a start of comment inserts the middle leader.
925 if (lead_len > 0)
927 if (current_flag == COM_START)
929 lead_repl = lead_middle;
930 lead_repl_len = (int)STRLEN(lead_middle);
934 * If we have hit RETURN immediately after the start
935 * comment leader, then put a space after the middle
936 * comment leader on the next line.
938 if (!vim_iswhite(saved_line[lead_len - 1])
939 && ((p_extra != NULL
940 && (int)curwin->w_cursor.col == lead_len)
941 || (p_extra == NULL
942 && saved_line[lead_len] == NUL)
943 || require_blank))
944 extra_space = TRUE;
946 break;
948 if (*p == COM_END)
951 * Doing "o" on the end of a comment does not insert leader.
952 * Remember where the end is, might want to use it to find the
953 * start (for C-comments).
955 if (dir == FORWARD)
957 comment_end = skipwhite(saved_line);
958 lead_len = 0;
959 break;
963 * Doing "O" on the end of a comment inserts the middle leader.
964 * Find the string for the middle leader, searching backwards.
966 while (p > curbuf->b_p_com && *p != ',')
967 --p;
968 for (lead_repl = p; lead_repl > curbuf->b_p_com
969 && lead_repl[-1] != ':'; --lead_repl)
971 lead_repl_len = (int)(p - lead_repl);
973 /* We can probably always add an extra space when doing "O" on
974 * the comment-end */
975 extra_space = TRUE;
977 /* Check whether we allow automatic ending of comments */
978 for (p2 = p; *p2 && *p2 != ':'; p2++)
980 if (*p2 == COM_AUTO_END)
981 end_comment_pending = -1; /* means we want to set it */
983 if (end_comment_pending == -1)
985 /* Find last character in end-comment string */
986 while (*p2 && *p2 != ',')
987 p2++;
988 end_comment_pending = p2[-1];
990 break;
992 if (*p == COM_FIRST)
995 * Comment leader for first line only: Don't repeat leader
996 * when using "O", blank out leader when using "o".
998 if (dir == BACKWARD)
999 lead_len = 0;
1000 else
1002 lead_repl = (char_u *)"";
1003 lead_repl_len = 0;
1005 break;
1008 if (lead_len)
1010 /* allocate buffer (may concatenate p_exta later) */
1011 leader = alloc(lead_len + lead_repl_len + extra_space +
1012 extra_len + 1);
1013 allocated = leader; /* remember to free it later */
1015 if (leader == NULL)
1016 lead_len = 0;
1017 else
1019 vim_strncpy(leader, saved_line, lead_len);
1022 * Replace leader with lead_repl, right or left adjusted
1024 if (lead_repl != NULL)
1026 int c = 0;
1027 int off = 0;
1029 for (p = lead_flags; *p && *p != ':'; ++p)
1031 if (*p == COM_RIGHT || *p == COM_LEFT)
1032 c = *p;
1033 else if (VIM_ISDIGIT(*p) || *p == '-')
1034 off = getdigits(&p);
1036 if (c == COM_RIGHT) /* right adjusted leader */
1038 /* find last non-white in the leader to line up with */
1039 for (p = leader + lead_len - 1; p > leader
1040 && vim_iswhite(*p); --p)
1042 ++p;
1044 #ifdef FEAT_MBYTE
1045 /* Compute the length of the replaced characters in
1046 * screen characters, not bytes. */
1048 int repl_size = vim_strnsize(lead_repl,
1049 lead_repl_len);
1050 int old_size = 0;
1051 char_u *endp = p;
1052 int l;
1054 while (old_size < repl_size && p > leader)
1056 mb_ptr_back(leader, p);
1057 old_size += ptr2cells(p);
1059 l = lead_repl_len - (int)(endp - p);
1060 if (l != 0)
1061 mch_memmove(endp + l, endp,
1062 (size_t)((leader + lead_len) - endp));
1063 lead_len += l;
1065 #else
1066 if (p < leader + lead_repl_len)
1067 p = leader;
1068 else
1069 p -= lead_repl_len;
1070 #endif
1071 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1072 if (p + lead_repl_len > leader + lead_len)
1073 p[lead_repl_len] = NUL;
1075 /* blank-out any other chars from the old leader. */
1076 while (--p >= leader)
1078 #ifdef FEAT_MBYTE
1079 int l = mb_head_off(leader, p);
1081 if (l > 1)
1083 p -= l;
1084 if (ptr2cells(p) > 1)
1086 p[1] = ' ';
1087 --l;
1089 mch_memmove(p + 1, p + l + 1,
1090 (size_t)((leader + lead_len) - (p + l + 1)));
1091 lead_len -= l;
1092 *p = ' ';
1094 else
1095 #endif
1096 if (!vim_iswhite(*p))
1097 *p = ' ';
1100 else /* left adjusted leader */
1102 p = skipwhite(leader);
1103 #ifdef FEAT_MBYTE
1104 /* Compute the length of the replaced characters in
1105 * screen characters, not bytes. Move the part that is
1106 * not to be overwritten. */
1108 int repl_size = vim_strnsize(lead_repl,
1109 lead_repl_len);
1110 int i;
1111 int l;
1113 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1115 l = (*mb_ptr2len)(p + i);
1116 if (vim_strnsize(p, i + l) > repl_size)
1117 break;
1119 if (i != lead_repl_len)
1121 mch_memmove(p + lead_repl_len, p + i,
1122 (size_t)(lead_len - i - (leader - p)));
1123 lead_len += lead_repl_len - i;
1126 #endif
1127 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1129 /* Replace any remaining non-white chars in the old
1130 * leader by spaces. Keep Tabs, the indent must
1131 * remain the same. */
1132 for (p += lead_repl_len; p < leader + lead_len; ++p)
1133 if (!vim_iswhite(*p))
1135 /* Don't put a space before a TAB. */
1136 if (p + 1 < leader + lead_len && p[1] == TAB)
1138 --lead_len;
1139 mch_memmove(p, p + 1,
1140 (leader + lead_len) - p);
1142 else
1144 #ifdef FEAT_MBYTE
1145 int l = (*mb_ptr2len)(p);
1147 if (l > 1)
1149 if (ptr2cells(p) > 1)
1151 /* Replace a double-wide char with
1152 * two spaces */
1153 --l;
1154 *p++ = ' ';
1156 mch_memmove(p + 1, p + l,
1157 (leader + lead_len) - p);
1158 lead_len -= l - 1;
1160 #endif
1161 *p = ' ';
1164 *p = NUL;
1167 /* Recompute the indent, it may have changed. */
1168 if (curbuf->b_p_ai
1169 #ifdef FEAT_SMARTINDENT
1170 || do_si
1171 #endif
1173 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1175 /* Add the indent offset */
1176 if (newindent + off < 0)
1178 off = -newindent;
1179 newindent = 0;
1181 else
1182 newindent += off;
1184 /* Correct trailing spaces for the shift, so that
1185 * alignment remains equal. */
1186 while (off > 0 && lead_len > 0
1187 && leader[lead_len - 1] == ' ')
1189 /* Don't do it when there is a tab before the space */
1190 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1191 break;
1192 --lead_len;
1193 --off;
1196 /* If the leader ends in white space, don't add an
1197 * extra space */
1198 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1199 extra_space = FALSE;
1200 leader[lead_len] = NUL;
1203 if (extra_space)
1205 leader[lead_len++] = ' ';
1206 leader[lead_len] = NUL;
1209 newcol = lead_len;
1212 * if a new indent will be set below, remove the indent that
1213 * is in the comment leader
1215 if (newindent
1216 #ifdef FEAT_SMARTINDENT
1217 || did_si
1218 #endif
1221 while (lead_len && vim_iswhite(*leader))
1223 --lead_len;
1224 --newcol;
1225 ++leader;
1230 #ifdef FEAT_SMARTINDENT
1231 did_si = can_si = FALSE;
1232 #endif
1234 else if (comment_end != NULL)
1237 * We have finished a comment, so we don't use the leader.
1238 * If this was a C-comment and 'ai' or 'si' is set do a normal
1239 * indent to align with the line containing the start of the
1240 * comment.
1242 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1243 (curbuf->b_p_ai
1244 #ifdef FEAT_SMARTINDENT
1245 || do_si
1246 #endif
1249 old_cursor = curwin->w_cursor;
1250 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1251 if ((pos = findmatch(NULL, NUL)) != NULL)
1253 curwin->w_cursor.lnum = pos->lnum;
1254 newindent = get_indent();
1256 curwin->w_cursor = old_cursor;
1260 #endif
1262 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1263 if (p_extra != NULL)
1265 *p_extra = saved_char; /* restore char that NUL replaced */
1268 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1269 * non-blank.
1271 * When in REPLACE mode, put the deleted blanks on the replace stack,
1272 * preceded by a NUL, so they can be put back when a BS is entered.
1274 if (REPLACE_NORMAL(State))
1275 replace_push(NUL); /* end of extra blanks */
1276 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1278 while ((*p_extra == ' ' || *p_extra == '\t')
1279 #ifdef FEAT_MBYTE
1280 && (!enc_utf8
1281 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1282 #endif
1285 if (REPLACE_NORMAL(State))
1286 replace_push(*p_extra);
1287 ++p_extra;
1288 ++less_cols_off;
1291 if (*p_extra != NUL)
1292 did_ai = FALSE; /* append some text, don't truncate now */
1294 /* columns for marks adjusted for removed columns */
1295 less_cols = (int)(p_extra - saved_line);
1298 if (p_extra == NULL)
1299 p_extra = (char_u *)""; /* append empty line */
1301 #ifdef FEAT_COMMENTS
1302 /* concatenate leader and p_extra, if there is a leader */
1303 if (lead_len)
1305 STRCAT(leader, p_extra);
1306 p_extra = leader;
1307 did_ai = TRUE; /* So truncating blanks works with comments */
1308 less_cols -= lead_len;
1310 else
1311 end_comment_pending = NUL; /* turns out there was no leader */
1312 #endif
1314 old_cursor = curwin->w_cursor;
1315 if (dir == BACKWARD)
1316 --curwin->w_cursor.lnum;
1317 #ifdef FEAT_VREPLACE
1318 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1319 #endif
1321 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1322 == FAIL)
1323 goto theend;
1324 /* Postpone calling changed_lines(), because it would mess up folding
1325 * with markers. */
1326 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1327 did_append = TRUE;
1329 #ifdef FEAT_VREPLACE
1330 else
1333 * In VREPLACE mode we are starting to replace the next line.
1335 curwin->w_cursor.lnum++;
1336 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1338 /* In case we NL to a new line, BS to the previous one, and NL
1339 * again, we don't want to save the new line for undo twice.
1341 (void)u_save_cursor(); /* errors are ignored! */
1342 vr_lines_changed++;
1344 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1345 changed_bytes(curwin->w_cursor.lnum, 0);
1346 curwin->w_cursor.lnum--;
1347 did_append = FALSE;
1349 #endif
1351 if (newindent
1352 #ifdef FEAT_SMARTINDENT
1353 || did_si
1354 #endif
1357 ++curwin->w_cursor.lnum;
1358 #ifdef FEAT_SMARTINDENT
1359 if (did_si)
1361 if (p_sr)
1362 newindent -= newindent % (int)curbuf->b_p_sw;
1363 newindent += (int)curbuf->b_p_sw;
1365 #endif
1366 /* Copy the indent */
1367 if (curbuf->b_p_ci)
1369 (void)copy_indent(newindent, saved_line);
1372 * Set the 'preserveindent' option so that any further screwing
1373 * with the line doesn't entirely destroy our efforts to preserve
1374 * it. It gets restored at the function end.
1376 curbuf->b_p_pi = TRUE;
1378 else
1379 (void)set_indent(newindent, SIN_INSERT);
1380 less_cols -= curwin->w_cursor.col;
1382 ai_col = curwin->w_cursor.col;
1385 * In REPLACE mode, for each character in the new indent, there must
1386 * be a NUL on the replace stack, for when it is deleted with BS
1388 if (REPLACE_NORMAL(State))
1389 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1390 replace_push(NUL);
1391 newcol += curwin->w_cursor.col;
1392 #ifdef FEAT_SMARTINDENT
1393 if (no_si)
1394 did_si = FALSE;
1395 #endif
1398 #ifdef FEAT_COMMENTS
1400 * In REPLACE mode, for each character in the extra leader, there must be
1401 * a NUL on the replace stack, for when it is deleted with BS.
1403 if (REPLACE_NORMAL(State))
1404 while (lead_len-- > 0)
1405 replace_push(NUL);
1406 #endif
1408 curwin->w_cursor = old_cursor;
1410 if (dir == FORWARD)
1412 if (trunc_line || (State & INSERT))
1414 /* truncate current line at cursor */
1415 saved_line[curwin->w_cursor.col] = NUL;
1416 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1417 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1418 truncate_spaces(saved_line);
1419 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1420 saved_line = NULL;
1421 if (did_append)
1423 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1424 curwin->w_cursor.lnum + 1, 1L);
1425 did_append = FALSE;
1427 /* Move marks after the line break to the new line. */
1428 if (flags & OPENLINE_MARKFIX)
1429 mark_col_adjust(curwin->w_cursor.lnum,
1430 curwin->w_cursor.col + less_cols_off,
1431 1L, (long)-less_cols);
1433 else
1434 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1438 * Put the cursor on the new line. Careful: the scrollup() above may
1439 * have moved w_cursor, we must use old_cursor.
1441 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1443 if (did_append)
1444 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1446 curwin->w_cursor.col = newcol;
1447 #ifdef FEAT_VIRTUALEDIT
1448 curwin->w_cursor.coladd = 0;
1449 #endif
1451 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1453 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1454 * fixthisline() from doing it (via change_indent()) by telling it we're in
1455 * normal INSERT mode.
1457 if (State & VREPLACE_FLAG)
1459 vreplace_mode = State; /* So we know to put things right later */
1460 State = INSERT;
1462 else
1463 vreplace_mode = 0;
1464 #endif
1465 #ifdef FEAT_LISP
1467 * May do lisp indenting.
1469 if (!p_paste
1470 # ifdef FEAT_COMMENTS
1471 && leader == NULL
1472 # endif
1473 && curbuf->b_p_lisp
1474 && curbuf->b_p_ai)
1476 fixthisline(get_lisp_indent);
1477 p = ml_get_curline();
1478 ai_col = (colnr_T)(skipwhite(p) - p);
1480 #endif
1481 #ifdef FEAT_CINDENT
1483 * May do indenting after opening a new line.
1485 if (!p_paste
1486 && (curbuf->b_p_cin
1487 # ifdef FEAT_EVAL
1488 || *curbuf->b_p_inde != NUL
1489 # endif
1491 && in_cinkeys(dir == FORWARD
1492 ? KEY_OPEN_FORW
1493 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1495 do_c_expr_indent();
1496 p = ml_get_curline();
1497 ai_col = (colnr_T)(skipwhite(p) - p);
1499 #endif
1500 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1501 if (vreplace_mode != 0)
1502 State = vreplace_mode;
1503 #endif
1505 #ifdef FEAT_VREPLACE
1507 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1508 * original line, and inserts the new stuff char by char, pushing old stuff
1509 * onto the replace stack (via ins_char()).
1511 if (State & VREPLACE_FLAG)
1513 /* Put new line in p_extra */
1514 p_extra = vim_strsave(ml_get_curline());
1515 if (p_extra == NULL)
1516 goto theend;
1518 /* Put back original line */
1519 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1521 /* Insert new stuff into line again */
1522 curwin->w_cursor.col = 0;
1523 #ifdef FEAT_VIRTUALEDIT
1524 curwin->w_cursor.coladd = 0;
1525 #endif
1526 ins_bytes(p_extra); /* will call changed_bytes() */
1527 vim_free(p_extra);
1528 next_line = NULL;
1530 #endif
1532 retval = TRUE; /* success! */
1533 theend:
1534 curbuf->b_p_pi = saved_pi;
1535 vim_free(saved_line);
1536 vim_free(next_line);
1537 vim_free(allocated);
1538 return retval;
1541 #if defined(FEAT_COMMENTS) || defined(PROTO)
1543 * get_leader_len() returns the length of the prefix of the given string
1544 * which introduces a comment. If this string is not a comment then 0 is
1545 * returned.
1546 * When "flags" is not NULL, it is set to point to the flags of the recognized
1547 * comment leader.
1548 * "backward" must be true for the "O" command.
1551 get_leader_len(line, flags, backward)
1552 char_u *line;
1553 char_u **flags;
1554 int backward;
1556 int i, j;
1557 int got_com = FALSE;
1558 int found_one;
1559 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1560 char_u *string; /* pointer to comment string */
1561 char_u *list;
1563 i = 0;
1564 while (vim_iswhite(line[i])) /* leading white space is ignored */
1565 ++i;
1568 * Repeat to match several nested comment strings.
1570 while (line[i])
1573 * scan through the 'comments' option for a match
1575 found_one = FALSE;
1576 for (list = curbuf->b_p_com; *list; )
1579 * Get one option part into part_buf[]. Advance list to next one.
1580 * put string at start of string.
1582 if (!got_com && flags != NULL) /* remember where flags started */
1583 *flags = list;
1584 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1585 string = vim_strchr(part_buf, ':');
1586 if (string == NULL) /* missing ':', ignore this part */
1587 continue;
1588 *string++ = NUL; /* isolate flags from string */
1591 * When already found a nested comment, only accept further
1592 * nested comments.
1594 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1595 continue;
1597 /* When 'O' flag used don't use for "O" command */
1598 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1599 continue;
1602 * Line contents and string must match.
1603 * When string starts with white space, must have some white space
1604 * (but the amount does not need to match, there might be a mix of
1605 * TABs and spaces).
1607 if (vim_iswhite(string[0]))
1609 if (i == 0 || !vim_iswhite(line[i - 1]))
1610 continue;
1611 while (vim_iswhite(string[0]))
1612 ++string;
1614 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1616 if (string[j] != NUL)
1617 continue;
1620 * When 'b' flag used, there must be white space or an
1621 * end-of-line after the string in the line.
1623 if (vim_strchr(part_buf, COM_BLANK) != NULL
1624 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1625 continue;
1628 * We have found a match, stop searching.
1630 i += j;
1631 got_com = TRUE;
1632 found_one = TRUE;
1633 break;
1637 * No match found, stop scanning.
1639 if (!found_one)
1640 break;
1643 * Include any trailing white space.
1645 while (vim_iswhite(line[i]))
1646 ++i;
1649 * If this comment doesn't nest, stop here.
1651 if (vim_strchr(part_buf, COM_NEST) == NULL)
1652 break;
1654 return (got_com ? i : 0);
1656 #endif
1659 * Return the number of window lines occupied by buffer line "lnum".
1662 plines(lnum)
1663 linenr_T lnum;
1665 return plines_win(curwin, lnum, TRUE);
1669 plines_win(wp, lnum, winheight)
1670 win_T *wp;
1671 linenr_T lnum;
1672 int winheight; /* when TRUE limit to window height */
1674 #if defined(FEAT_DIFF) || defined(PROTO)
1675 /* Check for filler lines above this buffer line. When folded the result
1676 * is one line anyway. */
1677 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1681 plines_nofill(lnum)
1682 linenr_T lnum;
1684 return plines_win_nofill(curwin, lnum, TRUE);
1688 plines_win_nofill(wp, lnum, winheight)
1689 win_T *wp;
1690 linenr_T lnum;
1691 int winheight; /* when TRUE limit to window height */
1693 #endif
1694 int lines;
1696 if (!wp->w_p_wrap)
1697 return 1;
1699 #ifdef FEAT_VERTSPLIT
1700 if (wp->w_width == 0)
1701 return 1;
1702 #endif
1704 #ifdef FEAT_FOLDING
1705 /* A folded lines is handled just like an empty line. */
1706 /* NOTE: Caller must handle lines that are MAYBE folded. */
1707 if (lineFolded(wp, lnum) == TRUE)
1708 return 1;
1709 #endif
1711 lines = plines_win_nofold(wp, lnum);
1712 if (winheight > 0 && lines > wp->w_height)
1713 return (int)wp->w_height;
1714 return lines;
1718 * Return number of window lines physical line "lnum" will occupy in window
1719 * "wp". Does not care about folding, 'wrap' or 'diff'.
1722 plines_win_nofold(wp, lnum)
1723 win_T *wp;
1724 linenr_T lnum;
1726 char_u *s;
1727 long col;
1728 int width;
1730 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1731 if (*s == NUL) /* empty line */
1732 return 1;
1733 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1736 * If list mode is on, then the '$' at the end of the line may take up one
1737 * extra column.
1739 if (wp->w_p_list && lcs_eol != NUL)
1740 col += 1;
1743 * Add column offset for 'number' and 'foldcolumn'.
1745 width = W_WIDTH(wp) - win_col_off(wp);
1746 if (width <= 0)
1747 return 32000;
1748 if (col <= width)
1749 return 1;
1750 col -= width;
1751 width += win_col_off2(wp);
1752 return (col + (width - 1)) / width + 1;
1756 * Like plines_win(), but only reports the number of physical screen lines
1757 * used from the start of the line to the given column number.
1760 plines_win_col(wp, lnum, column)
1761 win_T *wp;
1762 linenr_T lnum;
1763 long column;
1765 long col;
1766 char_u *s;
1767 int lines = 0;
1768 int width;
1770 #ifdef FEAT_DIFF
1771 /* Check for filler lines above this buffer line. When folded the result
1772 * is one line anyway. */
1773 lines = diff_check_fill(wp, lnum);
1774 #endif
1776 if (!wp->w_p_wrap)
1777 return lines + 1;
1779 #ifdef FEAT_VERTSPLIT
1780 if (wp->w_width == 0)
1781 return lines + 1;
1782 #endif
1784 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1786 col = 0;
1787 while (*s != NUL && --column >= 0)
1789 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
1790 mb_ptr_adv(s);
1794 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1795 * INSERT mode, then col must be adjusted so that it represents the last
1796 * screen position of the TAB. This only fixes an error when the TAB wraps
1797 * from one screen line to the next (when 'columns' is not a multiple of
1798 * 'ts') -- webb.
1800 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1801 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1804 * Add column offset for 'number', 'foldcolumn', etc.
1806 width = W_WIDTH(wp) - win_col_off(wp);
1807 if (width <= 0)
1808 return 9999;
1810 lines += 1;
1811 if (col > width)
1812 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1813 return lines;
1817 plines_m_win(wp, first, last)
1818 win_T *wp;
1819 linenr_T first, last;
1821 int count = 0;
1823 while (first <= last)
1825 #ifdef FEAT_FOLDING
1826 int x;
1828 /* Check if there are any really folded lines, but also included lines
1829 * that are maybe folded. */
1830 x = foldedCount(wp, first, NULL);
1831 if (x > 0)
1833 ++count; /* count 1 for "+-- folded" line */
1834 first += x;
1836 else
1837 #endif
1839 #ifdef FEAT_DIFF
1840 if (first == wp->w_topline)
1841 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1842 else
1843 #endif
1844 count += plines_win(wp, first, TRUE);
1845 ++first;
1848 return (count);
1851 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1853 * Insert string "p" at the cursor position. Stops at a NUL byte.
1854 * Handles Replace mode and multi-byte characters.
1856 void
1857 ins_bytes(p)
1858 char_u *p;
1860 ins_bytes_len(p, (int)STRLEN(p));
1862 #endif
1864 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1865 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1867 * Insert string "p" with length "len" at the cursor position.
1868 * Handles Replace mode and multi-byte characters.
1870 void
1871 ins_bytes_len(p, len)
1872 char_u *p;
1873 int len;
1875 int i;
1876 # ifdef FEAT_MBYTE
1877 int n;
1879 if (has_mbyte)
1880 for (i = 0; i < len; i += n)
1882 if (enc_utf8)
1883 /* avoid reading past p[len] */
1884 n = utfc_ptr2len_len(p + i, len - i);
1885 else
1886 n = (*mb_ptr2len)(p + i);
1887 ins_char_bytes(p + i, n);
1889 else
1890 # endif
1891 for (i = 0; i < len; ++i)
1892 ins_char(p[i]);
1894 #endif
1897 * Insert or replace a single character at the cursor position.
1898 * When in REPLACE or VREPLACE mode, replace any existing character.
1899 * Caller must have prepared for undo.
1900 * For multi-byte characters we get the whole character, the caller must
1901 * convert bytes to a character.
1903 void
1904 ins_char(c)
1905 int c;
1907 #if defined(FEAT_MBYTE) || defined(PROTO)
1908 char_u buf[MB_MAXBYTES];
1909 int n;
1911 n = (*mb_char2bytes)(c, buf);
1913 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1914 * Happens for CTRL-Vu9900. */
1915 if (buf[0] == 0)
1916 buf[0] = '\n';
1918 ins_char_bytes(buf, n);
1921 void
1922 ins_char_bytes(buf, charlen)
1923 char_u *buf;
1924 int charlen;
1926 int c = buf[0];
1927 #endif
1928 int newlen; /* nr of bytes inserted */
1929 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1930 char_u *p;
1931 char_u *newp;
1932 char_u *oldp;
1933 int linelen; /* length of old line including NUL */
1934 colnr_T col;
1935 linenr_T lnum = curwin->w_cursor.lnum;
1936 int i;
1938 #ifdef FEAT_VIRTUALEDIT
1939 /* Break tabs if needed. */
1940 if (virtual_active() && curwin->w_cursor.coladd > 0)
1941 coladvance_force(getviscol());
1942 #endif
1944 col = curwin->w_cursor.col;
1945 oldp = ml_get(lnum);
1946 linelen = (int)STRLEN(oldp) + 1;
1948 /* The lengths default to the values for when not replacing. */
1949 oldlen = 0;
1950 #ifdef FEAT_MBYTE
1951 newlen = charlen;
1952 #else
1953 newlen = 1;
1954 #endif
1956 if (State & REPLACE_FLAG)
1958 #ifdef FEAT_VREPLACE
1959 if (State & VREPLACE_FLAG)
1961 colnr_T new_vcol = 0; /* init for GCC */
1962 colnr_T vcol;
1963 int old_list;
1964 #ifndef FEAT_MBYTE
1965 char_u buf[2];
1966 #endif
1969 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1970 * Returns the old value of list, so when finished,
1971 * curwin->w_p_list should be set back to this.
1973 old_list = curwin->w_p_list;
1974 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
1975 curwin->w_p_list = FALSE;
1978 * In virtual replace mode each character may replace one or more
1979 * characters (zero if it's a TAB). Count the number of bytes to
1980 * be deleted to make room for the new character, counting screen
1981 * cells. May result in adding spaces to fill a gap.
1983 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
1984 #ifndef FEAT_MBYTE
1985 buf[0] = c;
1986 buf[1] = NUL;
1987 #endif
1988 new_vcol = vcol + chartabsize(buf, vcol);
1989 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
1991 vcol += chartabsize(oldp + col + oldlen, vcol);
1992 /* Don't need to remove a TAB that takes us to the right
1993 * position. */
1994 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
1995 break;
1996 #ifdef FEAT_MBYTE
1997 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
1998 #else
1999 ++oldlen;
2000 #endif
2001 /* Deleted a bit too much, insert spaces. */
2002 if (vcol > new_vcol)
2003 newlen += vcol - new_vcol;
2005 curwin->w_p_list = old_list;
2007 else
2008 #endif
2009 if (oldp[col] != NUL)
2011 /* normal replace */
2012 #ifdef FEAT_MBYTE
2013 oldlen = (*mb_ptr2len)(oldp + col);
2014 #else
2015 oldlen = 1;
2016 #endif
2020 /* Push the replaced bytes onto the replace stack, so that they can be
2021 * put back when BS is used. The bytes of a multi-byte character are
2022 * done the other way around, so that the first byte is popped off
2023 * first (it tells the byte length of the character). */
2024 replace_push(NUL);
2025 for (i = 0; i < oldlen; ++i)
2027 #ifdef FEAT_MBYTE
2028 if (has_mbyte)
2029 i += replace_push_mb(oldp + col + i) - 1;
2030 else
2031 #endif
2032 replace_push(oldp[col + i]);
2036 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2037 if (newp == NULL)
2038 return;
2040 /* Copy bytes before the cursor. */
2041 if (col > 0)
2042 mch_memmove(newp, oldp, (size_t)col);
2044 /* Copy bytes after the changed character(s). */
2045 p = newp + col;
2046 mch_memmove(p + newlen, oldp + col + oldlen,
2047 (size_t)(linelen - col - oldlen));
2049 /* Insert or overwrite the new character. */
2050 #ifdef FEAT_MBYTE
2051 mch_memmove(p, buf, charlen);
2052 i = charlen;
2053 #else
2054 *p = c;
2055 i = 1;
2056 #endif
2058 /* Fill with spaces when necessary. */
2059 while (i < newlen)
2060 p[i++] = ' ';
2062 /* Replace the line in the buffer. */
2063 ml_replace(lnum, newp, FALSE);
2065 /* mark the buffer as changed and prepare for displaying */
2066 changed_bytes(lnum, col);
2069 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2070 * show the match for right parens and braces.
2072 if (p_sm && (State & INSERT)
2073 && msg_silent == 0
2074 #ifdef FEAT_MBYTE
2075 && charlen == 1
2076 #endif
2077 #ifdef FEAT_INS_EXPAND
2078 && !ins_compl_active()
2079 #endif
2081 showmatch(c);
2083 #ifdef FEAT_RIGHTLEFT
2084 if (!p_ri || (State & REPLACE_FLAG))
2085 #endif
2087 /* Normal insert: move cursor right */
2088 #ifdef FEAT_MBYTE
2089 curwin->w_cursor.col += charlen;
2090 #else
2091 ++curwin->w_cursor.col;
2092 #endif
2095 * TODO: should try to update w_row here, to avoid recomputing it later.
2100 * Insert a string at the cursor position.
2101 * Note: Does NOT handle Replace mode.
2102 * Caller must have prepared for undo.
2104 void
2105 ins_str(s)
2106 char_u *s;
2108 char_u *oldp, *newp;
2109 int newlen = (int)STRLEN(s);
2110 int oldlen;
2111 colnr_T col;
2112 linenr_T lnum = curwin->w_cursor.lnum;
2114 #ifdef FEAT_VIRTUALEDIT
2115 if (virtual_active() && curwin->w_cursor.coladd > 0)
2116 coladvance_force(getviscol());
2117 #endif
2119 col = curwin->w_cursor.col;
2120 oldp = ml_get(lnum);
2121 oldlen = (int)STRLEN(oldp);
2123 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2124 if (newp == NULL)
2125 return;
2126 if (col > 0)
2127 mch_memmove(newp, oldp, (size_t)col);
2128 mch_memmove(newp + col, s, (size_t)newlen);
2129 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2130 ml_replace(lnum, newp, FALSE);
2131 changed_bytes(lnum, col);
2132 curwin->w_cursor.col += newlen;
2136 * Delete one character under the cursor.
2137 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2138 * Caller must have prepared for undo.
2140 * return FAIL for failure, OK otherwise
2143 del_char(fixpos)
2144 int fixpos;
2146 #ifdef FEAT_MBYTE
2147 if (has_mbyte)
2149 /* Make sure the cursor is at the start of a character. */
2150 mb_adjust_cursor();
2151 if (*ml_get_cursor() == NUL)
2152 return FAIL;
2153 return del_chars(1L, fixpos);
2155 #endif
2156 return del_bytes(1L, fixpos, TRUE);
2159 #if defined(FEAT_MBYTE) || defined(PROTO)
2161 * Like del_bytes(), but delete characters instead of bytes.
2164 del_chars(count, fixpos)
2165 long count;
2166 int fixpos;
2168 long bytes = 0;
2169 long i;
2170 char_u *p;
2171 int l;
2173 p = ml_get_cursor();
2174 for (i = 0; i < count && *p != NUL; ++i)
2176 l = (*mb_ptr2len)(p);
2177 bytes += l;
2178 p += l;
2180 return del_bytes(bytes, fixpos, TRUE);
2182 #endif
2185 * Delete "count" bytes under the cursor.
2186 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2187 * Caller must have prepared for undo.
2189 * return FAIL for failure, OK otherwise
2191 /*ARGSUSED*/
2193 del_bytes(count, fixpos_arg, use_delcombine)
2194 long count;
2195 int fixpos_arg;
2196 int use_delcombine; /* 'delcombine' option applies */
2198 char_u *oldp, *newp;
2199 colnr_T oldlen;
2200 linenr_T lnum = curwin->w_cursor.lnum;
2201 colnr_T col = curwin->w_cursor.col;
2202 int was_alloced;
2203 long movelen;
2204 int fixpos = fixpos_arg;
2206 oldp = ml_get(lnum);
2207 oldlen = (int)STRLEN(oldp);
2210 * Can't do anything when the cursor is on the NUL after the line.
2212 if (col >= oldlen)
2213 return FAIL;
2215 #ifdef FEAT_MBYTE
2216 /* If 'delcombine' is set and deleting (less than) one character, only
2217 * delete the last combining character. */
2218 if (p_deco && use_delcombine && enc_utf8
2219 && utfc_ptr2len(oldp + col) >= count)
2221 int cc[MAX_MCO];
2222 int n;
2224 (void)utfc_ptr2char(oldp + col, cc);
2225 if (cc[0] != NUL)
2227 /* Find the last composing char, there can be several. */
2228 n = col;
2231 col = n;
2232 count = utf_ptr2len(oldp + n);
2233 n += count;
2234 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2235 fixpos = 0;
2238 #endif
2241 * When count is too big, reduce it.
2243 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2244 if (movelen <= 1)
2247 * If we just took off the last character of a non-blank line, and
2248 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2249 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2251 if (col > 0 && fixpos && restart_edit == 0
2252 #ifdef FEAT_VIRTUALEDIT
2253 && (ve_flags & VE_ONEMORE) == 0
2254 #endif
2257 --curwin->w_cursor.col;
2258 #ifdef FEAT_VIRTUALEDIT
2259 curwin->w_cursor.coladd = 0;
2260 #endif
2261 #ifdef FEAT_MBYTE
2262 if (has_mbyte)
2263 curwin->w_cursor.col -=
2264 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2265 #endif
2267 count = oldlen - col;
2268 movelen = 1;
2272 * If the old line has been allocated the deletion can be done in the
2273 * existing line. Otherwise a new line has to be allocated
2274 * Can't do this when using Netbeans, because we would need to invoke
2275 * netbeans_removed(), which deallocates the line. Let ml_replace() take
2276 * care of notifiying Netbeans.
2278 #ifdef FEAT_NETBEANS_INTG
2279 if (usingNetbeans)
2280 was_alloced = FALSE;
2281 else
2282 #endif
2283 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
2284 if (was_alloced)
2285 newp = oldp; /* use same allocated memory */
2286 else
2287 { /* need to allocate a new line */
2288 newp = alloc((unsigned)(oldlen + 1 - count));
2289 if (newp == NULL)
2290 return FAIL;
2291 mch_memmove(newp, oldp, (size_t)col);
2293 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2294 if (!was_alloced)
2295 ml_replace(lnum, newp, FALSE);
2297 /* mark the buffer as changed and prepare for displaying */
2298 changed_bytes(lnum, curwin->w_cursor.col);
2300 return OK;
2304 * Delete from cursor to end of line.
2305 * Caller must have prepared for undo.
2307 * return FAIL for failure, OK otherwise
2310 truncate_line(fixpos)
2311 int fixpos; /* if TRUE fix the cursor position when done */
2313 char_u *newp;
2314 linenr_T lnum = curwin->w_cursor.lnum;
2315 colnr_T col = curwin->w_cursor.col;
2317 if (col == 0)
2318 newp = vim_strsave((char_u *)"");
2319 else
2320 newp = vim_strnsave(ml_get(lnum), col);
2322 if (newp == NULL)
2323 return FAIL;
2325 ml_replace(lnum, newp, FALSE);
2327 /* mark the buffer as changed and prepare for displaying */
2328 changed_bytes(lnum, curwin->w_cursor.col);
2331 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2333 if (fixpos && curwin->w_cursor.col > 0)
2334 --curwin->w_cursor.col;
2336 return OK;
2340 * Delete "nlines" lines at the cursor.
2341 * Saves the lines for undo first if "undo" is TRUE.
2343 void
2344 del_lines(nlines, undo)
2345 long nlines; /* number of lines to delete */
2346 int undo; /* if TRUE, prepare for undo */
2348 long n;
2350 if (nlines <= 0)
2351 return;
2353 /* save the deleted lines for undo */
2354 if (undo && u_savedel(curwin->w_cursor.lnum, nlines) == FAIL)
2355 return;
2357 for (n = 0; n < nlines; )
2359 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2360 break;
2362 ml_delete(curwin->w_cursor.lnum, TRUE);
2363 ++n;
2365 /* If we delete the last line in the file, stop */
2366 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
2367 break;
2369 /* adjust marks, mark the buffer as changed and prepare for displaying */
2370 deleted_lines_mark(curwin->w_cursor.lnum, n);
2372 curwin->w_cursor.col = 0;
2373 check_cursor_lnum();
2377 gchar_pos(pos)
2378 pos_T *pos;
2380 char_u *ptr = ml_get_pos(pos);
2382 #ifdef FEAT_MBYTE
2383 if (has_mbyte)
2384 return (*mb_ptr2char)(ptr);
2385 #endif
2386 return (int)*ptr;
2390 gchar_cursor()
2392 #ifdef FEAT_MBYTE
2393 if (has_mbyte)
2394 return (*mb_ptr2char)(ml_get_cursor());
2395 #endif
2396 return (int)*ml_get_cursor();
2400 * Write a character at the current cursor position.
2401 * It is directly written into the block.
2403 void
2404 pchar_cursor(c)
2405 int c;
2407 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2408 + curwin->w_cursor.col) = c;
2411 #if 0 /* not used */
2413 * Put *pos at end of current buffer
2415 void
2416 goto_endofbuf(pos)
2417 pos_T *pos;
2419 char_u *p;
2421 pos->lnum = curbuf->b_ml.ml_line_count;
2422 pos->col = 0;
2423 p = ml_get(pos->lnum);
2424 while (*p++)
2425 ++pos->col;
2427 #endif
2430 * When extra == 0: Return TRUE if the cursor is before or on the first
2431 * non-blank in the line.
2432 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2433 * the line.
2436 inindent(extra)
2437 int extra;
2439 char_u *ptr;
2440 colnr_T col;
2442 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2443 ++ptr;
2444 if (col >= curwin->w_cursor.col + extra)
2445 return TRUE;
2446 else
2447 return FALSE;
2451 * Skip to next part of an option argument: Skip space and comma.
2453 char_u *
2454 skip_to_option_part(p)
2455 char_u *p;
2457 if (*p == ',')
2458 ++p;
2459 while (*p == ' ')
2460 ++p;
2461 return p;
2465 * changed() is called when something in the current buffer is changed.
2467 * Most often called through changed_bytes() and changed_lines(), which also
2468 * mark the area of the display to be redrawn.
2470 void
2471 changed()
2473 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2474 /* The text of the preediting area is inserted, but this doesn't
2475 * mean a change of the buffer yet. That is delayed until the
2476 * text is committed. (this means preedit becomes empty) */
2477 if (im_is_preediting() && !xim_changed_while_preediting)
2478 return;
2479 xim_changed_while_preediting = FALSE;
2480 #endif
2482 if (!curbuf->b_changed)
2484 int save_msg_scroll = msg_scroll;
2486 /* Give a warning about changing a read-only file. This may also
2487 * check-out the file, thus change "curbuf"! */
2488 change_warning(0);
2490 /* Create a swap file if that is wanted.
2491 * Don't do this for "nofile" and "nowrite" buffer types. */
2492 if (curbuf->b_may_swap
2493 #ifdef FEAT_QUICKFIX
2494 && !bt_dontwrite(curbuf)
2495 #endif
2498 ml_open_file(curbuf);
2500 /* The ml_open_file() can cause an ATTENTION message.
2501 * Wait two seconds, to make sure the user reads this unexpected
2502 * message. Since we could be anywhere, call wait_return() now,
2503 * and don't let the emsg() set msg_scroll. */
2504 if (need_wait_return && emsg_silent == 0)
2506 out_flush();
2507 ui_delay(2000L, TRUE);
2508 wait_return(TRUE);
2509 msg_scroll = save_msg_scroll;
2512 curbuf->b_changed = TRUE;
2513 ml_setflags(curbuf);
2514 #ifdef FEAT_WINDOWS
2515 check_status(curbuf);
2516 redraw_tabline = TRUE;
2517 #endif
2518 #ifdef FEAT_TITLE
2519 need_maketitle = TRUE; /* set window title later */
2520 #endif
2522 ++curbuf->b_changedtick;
2525 static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2526 static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
2527 static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2530 * Changed bytes within a single line for the current buffer.
2531 * - marks the windows on this buffer to be redisplayed
2532 * - marks the buffer changed by calling changed()
2533 * - invalidates cached values
2535 void
2536 changed_bytes(lnum, col)
2537 linenr_T lnum;
2538 colnr_T col;
2540 changedOneline(curbuf, lnum);
2541 changed_common(lnum, col, lnum + 1, 0L);
2543 #ifdef FEAT_DIFF
2544 /* Diff highlighting in other diff windows may need to be updated too. */
2545 if (curwin->w_p_diff)
2547 win_T *wp;
2548 linenr_T wlnum;
2550 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2551 if (wp->w_p_diff && wp != curwin)
2553 redraw_win_later(wp, VALID);
2554 wlnum = diff_lnum_win(lnum, wp);
2555 if (wlnum > 0)
2556 changedOneline(wp->w_buffer, wlnum);
2559 #endif
2562 static void
2563 changedOneline(buf, lnum)
2564 buf_T *buf;
2565 linenr_T lnum;
2567 if (buf->b_mod_set)
2569 /* find the maximum area that must be redisplayed */
2570 if (lnum < buf->b_mod_top)
2571 buf->b_mod_top = lnum;
2572 else if (lnum >= buf->b_mod_bot)
2573 buf->b_mod_bot = lnum + 1;
2575 else
2577 /* set the area that must be redisplayed to one line */
2578 buf->b_mod_set = TRUE;
2579 buf->b_mod_top = lnum;
2580 buf->b_mod_bot = lnum + 1;
2581 buf->b_mod_xlines = 0;
2586 * Appended "count" lines below line "lnum" in the current buffer.
2587 * Must be called AFTER the change and after mark_adjust().
2588 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2590 void
2591 appended_lines(lnum, count)
2592 linenr_T lnum;
2593 long count;
2595 changed_lines(lnum + 1, 0, lnum + 1, count);
2599 * Like appended_lines(), but adjust marks first.
2601 void
2602 appended_lines_mark(lnum, count)
2603 linenr_T lnum;
2604 long count;
2606 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2607 changed_lines(lnum + 1, 0, lnum + 1, count);
2611 * Deleted "count" lines at line "lnum" in the current buffer.
2612 * Must be called AFTER the change and after mark_adjust().
2613 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2615 void
2616 deleted_lines(lnum, count)
2617 linenr_T lnum;
2618 long count;
2620 changed_lines(lnum, 0, lnum + count, -count);
2624 * Like deleted_lines(), but adjust marks first.
2626 void
2627 deleted_lines_mark(lnum, count)
2628 linenr_T lnum;
2629 long count;
2631 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2632 changed_lines(lnum, 0, lnum + count, -count);
2636 * Changed lines for the current buffer.
2637 * Must be called AFTER the change and after mark_adjust().
2638 * - mark the buffer changed by calling changed()
2639 * - mark the windows on this buffer to be redisplayed
2640 * - invalidate cached values
2641 * "lnum" is the first line that needs displaying, "lnume" the first line
2642 * below the changed lines (BEFORE the change).
2643 * When only inserting lines, "lnum" and "lnume" are equal.
2644 * Takes care of calling changed() and updating b_mod_*.
2646 void
2647 changed_lines(lnum, col, lnume, xtra)
2648 linenr_T lnum; /* first line with change */
2649 colnr_T col; /* column in first line with change */
2650 linenr_T lnume; /* line below last changed line */
2651 long xtra; /* number of extra lines (negative when deleting) */
2653 changed_lines_buf(curbuf, lnum, lnume, xtra);
2655 #ifdef FEAT_DIFF
2656 if (xtra == 0 && curwin->w_p_diff)
2658 /* When the number of lines doesn't change then mark_adjust() isn't
2659 * called and other diff buffers still need to be marked for
2660 * displaying. */
2661 win_T *wp;
2662 linenr_T wlnum;
2664 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2665 if (wp->w_p_diff && wp != curwin)
2667 redraw_win_later(wp, VALID);
2668 wlnum = diff_lnum_win(lnum, wp);
2669 if (wlnum > 0)
2670 changed_lines_buf(wp->w_buffer, wlnum,
2671 lnume - lnum + wlnum, 0L);
2674 #endif
2676 changed_common(lnum, col, lnume, xtra);
2679 static void
2680 changed_lines_buf(buf, lnum, lnume, xtra)
2681 buf_T *buf;
2682 linenr_T lnum; /* first line with change */
2683 linenr_T lnume; /* line below last changed line */
2684 long xtra; /* number of extra lines (negative when deleting) */
2686 if (buf->b_mod_set)
2688 /* find the maximum area that must be redisplayed */
2689 if (lnum < buf->b_mod_top)
2690 buf->b_mod_top = lnum;
2691 if (lnum < buf->b_mod_bot)
2693 /* adjust old bot position for xtra lines */
2694 buf->b_mod_bot += xtra;
2695 if (buf->b_mod_bot < lnum)
2696 buf->b_mod_bot = lnum;
2698 if (lnume + xtra > buf->b_mod_bot)
2699 buf->b_mod_bot = lnume + xtra;
2700 buf->b_mod_xlines += xtra;
2702 else
2704 /* set the area that must be redisplayed */
2705 buf->b_mod_set = TRUE;
2706 buf->b_mod_top = lnum;
2707 buf->b_mod_bot = lnume + xtra;
2708 buf->b_mod_xlines = xtra;
2712 static void
2713 changed_common(lnum, col, lnume, xtra)
2714 linenr_T lnum;
2715 colnr_T col;
2716 linenr_T lnume;
2717 long xtra;
2719 win_T *wp;
2720 int i;
2721 #ifdef FEAT_JUMPLIST
2722 int cols;
2723 pos_T *p;
2724 int add;
2725 #endif
2727 /* mark the buffer as modified */
2728 changed();
2730 /* set the '. mark */
2731 if (!cmdmod.keepjumps)
2733 curbuf->b_last_change.lnum = lnum;
2734 curbuf->b_last_change.col = col;
2736 #ifdef FEAT_JUMPLIST
2737 /* Create a new entry if a new undo-able change was started or we
2738 * don't have an entry yet. */
2739 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2741 if (curbuf->b_changelistlen == 0)
2742 add = TRUE;
2743 else
2745 /* Don't create a new entry when the line number is the same
2746 * as the last one and the column is not too far away. Avoids
2747 * creating many entries for typing "xxxxx". */
2748 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2749 if (p->lnum != lnum)
2750 add = TRUE;
2751 else
2753 cols = comp_textwidth(FALSE);
2754 if (cols == 0)
2755 cols = 79;
2756 add = (p->col + cols < col || col + cols < p->col);
2759 if (add)
2761 /* This is the first of a new sequence of undo-able changes
2762 * and it's at some distance of the last change. Use a new
2763 * position in the changelist. */
2764 curbuf->b_new_change = FALSE;
2766 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2768 /* changelist is full: remove oldest entry */
2769 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2770 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2771 sizeof(pos_T) * (JUMPLISTSIZE - 1));
2772 FOR_ALL_WINDOWS(wp)
2774 /* Correct position in changelist for other windows on
2775 * this buffer. */
2776 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2777 --wp->w_changelistidx;
2780 FOR_ALL_WINDOWS(wp)
2782 /* For other windows, if the position in the changelist is
2783 * at the end it stays at the end. */
2784 if (wp->w_buffer == curbuf
2785 && wp->w_changelistidx == curbuf->b_changelistlen)
2786 ++wp->w_changelistidx;
2788 ++curbuf->b_changelistlen;
2791 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2792 curbuf->b_last_change;
2793 /* The current window is always after the last change, so that "g,"
2794 * takes you back to it. */
2795 curwin->w_changelistidx = curbuf->b_changelistlen;
2796 #endif
2799 FOR_ALL_WINDOWS(wp)
2801 if (wp->w_buffer == curbuf)
2803 /* Mark this window to be redrawn later. */
2804 if (wp->w_redr_type < VALID)
2805 wp->w_redr_type = VALID;
2807 /* Check if a change in the buffer has invalidated the cached
2808 * values for the cursor. */
2809 #ifdef FEAT_FOLDING
2811 * Update the folds for this window. Can't postpone this, because
2812 * a following operator might work on the whole fold: ">>dd".
2814 foldUpdate(wp, lnum, lnume + xtra - 1);
2816 /* The change may cause lines above or below the change to become
2817 * included in a fold. Set lnum/lnume to the first/last line that
2818 * might be displayed differently.
2819 * Set w_cline_folded here as an efficient way to update it when
2820 * inserting lines just above a closed fold. */
2821 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2822 if (wp->w_cursor.lnum == lnum)
2823 wp->w_cline_folded = i;
2824 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2825 if (wp->w_cursor.lnum == lnume)
2826 wp->w_cline_folded = i;
2828 /* If the changed line is in a range of previously folded lines,
2829 * compare with the first line in that range. */
2830 if (wp->w_cursor.lnum <= lnum)
2832 i = find_wl_entry(wp, lnum);
2833 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2834 changed_line_abv_curs_win(wp);
2836 #endif
2838 if (wp->w_cursor.lnum > lnum)
2839 changed_line_abv_curs_win(wp);
2840 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2841 changed_cline_bef_curs_win(wp);
2842 if (wp->w_botline >= lnum)
2844 /* Assume that botline doesn't change (inserted lines make
2845 * other lines scroll down below botline). */
2846 approximate_botline_win(wp);
2849 /* Check if any w_lines[] entries have become invalid.
2850 * For entries below the change: Correct the lnums for
2851 * inserted/deleted lines. Makes it possible to stop displaying
2852 * after the change. */
2853 for (i = 0; i < wp->w_lines_valid; ++i)
2854 if (wp->w_lines[i].wl_valid)
2856 if (wp->w_lines[i].wl_lnum >= lnum)
2858 if (wp->w_lines[i].wl_lnum < lnume)
2860 /* line included in change */
2861 wp->w_lines[i].wl_valid = FALSE;
2863 else if (xtra != 0)
2865 /* line below change */
2866 wp->w_lines[i].wl_lnum += xtra;
2867 #ifdef FEAT_FOLDING
2868 wp->w_lines[i].wl_lastlnum += xtra;
2869 #endif
2872 #ifdef FEAT_FOLDING
2873 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2875 /* change somewhere inside this range of folded lines,
2876 * may need to be redrawn */
2877 wp->w_lines[i].wl_valid = FALSE;
2879 #endif
2884 /* Call update_screen() later, which checks out what needs to be redrawn,
2885 * since it notices b_mod_set and then uses b_mod_*. */
2886 if (must_redraw < VALID)
2887 must_redraw = VALID;
2889 #ifdef FEAT_AUTOCMD
2890 /* when the cursor line is changed always trigger CursorMoved */
2891 if (lnum <= curwin->w_cursor.lnum
2892 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
2893 last_cursormoved.lnum = 0;
2894 #endif
2898 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2900 void
2901 unchanged(buf, ff)
2902 buf_T *buf;
2903 int ff; /* also reset 'fileformat' */
2905 if (buf->b_changed || (ff && file_ff_differs(buf)))
2907 buf->b_changed = 0;
2908 ml_setflags(buf);
2909 if (ff)
2910 save_file_ff(buf);
2911 #ifdef FEAT_WINDOWS
2912 check_status(buf);
2913 redraw_tabline = TRUE;
2914 #endif
2915 #ifdef FEAT_TITLE
2916 need_maketitle = TRUE; /* set window title later */
2917 #endif
2919 ++buf->b_changedtick;
2920 #ifdef FEAT_NETBEANS_INTG
2921 netbeans_unmodified(buf);
2922 #endif
2925 #if defined(FEAT_WINDOWS) || defined(PROTO)
2927 * check_status: called when the status bars for the buffer 'buf'
2928 * need to be updated
2930 void
2931 check_status(buf)
2932 buf_T *buf;
2934 win_T *wp;
2936 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2937 if (wp->w_buffer == buf && wp->w_status_height)
2939 wp->w_redr_status = TRUE;
2940 if (must_redraw < VALID)
2941 must_redraw = VALID;
2944 #endif
2947 * If the file is readonly, give a warning message with the first change.
2948 * Don't do this for autocommands.
2949 * Don't use emsg(), because it flushes the macro buffer.
2950 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
2951 * will be TRUE.
2953 void
2954 change_warning(col)
2955 int col; /* column for message; non-zero when in insert
2956 mode and 'showmode' is on */
2958 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
2960 if (curbuf->b_did_warn == FALSE
2961 && curbufIsChanged() == 0
2962 #ifdef FEAT_AUTOCMD
2963 && !autocmd_busy
2964 #endif
2965 && curbuf->b_p_ro)
2967 #ifdef FEAT_AUTOCMD
2968 ++curbuf_lock;
2969 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
2970 --curbuf_lock;
2971 if (!curbuf->b_p_ro)
2972 return;
2973 #endif
2975 * Do what msg() does, but with a column offset if the warning should
2976 * be after the mode message.
2978 msg_start();
2979 if (msg_row == Rows - 1)
2980 msg_col = col;
2981 msg_source(hl_attr(HLF_W));
2982 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
2983 #ifdef FEAT_EVAL
2984 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
2985 #endif
2986 msg_clr_eos();
2987 (void)msg_end();
2988 if (msg_silent == 0 && !silent_mode)
2990 out_flush();
2991 ui_delay(1000L, TRUE); /* give the user time to think about it */
2993 curbuf->b_did_warn = TRUE;
2994 redraw_cmdline = FALSE; /* don't redraw and erase the message */
2995 if (msg_row < Rows - 1)
2996 showmode();
3001 * Ask for a reply from the user, a 'y' or a 'n'.
3002 * No other characters are accepted, the message is repeated until a valid
3003 * reply is entered or CTRL-C is hit.
3004 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3005 * from any buffers but directly from the user.
3007 * return the 'y' or 'n'
3010 ask_yesno(str, direct)
3011 char_u *str;
3012 int direct;
3014 int r = ' ';
3015 int save_State = State;
3017 if (exiting) /* put terminal in raw mode for this question */
3018 settmode(TMODE_RAW);
3019 ++no_wait_return;
3020 #ifdef USE_ON_FLY_SCROLL
3021 dont_scroll = TRUE; /* disallow scrolling here */
3022 #endif
3023 State = CONFIRM; /* mouse behaves like with :confirm */
3024 #ifdef FEAT_MOUSE
3025 setmouse(); /* disables mouse for xterm */
3026 #endif
3027 ++no_mapping;
3028 ++allow_keys; /* no mapping here, but recognize keys */
3030 while (r != 'y' && r != 'n')
3032 /* same highlighting as for wait_return */
3033 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3034 if (direct)
3035 r = get_keystroke();
3036 else
3037 r = plain_vgetc();
3038 if (r == Ctrl_C || r == ESC)
3039 r = 'n';
3040 msg_putchar(r); /* show what you typed */
3041 out_flush();
3043 --no_wait_return;
3044 State = save_State;
3045 #ifdef FEAT_MOUSE
3046 setmouse();
3047 #endif
3048 --no_mapping;
3049 --allow_keys;
3051 return r;
3055 * Get a key stroke directly from the user.
3056 * Ignores mouse clicks and scrollbar events, except a click for the left
3057 * button (used at the more prompt).
3058 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3059 * Disadvantage: typeahead is ignored.
3060 * Translates the interrupt character for unix to ESC.
3063 get_keystroke()
3065 #define CBUFLEN 151
3066 char_u buf[CBUFLEN];
3067 int len = 0;
3068 int n;
3069 int save_mapped_ctrl_c = mapped_ctrl_c;
3070 int waited = 0;
3072 mapped_ctrl_c = FALSE; /* mappings are not used here */
3073 for (;;)
3075 cursor_on();
3076 out_flush();
3078 /* First time: blocking wait. Second time: wait up to 100ms for a
3079 * terminal code to complete. Leave some room for check_termcode() to
3080 * insert a key code into (max 5 chars plus NUL). And
3081 * fix_input_buffer() can triple the number of bytes. */
3082 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3083 len == 0 ? -1L : 100L, 0);
3084 if (n > 0)
3086 /* Replace zero and CSI by a special key code. */
3087 n = fix_input_buffer(buf + len, n, FALSE);
3088 len += n;
3089 waited = 0;
3091 else if (len > 0)
3092 ++waited; /* keep track of the waiting time */
3094 /* Incomplete termcode and not timed out yet: get more characters */
3095 if ((n = check_termcode(1, buf, len)) < 0
3096 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
3097 continue;
3099 /* found a termcode: adjust length */
3100 if (n > 0)
3101 len = n;
3102 if (len == 0) /* nothing typed yet */
3103 continue;
3105 /* Handle modifier and/or special key code. */
3106 n = buf[0];
3107 if (n == K_SPECIAL)
3109 n = TO_SPECIAL(buf[1], buf[2]);
3110 if (buf[1] == KS_MODIFIER
3111 || n == K_IGNORE
3112 #ifdef FEAT_MOUSE
3113 || n == K_LEFTMOUSE_NM
3114 || n == K_LEFTDRAG
3115 || n == K_LEFTRELEASE
3116 || n == K_LEFTRELEASE_NM
3117 || n == K_MIDDLEMOUSE
3118 || n == K_MIDDLEDRAG
3119 || n == K_MIDDLERELEASE
3120 || n == K_RIGHTMOUSE
3121 || n == K_RIGHTDRAG
3122 || n == K_RIGHTRELEASE
3123 || n == K_MOUSEDOWN
3124 || n == K_MOUSEUP
3125 || n == K_X1MOUSE
3126 || n == K_X1DRAG
3127 || n == K_X1RELEASE
3128 || n == K_X2MOUSE
3129 || n == K_X2DRAG
3130 || n == K_X2RELEASE
3131 # ifdef FEAT_GUI
3132 || n == K_VER_SCROLLBAR
3133 || n == K_HOR_SCROLLBAR
3134 # endif
3135 #endif
3138 if (buf[1] == KS_MODIFIER)
3139 mod_mask = buf[2];
3140 len -= 3;
3141 if (len > 0)
3142 mch_memmove(buf, buf + 3, (size_t)len);
3143 continue;
3145 break;
3147 #ifdef FEAT_MBYTE
3148 if (has_mbyte)
3150 if (MB_BYTE2LEN(n) > len)
3151 continue; /* more bytes to get */
3152 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3153 n = (*mb_ptr2char)(buf);
3155 #endif
3156 #ifdef UNIX
3157 if (n == intr_char)
3158 n = ESC;
3159 #endif
3160 break;
3163 mapped_ctrl_c = save_mapped_ctrl_c;
3164 return n;
3168 * Get a number from the user.
3169 * When "mouse_used" is not NULL allow using the mouse.
3172 get_number(colon, mouse_used)
3173 int colon; /* allow colon to abort */
3174 int *mouse_used;
3176 int n = 0;
3177 int c;
3178 int typed = 0;
3180 if (mouse_used != NULL)
3181 *mouse_used = FALSE;
3183 /* When not printing messages, the user won't know what to type, return a
3184 * zero (as if CR was hit). */
3185 if (msg_silent != 0)
3186 return 0;
3188 #ifdef USE_ON_FLY_SCROLL
3189 dont_scroll = TRUE; /* disallow scrolling here */
3190 #endif
3191 ++no_mapping;
3192 ++allow_keys; /* no mapping here, but recognize keys */
3193 for (;;)
3195 windgoto(msg_row, msg_col);
3196 c = safe_vgetc();
3197 if (VIM_ISDIGIT(c))
3199 n = n * 10 + c - '0';
3200 msg_putchar(c);
3201 ++typed;
3203 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3205 if (typed > 0)
3207 MSG_PUTS("\b \b");
3208 --typed;
3210 n /= 10;
3212 #ifdef FEAT_MOUSE
3213 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3215 *mouse_used = TRUE;
3216 n = mouse_row + 1;
3217 break;
3219 #endif
3220 else if (n == 0 && c == ':' && colon)
3222 stuffcharReadbuff(':');
3223 if (!exmode_active)
3224 cmdline_row = msg_row;
3225 skip_redraw = TRUE; /* skip redraw once */
3226 do_redraw = FALSE;
3227 break;
3229 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3230 break;
3232 --no_mapping;
3233 --allow_keys;
3234 return n;
3238 * Ask the user to enter a number.
3239 * When "mouse_used" is not NULL allow using the mouse and in that case return
3240 * the line number.
3243 prompt_for_number(mouse_used)
3244 int *mouse_used;
3246 int i;
3247 int save_cmdline_row;
3248 int save_State;
3250 /* When using ":silent" assume that <CR> was entered. */
3251 if (mouse_used != NULL)
3252 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
3253 else
3254 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
3256 /* Set the state such that text can be selected/copied/pasted and we still
3257 * get mouse events. */
3258 save_cmdline_row = cmdline_row;
3259 cmdline_row = 0;
3260 save_State = State;
3261 State = CMDLINE;
3263 i = get_number(TRUE, mouse_used);
3264 if (KeyTyped)
3266 /* don't call wait_return() now */
3267 /* msg_putchar('\n'); */
3268 cmdline_row = msg_row - 1;
3269 need_wait_return = FALSE;
3270 msg_didany = FALSE;
3272 else
3273 cmdline_row = save_cmdline_row;
3274 State = save_State;
3276 return i;
3279 void
3280 msgmore(n)
3281 long n;
3283 long pn;
3285 if (global_busy /* no messages now, wait until global is finished */
3286 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3287 return;
3289 /* We don't want to overwrite another important message, but do overwrite
3290 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3291 * then "put" reports the last action. */
3292 if (keep_msg != NULL && !keep_msg_more)
3293 return;
3295 if (n > 0)
3296 pn = n;
3297 else
3298 pn = -n;
3300 if (pn > p_report)
3302 if (pn == 1)
3304 if (n > 0)
3305 STRCPY(msg_buf, _("1 more line"));
3306 else
3307 STRCPY(msg_buf, _("1 line less"));
3309 else
3311 if (n > 0)
3312 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3313 else
3314 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3316 if (got_int)
3317 STRCAT(msg_buf, _(" (Interrupted)"));
3318 if (msg(msg_buf))
3320 set_keep_msg(msg_buf, 0);
3321 keep_msg_more = TRUE;
3327 * flush map and typeahead buffers and give a warning for an error
3329 void
3330 beep_flush()
3332 if (emsg_silent == 0)
3334 flush_buffers(FALSE);
3335 vim_beep();
3340 * give a warning for an error
3342 void
3343 vim_beep()
3345 if (emsg_silent == 0)
3347 if (p_vb
3348 #ifdef FEAT_GUI
3349 /* While the GUI is starting up the termcap is set for the GUI
3350 * but the output still goes to a terminal. */
3351 && !(gui.in_use && gui.starting)
3352 #endif
3355 out_str(T_VB);
3357 else
3359 #ifdef MSDOS
3361 * The number of beeps outputted is reduced to avoid having to wait
3362 * for all the beeps to finish. This is only a problem on systems
3363 * where the beeps don't overlap.
3365 if (beep_count == 0 || beep_count == 10)
3367 out_char(BELL);
3368 beep_count = 1;
3370 else
3371 ++beep_count;
3372 #else
3373 out_char(BELL);
3374 #endif
3377 /* When 'verbose' is set and we are sourcing a script or executing a
3378 * function give the user a hint where the beep comes from. */
3379 if (vim_strchr(p_debug, 'e') != NULL)
3381 msg_source(hl_attr(HLF_W));
3382 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3388 * To get the "real" home directory:
3389 * - get value of $HOME
3390 * For Unix:
3391 * - go to that directory
3392 * - do mch_dirname() to get the real name of that directory.
3393 * This also works with mounts and links.
3394 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3396 static char_u *homedir = NULL;
3398 void
3399 init_homedir()
3401 char_u *var;
3403 /* In case we are called a second time (when 'encoding' changes). */
3404 vim_free(homedir);
3405 homedir = NULL;
3407 #ifdef VMS
3408 var = mch_getenv((char_u *)"SYS$LOGIN");
3409 #else
3410 var = mch_getenv((char_u *)"HOME");
3411 #endif
3413 if (var != NULL && *var == NUL) /* empty is same as not set */
3414 var = NULL;
3416 #ifdef WIN3264
3418 * Weird but true: $HOME may contain an indirect reference to another
3419 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3420 * when $HOME is being set.
3422 if (var != NULL && *var == '%')
3424 char_u *p;
3425 char_u *exp;
3427 p = vim_strchr(var + 1, '%');
3428 if (p != NULL)
3430 vim_strncpy(NameBuff, var + 1, p - (var + 1));
3431 exp = mch_getenv(NameBuff);
3432 if (exp != NULL && *exp != NUL
3433 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3435 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
3436 var = NameBuff;
3437 /* Also set $HOME, it's needed for _viminfo. */
3438 vim_setenv((char_u *)"HOME", NameBuff);
3444 * Typically, $HOME is not defined on Windows, unless the user has
3445 * specifically defined it for Vim's sake. However, on Windows NT
3446 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3447 * each user. Try constructing $HOME from these.
3449 if (var == NULL)
3451 char_u *homedrive, *homepath;
3453 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3454 homepath = mch_getenv((char_u *)"HOMEPATH");
3455 if (homedrive != NULL && homepath != NULL
3456 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3458 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3459 if (NameBuff[0] != NUL)
3461 var = NameBuff;
3462 /* Also set $HOME, it's needed for _viminfo. */
3463 vim_setenv((char_u *)"HOME", NameBuff);
3468 # if defined(FEAT_MBYTE)
3469 if (enc_utf8 && var != NULL)
3471 int len;
3472 char_u *pp;
3474 /* Convert from active codepage to UTF-8. Other conversions are
3475 * not done, because they would fail for non-ASCII characters. */
3476 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
3477 if (pp != NULL)
3479 homedir = pp;
3480 return;
3483 # endif
3484 #endif
3486 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3488 * Default home dir is C:/
3489 * Best assumption we can make in such a situation.
3491 if (var == NULL)
3492 var = "C:/";
3493 #endif
3494 if (var != NULL)
3496 #ifdef UNIX
3498 * Change to the directory and get the actual path. This resolves
3499 * links. Don't do it when we can't return.
3501 if (mch_dirname(NameBuff, MAXPATHL) == OK
3502 && mch_chdir((char *)NameBuff) == 0)
3504 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3505 var = IObuff;
3506 if (mch_chdir((char *)NameBuff) != 0)
3507 EMSG(_(e_prev_dir));
3509 #endif
3510 homedir = vim_strsave(var);
3514 #if defined(EXITFREE) || defined(PROTO)
3515 void
3516 free_homedir()
3518 vim_free(homedir);
3520 #endif
3523 * Call expand_env() and store the result in an allocated string.
3524 * This is not very memory efficient, this expects the result to be freed
3525 * again soon.
3527 char_u *
3528 expand_env_save(src)
3529 char_u *src;
3531 return expand_env_save_opt(src, FALSE);
3535 * Idem, but when "one" is TRUE handle the string as one file name, only
3536 * expand "~" at the start.
3538 char_u *
3539 expand_env_save_opt(src, one)
3540 char_u *src;
3541 int one;
3543 char_u *p;
3545 p = alloc(MAXPATHL);
3546 if (p != NULL)
3547 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3548 return p;
3552 * Expand environment variable with path name.
3553 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3554 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
3555 * If anything fails no expansion is done and dst equals src.
3557 void
3558 expand_env(src, dst, dstlen)
3559 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3560 char_u *dst; /* where to put the result */
3561 int dstlen; /* maximum length of the result */
3563 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
3566 void
3567 expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
3568 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
3569 char_u *dst; /* where to put the result */
3570 int dstlen; /* maximum length of the result */
3571 int esc; /* escape spaces in expanded variables */
3572 int one; /* "srcp" is one file name */
3573 char_u *startstr; /* start again after this (can be NULL) */
3575 char_u *src;
3576 char_u *tail;
3577 int c;
3578 char_u *var;
3579 int copy_char;
3580 int mustfree; /* var was allocated, need to free it later */
3581 int at_start = TRUE; /* at start of a name */
3582 int startstr_len = 0;
3584 if (startstr != NULL)
3585 startstr_len = (int)STRLEN(startstr);
3587 src = skipwhite(srcp);
3588 --dstlen; /* leave one char space for "\," */
3589 while (*src && dstlen > 0)
3591 copy_char = TRUE;
3592 if ((*src == '$'
3593 #ifdef VMS
3594 && at_start
3595 #endif
3597 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3598 || *src == '%'
3599 #endif
3600 || (*src == '~' && at_start))
3602 mustfree = FALSE;
3605 * The variable name is copied into dst temporarily, because it may
3606 * be a string in read-only memory and a NUL needs to be appended.
3608 if (*src != '~') /* environment var */
3610 tail = src + 1;
3611 var = dst;
3612 c = dstlen - 1;
3614 #ifdef UNIX
3615 /* Unix has ${var-name} type environment vars */
3616 if (*tail == '{' && !vim_isIDc('{'))
3618 tail++; /* ignore '{' */
3619 while (c-- > 0 && *tail && *tail != '}')
3620 *var++ = *tail++;
3622 else
3623 #endif
3625 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3626 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3627 || (*src == '%' && *tail != '%')
3628 #endif
3631 #ifdef OS2 /* env vars only in uppercase */
3632 *var++ = TOUPPER_LOC(*tail);
3633 tail++; /* toupper() may be a macro! */
3634 #else
3635 *var++ = *tail++;
3636 #endif
3640 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3641 # ifdef UNIX
3642 if (src[1] == '{' && *tail != '}')
3643 # else
3644 if (*src == '%' && *tail != '%')
3645 # endif
3646 var = NULL;
3647 else
3649 # ifdef UNIX
3650 if (src[1] == '{')
3651 # else
3652 if (*src == '%')
3653 #endif
3654 ++tail;
3655 #endif
3656 *var = NUL;
3657 var = vim_getenv(dst, &mustfree);
3658 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3660 #endif
3662 /* home directory */
3663 else if ( src[1] == NUL
3664 || vim_ispathsep(src[1])
3665 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3667 var = homedir;
3668 tail = src + 1;
3670 else /* user directory */
3672 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3674 * Copy ~user to dst[], so we can put a NUL after it.
3676 tail = src;
3677 var = dst;
3678 c = dstlen - 1;
3679 while ( c-- > 0
3680 && *tail
3681 && vim_isfilec(*tail)
3682 && !vim_ispathsep(*tail))
3683 *var++ = *tail++;
3684 *var = NUL;
3685 # ifdef UNIX
3687 * If the system supports getpwnam(), use it.
3688 * Otherwise, or if getpwnam() fails, the shell is used to
3689 * expand ~user. This is slower and may fail if the shell
3690 * does not support ~user (old versions of /bin/sh).
3692 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3694 struct passwd *pw;
3696 /* Note: memory allocated by getpwnam() is never freed.
3697 * Calling endpwent() apparently doesn't help. */
3698 pw = getpwnam((char *)dst + 1);
3699 if (pw != NULL)
3700 var = (char_u *)pw->pw_dir;
3701 else
3702 var = NULL;
3704 if (var == NULL)
3705 # endif
3707 expand_T xpc;
3709 ExpandInit(&xpc);
3710 xpc.xp_context = EXPAND_FILES;
3711 var = ExpandOne(&xpc, dst, NULL,
3712 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
3713 mustfree = TRUE;
3716 # else /* !UNIX, thus VMS */
3718 * USER_HOME is a comma-separated list of
3719 * directories to search for the user account in.
3722 char_u test[MAXPATHL], paths[MAXPATHL];
3723 char_u *path, *next_path, *ptr;
3724 struct stat st;
3726 STRCPY(paths, USER_HOME);
3727 next_path = paths;
3728 while (*next_path)
3730 for (path = next_path; *next_path && *next_path != ',';
3731 next_path++);
3732 if (*next_path)
3733 *next_path++ = NUL;
3734 STRCPY(test, path);
3735 STRCAT(test, "/");
3736 STRCAT(test, dst + 1);
3737 if (mch_stat(test, &st) == 0)
3739 var = alloc(STRLEN(test) + 1);
3740 STRCPY(var, test);
3741 mustfree = TRUE;
3742 break;
3746 # endif /* UNIX */
3747 #else
3748 /* cannot expand user's home directory, so don't try */
3749 var = NULL;
3750 tail = (char_u *)""; /* for gcc */
3751 #endif /* UNIX || VMS */
3754 #ifdef BACKSLASH_IN_FILENAME
3755 /* If 'shellslash' is set change backslashes to forward slashes.
3756 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3757 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3759 char_u *p = vim_strsave(var);
3761 if (p != NULL)
3763 if (mustfree)
3764 vim_free(var);
3765 var = p;
3766 mustfree = TRUE;
3767 forward_slash(var);
3770 #endif
3772 /* If "var" contains white space, escape it with a backslash.
3773 * Required for ":e ~/tt" when $HOME includes a space. */
3774 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3776 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3778 if (p != NULL)
3780 if (mustfree)
3781 vim_free(var);
3782 var = p;
3783 mustfree = TRUE;
3787 if (var != NULL && *var != NUL
3788 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3790 STRCPY(dst, var);
3791 dstlen -= (int)STRLEN(var);
3792 c = (int)STRLEN(var);
3793 /* if var[] ends in a path separator and tail[] starts
3794 * with it, skip a character */
3795 if (*var != NUL && after_pathsep(dst, dst + c)
3796 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3797 && dst[-1] != ':'
3798 #endif
3799 && vim_ispathsep(*tail))
3800 ++tail;
3801 dst += c;
3802 src = tail;
3803 copy_char = FALSE;
3805 if (mustfree)
3806 vim_free(var);
3809 if (copy_char) /* copy at least one char */
3812 * Recognize the start of a new name, for '~'.
3813 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3814 * ":edit foo ~ foo".
3816 at_start = FALSE;
3817 if (src[0] == '\\' && src[1] != NUL)
3819 *dst++ = *src++;
3820 --dstlen;
3822 else if ((src[0] == ' ' || src[0] == ',') && !one)
3823 at_start = TRUE;
3824 *dst++ = *src++;
3825 --dstlen;
3827 if (startstr != NULL && src - startstr_len >= srcp
3828 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3829 at_start = TRUE;
3832 *dst = NUL;
3836 * Vim's version of getenv().
3837 * Special handling of $HOME, $VIM and $VIMRUNTIME.
3838 * Also does ACP to 'enc' conversion for Win32.
3840 char_u *
3841 vim_getenv(name, mustfree)
3842 char_u *name;
3843 int *mustfree; /* set to TRUE when returned is allocated */
3845 char_u *p;
3846 char_u *pend;
3847 int vimruntime;
3849 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3850 /* use "C:/" when $HOME is not set */
3851 if (STRCMP(name, "HOME") == 0)
3852 return homedir;
3853 #endif
3855 p = mch_getenv(name);
3856 if (p != NULL && *p == NUL) /* empty is the same as not set */
3857 p = NULL;
3859 if (p != NULL)
3861 #if defined(FEAT_MBYTE) && defined(WIN3264)
3862 if (enc_utf8)
3864 int len;
3865 char_u *pp;
3867 /* Convert from active codepage to UTF-8. Other conversions are
3868 * not done, because they would fail for non-ASCII characters. */
3869 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
3870 if (pp != NULL)
3872 p = pp;
3873 *mustfree = TRUE;
3876 #endif
3877 return p;
3880 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3881 if (!vimruntime && STRCMP(name, "VIM") != 0)
3882 return NULL;
3885 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3886 * Don't do this when default_vimruntime_dir is non-empty.
3888 if (vimruntime
3889 #ifdef HAVE_PATHDEF
3890 && *default_vimruntime_dir == NUL
3891 #endif
3894 p = mch_getenv((char_u *)"VIM");
3895 if (p != NULL && *p == NUL) /* empty is the same as not set */
3896 p = NULL;
3897 if (p != NULL)
3899 p = vim_version_dir(p);
3900 if (p != NULL)
3901 *mustfree = TRUE;
3902 else
3903 p = mch_getenv((char_u *)"VIM");
3905 #if defined(FEAT_MBYTE) && defined(WIN3264)
3906 if (enc_utf8)
3908 int len;
3909 char_u *pp;
3911 /* Convert from active codepage to UTF-8. Other conversions
3912 * are not done, because they would fail for non-ASCII
3913 * characters. */
3914 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
3915 if (pp != NULL)
3917 if (mustfree)
3918 vim_free(p);
3919 p = pp;
3920 *mustfree = TRUE;
3923 #endif
3928 * When expanding $VIM or $VIMRUNTIME fails, try using:
3929 * - the directory name from 'helpfile' (unless it contains '$')
3930 * - the executable name from argv[0]
3932 if (p == NULL)
3934 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3935 p = p_hf;
3936 #ifdef USE_EXE_NAME
3938 * Use the name of the executable, obtained from argv[0].
3940 else
3941 p = exe_name;
3942 #endif
3943 if (p != NULL)
3945 /* remove the file name */
3946 pend = gettail(p);
3948 /* remove "doc/" from 'helpfile', if present */
3949 if (p == p_hf)
3950 pend = remove_tail(p, pend, (char_u *)"doc");
3952 #ifdef USE_EXE_NAME
3953 # ifdef MACOS_X
3954 /* remove "MacOS" from exe_name and add "Resources/vim" */
3955 if (p == exe_name)
3957 char_u *pend1;
3958 char_u *pnew;
3960 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
3961 if (pend1 != pend)
3963 pnew = alloc((unsigned)(pend1 - p) + 15);
3964 if (pnew != NULL)
3966 STRNCPY(pnew, p, (pend1 - p));
3967 STRCPY(pnew + (pend1 - p), "Resources/vim");
3968 p = pnew;
3969 pend = p + STRLEN(p);
3973 # endif
3974 /* remove "src/" from exe_name, if present */
3975 if (p == exe_name)
3976 pend = remove_tail(p, pend, (char_u *)"src");
3977 #endif
3979 /* for $VIM, remove "runtime/" or "vim54/", if present */
3980 if (!vimruntime)
3982 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
3983 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
3986 /* remove trailing path separator */
3987 #ifndef MACOS_CLASSIC
3988 /* With MacOS path (with colons) the final colon is required */
3989 /* to avoid confusion between absolute and relative path */
3990 if (pend > p && after_pathsep(p, pend))
3991 --pend;
3992 #endif
3994 #ifdef MACOS_X
3995 if (p == exe_name || p == p_hf)
3996 #endif
3997 /* check that the result is a directory name */
3998 p = vim_strnsave(p, (int)(pend - p));
4000 if (p != NULL && !mch_isdir(p))
4002 vim_free(p);
4003 p = NULL;
4005 else
4007 #ifdef USE_EXE_NAME
4008 /* may add "/vim54" or "/runtime" if it exists */
4009 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4011 vim_free(p);
4012 p = pend;
4014 #endif
4015 *mustfree = TRUE;
4020 #ifdef HAVE_PATHDEF
4021 /* When there is a pathdef.c file we can use default_vim_dir and
4022 * default_vimruntime_dir */
4023 if (p == NULL)
4025 /* Only use default_vimruntime_dir when it is not empty */
4026 if (vimruntime && *default_vimruntime_dir != NUL)
4028 p = default_vimruntime_dir;
4029 *mustfree = FALSE;
4031 else if (*default_vim_dir != NUL)
4033 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4034 *mustfree = TRUE;
4035 else
4037 p = default_vim_dir;
4038 *mustfree = FALSE;
4042 #endif
4045 * Set the environment variable, so that the new value can be found fast
4046 * next time, and others can also use it (e.g. Perl).
4048 if (p != NULL)
4050 if (vimruntime)
4052 vim_setenv((char_u *)"VIMRUNTIME", p);
4053 didset_vimruntime = TRUE;
4054 #ifdef FEAT_GETTEXT
4056 char_u *buf = concat_str(p, (char_u *)"/lang");
4058 if (buf != NULL)
4060 bindtextdomain(VIMPACKAGE, (char *)buf);
4061 vim_free(buf);
4064 #endif
4066 else
4068 vim_setenv((char_u *)"VIM", p);
4069 didset_vim = TRUE;
4072 return p;
4076 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4077 * Return NULL if not, return its name in allocated memory otherwise.
4079 static char_u *
4080 vim_version_dir(vimdir)
4081 char_u *vimdir;
4083 char_u *p;
4085 if (vimdir == NULL || *vimdir == NUL)
4086 return NULL;
4087 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4088 if (p != NULL && mch_isdir(p))
4089 return p;
4090 vim_free(p);
4091 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4092 if (p != NULL && mch_isdir(p))
4093 return p;
4094 vim_free(p);
4095 return NULL;
4099 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4100 * the length of "name/". Otherwise return "pend".
4102 static char_u *
4103 remove_tail(p, pend, name)
4104 char_u *p;
4105 char_u *pend;
4106 char_u *name;
4108 int len = (int)STRLEN(name) + 1;
4109 char_u *newend = pend - len;
4111 if (newend >= p
4112 && fnamencmp(newend, name, len - 1) == 0
4113 && (newend == p || after_pathsep(p, newend)))
4114 return newend;
4115 return pend;
4119 * Our portable version of setenv.
4121 void
4122 vim_setenv(name, val)
4123 char_u *name;
4124 char_u *val;
4126 #ifdef HAVE_SETENV
4127 mch_setenv((char *)name, (char *)val, 1);
4128 #else
4129 char_u *envbuf;
4132 * Putenv does not copy the string, it has to remain
4133 * valid. The allocated memory will never be freed.
4135 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4136 if (envbuf != NULL)
4138 sprintf((char *)envbuf, "%s=%s", name, val);
4139 putenv((char *)envbuf);
4141 #endif
4144 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4146 * Function given to ExpandGeneric() to obtain an environment variable name.
4148 /*ARGSUSED*/
4149 char_u *
4150 get_env_name(xp, idx)
4151 expand_T *xp;
4152 int idx;
4154 # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4156 * No environ[] on the Amiga and on the Mac (using MPW).
4158 return NULL;
4159 # else
4160 # ifndef __WIN32__
4161 /* Borland C++ 5.2 has this in a header file. */
4162 extern char **environ;
4163 # endif
4164 # define ENVNAMELEN 100
4165 static char_u name[ENVNAMELEN];
4166 char_u *str;
4167 int n;
4169 str = (char_u *)environ[idx];
4170 if (str == NULL)
4171 return NULL;
4173 for (n = 0; n < ENVNAMELEN - 1; ++n)
4175 if (str[n] == '=' || str[n] == NUL)
4176 break;
4177 name[n] = str[n];
4179 name[n] = NUL;
4180 return name;
4181 # endif
4183 #endif
4186 * Replace home directory by "~" in each space or comma separated file name in
4187 * 'src'.
4188 * If anything fails (except when out of space) dst equals src.
4190 void
4191 home_replace(buf, src, dst, dstlen, one)
4192 buf_T *buf; /* when not NULL, check for help files */
4193 char_u *src; /* input file name */
4194 char_u *dst; /* where to put the result */
4195 int dstlen; /* maximum length of the result */
4196 int one; /* if TRUE, only replace one file name, include
4197 spaces and commas in the file name. */
4199 size_t dirlen = 0, envlen = 0;
4200 size_t len;
4201 char_u *homedir_env;
4202 char_u *p;
4204 if (src == NULL)
4206 *dst = NUL;
4207 return;
4211 * If the file is a help file, remove the path completely.
4213 if (buf != NULL && buf->b_help)
4215 STRCPY(dst, gettail(src));
4216 return;
4220 * We check both the value of the $HOME environment variable and the
4221 * "real" home directory.
4223 if (homedir != NULL)
4224 dirlen = STRLEN(homedir);
4226 #ifdef VMS
4227 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4228 #else
4229 homedir_env = mch_getenv((char_u *)"HOME");
4230 #endif
4232 if (homedir_env != NULL && *homedir_env == NUL)
4233 homedir_env = NULL;
4234 if (homedir_env != NULL)
4235 envlen = STRLEN(homedir_env);
4237 if (!one)
4238 src = skipwhite(src);
4239 while (*src && dstlen > 0)
4242 * Here we are at the beginning of a file name.
4243 * First, check to see if the beginning of the file name matches
4244 * $HOME or the "real" home directory. Check that there is a '/'
4245 * after the match (so that if e.g. the file is "/home/pieter/bla",
4246 * and the home directory is "/home/piet", the file does not end up
4247 * as "~er/bla" (which would seem to indicate the file "bla" in user
4248 * er's home directory)).
4250 p = homedir;
4251 len = dirlen;
4252 for (;;)
4254 if ( len
4255 && fnamencmp(src, p, len) == 0
4256 && (vim_ispathsep(src[len])
4257 || (!one && (src[len] == ',' || src[len] == ' '))
4258 || src[len] == NUL))
4260 src += len;
4261 if (--dstlen > 0)
4262 *dst++ = '~';
4265 * If it's just the home directory, add "/".
4267 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4268 *dst++ = '/';
4269 break;
4271 if (p == homedir_env)
4272 break;
4273 p = homedir_env;
4274 len = envlen;
4277 /* if (!one) skip to separator: space or comma */
4278 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4279 *dst++ = *src++;
4280 /* skip separator */
4281 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4282 *dst++ = *src++;
4284 /* if (dstlen == 0) out of space, what to do??? */
4286 *dst = NUL;
4290 * Like home_replace, store the replaced string in allocated memory.
4291 * When something fails, NULL is returned.
4293 char_u *
4294 home_replace_save(buf, src)
4295 buf_T *buf; /* when not NULL, check for help files */
4296 char_u *src; /* input file name */
4298 char_u *dst;
4299 unsigned len;
4301 len = 3; /* space for "~/" and trailing NUL */
4302 if (src != NULL) /* just in case */
4303 len += (unsigned)STRLEN(src);
4304 dst = alloc(len);
4305 if (dst != NULL)
4306 home_replace(buf, src, dst, len, TRUE);
4307 return dst;
4311 * Compare two file names and return:
4312 * FPC_SAME if they both exist and are the same file.
4313 * FPC_SAMEX if they both don't exist and have the same file name.
4314 * FPC_DIFF if they both exist and are different files.
4315 * FPC_NOTX if they both don't exist.
4316 * FPC_DIFFX if one of them doesn't exist.
4317 * For the first name environment variables are expanded
4320 fullpathcmp(s1, s2, checkname)
4321 char_u *s1, *s2;
4322 int checkname; /* when both don't exist, check file names */
4324 #ifdef UNIX
4325 char_u exp1[MAXPATHL];
4326 char_u full1[MAXPATHL];
4327 char_u full2[MAXPATHL];
4328 struct stat st1, st2;
4329 int r1, r2;
4331 expand_env(s1, exp1, MAXPATHL);
4332 r1 = mch_stat((char *)exp1, &st1);
4333 r2 = mch_stat((char *)s2, &st2);
4334 if (r1 != 0 && r2 != 0)
4336 /* if mch_stat() doesn't work, may compare the names */
4337 if (checkname)
4339 if (fnamecmp(exp1, s2) == 0)
4340 return FPC_SAMEX;
4341 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4342 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4343 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4344 return FPC_SAMEX;
4346 return FPC_NOTX;
4348 if (r1 != 0 || r2 != 0)
4349 return FPC_DIFFX;
4350 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4351 return FPC_SAME;
4352 return FPC_DIFF;
4353 #else
4354 char_u *exp1; /* expanded s1 */
4355 char_u *full1; /* full path of s1 */
4356 char_u *full2; /* full path of s2 */
4357 int retval = FPC_DIFF;
4358 int r1, r2;
4360 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4361 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4363 full1 = exp1 + MAXPATHL;
4364 full2 = full1 + MAXPATHL;
4366 expand_env(s1, exp1, MAXPATHL);
4367 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4368 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4370 /* If vim_FullName() fails, the file probably doesn't exist. */
4371 if (r1 != OK && r2 != OK)
4373 if (checkname && fnamecmp(exp1, s2) == 0)
4374 retval = FPC_SAMEX;
4375 else
4376 retval = FPC_NOTX;
4378 else if (r1 != OK || r2 != OK)
4379 retval = FPC_DIFFX;
4380 else if (fnamecmp(full1, full2))
4381 retval = FPC_DIFF;
4382 else
4383 retval = FPC_SAME;
4384 vim_free(exp1);
4386 return retval;
4387 #endif
4391 * Get the tail of a path: the file name.
4392 * Fail safe: never returns NULL.
4394 char_u *
4395 gettail(fname)
4396 char_u *fname;
4398 char_u *p1, *p2;
4400 if (fname == NULL)
4401 return (char_u *)"";
4402 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4404 if (vim_ispathsep(*p2))
4405 p1 = p2 + 1;
4406 mb_ptr_adv(p2);
4408 return p1;
4412 * Get pointer to tail of "fname", including path separators. Putting a NUL
4413 * here leaves the directory name. Takes care of "c:/" and "//".
4414 * Always returns a valid pointer.
4416 char_u *
4417 gettail_sep(fname)
4418 char_u *fname;
4420 char_u *p;
4421 char_u *t;
4423 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4424 t = gettail(fname);
4425 while (t > p && after_pathsep(fname, t))
4426 --t;
4427 #ifdef VMS
4428 /* path separator is part of the path */
4429 ++t;
4430 #endif
4431 return t;
4435 * get the next path component (just after the next path separator).
4437 char_u *
4438 getnextcomp(fname)
4439 char_u *fname;
4441 while (*fname && !vim_ispathsep(*fname))
4442 mb_ptr_adv(fname);
4443 if (*fname)
4444 ++fname;
4445 return fname;
4449 * Get a pointer to one character past the head of a path name.
4450 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4451 * If there is no head, path is returned.
4453 char_u *
4454 get_past_head(path)
4455 char_u *path;
4457 char_u *retval;
4459 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4460 /* may skip "c:" */
4461 if (isalpha(path[0]) && path[1] == ':')
4462 retval = path + 2;
4463 else
4464 retval = path;
4465 #else
4466 # if defined(AMIGA)
4467 /* may skip "label:" */
4468 retval = vim_strchr(path, ':');
4469 if (retval == NULL)
4470 retval = path;
4471 # else /* Unix */
4472 retval = path;
4473 # endif
4474 #endif
4476 while (vim_ispathsep(*retval))
4477 ++retval;
4479 return retval;
4483 * return TRUE if 'c' is a path separator.
4486 vim_ispathsep(c)
4487 int c;
4489 #ifdef RISCOS
4490 return (c == '.' || c == ':');
4491 #else
4492 # ifdef UNIX
4493 return (c == '/'); /* UNIX has ':' inside file names */
4494 # else
4495 # ifdef BACKSLASH_IN_FILENAME
4496 return (c == ':' || c == '/' || c == '\\');
4497 # else
4498 # ifdef VMS
4499 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4500 return (c == ':' || c == '[' || c == ']' || c == '/'
4501 || c == '<' || c == '>' || c == '"' );
4502 # else /* Amiga */
4503 return (c == ':' || c == '/');
4504 # endif /* VMS */
4505 # endif
4506 # endif
4507 #endif /* RISC OS */
4510 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
4512 * return TRUE if 'c' is a path list separator.
4515 vim_ispathlistsep(c)
4516 int c;
4518 #ifdef UNIX
4519 return (c == ':');
4520 #else
4521 return (c == ';'); /* might not be right for every system... */
4522 #endif
4524 #endif
4526 #if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4527 || defined(FEAT_EVAL) || defined(PROTO)
4529 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4530 * It's done in-place.
4532 void
4533 shorten_dir(str)
4534 char_u *str;
4536 char_u *tail, *s, *d;
4537 int skip = FALSE;
4539 tail = gettail(str);
4540 d = str;
4541 for (s = str; ; ++s)
4543 if (s >= tail) /* copy the whole tail */
4545 *d++ = *s;
4546 if (*s == NUL)
4547 break;
4549 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4551 *d++ = *s;
4552 skip = FALSE;
4554 else if (!skip)
4556 *d++ = *s; /* copy next char */
4557 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4558 skip = TRUE;
4559 # ifdef FEAT_MBYTE
4560 if (has_mbyte)
4562 int l = mb_ptr2len(s);
4564 while (--l > 0)
4565 *d++ = *++s;
4567 # endif
4571 #endif
4574 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4575 * Also returns TRUE if there is no directory name.
4576 * "fname" must be writable!.
4579 dir_of_file_exists(fname)
4580 char_u *fname;
4582 char_u *p;
4583 int c;
4584 int retval;
4586 p = gettail_sep(fname);
4587 if (p == fname)
4588 return TRUE;
4589 c = *p;
4590 *p = NUL;
4591 retval = mch_isdir(fname);
4592 *p = c;
4593 return retval;
4596 #if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4597 || defined(PROTO)
4599 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4602 vim_fnamecmp(x, y)
4603 char_u *x, *y;
4605 return vim_fnamencmp(x, y, MAXPATHL);
4609 vim_fnamencmp(x, y, len)
4610 char_u *x, *y;
4611 size_t len;
4613 while (len > 0 && *x && *y)
4615 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4616 && !(*x == '/' && *y == '\\')
4617 && !(*x == '\\' && *y == '/'))
4618 break;
4619 ++x;
4620 ++y;
4621 --len;
4623 if (len == 0)
4624 return 0;
4625 return (*x - *y);
4627 #endif
4630 * Concatenate file names fname1 and fname2 into allocated memory.
4631 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
4633 char_u *
4634 concat_fnames(fname1, fname2, sep)
4635 char_u *fname1;
4636 char_u *fname2;
4637 int sep;
4639 char_u *dest;
4641 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4642 if (dest != NULL)
4644 STRCPY(dest, fname1);
4645 if (sep)
4646 add_pathsep(dest);
4647 STRCAT(dest, fname2);
4649 return dest;
4652 #if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4654 * Concatenate two strings and return the result in allocated memory.
4655 * Returns NULL when out of memory.
4657 char_u *
4658 concat_str(str1, str2)
4659 char_u *str1;
4660 char_u *str2;
4662 char_u *dest;
4663 size_t l = STRLEN(str1);
4665 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4666 if (dest != NULL)
4668 STRCPY(dest, str1);
4669 STRCPY(dest + l, str2);
4671 return dest;
4673 #endif
4676 * Add a path separator to a file name, unless it already ends in a path
4677 * separator.
4679 void
4680 add_pathsep(p)
4681 char_u *p;
4683 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
4684 STRCAT(p, PATHSEPSTR);
4688 * FullName_save - Make an allocated copy of a full file name.
4689 * Returns NULL when out of memory.
4691 char_u *
4692 FullName_save(fname, force)
4693 char_u *fname;
4694 int force; /* force expansion, even when it already looks
4695 like a full path name */
4697 char_u *buf;
4698 char_u *new_fname = NULL;
4700 if (fname == NULL)
4701 return NULL;
4703 buf = alloc((unsigned)MAXPATHL);
4704 if (buf != NULL)
4706 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4707 new_fname = vim_strsave(buf);
4708 else
4709 new_fname = vim_strsave(fname);
4710 vim_free(buf);
4712 return new_fname;
4715 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4717 static char_u *skip_string __ARGS((char_u *p));
4720 * Find the start of a comment, not knowing if we are in a comment right now.
4721 * Search starts at w_cursor.lnum and goes backwards.
4723 pos_T *
4724 find_start_comment(ind_maxcomment) /* XXX */
4725 int ind_maxcomment;
4727 pos_T *pos;
4728 char_u *line;
4729 char_u *p;
4730 int cur_maxcomment = ind_maxcomment;
4732 for (;;)
4734 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4735 if (pos == NULL)
4736 break;
4739 * Check if the comment start we found is inside a string.
4740 * If it is then restrict the search to below this line and try again.
4742 line = ml_get(pos->lnum);
4743 for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
4744 p = skip_string(p);
4745 if ((unsigned)(p - line) <= pos->col)
4746 break;
4747 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4748 if (cur_maxcomment <= 0)
4750 pos = NULL;
4751 break;
4754 return pos;
4758 * Skip to the end of a "string" and a 'c' character.
4759 * If there is no string or character, return argument unmodified.
4761 static char_u *
4762 skip_string(p)
4763 char_u *p;
4765 int i;
4768 * We loop, because strings may be concatenated: "date""time".
4770 for ( ; ; ++p)
4772 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4774 if (!p[1]) /* ' at end of line */
4775 break;
4776 i = 2;
4777 if (p[1] == '\\') /* '\n' or '\000' */
4779 ++i;
4780 while (vim_isdigit(p[i - 1])) /* '\000' */
4781 ++i;
4783 if (p[i] == '\'') /* check for trailing ' */
4785 p += i;
4786 continue;
4789 else if (p[0] == '"') /* start of string */
4791 for (++p; p[0]; ++p)
4793 if (p[0] == '\\' && p[1] != NUL)
4794 ++p;
4795 else if (p[0] == '"') /* end of string */
4796 break;
4798 if (p[0] == '"')
4799 continue;
4801 break; /* no string found */
4803 if (!*p)
4804 --p; /* backup from NUL */
4805 return p;
4807 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
4809 #if defined(FEAT_CINDENT) || defined(PROTO)
4812 * Do C or expression indenting on the current line.
4814 void
4815 do_c_expr_indent()
4817 # ifdef FEAT_EVAL
4818 if (*curbuf->b_p_inde != NUL)
4819 fixthisline(get_expr_indent);
4820 else
4821 # endif
4822 fixthisline(get_c_indent);
4826 * Functions for C-indenting.
4827 * Most of this originally comes from Eric Fischer.
4830 * Below "XXX" means that this function may unlock the current line.
4833 static char_u *cin_skipcomment __ARGS((char_u *));
4834 static int cin_nocode __ARGS((char_u *));
4835 static pos_T *find_line_comment __ARGS((void));
4836 static int cin_islabel_skip __ARGS((char_u **));
4837 static int cin_isdefault __ARGS((char_u *));
4838 static char_u *after_label __ARGS((char_u *l));
4839 static int get_indent_nolabel __ARGS((linenr_T lnum));
4840 static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4841 static int cin_first_id_amount __ARGS((void));
4842 static int cin_get_equal_amount __ARGS((linenr_T lnum));
4843 static int cin_ispreproc __ARGS((char_u *));
4844 static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4845 static int cin_iscomment __ARGS((char_u *));
4846 static int cin_islinecomment __ARGS((char_u *));
4847 static int cin_isterminated __ARGS((char_u *, int, int));
4848 static int cin_isinit __ARGS((void));
4849 static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4850 static int cin_isif __ARGS((char_u *));
4851 static int cin_iselse __ARGS((char_u *));
4852 static int cin_isdo __ARGS((char_u *));
4853 static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
4854 static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
4855 static int cin_isbreak __ARGS((char_u *));
4856 static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
4857 static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
4858 static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4859 static int cin_skip2pos __ARGS((pos_T *trypos));
4860 static pos_T *find_start_brace __ARGS((int));
4861 static pos_T *find_match_paren __ARGS((int, int));
4862 static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4863 static int find_last_paren __ARGS((char_u *l, int start, int end));
4864 static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4866 static int ind_hash_comment = 0; /* # starts a comment */
4869 * Skip over white space and C comments within the line.
4870 * Also skip over Perl/shell comments if desired.
4872 static char_u *
4873 cin_skipcomment(s)
4874 char_u *s;
4876 while (*s)
4878 char_u *prev_s = s;
4880 s = skipwhite(s);
4882 /* Perl/shell # comment comment continues until eol. Require a space
4883 * before # to avoid recognizing $#array. */
4884 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
4886 s += STRLEN(s);
4887 break;
4889 if (*s != '/')
4890 break;
4891 ++s;
4892 if (*s == '/') /* slash-slash comment continues till eol */
4894 s += STRLEN(s);
4895 break;
4897 if (*s != '*')
4898 break;
4899 for (++s; *s; ++s) /* skip slash-star comment */
4900 if (s[0] == '*' && s[1] == '/')
4902 s += 2;
4903 break;
4906 return s;
4910 * Return TRUE if there there is no code at *s. White space and comments are
4911 * not considered code.
4913 static int
4914 cin_nocode(s)
4915 char_u *s;
4917 return *cin_skipcomment(s) == NUL;
4921 * Check previous lines for a "//" line comment, skipping over blank lines.
4923 static pos_T *
4924 find_line_comment() /* XXX */
4926 static pos_T pos;
4927 char_u *line;
4928 char_u *p;
4930 pos = curwin->w_cursor;
4931 while (--pos.lnum > 0)
4933 line = ml_get(pos.lnum);
4934 p = skipwhite(line);
4935 if (cin_islinecomment(p))
4937 pos.col = (int)(p - line);
4938 return &pos;
4940 if (*p != NUL)
4941 break;
4943 return NULL;
4947 * Check if string matches "label:"; move to character after ':' if true.
4949 static int
4950 cin_islabel_skip(s)
4951 char_u **s;
4953 if (!vim_isIDc(**s)) /* need at least one ID character */
4954 return FALSE;
4956 while (vim_isIDc(**s))
4957 (*s)++;
4959 *s = cin_skipcomment(*s);
4961 /* "::" is not a label, it's C++ */
4962 return (**s == ':' && *++*s != ':');
4966 * Recognize a label: "label:".
4967 * Note: curwin->w_cursor must be where we are looking for the label.
4970 cin_islabel(ind_maxcomment) /* XXX */
4971 int ind_maxcomment;
4973 char_u *s;
4975 s = cin_skipcomment(ml_get_curline());
4978 * Exclude "default" from labels, since it should be indented
4979 * like a switch label. Same for C++ scope declarations.
4981 if (cin_isdefault(s))
4982 return FALSE;
4983 if (cin_isscopedecl(s))
4984 return FALSE;
4986 if (cin_islabel_skip(&s))
4989 * Only accept a label if the previous line is terminated or is a case
4990 * label.
4992 pos_T cursor_save;
4993 pos_T *trypos;
4994 char_u *line;
4996 cursor_save = curwin->w_cursor;
4997 while (curwin->w_cursor.lnum > 1)
4999 --curwin->w_cursor.lnum;
5002 * If we're in a comment now, skip to the start of the comment.
5004 curwin->w_cursor.col = 0;
5005 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5006 curwin->w_cursor = *trypos;
5008 line = ml_get_curline();
5009 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5010 continue;
5011 if (*(line = cin_skipcomment(line)) == NUL)
5012 continue;
5014 curwin->w_cursor = cursor_save;
5015 if (cin_isterminated(line, TRUE, FALSE)
5016 || cin_isscopedecl(line)
5017 || cin_iscase(line)
5018 || (cin_islabel_skip(&line) && cin_nocode(line)))
5019 return TRUE;
5020 return FALSE;
5022 curwin->w_cursor = cursor_save;
5023 return TRUE; /* label at start of file??? */
5025 return FALSE;
5029 * Recognize structure initialization and enumerations.
5030 * Q&D-Implementation:
5031 * check for "=" at end or "[typedef] enum" at beginning of line.
5033 static int
5034 cin_isinit(void)
5036 char_u *s;
5038 s = cin_skipcomment(ml_get_curline());
5040 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5041 s = cin_skipcomment(s + 7);
5043 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5044 return TRUE;
5046 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5047 return TRUE;
5049 return FALSE;
5053 * Recognize a switch label: "case .*:" or "default:".
5056 cin_iscase(s)
5057 char_u *s;
5059 s = cin_skipcomment(s);
5060 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5062 for (s += 4; *s; ++s)
5064 s = cin_skipcomment(s);
5065 if (*s == ':')
5067 if (s[1] == ':') /* skip over "::" for C++ */
5068 ++s;
5069 else
5070 return TRUE;
5072 if (*s == '\'' && s[1] && s[2] == '\'')
5073 s += 2; /* skip over '.' */
5074 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5075 return FALSE; /* stop at comment */
5076 else if (*s == '"')
5077 return FALSE; /* stop at string */
5079 return FALSE;
5082 if (cin_isdefault(s))
5083 return TRUE;
5084 return FALSE;
5088 * Recognize a "default" switch label.
5090 static int
5091 cin_isdefault(s)
5092 char_u *s;
5094 return (STRNCMP(s, "default", 7) == 0
5095 && *(s = cin_skipcomment(s + 7)) == ':'
5096 && s[1] != ':');
5100 * Recognize a "public/private/proctected" scope declaration label.
5103 cin_isscopedecl(s)
5104 char_u *s;
5106 int i;
5108 s = cin_skipcomment(s);
5109 if (STRNCMP(s, "public", 6) == 0)
5110 i = 6;
5111 else if (STRNCMP(s, "protected", 9) == 0)
5112 i = 9;
5113 else if (STRNCMP(s, "private", 7) == 0)
5114 i = 7;
5115 else
5116 return FALSE;
5117 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5121 * Return a pointer to the first non-empty non-comment character after a ':'.
5122 * Return NULL if not found.
5123 * case 234: a = b;
5126 static char_u *
5127 after_label(l)
5128 char_u *l;
5130 for ( ; *l; ++l)
5132 if (*l == ':')
5134 if (l[1] == ':') /* skip over "::" for C++ */
5135 ++l;
5136 else if (!cin_iscase(l + 1))
5137 break;
5139 else if (*l == '\'' && l[1] && l[2] == '\'')
5140 l += 2; /* skip over 'x' */
5142 if (*l == NUL)
5143 return NULL;
5144 l = cin_skipcomment(l + 1);
5145 if (*l == NUL)
5146 return NULL;
5147 return l;
5151 * Get indent of line "lnum", skipping a label.
5152 * Return 0 if there is nothing after the label.
5154 static int
5155 get_indent_nolabel(lnum) /* XXX */
5156 linenr_T lnum;
5158 char_u *l;
5159 pos_T fp;
5160 colnr_T col;
5161 char_u *p;
5163 l = ml_get(lnum);
5164 p = after_label(l);
5165 if (p == NULL)
5166 return 0;
5168 fp.col = (colnr_T)(p - l);
5169 fp.lnum = lnum;
5170 getvcol(curwin, &fp, &col, NULL, NULL);
5171 return (int)col;
5175 * Find indent for line "lnum", ignoring any case or jump label.
5176 * Also return a pointer to the text (after the label) in "pp".
5177 * label: if (asdf && asdfasdf)
5180 static int
5181 skip_label(lnum, pp, ind_maxcomment)
5182 linenr_T lnum;
5183 char_u **pp;
5184 int ind_maxcomment;
5186 char_u *l;
5187 int amount;
5188 pos_T cursor_save;
5190 cursor_save = curwin->w_cursor;
5191 curwin->w_cursor.lnum = lnum;
5192 l = ml_get_curline();
5193 /* XXX */
5194 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5196 amount = get_indent_nolabel(lnum);
5197 l = after_label(ml_get_curline());
5198 if (l == NULL) /* just in case */
5199 l = ml_get_curline();
5201 else
5203 amount = get_indent();
5204 l = ml_get_curline();
5206 *pp = l;
5208 curwin->w_cursor = cursor_save;
5209 return amount;
5213 * Return the indent of the first variable name after a type in a declaration.
5214 * int a, indent of "a"
5215 * static struct foo b, indent of "b"
5216 * enum bla c, indent of "c"
5217 * Returns zero when it doesn't look like a declaration.
5219 static int
5220 cin_first_id_amount()
5222 char_u *line, *p, *s;
5223 int len;
5224 pos_T fp;
5225 colnr_T col;
5227 line = ml_get_curline();
5228 p = skipwhite(line);
5229 len = (int)(skiptowhite(p) - p);
5230 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5232 p = skipwhite(p + 6);
5233 len = (int)(skiptowhite(p) - p);
5235 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5236 p = skipwhite(p + 6);
5237 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5238 p = skipwhite(p + 4);
5239 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5240 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5242 s = skipwhite(p + len);
5243 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5244 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5245 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5246 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5247 p = s;
5249 for (len = 0; vim_isIDc(p[len]); ++len)
5251 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5252 return 0;
5254 p = skipwhite(p + len);
5255 fp.lnum = curwin->w_cursor.lnum;
5256 fp.col = (colnr_T)(p - line);
5257 getvcol(curwin, &fp, &col, NULL, NULL);
5258 return (int)col;
5262 * Return the indent of the first non-blank after an equal sign.
5263 * char *foo = "here";
5264 * Return zero if no (useful) equal sign found.
5265 * Return -1 if the line above "lnum" ends in a backslash.
5266 * foo = "asdf\
5267 * asdf\
5268 * here";
5270 static int
5271 cin_get_equal_amount(lnum)
5272 linenr_T lnum;
5274 char_u *line;
5275 char_u *s;
5276 colnr_T col;
5277 pos_T fp;
5279 if (lnum > 1)
5281 line = ml_get(lnum - 1);
5282 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5283 return -1;
5286 line = s = ml_get(lnum);
5287 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5289 if (cin_iscomment(s)) /* ignore comments */
5290 s = cin_skipcomment(s);
5291 else
5292 ++s;
5294 if (*s != '=')
5295 return 0;
5297 s = skipwhite(s + 1);
5298 if (cin_nocode(s))
5299 return 0;
5301 if (*s == '"') /* nice alignment for continued strings */
5302 ++s;
5304 fp.lnum = lnum;
5305 fp.col = (colnr_T)(s - line);
5306 getvcol(curwin, &fp, &col, NULL, NULL);
5307 return (int)col;
5311 * Recognize a preprocessor statement: Any line that starts with '#'.
5313 static int
5314 cin_ispreproc(s)
5315 char_u *s;
5317 s = skipwhite(s);
5318 if (*s == '#')
5319 return TRUE;
5320 return FALSE;
5324 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5325 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5326 * start and return the line in "*pp".
5328 static int
5329 cin_ispreproc_cont(pp, lnump)
5330 char_u **pp;
5331 linenr_T *lnump;
5333 char_u *line = *pp;
5334 linenr_T lnum = *lnump;
5335 int retval = FALSE;
5337 for (;;)
5339 if (cin_ispreproc(line))
5341 retval = TRUE;
5342 *lnump = lnum;
5343 break;
5345 if (lnum == 1)
5346 break;
5347 line = ml_get(--lnum);
5348 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5349 break;
5352 if (lnum != *lnump)
5353 *pp = ml_get(*lnump);
5354 return retval;
5358 * Recognize the start of a C or C++ comment.
5360 static int
5361 cin_iscomment(p)
5362 char_u *p;
5364 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5368 * Recognize the start of a "//" comment.
5370 static int
5371 cin_islinecomment(p)
5372 char_u *p;
5374 return (p[0] == '/' && p[1] == '/');
5378 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5379 * Don't consider "} else" a terminated line.
5380 * Return the character terminating the line (ending char's have precedence if
5381 * both apply in order to determine initializations).
5383 static int
5384 cin_isterminated(s, incl_open, incl_comma)
5385 char_u *s;
5386 int incl_open; /* include '{' at the end as terminator */
5387 int incl_comma; /* recognize a trailing comma */
5389 char_u found_start = 0;
5391 s = cin_skipcomment(s);
5393 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5394 found_start = *s;
5396 while (*s)
5398 /* skip over comments, "" strings and 'c'haracters */
5399 s = skip_string(cin_skipcomment(s));
5400 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5401 || (incl_comma && *s == ','))
5402 && cin_nocode(s + 1))
5403 return *s;
5405 if (*s)
5406 s++;
5408 return found_start;
5412 * Recognize the basic picture of a function declaration -- it needs to
5413 * have an open paren somewhere and a close paren at the end of the line and
5414 * no semicolons anywhere.
5415 * When a line ends in a comma we continue looking in the next line.
5416 * "sp" points to a string with the line. When looking at other lines it must
5417 * be restored to the line. When it's NULL fetch lines here.
5418 * "lnum" is where we start looking.
5420 static int
5421 cin_isfuncdecl(sp, first_lnum)
5422 char_u **sp;
5423 linenr_T first_lnum;
5425 char_u *s;
5426 linenr_T lnum = first_lnum;
5427 int retval = FALSE;
5429 if (sp == NULL)
5430 s = ml_get(lnum);
5431 else
5432 s = *sp;
5434 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5436 if (cin_iscomment(s)) /* ignore comments */
5437 s = cin_skipcomment(s);
5438 else
5439 ++s;
5441 if (*s != '(')
5442 return FALSE; /* ';', ' or " before any () or no '(' */
5444 while (*s && *s != ';' && *s != '\'' && *s != '"')
5446 if (*s == ')' && cin_nocode(s + 1))
5448 /* ')' at the end: may have found a match
5449 * Check for he previous line not to end in a backslash:
5450 * #if defined(x) && \
5451 * defined(y)
5453 lnum = first_lnum - 1;
5454 s = ml_get(lnum);
5455 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5456 retval = TRUE;
5457 goto done;
5459 if (*s == ',' && cin_nocode(s + 1))
5461 /* ',' at the end: continue looking in the next line */
5462 if (lnum >= curbuf->b_ml.ml_line_count)
5463 break;
5465 s = ml_get(++lnum);
5467 else if (cin_iscomment(s)) /* ignore comments */
5468 s = cin_skipcomment(s);
5469 else
5470 ++s;
5473 done:
5474 if (lnum != first_lnum && sp != NULL)
5475 *sp = ml_get(first_lnum);
5477 return retval;
5480 static int
5481 cin_isif(p)
5482 char_u *p;
5484 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5487 static int
5488 cin_iselse(p)
5489 char_u *p;
5491 if (*p == '}') /* accept "} else" */
5492 p = cin_skipcomment(p + 1);
5493 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5496 static int
5497 cin_isdo(p)
5498 char_u *p;
5500 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5504 * Check if this is a "while" that should have a matching "do".
5505 * We only accept a "while (condition) ;", with only white space between the
5506 * ')' and ';'. The condition may be spread over several lines.
5508 static int
5509 cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5510 char_u *p;
5511 linenr_T lnum;
5512 int ind_maxparen;
5514 pos_T cursor_save;
5515 pos_T *trypos;
5516 int retval = FALSE;
5518 p = cin_skipcomment(p);
5519 if (*p == '}') /* accept "} while (cond);" */
5520 p = cin_skipcomment(p + 1);
5521 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5523 cursor_save = curwin->w_cursor;
5524 curwin->w_cursor.lnum = lnum;
5525 curwin->w_cursor.col = 0;
5526 p = ml_get_curline();
5527 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5529 ++p;
5530 ++curwin->w_cursor.col;
5532 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5533 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5534 retval = TRUE;
5535 curwin->w_cursor = cursor_save;
5537 return retval;
5541 * Return TRUE if we are at the end of a do-while.
5542 * do
5543 * nothing;
5544 * while (foo
5545 * && bar); <-- here
5546 * Adjust the cursor to the line with "while".
5548 static int
5549 cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5550 int terminated;
5551 int ind_maxparen;
5552 int ind_maxcomment;
5554 char_u *line;
5555 char_u *p;
5556 char_u *s;
5557 pos_T *trypos;
5558 int i;
5560 if (terminated != ';') /* there must be a ';' at the end */
5561 return FALSE;
5563 p = line = ml_get_curline();
5564 while (*p != NUL)
5566 p = cin_skipcomment(p);
5567 if (*p == ')')
5569 s = skipwhite(p + 1);
5570 if (*s == ';' && cin_nocode(s + 1))
5572 /* Found ");" at end of the line, now check there is "while"
5573 * before the matching '('. XXX */
5574 i = (int)(p - line);
5575 curwin->w_cursor.col = i;
5576 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5577 if (trypos != NULL)
5579 s = cin_skipcomment(ml_get(trypos->lnum));
5580 if (*s == '}') /* accept "} while (cond);" */
5581 s = cin_skipcomment(s + 1);
5582 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5584 curwin->w_cursor.lnum = trypos->lnum;
5585 return TRUE;
5589 /* Searching may have made "line" invalid, get it again. */
5590 line = ml_get_curline();
5591 p = line + i;
5594 if (*p != NUL)
5595 ++p;
5597 return FALSE;
5600 static int
5601 cin_isbreak(p)
5602 char_u *p;
5604 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5608 * Find the position of a C++ base-class declaration or
5609 * constructor-initialization. eg:
5611 * class MyClass :
5612 * baseClass <-- here
5613 * class MyClass : public baseClass,
5614 * anotherBaseClass <-- here (should probably lineup ??)
5615 * MyClass::MyClass(...) :
5616 * baseClass(...) <-- here (constructor-initialization)
5618 * This is a lot of guessing. Watch out for "cond ? func() : foo".
5620 static int
5621 cin_is_cpp_baseclass(col)
5622 colnr_T *col; /* return: column to align with */
5624 char_u *s;
5625 int class_or_struct, lookfor_ctor_init, cpp_base_class;
5626 linenr_T lnum = curwin->w_cursor.lnum;
5627 char_u *line = ml_get_curline();
5629 *col = 0;
5631 s = skipwhite(line);
5632 if (*s == '#') /* skip #define FOO x ? (x) : x */
5633 return FALSE;
5634 s = cin_skipcomment(s);
5635 if (*s == NUL)
5636 return FALSE;
5638 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5640 /* Search for a line starting with '#', empty, ending in ';' or containing
5641 * '{' or '}' and start below it. This handles the following situations:
5642 * a = cond ?
5643 * func() :
5644 * asdf;
5645 * func::foo()
5646 * : something
5647 * {}
5648 * Foo::Foo (int one, int two)
5649 * : something(4),
5650 * somethingelse(3)
5651 * {}
5653 while (lnum > 1)
5655 line = ml_get(lnum - 1);
5656 s = skipwhite(line);
5657 if (*s == '#' || *s == NUL)
5658 break;
5659 while (*s != NUL)
5661 s = cin_skipcomment(s);
5662 if (*s == '{' || *s == '}'
5663 || (*s == ';' && cin_nocode(s + 1)))
5664 break;
5665 if (*s != NUL)
5666 ++s;
5668 if (*s != NUL)
5669 break;
5670 --lnum;
5673 line = ml_get(lnum);
5674 s = cin_skipcomment(line);
5675 for (;;)
5677 if (*s == NUL)
5679 if (lnum == curwin->w_cursor.lnum)
5680 break;
5681 /* Continue in the cursor line. */
5682 line = ml_get(++lnum);
5683 s = cin_skipcomment(line);
5684 if (*s == NUL)
5685 continue;
5688 if (s[0] == ':')
5690 if (s[1] == ':')
5692 /* skip double colon. It can't be a constructor
5693 * initialization any more */
5694 lookfor_ctor_init = FALSE;
5695 s = cin_skipcomment(s + 2);
5697 else if (lookfor_ctor_init || class_or_struct)
5699 /* we have something found, that looks like the start of
5700 * cpp-base-class-declaration or constructor-initialization */
5701 cpp_base_class = TRUE;
5702 lookfor_ctor_init = class_or_struct = FALSE;
5703 *col = 0;
5704 s = cin_skipcomment(s + 1);
5706 else
5707 s = cin_skipcomment(s + 1);
5709 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5710 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5712 class_or_struct = TRUE;
5713 lookfor_ctor_init = FALSE;
5715 if (*s == 'c')
5716 s = cin_skipcomment(s + 5);
5717 else
5718 s = cin_skipcomment(s + 6);
5720 else
5722 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5724 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5726 else if (s[0] == ')')
5728 /* Constructor-initialization is assumed if we come across
5729 * something like "):" */
5730 class_or_struct = FALSE;
5731 lookfor_ctor_init = TRUE;
5733 else if (s[0] == '?')
5735 /* Avoid seeing '() :' after '?' as constructor init. */
5736 return FALSE;
5738 else if (!vim_isIDc(s[0]))
5740 /* if it is not an identifier, we are wrong */
5741 class_or_struct = FALSE;
5742 lookfor_ctor_init = FALSE;
5744 else if (*col == 0)
5746 /* it can't be a constructor-initialization any more */
5747 lookfor_ctor_init = FALSE;
5749 /* the first statement starts here: lineup with this one... */
5750 if (cpp_base_class)
5751 *col = (colnr_T)(s - line);
5754 /* When the line ends in a comma don't align with it. */
5755 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5756 *col = 0;
5758 s = cin_skipcomment(s + 1);
5762 return cpp_base_class;
5765 static int
5766 get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5767 int col;
5768 int ind_maxparen;
5769 int ind_maxcomment;
5770 int ind_cpp_baseclass;
5772 int amount;
5773 colnr_T vcol;
5774 pos_T *trypos;
5776 if (col == 0)
5778 amount = get_indent();
5779 if (find_last_paren(ml_get_curline(), '(', ')')
5780 && (trypos = find_match_paren(ind_maxparen,
5781 ind_maxcomment)) != NULL)
5782 amount = get_indent_lnum(trypos->lnum); /* XXX */
5783 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5784 amount += ind_cpp_baseclass;
5786 else
5788 curwin->w_cursor.col = col;
5789 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5790 amount = (int)vcol;
5792 if (amount < ind_cpp_baseclass)
5793 amount = ind_cpp_baseclass;
5794 return amount;
5798 * Return TRUE if string "s" ends with the string "find", possibly followed by
5799 * white space and comments. Skip strings and comments.
5800 * Ignore "ignore" after "find" if it's not NULL.
5802 static int
5803 cin_ends_in(s, find, ignore)
5804 char_u *s;
5805 char_u *find;
5806 char_u *ignore;
5808 char_u *p = s;
5809 char_u *r;
5810 int len = (int)STRLEN(find);
5812 while (*p != NUL)
5814 p = cin_skipcomment(p);
5815 if (STRNCMP(p, find, len) == 0)
5817 r = skipwhite(p + len);
5818 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5819 r = skipwhite(r + STRLEN(ignore));
5820 if (cin_nocode(r))
5821 return TRUE;
5823 if (*p != NUL)
5824 ++p;
5826 return FALSE;
5830 * Skip strings, chars and comments until at or past "trypos".
5831 * Return the column found.
5833 static int
5834 cin_skip2pos(trypos)
5835 pos_T *trypos;
5837 char_u *line;
5838 char_u *p;
5840 p = line = ml_get(trypos->lnum);
5841 while (*p && (colnr_T)(p - line) < trypos->col)
5843 if (cin_iscomment(p))
5844 p = cin_skipcomment(p);
5845 else
5847 p = skip_string(p);
5848 ++p;
5851 return (int)(p - line);
5855 * Find the '{' at the start of the block we are in.
5856 * Return NULL if no match found.
5857 * Ignore a '{' that is in a comment, makes indenting the next three lines
5858 * work. */
5859 /* foo() */
5860 /* { */
5861 /* } */
5863 static pos_T *
5864 find_start_brace(ind_maxcomment) /* XXX */
5865 int ind_maxcomment;
5867 pos_T cursor_save;
5868 pos_T *trypos;
5869 pos_T *pos;
5870 static pos_T pos_copy;
5872 cursor_save = curwin->w_cursor;
5873 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5875 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5876 trypos = &pos_copy;
5877 curwin->w_cursor = *trypos;
5878 pos = NULL;
5879 /* ignore the { if it's in a // or / * * / comment */
5880 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5881 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5882 break;
5883 if (pos != NULL)
5884 curwin->w_cursor.lnum = pos->lnum;
5886 curwin->w_cursor = cursor_save;
5887 return trypos;
5891 * Find the matching '(', failing if it is in a comment.
5892 * Return NULL of no match found.
5894 static pos_T *
5895 find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5896 int ind_maxparen;
5897 int ind_maxcomment;
5899 pos_T cursor_save;
5900 pos_T *trypos;
5901 static pos_T pos_copy;
5903 cursor_save = curwin->w_cursor;
5904 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5906 /* check if the ( is in a // comment */
5907 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5908 trypos = NULL;
5909 else
5911 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5912 trypos = &pos_copy;
5913 curwin->w_cursor = *trypos;
5914 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5915 trypos = NULL;
5918 curwin->w_cursor = cursor_save;
5919 return trypos;
5923 * Return ind_maxparen corrected for the difference in line number between the
5924 * cursor position and "startpos". This makes sure that searching for a
5925 * matching paren above the cursor line doesn't find a match because of
5926 * looking a few lines further.
5928 static int
5929 corr_ind_maxparen(ind_maxparen, startpos)
5930 int ind_maxparen;
5931 pos_T *startpos;
5933 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5935 if (n > 0 && n < ind_maxparen / 2)
5936 return ind_maxparen - (int)n;
5937 return ind_maxparen;
5941 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5942 * line "l".
5944 static int
5945 find_last_paren(l, start, end)
5946 char_u *l;
5947 int start, end;
5949 int i;
5950 int retval = FALSE;
5951 int open_count = 0;
5953 curwin->w_cursor.col = 0; /* default is start of line */
5955 for (i = 0; l[i]; i++)
5957 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5958 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5959 if (l[i] == start)
5960 ++open_count;
5961 else if (l[i] == end)
5963 if (open_count > 0)
5964 --open_count;
5965 else
5967 curwin->w_cursor.col = i;
5968 retval = TRUE;
5972 return retval;
5976 get_c_indent()
5979 * spaces from a block's opening brace the prevailing indent for that
5980 * block should be
5982 int ind_level = curbuf->b_p_sw;
5985 * spaces from the edge of the line an open brace that's at the end of a
5986 * line is imagined to be.
5988 int ind_open_imag = 0;
5991 * spaces from the prevailing indent for a line that is not precededof by
5992 * an opening brace.
5994 int ind_no_brace = 0;
5997 * column where the first { of a function should be located }
5999 int ind_first_open = 0;
6002 * spaces from the prevailing indent a leftmost open brace should be
6003 * located
6005 int ind_open_extra = 0;
6008 * spaces from the matching open brace (real location for one at the left
6009 * edge; imaginary location from one that ends a line) the matching close
6010 * brace should be located
6012 int ind_close_extra = 0;
6015 * spaces from the edge of the line an open brace sitting in the leftmost
6016 * column is imagined to be
6018 int ind_open_left_imag = 0;
6021 * spaces from the switch() indent a "case xx" label should be located
6023 int ind_case = curbuf->b_p_sw;
6026 * spaces from the "case xx:" code after a switch() should be located
6028 int ind_case_code = curbuf->b_p_sw;
6031 * lineup break at end of case in switch() with case label
6033 int ind_case_break = 0;
6036 * spaces from the class declaration indent a scope declaration label
6037 * should be located
6039 int ind_scopedecl = curbuf->b_p_sw;
6042 * spaces from the scope declaration label code should be located
6044 int ind_scopedecl_code = curbuf->b_p_sw;
6047 * amount K&R-style parameters should be indented
6049 int ind_param = curbuf->b_p_sw;
6052 * amount a function type spec should be indented
6054 int ind_func_type = curbuf->b_p_sw;
6057 * amount a cpp base class declaration or constructor initialization
6058 * should be indented
6060 int ind_cpp_baseclass = curbuf->b_p_sw;
6063 * additional spaces beyond the prevailing indent a continuation line
6064 * should be located
6066 int ind_continuation = curbuf->b_p_sw;
6069 * spaces from the indent of the line with an unclosed parentheses
6071 int ind_unclosed = curbuf->b_p_sw * 2;
6074 * spaces from the indent of the line with an unclosed parentheses, which
6075 * itself is also unclosed
6077 int ind_unclosed2 = curbuf->b_p_sw;
6080 * suppress ignoring spaces from the indent of a line starting with an
6081 * unclosed parentheses.
6083 int ind_unclosed_noignore = 0;
6086 * If the opening paren is the last nonwhite character on the line, and
6087 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6088 * context (for very long lines).
6090 int ind_unclosed_wrapped = 0;
6093 * suppress ignoring white space when lining up with the character after
6094 * an unclosed parentheses.
6096 int ind_unclosed_whiteok = 0;
6099 * indent a closing parentheses under the line start of the matching
6100 * opening parentheses.
6102 int ind_matching_paren = 0;
6105 * indent a closing parentheses under the previous line.
6107 int ind_paren_prev = 0;
6110 * Extra indent for comments.
6112 int ind_comment = 0;
6115 * spaces from the comment opener when there is nothing after it.
6117 int ind_in_comment = 3;
6120 * boolean: if non-zero, use ind_in_comment even if there is something
6121 * after the comment opener.
6123 int ind_in_comment2 = 0;
6126 * max lines to search for an open paren
6128 int ind_maxparen = 20;
6131 * max lines to search for an open comment
6133 int ind_maxcomment = 70;
6136 * handle braces for java code
6138 int ind_java = 0;
6141 * handle blocked cases correctly
6143 int ind_keep_case_label = 0;
6145 pos_T cur_curpos;
6146 int amount;
6147 int scope_amount;
6148 int cur_amount = MAXCOL;
6149 colnr_T col;
6150 char_u *theline;
6151 char_u *linecopy;
6152 pos_T *trypos;
6153 pos_T *tryposBrace = NULL;
6154 pos_T our_paren_pos;
6155 char_u *start;
6156 int start_brace;
6157 #define BRACE_IN_COL0 1 /* '{' is in column 0 */
6158 #define BRACE_AT_START 2 /* '{' is at start of line */
6159 #define BRACE_AT_END 3 /* '{' is at end of line */
6160 linenr_T ourscope;
6161 char_u *l;
6162 char_u *look;
6163 char_u terminated;
6164 int lookfor;
6165 #define LOOKFOR_INITIAL 0
6166 #define LOOKFOR_IF 1
6167 #define LOOKFOR_DO 2
6168 #define LOOKFOR_CASE 3
6169 #define LOOKFOR_ANY 4
6170 #define LOOKFOR_TERM 5
6171 #define LOOKFOR_UNTERM 6
6172 #define LOOKFOR_SCOPEDECL 7
6173 #define LOOKFOR_NOBREAK 8
6174 #define LOOKFOR_CPP_BASECLASS 9
6175 #define LOOKFOR_ENUM_OR_INIT 10
6177 int whilelevel;
6178 linenr_T lnum;
6179 char_u *options;
6180 int fraction = 0; /* init for GCC */
6181 int divider;
6182 int n;
6183 int iscase;
6184 int lookfor_break;
6185 int cont_amount = 0; /* amount for continuation line */
6187 for (options = curbuf->b_p_cino; *options; )
6189 l = options++;
6190 if (*options == '-')
6191 ++options;
6192 n = getdigits(&options);
6193 divider = 0;
6194 if (*options == '.') /* ".5s" means a fraction */
6196 fraction = atol((char *)++options);
6197 while (VIM_ISDIGIT(*options))
6199 ++options;
6200 if (divider)
6201 divider *= 10;
6202 else
6203 divider = 10;
6206 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6208 if (n == 0 && fraction == 0)
6209 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6210 else
6212 n *= curbuf->b_p_sw;
6213 if (divider)
6214 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6216 ++options;
6218 if (l[1] == '-')
6219 n = -n;
6220 /* When adding an entry here, also update the default 'cinoptions' in
6221 * doc/indent.txt, and add explanation for it! */
6222 switch (*l)
6224 case '>': ind_level = n; break;
6225 case 'e': ind_open_imag = n; break;
6226 case 'n': ind_no_brace = n; break;
6227 case 'f': ind_first_open = n; break;
6228 case '{': ind_open_extra = n; break;
6229 case '}': ind_close_extra = n; break;
6230 case '^': ind_open_left_imag = n; break;
6231 case ':': ind_case = n; break;
6232 case '=': ind_case_code = n; break;
6233 case 'b': ind_case_break = n; break;
6234 case 'p': ind_param = n; break;
6235 case 't': ind_func_type = n; break;
6236 case '/': ind_comment = n; break;
6237 case 'c': ind_in_comment = n; break;
6238 case 'C': ind_in_comment2 = n; break;
6239 case 'i': ind_cpp_baseclass = n; break;
6240 case '+': ind_continuation = n; break;
6241 case '(': ind_unclosed = n; break;
6242 case 'u': ind_unclosed2 = n; break;
6243 case 'U': ind_unclosed_noignore = n; break;
6244 case 'W': ind_unclosed_wrapped = n; break;
6245 case 'w': ind_unclosed_whiteok = n; break;
6246 case 'm': ind_matching_paren = n; break;
6247 case 'M': ind_paren_prev = n; break;
6248 case ')': ind_maxparen = n; break;
6249 case '*': ind_maxcomment = n; break;
6250 case 'g': ind_scopedecl = n; break;
6251 case 'h': ind_scopedecl_code = n; break;
6252 case 'j': ind_java = n; break;
6253 case 'l': ind_keep_case_label = n; break;
6254 case '#': ind_hash_comment = n; break;
6258 /* remember where the cursor was when we started */
6259 cur_curpos = curwin->w_cursor;
6261 /* Get a copy of the current contents of the line.
6262 * This is required, because only the most recent line obtained with
6263 * ml_get is valid! */
6264 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6265 if (linecopy == NULL)
6266 return 0;
6269 * In insert mode and the cursor is on a ')' truncate the line at the
6270 * cursor position. We don't want to line up with the matching '(' when
6271 * inserting new stuff.
6272 * For unknown reasons the cursor might be past the end of the line, thus
6273 * check for that.
6275 if ((State & INSERT)
6276 && curwin->w_cursor.col < STRLEN(linecopy)
6277 && linecopy[curwin->w_cursor.col] == ')')
6278 linecopy[curwin->w_cursor.col] = NUL;
6280 theline = skipwhite(linecopy);
6282 /* move the cursor to the start of the line */
6284 curwin->w_cursor.col = 0;
6287 * #defines and so on always go at the left when included in 'cinkeys'.
6289 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6291 amount = 0;
6295 * Is it a non-case label? Then that goes at the left margin too.
6297 else if (cin_islabel(ind_maxcomment)) /* XXX */
6299 amount = 0;
6303 * If we're inside a "//" comment and there is a "//" comment in a
6304 * previous line, lineup with that one.
6306 else if (cin_islinecomment(theline)
6307 && (trypos = find_line_comment()) != NULL) /* XXX */
6309 /* find how indented the line beginning the comment is */
6310 getvcol(curwin, trypos, &col, NULL, NULL);
6311 amount = col;
6315 * If we're inside a comment and not looking at the start of the
6316 * comment, try using the 'comments' option.
6318 else if (!cin_iscomment(theline)
6319 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6321 int lead_start_len = 2;
6322 int lead_middle_len = 1;
6323 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6324 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6325 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6326 char_u *p;
6327 int start_align = 0;
6328 int start_off = 0;
6329 int done = FALSE;
6331 /* find how indented the line beginning the comment is */
6332 getvcol(curwin, trypos, &col, NULL, NULL);
6333 amount = col;
6335 p = curbuf->b_p_com;
6336 while (*p != NUL)
6338 int align = 0;
6339 int off = 0;
6340 int what = 0;
6342 while (*p != NUL && *p != ':')
6344 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6345 what = *p++;
6346 else if (*p == COM_LEFT || *p == COM_RIGHT)
6347 align = *p++;
6348 else if (VIM_ISDIGIT(*p) || *p == '-')
6349 off = getdigits(&p);
6350 else
6351 ++p;
6354 if (*p == ':')
6355 ++p;
6356 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6357 if (what == COM_START)
6359 STRCPY(lead_start, lead_end);
6360 lead_start_len = (int)STRLEN(lead_start);
6361 start_off = off;
6362 start_align = align;
6364 else if (what == COM_MIDDLE)
6366 STRCPY(lead_middle, lead_end);
6367 lead_middle_len = (int)STRLEN(lead_middle);
6369 else if (what == COM_END)
6371 /* If our line starts with the middle comment string, line it
6372 * up with the comment opener per the 'comments' option. */
6373 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6374 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6376 done = TRUE;
6377 if (curwin->w_cursor.lnum > 1)
6379 /* If the start comment string matches in the previous
6380 * line, use the indent of that line plus offset. If
6381 * the middle comment string matches in the previous
6382 * line, use the indent of that line. XXX */
6383 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6384 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6385 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6386 else if (STRNCMP(look, lead_middle,
6387 lead_middle_len) == 0)
6389 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6390 break;
6392 /* If the start comment string doesn't match with the
6393 * start of the comment, skip this entry. XXX */
6394 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6395 lead_start, lead_start_len) != 0)
6396 continue;
6398 if (start_off != 0)
6399 amount += start_off;
6400 else if (start_align == COM_RIGHT)
6401 amount += vim_strsize(lead_start)
6402 - vim_strsize(lead_middle);
6403 break;
6406 /* If our line starts with the end comment string, line it up
6407 * with the middle comment */
6408 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6409 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6411 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6412 /* XXX */
6413 if (off != 0)
6414 amount += off;
6415 else if (align == COM_RIGHT)
6416 amount += vim_strsize(lead_start)
6417 - vim_strsize(lead_middle);
6418 done = TRUE;
6419 break;
6424 /* If our line starts with an asterisk, line up with the
6425 * asterisk in the comment opener; otherwise, line up
6426 * with the first character of the comment text.
6428 if (done)
6430 else if (theline[0] == '*')
6431 amount += 1;
6432 else
6435 * If we are more than one line away from the comment opener, take
6436 * the indent of the previous non-empty line. If 'cino' has "CO"
6437 * and we are just below the comment opener and there are any
6438 * white characters after it line up with the text after it;
6439 * otherwise, add the amount specified by "c" in 'cino'
6441 amount = -1;
6442 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6444 if (linewhite(lnum)) /* skip blank lines */
6445 continue;
6446 amount = get_indent_lnum(lnum); /* XXX */
6447 break;
6449 if (amount == -1) /* use the comment opener */
6451 if (!ind_in_comment2)
6453 start = ml_get(trypos->lnum);
6454 look = start + trypos->col + 2; /* skip / and * */
6455 if (*look != NUL) /* if something after it */
6456 trypos->col = (colnr_T)(skipwhite(look) - start);
6458 getvcol(curwin, trypos, &col, NULL, NULL);
6459 amount = col;
6460 if (ind_in_comment2 || *look == NUL)
6461 amount += ind_in_comment;
6467 * Are we inside parentheses or braces?
6468 */ /* XXX */
6469 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6470 && ind_java == 0)
6471 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6472 || trypos != NULL)
6474 if (trypos != NULL && tryposBrace != NULL)
6476 /* Both an unmatched '(' and '{' is found. Use the one which is
6477 * closer to the current cursor position, set the other to NULL. */
6478 if (trypos->lnum != tryposBrace->lnum
6479 ? trypos->lnum < tryposBrace->lnum
6480 : trypos->col < tryposBrace->col)
6481 trypos = NULL;
6482 else
6483 tryposBrace = NULL;
6486 if (trypos != NULL)
6489 * If the matching paren is more than one line away, use the indent of
6490 * a previous non-empty line that matches the same paren.
6492 if (theline[0] == ')' && ind_paren_prev)
6494 /* Line up with the start of the matching paren line. */
6495 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6497 else
6499 amount = -1;
6500 our_paren_pos = *trypos;
6501 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
6503 l = skipwhite(ml_get(lnum));
6504 if (cin_nocode(l)) /* skip comment lines */
6505 continue;
6506 if (cin_ispreproc_cont(&l, &lnum))
6507 continue; /* ignore #define, #if, etc. */
6508 curwin->w_cursor.lnum = lnum;
6510 /* Skip a comment. XXX */
6511 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6513 lnum = trypos->lnum + 1;
6514 continue;
6517 /* XXX */
6518 if ((trypos = find_match_paren(
6519 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6520 ind_maxcomment)) != NULL
6521 && trypos->lnum == our_paren_pos.lnum
6522 && trypos->col == our_paren_pos.col)
6524 amount = get_indent_lnum(lnum); /* XXX */
6526 if (theline[0] == ')')
6528 if (our_paren_pos.lnum != lnum
6529 && cur_amount > amount)
6530 cur_amount = amount;
6531 amount = -1;
6533 break;
6539 * Line up with line where the matching paren is. XXX
6540 * If the line starts with a '(' or the indent for unclosed
6541 * parentheses is zero, line up with the unclosed parentheses.
6543 if (amount == -1)
6545 int ignore_paren_col = 0;
6547 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
6548 look = skipwhite(look);
6549 if (*look == '(')
6551 linenr_T save_lnum = curwin->w_cursor.lnum;
6552 char_u *line;
6553 int look_col;
6555 /* Ignore a '(' in front of the line that has a match before
6556 * our matching '('. */
6557 curwin->w_cursor.lnum = our_paren_pos.lnum;
6558 line = ml_get_curline();
6559 look_col = (int)(look - line);
6560 curwin->w_cursor.col = look_col + 1;
6561 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6562 != NULL
6563 && trypos->lnum == our_paren_pos.lnum
6564 && trypos->col < our_paren_pos.col)
6565 ignore_paren_col = trypos->col + 1;
6567 curwin->w_cursor.lnum = save_lnum;
6568 look = ml_get(our_paren_pos.lnum) + look_col;
6570 if (theline[0] == ')' || ind_unclosed == 0
6571 || (!ind_unclosed_noignore && *look == '('
6572 && ignore_paren_col == 0))
6575 * If we're looking at a close paren, line up right there;
6576 * otherwise, line up with the next (non-white) character.
6577 * When ind_unclosed_wrapped is set and the matching paren is
6578 * the last nonwhite character of the line, use either the
6579 * indent of the current line or the indentation of the next
6580 * outer paren and add ind_unclosed_wrapped (for very long
6581 * lines).
6583 if (theline[0] != ')')
6585 cur_amount = MAXCOL;
6586 l = ml_get(our_paren_pos.lnum);
6587 if (ind_unclosed_wrapped
6588 && cin_ends_in(l, (char_u *)"(", NULL))
6590 /* look for opening unmatched paren, indent one level
6591 * for each additional level */
6592 n = 1;
6593 for (col = 0; col < our_paren_pos.col; ++col)
6595 switch (l[col])
6597 case '(':
6598 case '{': ++n;
6599 break;
6601 case ')':
6602 case '}': if (n > 1)
6603 --n;
6604 break;
6608 our_paren_pos.col = 0;
6609 amount += n * ind_unclosed_wrapped;
6611 else if (ind_unclosed_whiteok)
6612 our_paren_pos.col++;
6613 else
6615 col = our_paren_pos.col + 1;
6616 while (vim_iswhite(l[col]))
6617 col++;
6618 if (l[col] != NUL) /* In case of trailing space */
6619 our_paren_pos.col = col;
6620 else
6621 our_paren_pos.col++;
6626 * Find how indented the paren is, or the character after it
6627 * if we did the above "if".
6629 if (our_paren_pos.col > 0)
6631 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6632 if (cur_amount > (int)col)
6633 cur_amount = col;
6637 if (theline[0] == ')' && ind_matching_paren)
6639 /* Line up with the start of the matching paren line. */
6641 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
6642 && *look == '(' && ignore_paren_col == 0))
6644 if (cur_amount != MAXCOL)
6645 amount = cur_amount;
6647 else
6649 /* Add ind_unclosed2 for each '(' before our matching one, but
6650 * ignore (void) before the line (ignore_paren_col). */
6651 col = our_paren_pos.col;
6652 while ((int)our_paren_pos.col > ignore_paren_col)
6654 --our_paren_pos.col;
6655 switch (*ml_get_pos(&our_paren_pos))
6657 case '(': amount += ind_unclosed2;
6658 col = our_paren_pos.col;
6659 break;
6660 case ')': amount -= ind_unclosed2;
6661 col = MAXCOL;
6662 break;
6666 /* Use ind_unclosed once, when the first '(' is not inside
6667 * braces */
6668 if (col == MAXCOL)
6669 amount += ind_unclosed;
6670 else
6672 curwin->w_cursor.lnum = our_paren_pos.lnum;
6673 curwin->w_cursor.col = col;
6674 if ((trypos = find_match_paren(ind_maxparen,
6675 ind_maxcomment)) != NULL)
6676 amount += ind_unclosed2;
6677 else
6678 amount += ind_unclosed;
6681 * For a line starting with ')' use the minimum of the two
6682 * positions, to avoid giving it more indent than the previous
6683 * lines:
6684 * func_long_name( if (x
6685 * arg && yy
6686 * ) ^ not here ) ^ not here
6688 if (cur_amount < amount)
6689 amount = cur_amount;
6693 /* add extra indent for a comment */
6694 if (cin_iscomment(theline))
6695 amount += ind_comment;
6699 * Are we at least inside braces, then?
6701 else
6703 trypos = tryposBrace;
6705 ourscope = trypos->lnum;
6706 start = ml_get(ourscope);
6709 * Now figure out how indented the line is in general.
6710 * If the brace was at the start of the line, we use that;
6711 * otherwise, check out the indentation of the line as
6712 * a whole and then add the "imaginary indent" to that.
6714 look = skipwhite(start);
6715 if (*look == '{')
6717 getvcol(curwin, trypos, &col, NULL, NULL);
6718 amount = col;
6719 if (*start == '{')
6720 start_brace = BRACE_IN_COL0;
6721 else
6722 start_brace = BRACE_AT_START;
6724 else
6727 * that opening brace might have been on a continuation
6728 * line. if so, find the start of the line.
6730 curwin->w_cursor.lnum = ourscope;
6733 * position the cursor over the rightmost paren, so that
6734 * matching it will take us back to the start of the line.
6736 lnum = ourscope;
6737 if (find_last_paren(start, '(', ')')
6738 && (trypos = find_match_paren(ind_maxparen,
6739 ind_maxcomment)) != NULL)
6740 lnum = trypos->lnum;
6743 * It could have been something like
6744 * case 1: if (asdf &&
6745 * ldfd) {
6748 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6749 amount = get_indent();
6750 else
6751 amount = skip_label(lnum, &l, ind_maxcomment);
6753 start_brace = BRACE_AT_END;
6757 * if we're looking at a closing brace, that's where
6758 * we want to be. otherwise, add the amount of room
6759 * that an indent is supposed to be.
6761 if (theline[0] == '}')
6764 * they may want closing braces to line up with something
6765 * other than the open brace. indulge them, if so.
6767 amount += ind_close_extra;
6769 else
6772 * If we're looking at an "else", try to find an "if"
6773 * to match it with.
6774 * If we're looking at a "while", try to find a "do"
6775 * to match it with.
6777 lookfor = LOOKFOR_INITIAL;
6778 if (cin_iselse(theline))
6779 lookfor = LOOKFOR_IF;
6780 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6781 /* XXX */
6782 lookfor = LOOKFOR_DO;
6783 if (lookfor != LOOKFOR_INITIAL)
6785 curwin->w_cursor.lnum = cur_curpos.lnum;
6786 if (find_match(lookfor, ourscope, ind_maxparen,
6787 ind_maxcomment) == OK)
6789 amount = get_indent(); /* XXX */
6790 goto theend;
6795 * We get here if we are not on an "while-of-do" or "else" (or
6796 * failed to find a matching "if").
6797 * Search backwards for something to line up with.
6798 * First set amount for when we don't find anything.
6802 * if the '{' is _really_ at the left margin, use the imaginary
6803 * location of a left-margin brace. Otherwise, correct the
6804 * location for ind_open_extra.
6807 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6809 amount = ind_open_left_imag;
6811 else
6813 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6814 amount += ind_open_imag;
6815 else
6817 /* Compensate for adding ind_open_extra later. */
6818 amount -= ind_open_extra;
6819 if (amount < 0)
6820 amount = 0;
6824 lookfor_break = FALSE;
6826 if (cin_iscase(theline)) /* it's a switch() label */
6828 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6829 amount += ind_case;
6831 else if (cin_isscopedecl(theline)) /* private:, ... */
6833 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6834 amount += ind_scopedecl;
6836 else
6838 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6839 lookfor_break = TRUE;
6841 lookfor = LOOKFOR_INITIAL;
6842 amount += ind_level; /* ind_level from start of block */
6844 scope_amount = amount;
6845 whilelevel = 0;
6848 * Search backwards. If we find something we recognize, line up
6849 * with that.
6851 * if we're looking at an open brace, indent
6852 * the usual amount relative to the conditional
6853 * that opens the block.
6855 curwin->w_cursor = cur_curpos;
6856 for (;;)
6858 curwin->w_cursor.lnum--;
6859 curwin->w_cursor.col = 0;
6862 * If we went all the way back to the start of our scope, line
6863 * up with it.
6865 if (curwin->w_cursor.lnum <= ourscope)
6867 /* we reached end of scope:
6868 * if looking for a enum or structure initialization
6869 * go further back:
6870 * if it is an initializer (enum xxx or xxx =), then
6871 * don't add ind_continuation, otherwise it is a variable
6872 * declaration:
6873 * int x,
6874 * here; <-- add ind_continuation
6876 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6878 if (curwin->w_cursor.lnum == 0
6879 || curwin->w_cursor.lnum
6880 < ourscope - ind_maxparen)
6882 /* nothing found (abuse ind_maxparen as limit)
6883 * assume terminated line (i.e. a variable
6884 * initialization) */
6885 if (cont_amount > 0)
6886 amount = cont_amount;
6887 else
6888 amount += ind_continuation;
6889 break;
6892 l = ml_get_curline();
6895 * If we're in a comment now, skip to the start of the
6896 * comment.
6898 trypos = find_start_comment(ind_maxcomment);
6899 if (trypos != NULL)
6901 curwin->w_cursor.lnum = trypos->lnum + 1;
6902 curwin->w_cursor.col = 0;
6903 continue;
6907 * Skip preprocessor directives and blank lines.
6909 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6910 continue;
6912 if (cin_nocode(l))
6913 continue;
6915 terminated = cin_isterminated(l, FALSE, TRUE);
6918 * If we are at top level and the line looks like a
6919 * function declaration, we are done
6920 * (it's a variable declaration).
6922 if (start_brace != BRACE_IN_COL0
6923 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6925 /* if the line is terminated with another ','
6926 * it is a continued variable initialization.
6927 * don't add extra indent.
6928 * TODO: does not work, if a function
6929 * declaration is split over multiple lines:
6930 * cin_isfuncdecl returns FALSE then.
6932 if (terminated == ',')
6933 break;
6935 /* if it es a enum declaration or an assignment,
6936 * we are done.
6938 if (terminated != ';' && cin_isinit())
6939 break;
6941 /* nothing useful found */
6942 if (terminated == 0 || terminated == '{')
6943 continue;
6946 if (terminated != ';')
6948 /* Skip parens and braces. Position the cursor
6949 * over the rightmost paren, so that matching it
6950 * will take us back to the start of the line.
6951 */ /* XXX */
6952 trypos = NULL;
6953 if (find_last_paren(l, '(', ')'))
6954 trypos = find_match_paren(ind_maxparen,
6955 ind_maxcomment);
6957 if (trypos == NULL && find_last_paren(l, '{', '}'))
6958 trypos = find_start_brace(ind_maxcomment);
6960 if (trypos != NULL)
6962 curwin->w_cursor.lnum = trypos->lnum + 1;
6963 curwin->w_cursor.col = 0;
6964 continue;
6968 /* it's a variable declaration, add indentation
6969 * like in
6970 * int a,
6971 * b;
6973 if (cont_amount > 0)
6974 amount = cont_amount;
6975 else
6976 amount += ind_continuation;
6978 else if (lookfor == LOOKFOR_UNTERM)
6980 if (cont_amount > 0)
6981 amount = cont_amount;
6982 else
6983 amount += ind_continuation;
6985 else if (lookfor != LOOKFOR_TERM
6986 && lookfor != LOOKFOR_CPP_BASECLASS)
6988 amount = scope_amount;
6989 if (theline[0] == '{')
6990 amount += ind_open_extra;
6992 break;
6996 * If we're in a comment now, skip to the start of the comment.
6997 */ /* XXX */
6998 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7000 curwin->w_cursor.lnum = trypos->lnum + 1;
7001 curwin->w_cursor.col = 0;
7002 continue;
7005 l = ml_get_curline();
7008 * If this is a switch() label, may line up relative to that.
7009 * If this is a C++ scope declaration, do the same.
7011 iscase = cin_iscase(l);
7012 if (iscase || cin_isscopedecl(l))
7014 /* we are only looking for cpp base class
7015 * declaration/initialization any longer */
7016 if (lookfor == LOOKFOR_CPP_BASECLASS)
7017 break;
7019 /* When looking for a "do" we are not interested in
7020 * labels. */
7021 if (whilelevel > 0)
7022 continue;
7025 * case xx:
7026 * c = 99 + <- this indent plus continuation
7027 *-> here;
7029 if (lookfor == LOOKFOR_UNTERM
7030 || lookfor == LOOKFOR_ENUM_OR_INIT)
7032 if (cont_amount > 0)
7033 amount = cont_amount;
7034 else
7035 amount += ind_continuation;
7036 break;
7040 * case xx: <- line up with this case
7041 * x = 333;
7042 * case yy:
7044 if ( (iscase && lookfor == LOOKFOR_CASE)
7045 || (iscase && lookfor_break)
7046 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7049 * Check that this case label is not for another
7050 * switch()
7051 */ /* XXX */
7052 if ((trypos = find_start_brace(ind_maxcomment)) ==
7053 NULL || trypos->lnum == ourscope)
7055 amount = get_indent(); /* XXX */
7056 break;
7058 continue;
7061 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7064 * case xx: if (cond) <- line up with this if
7065 * y = y + 1;
7066 * -> s = 99;
7068 * case xx:
7069 * if (cond) <- line up with this line
7070 * y = y + 1;
7071 * -> s = 99;
7073 if (lookfor == LOOKFOR_TERM)
7075 if (n)
7076 amount = n;
7078 if (!lookfor_break)
7079 break;
7083 * case xx: x = x + 1; <- line up with this x
7084 * -> y = y + 1;
7086 * case xx: if (cond) <- line up with this if
7087 * -> y = y + 1;
7089 if (n)
7091 amount = n;
7092 l = after_label(ml_get_curline());
7093 if (l != NULL && cin_is_cinword(l))
7095 if (theline[0] == '{')
7096 amount += ind_open_extra;
7097 else
7098 amount += ind_level + ind_no_brace;
7100 break;
7104 * Try to get the indent of a statement before the switch
7105 * label. If nothing is found, line up relative to the
7106 * switch label.
7107 * break; <- may line up with this line
7108 * case xx:
7109 * -> y = 1;
7111 scope_amount = get_indent() + (iscase /* XXX */
7112 ? ind_case_code : ind_scopedecl_code);
7113 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7114 continue;
7118 * Looking for a switch() label or C++ scope declaration,
7119 * ignore other lines, skip {}-blocks.
7121 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7123 if (find_last_paren(l, '{', '}') && (trypos =
7124 find_start_brace(ind_maxcomment)) != NULL)
7126 curwin->w_cursor.lnum = trypos->lnum + 1;
7127 curwin->w_cursor.col = 0;
7129 continue;
7133 * Ignore jump labels with nothing after them.
7135 if (cin_islabel(ind_maxcomment))
7137 l = after_label(ml_get_curline());
7138 if (l == NULL || cin_nocode(l))
7139 continue;
7143 * Ignore #defines, #if, etc.
7144 * Ignore comment and empty lines.
7145 * (need to get the line again, cin_islabel() may have
7146 * unlocked it)
7148 l = ml_get_curline();
7149 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7150 || cin_nocode(l))
7151 continue;
7154 * Are we at the start of a cpp base class declaration or
7155 * constructor initialization?
7156 */ /* XXX */
7157 n = FALSE;
7158 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7160 n = cin_is_cpp_baseclass(&col);
7161 l = ml_get_curline();
7163 if (n)
7165 if (lookfor == LOOKFOR_UNTERM)
7167 if (cont_amount > 0)
7168 amount = cont_amount;
7169 else
7170 amount += ind_continuation;
7172 else if (theline[0] == '{')
7174 /* Need to find start of the declaration. */
7175 lookfor = LOOKFOR_UNTERM;
7176 ind_continuation = 0;
7177 continue;
7179 else
7180 /* XXX */
7181 amount = get_baseclass_amount(col, ind_maxparen,
7182 ind_maxcomment, ind_cpp_baseclass);
7183 break;
7185 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7187 /* only look, whether there is a cpp base class
7188 * declaration or initialization before the opening brace.
7190 if (cin_isterminated(l, TRUE, FALSE))
7191 break;
7192 else
7193 continue;
7197 * What happens next depends on the line being terminated.
7198 * If terminated with a ',' only consider it terminating if
7199 * there is another unterminated statement behind, eg:
7200 * 123,
7201 * sizeof
7202 * here
7203 * Otherwise check whether it is a enumeration or structure
7204 * initialisation (not indented) or a variable declaration
7205 * (indented).
7207 terminated = cin_isterminated(l, FALSE, TRUE);
7209 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7210 && terminated == ','))
7213 * if we're in the middle of a paren thing,
7214 * go back to the line that starts it so
7215 * we can get the right prevailing indent
7216 * if ( foo &&
7217 * bar )
7220 * position the cursor over the rightmost paren, so that
7221 * matching it will take us back to the start of the line.
7223 (void)find_last_paren(l, '(', ')');
7224 trypos = find_match_paren(
7225 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7226 ind_maxcomment);
7229 * If we are looking for ',', we also look for matching
7230 * braces.
7232 if (trypos == NULL && terminated == ','
7233 && find_last_paren(l, '{', '}'))
7234 trypos = find_start_brace(ind_maxcomment);
7236 if (trypos != NULL)
7239 * Check if we are on a case label now. This is
7240 * handled above.
7241 * case xx: if ( asdf &&
7242 * asdf)
7244 curwin->w_cursor = *trypos;
7245 l = ml_get_curline();
7246 if (cin_iscase(l) || cin_isscopedecl(l))
7248 ++curwin->w_cursor.lnum;
7249 curwin->w_cursor.col = 0;
7250 continue;
7255 * Skip over continuation lines to find the one to get the
7256 * indent from
7257 * char *usethis = "bla\
7258 * bla",
7259 * here;
7261 if (terminated == ',')
7263 while (curwin->w_cursor.lnum > 1)
7265 l = ml_get(curwin->w_cursor.lnum - 1);
7266 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7267 break;
7268 --curwin->w_cursor.lnum;
7269 curwin->w_cursor.col = 0;
7274 * Get indent and pointer to text for current line,
7275 * ignoring any jump label. XXX
7277 cur_amount = skip_label(curwin->w_cursor.lnum,
7278 &l, ind_maxcomment);
7281 * If this is just above the line we are indenting, and it
7282 * starts with a '{', line it up with this line.
7283 * while (not)
7284 * -> {
7287 if (terminated != ',' && lookfor != LOOKFOR_TERM
7288 && theline[0] == '{')
7290 amount = cur_amount;
7292 * Only add ind_open_extra when the current line
7293 * doesn't start with a '{', which must have a match
7294 * in the same line (scope is the same). Probably:
7295 * { 1, 2 },
7296 * -> { 3, 4 }
7298 if (*skipwhite(l) != '{')
7299 amount += ind_open_extra;
7301 if (ind_cpp_baseclass)
7303 /* have to look back, whether it is a cpp base
7304 * class declaration or initialization */
7305 lookfor = LOOKFOR_CPP_BASECLASS;
7306 continue;
7308 break;
7312 * Check if we are after an "if", "while", etc.
7313 * Also allow " } else".
7315 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7318 * Found an unterminated line after an if (), line up
7319 * with the last one.
7320 * if (cond)
7321 * 100 +
7322 * -> here;
7324 if (lookfor == LOOKFOR_UNTERM
7325 || lookfor == LOOKFOR_ENUM_OR_INIT)
7327 if (cont_amount > 0)
7328 amount = cont_amount;
7329 else
7330 amount += ind_continuation;
7331 break;
7335 * If this is just above the line we are indenting, we
7336 * are finished.
7337 * while (not)
7338 * -> here;
7339 * Otherwise this indent can be used when the line
7340 * before this is terminated.
7341 * yyy;
7342 * if (stat)
7343 * while (not)
7344 * xxx;
7345 * -> here;
7347 amount = cur_amount;
7348 if (theline[0] == '{')
7349 amount += ind_open_extra;
7350 if (lookfor != LOOKFOR_TERM)
7352 amount += ind_level + ind_no_brace;
7353 break;
7357 * Special trick: when expecting the while () after a
7358 * do, line up with the while()
7359 * do
7360 * x = 1;
7361 * -> here
7363 l = skipwhite(ml_get_curline());
7364 if (cin_isdo(l))
7366 if (whilelevel == 0)
7367 break;
7368 --whilelevel;
7372 * When searching for a terminated line, don't use the
7373 * one between the "if" and the "else".
7374 * Need to use the scope of this "else". XXX
7375 * If whilelevel != 0 continue looking for a "do {".
7377 if (cin_iselse(l)
7378 && whilelevel == 0
7379 && ((trypos = find_start_brace(ind_maxcomment))
7380 == NULL
7381 || find_match(LOOKFOR_IF, trypos->lnum,
7382 ind_maxparen, ind_maxcomment) == FAIL))
7383 break;
7387 * If we're below an unterminated line that is not an
7388 * "if" or something, we may line up with this line or
7389 * add something for a continuation line, depending on
7390 * the line before this one.
7392 else
7395 * Found two unterminated lines on a row, line up with
7396 * the last one.
7397 * c = 99 +
7398 * 100 +
7399 * -> here;
7401 if (lookfor == LOOKFOR_UNTERM)
7403 /* When line ends in a comma add extra indent */
7404 if (terminated == ',')
7405 amount += ind_continuation;
7406 break;
7409 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7411 /* Found two lines ending in ',', lineup with the
7412 * lowest one, but check for cpp base class
7413 * declaration/initialization, if it is an
7414 * opening brace or we are looking just for
7415 * enumerations/initializations. */
7416 if (terminated == ',')
7418 if (ind_cpp_baseclass == 0)
7419 break;
7421 lookfor = LOOKFOR_CPP_BASECLASS;
7422 continue;
7425 /* Ignore unterminated lines in between, but
7426 * reduce indent. */
7427 if (amount > cur_amount)
7428 amount = cur_amount;
7430 else
7433 * Found first unterminated line on a row, may
7434 * line up with this line, remember its indent
7435 * 100 +
7436 * -> here;
7438 amount = cur_amount;
7441 * If previous line ends in ',', check whether we
7442 * are in an initialization or enum
7443 * struct xxx =
7445 * sizeof a,
7446 * 124 };
7447 * or a normal possible continuation line.
7448 * but only, of no other statement has been found
7449 * yet.
7451 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7453 lookfor = LOOKFOR_ENUM_OR_INIT;
7454 cont_amount = cin_first_id_amount();
7456 else
7458 if (lookfor == LOOKFOR_INITIAL
7459 && *l != NUL
7460 && l[STRLEN(l) - 1] == '\\')
7461 /* XXX */
7462 cont_amount = cin_get_equal_amount(
7463 curwin->w_cursor.lnum);
7464 if (lookfor != LOOKFOR_TERM)
7465 lookfor = LOOKFOR_UNTERM;
7472 * Check if we are after a while (cond);
7473 * If so: Ignore until the matching "do".
7475 /* XXX */
7476 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7477 ind_maxcomment))
7480 * Found an unterminated line after a while ();, line up
7481 * with the last one.
7482 * while (cond);
7483 * 100 + <- line up with this one
7484 * -> here;
7486 if (lookfor == LOOKFOR_UNTERM
7487 || lookfor == LOOKFOR_ENUM_OR_INIT)
7489 if (cont_amount > 0)
7490 amount = cont_amount;
7491 else
7492 amount += ind_continuation;
7493 break;
7496 if (whilelevel == 0)
7498 lookfor = LOOKFOR_TERM;
7499 amount = get_indent(); /* XXX */
7500 if (theline[0] == '{')
7501 amount += ind_open_extra;
7503 ++whilelevel;
7507 * We are after a "normal" statement.
7508 * If we had another statement we can stop now and use the
7509 * indent of that other statement.
7510 * Otherwise the indent of the current statement may be used,
7511 * search backwards for the next "normal" statement.
7513 else
7516 * Skip single break line, if before a switch label. It
7517 * may be lined up with the case label.
7519 if (lookfor == LOOKFOR_NOBREAK
7520 && cin_isbreak(skipwhite(ml_get_curline())))
7522 lookfor = LOOKFOR_ANY;
7523 continue;
7527 * Handle "do {" line.
7529 if (whilelevel > 0)
7531 l = cin_skipcomment(ml_get_curline());
7532 if (cin_isdo(l))
7534 amount = get_indent(); /* XXX */
7535 --whilelevel;
7536 continue;
7541 * Found a terminated line above an unterminated line. Add
7542 * the amount for a continuation line.
7543 * x = 1;
7544 * y = foo +
7545 * -> here;
7546 * or
7547 * int x = 1;
7548 * int foo,
7549 * -> here;
7551 if (lookfor == LOOKFOR_UNTERM
7552 || lookfor == LOOKFOR_ENUM_OR_INIT)
7554 if (cont_amount > 0)
7555 amount = cont_amount;
7556 else
7557 amount += ind_continuation;
7558 break;
7562 * Found a terminated line above a terminated line or "if"
7563 * etc. line. Use the amount of the line below us.
7564 * x = 1; x = 1;
7565 * if (asdf) y = 2;
7566 * while (asdf) ->here;
7567 * here;
7568 * ->foo;
7570 if (lookfor == LOOKFOR_TERM)
7572 if (!lookfor_break && whilelevel == 0)
7573 break;
7577 * First line above the one we're indenting is terminated.
7578 * To know what needs to be done look further backward for
7579 * a terminated line.
7581 else
7584 * position the cursor over the rightmost paren, so
7585 * that matching it will take us back to the start of
7586 * the line. Helps for:
7587 * func(asdr,
7588 * asdfasdf);
7589 * here;
7591 term_again:
7592 l = ml_get_curline();
7593 if (find_last_paren(l, '(', ')')
7594 && (trypos = find_match_paren(ind_maxparen,
7595 ind_maxcomment)) != NULL)
7598 * Check if we are on a case label now. This is
7599 * handled above.
7600 * case xx: if ( asdf &&
7601 * asdf)
7603 curwin->w_cursor = *trypos;
7604 l = ml_get_curline();
7605 if (cin_iscase(l) || cin_isscopedecl(l))
7607 ++curwin->w_cursor.lnum;
7608 curwin->w_cursor.col = 0;
7609 continue;
7613 /* When aligning with the case statement, don't align
7614 * with a statement after it.
7615 * case 1: { <-- don't use this { position
7616 * stat;
7618 * case 2:
7619 * stat;
7622 iscase = (ind_keep_case_label && cin_iscase(l));
7625 * Get indent and pointer to text for current line,
7626 * ignoring any jump label.
7628 amount = skip_label(curwin->w_cursor.lnum,
7629 &l, ind_maxcomment);
7631 if (theline[0] == '{')
7632 amount += ind_open_extra;
7633 /* See remark above: "Only add ind_open_extra.." */
7634 l = skipwhite(l);
7635 if (*l == '{')
7636 amount -= ind_open_extra;
7637 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7640 * When a terminated line starts with "else" skip to
7641 * the matching "if":
7642 * else 3;
7643 * indent this;
7644 * Need to use the scope of this "else". XXX
7645 * If whilelevel != 0 continue looking for a "do {".
7647 if (lookfor == LOOKFOR_TERM
7648 && *l != '}'
7649 && cin_iselse(l)
7650 && whilelevel == 0)
7652 if ((trypos = find_start_brace(ind_maxcomment))
7653 == NULL
7654 || find_match(LOOKFOR_IF, trypos->lnum,
7655 ind_maxparen, ind_maxcomment) == FAIL)
7656 break;
7657 continue;
7661 * If we're at the end of a block, skip to the start of
7662 * that block.
7664 curwin->w_cursor.col = 0;
7665 if (*cin_skipcomment(l) == '}'
7666 && (trypos = find_start_brace(ind_maxcomment))
7667 != NULL) /* XXX */
7669 curwin->w_cursor = *trypos;
7670 /* if not "else {" check for terminated again */
7671 /* but skip block for "} else {" */
7672 l = cin_skipcomment(ml_get_curline());
7673 if (*l == '}' || !cin_iselse(l))
7674 goto term_again;
7675 ++curwin->w_cursor.lnum;
7676 curwin->w_cursor.col = 0;
7684 /* add extra indent for a comment */
7685 if (cin_iscomment(theline))
7686 amount += ind_comment;
7690 * ok -- we're not inside any sort of structure at all!
7692 * this means we're at the top level, and everything should
7693 * basically just match where the previous line is, except
7694 * for the lines immediately following a function declaration,
7695 * which are K&R-style parameters and need to be indented.
7697 else
7700 * if our line starts with an open brace, forget about any
7701 * prevailing indent and make sure it looks like the start
7702 * of a function
7705 if (theline[0] == '{')
7707 amount = ind_first_open;
7711 * If the NEXT line is a function declaration, the current
7712 * line needs to be indented as a function type spec.
7713 * Don't do this if the current line looks like a comment
7714 * or if the current line is terminated, ie. ends in ';'.
7716 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7717 && !cin_nocode(theline)
7718 && !cin_ends_in(theline, (char_u *)":", NULL)
7719 && !cin_ends_in(theline, (char_u *)",", NULL)
7720 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7721 && !cin_isterminated(theline, FALSE, TRUE))
7723 amount = ind_func_type;
7725 else
7727 amount = 0;
7728 curwin->w_cursor = cur_curpos;
7730 /* search backwards until we find something we recognize */
7732 while (curwin->w_cursor.lnum > 1)
7734 curwin->w_cursor.lnum--;
7735 curwin->w_cursor.col = 0;
7737 l = ml_get_curline();
7740 * If we're in a comment now, skip to the start of the comment.
7741 */ /* XXX */
7742 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7744 curwin->w_cursor.lnum = trypos->lnum + 1;
7745 curwin->w_cursor.col = 0;
7746 continue;
7750 * Are we at the start of a cpp base class declaration or
7751 * constructor initialization?
7752 */ /* XXX */
7753 n = FALSE;
7754 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7756 n = cin_is_cpp_baseclass(&col);
7757 l = ml_get_curline();
7759 if (n)
7761 /* XXX */
7762 amount = get_baseclass_amount(col, ind_maxparen,
7763 ind_maxcomment, ind_cpp_baseclass);
7764 break;
7768 * Skip preprocessor directives and blank lines.
7770 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7771 continue;
7773 if (cin_nocode(l))
7774 continue;
7777 * If the previous line ends in ',', use one level of
7778 * indentation:
7779 * int foo,
7780 * bar;
7781 * do this before checking for '}' in case of eg.
7782 * enum foobar
7784 * ...
7785 * } foo,
7786 * bar;
7788 n = 0;
7789 if (cin_ends_in(l, (char_u *)",", NULL)
7790 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7792 /* take us back to opening paren */
7793 if (find_last_paren(l, '(', ')')
7794 && (trypos = find_match_paren(ind_maxparen,
7795 ind_maxcomment)) != NULL)
7796 curwin->w_cursor = *trypos;
7798 /* For a line ending in ',' that is a continuation line go
7799 * back to the first line with a backslash:
7800 * char *foo = "bla\
7801 * bla",
7802 * here;
7804 while (n == 0 && curwin->w_cursor.lnum > 1)
7806 l = ml_get(curwin->w_cursor.lnum - 1);
7807 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7808 break;
7809 --curwin->w_cursor.lnum;
7810 curwin->w_cursor.col = 0;
7813 amount = get_indent(); /* XXX */
7815 if (amount == 0)
7816 amount = cin_first_id_amount();
7817 if (amount == 0)
7818 amount = ind_continuation;
7819 break;
7823 * If the line looks like a function declaration, and we're
7824 * not in a comment, put it the left margin.
7826 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7827 break;
7828 l = ml_get_curline();
7831 * Finding the closing '}' of a previous function. Put
7832 * current line at the left margin. For when 'cino' has "fs".
7834 if (*skipwhite(l) == '}')
7835 break;
7837 /* (matching {)
7838 * If the previous line ends on '};' (maybe followed by
7839 * comments) align at column 0. For example:
7840 * char *string_array[] = { "foo",
7841 * / * x * / "b};ar" }; / * foobar * /
7843 if (cin_ends_in(l, (char_u *)"};", NULL))
7844 break;
7847 * If the PREVIOUS line is a function declaration, the current
7848 * line (and the ones that follow) needs to be indented as
7849 * parameters.
7851 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7853 amount = ind_param;
7854 break;
7858 * If the previous line ends in ';' and the line before the
7859 * previous line ends in ',' or '\', ident to column zero:
7860 * int foo,
7861 * bar;
7862 * indent_to_0 here;
7864 if (cin_ends_in(l, (char_u *)";", NULL))
7866 l = ml_get(curwin->w_cursor.lnum - 1);
7867 if (cin_ends_in(l, (char_u *)",", NULL)
7868 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7869 break;
7870 l = ml_get_curline();
7874 * Doesn't look like anything interesting -- so just
7875 * use the indent of this line.
7877 * Position the cursor over the rightmost paren, so that
7878 * matching it will take us back to the start of the line.
7880 find_last_paren(l, '(', ')');
7882 if ((trypos = find_match_paren(ind_maxparen,
7883 ind_maxcomment)) != NULL)
7884 curwin->w_cursor = *trypos;
7885 amount = get_indent(); /* XXX */
7886 break;
7889 /* add extra indent for a comment */
7890 if (cin_iscomment(theline))
7891 amount += ind_comment;
7893 /* add extra indent if the previous line ended in a backslash:
7894 * "asdfasdf\
7895 * here";
7896 * char *foo = "asdf\
7897 * here";
7899 if (cur_curpos.lnum > 1)
7901 l = ml_get(cur_curpos.lnum - 1);
7902 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7904 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7905 if (cur_amount > 0)
7906 amount = cur_amount;
7907 else if (cur_amount == 0)
7908 amount += ind_continuation;
7914 theend:
7915 /* put the cursor back where it belongs */
7916 curwin->w_cursor = cur_curpos;
7918 vim_free(linecopy);
7920 if (amount < 0)
7921 return 0;
7922 return amount;
7925 static int
7926 find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7927 int lookfor;
7928 linenr_T ourscope;
7929 int ind_maxparen;
7930 int ind_maxcomment;
7932 char_u *look;
7933 pos_T *theirscope;
7934 char_u *mightbeif;
7935 int elselevel;
7936 int whilelevel;
7938 if (lookfor == LOOKFOR_IF)
7940 elselevel = 1;
7941 whilelevel = 0;
7943 else
7945 elselevel = 0;
7946 whilelevel = 1;
7949 curwin->w_cursor.col = 0;
7951 while (curwin->w_cursor.lnum > ourscope + 1)
7953 curwin->w_cursor.lnum--;
7954 curwin->w_cursor.col = 0;
7956 look = cin_skipcomment(ml_get_curline());
7957 if (cin_iselse(look)
7958 || cin_isif(look)
7959 || cin_isdo(look) /* XXX */
7960 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7963 * if we've gone outside the braces entirely,
7964 * we must be out of scope...
7966 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7967 if (theirscope == NULL)
7968 break;
7971 * and if the brace enclosing this is further
7972 * back than the one enclosing the else, we're
7973 * out of luck too.
7975 if (theirscope->lnum < ourscope)
7976 break;
7979 * and if they're enclosed in a *deeper* brace,
7980 * then we can ignore it because it's in a
7981 * different scope...
7983 if (theirscope->lnum > ourscope)
7984 continue;
7987 * if it was an "else" (that's not an "else if")
7988 * then we need to go back to another if, so
7989 * increment elselevel
7991 look = cin_skipcomment(ml_get_curline());
7992 if (cin_iselse(look))
7994 mightbeif = cin_skipcomment(look + 4);
7995 if (!cin_isif(mightbeif))
7996 ++elselevel;
7997 continue;
8001 * if it was a "while" then we need to go back to
8002 * another "do", so increment whilelevel. XXX
8004 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8006 ++whilelevel;
8007 continue;
8010 /* If it's an "if" decrement elselevel */
8011 look = cin_skipcomment(ml_get_curline());
8012 if (cin_isif(look))
8014 elselevel--;
8016 * When looking for an "if" ignore "while"s that
8017 * get in the way.
8019 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8020 whilelevel = 0;
8023 /* If it's a "do" decrement whilelevel */
8024 if (cin_isdo(look))
8025 whilelevel--;
8028 * if we've used up all the elses, then
8029 * this must be the if that we want!
8030 * match the indent level of that if.
8032 if (elselevel <= 0 && whilelevel <= 0)
8034 return OK;
8038 return FAIL;
8041 # if defined(FEAT_EVAL) || defined(PROTO)
8043 * Get indent level from 'indentexpr'.
8046 get_expr_indent()
8048 int indent;
8049 pos_T pos;
8050 int save_State;
8051 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8052 OPT_LOCAL);
8054 pos = curwin->w_cursor;
8055 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
8056 if (use_sandbox)
8057 ++sandbox;
8058 ++textlock;
8059 indent = eval_to_number(curbuf->b_p_inde);
8060 if (use_sandbox)
8061 --sandbox;
8062 --textlock;
8064 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8065 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8066 * command. */
8067 save_State = State;
8068 State = INSERT;
8069 curwin->w_cursor = pos;
8070 check_cursor();
8071 State = save_State;
8073 /* If there is an error, just keep the current indent. */
8074 if (indent < 0)
8075 indent = get_indent();
8077 return indent;
8079 # endif
8081 #endif /* FEAT_CINDENT */
8083 #if defined(FEAT_LISP) || defined(PROTO)
8085 static int lisp_match __ARGS((char_u *p));
8087 static int
8088 lisp_match(p)
8089 char_u *p;
8091 char_u buf[LSIZE];
8092 int len;
8093 char_u *word = p_lispwords;
8095 while (*word != NUL)
8097 (void)copy_option_part(&word, buf, LSIZE, ",");
8098 len = (int)STRLEN(buf);
8099 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8100 return TRUE;
8102 return FALSE;
8106 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8107 * The incompatible newer method is quite a bit better at indenting
8108 * code in lisp-like languages than the traditional one; it's still
8109 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8111 * TODO:
8112 * Findmatch() should be adapted for lisp, also to make showmatch
8113 * work correctly: now (v5.3) it seems all C/C++ oriented:
8114 * - it does not recognize the #\( and #\) notations as character literals
8115 * - it doesn't know about comments starting with a semicolon
8116 * - it incorrectly interprets '(' as a character literal
8117 * All this messes up get_lisp_indent in some rare cases.
8118 * Update from Sergey Khorev:
8119 * I tried to fix the first two issues.
8122 get_lisp_indent()
8124 pos_T *pos, realpos, paren;
8125 int amount;
8126 char_u *that;
8127 colnr_T col;
8128 colnr_T firsttry;
8129 int parencount, quotecount;
8130 int vi_lisp;
8132 /* Set vi_lisp to use the vi-compatible method */
8133 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8135 realpos = curwin->w_cursor;
8136 curwin->w_cursor.col = 0;
8138 if ((pos = findmatch(NULL, '(')) == NULL)
8139 pos = findmatch(NULL, '[');
8140 else
8142 paren = *pos;
8143 pos = findmatch(NULL, '[');
8144 if (pos == NULL || ltp(pos, &paren))
8145 pos = &paren;
8147 if (pos != NULL)
8149 /* Extra trick: Take the indent of the first previous non-white
8150 * line that is at the same () level. */
8151 amount = -1;
8152 parencount = 0;
8154 while (--curwin->w_cursor.lnum >= pos->lnum)
8156 if (linewhite(curwin->w_cursor.lnum))
8157 continue;
8158 for (that = ml_get_curline(); *that != NUL; ++that)
8160 if (*that == ';')
8162 while (*(that + 1) != NUL)
8163 ++that;
8164 continue;
8166 if (*that == '\\')
8168 if (*(that + 1) != NUL)
8169 ++that;
8170 continue;
8172 if (*that == '"' && *(that + 1) != NUL)
8174 while (*++that && *that != '"')
8176 /* skipping escaped characters in the string */
8177 if (*that == '\\')
8179 if (*++that == NUL)
8180 break;
8181 if (that[1] == NUL)
8183 ++that;
8184 break;
8189 if (*that == '(' || *that == '[')
8190 ++parencount;
8191 else if (*that == ')' || *that == ']')
8192 --parencount;
8194 if (parencount == 0)
8196 amount = get_indent();
8197 break;
8201 if (amount == -1)
8203 curwin->w_cursor.lnum = pos->lnum;
8204 curwin->w_cursor.col = pos->col;
8205 col = pos->col;
8207 that = ml_get_curline();
8209 if (vi_lisp && get_indent() == 0)
8210 amount = 2;
8211 else
8213 amount = 0;
8214 while (*that && col)
8216 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8217 col--;
8221 * Some keywords require "body" indenting rules (the
8222 * non-standard-lisp ones are Scheme special forms):
8224 * (let ((a 1)) instead (let ((a 1))
8225 * (...)) of (...))
8228 if (!vi_lisp && (*that == '(' || *that == '[')
8229 && lisp_match(that + 1))
8230 amount += 2;
8231 else
8233 that++;
8234 amount++;
8235 firsttry = amount;
8237 while (vim_iswhite(*that))
8239 amount += lbr_chartabsize(that, (colnr_T)amount);
8240 ++that;
8243 if (*that && *that != ';') /* not a comment line */
8245 /* test *that != '(' to accommodate first let/do
8246 * argument if it is more than one line */
8247 if (!vi_lisp && *that != '(' && *that != '[')
8248 firsttry++;
8250 parencount = 0;
8251 quotecount = 0;
8253 if (vi_lisp
8254 || (*that != '"'
8255 && *that != '\''
8256 && *that != '#'
8257 && (*that < '0' || *that > '9')))
8259 while (*that
8260 && (!vim_iswhite(*that)
8261 || quotecount
8262 || parencount)
8263 && (!((*that == '(' || *that == '[')
8264 && !quotecount
8265 && !parencount
8266 && vi_lisp)))
8268 if (*that == '"')
8269 quotecount = !quotecount;
8270 if ((*that == '(' || *that == '[')
8271 && !quotecount)
8272 ++parencount;
8273 if ((*that == ')' || *that == ']')
8274 && !quotecount)
8275 --parencount;
8276 if (*that == '\\' && *(that+1) != NUL)
8277 amount += lbr_chartabsize_adv(&that,
8278 (colnr_T)amount);
8279 amount += lbr_chartabsize_adv(&that,
8280 (colnr_T)amount);
8283 while (vim_iswhite(*that))
8285 amount += lbr_chartabsize(that, (colnr_T)amount);
8286 that++;
8288 if (!*that || *that == ';')
8289 amount = firsttry;
8295 else
8296 amount = 0; /* no matching '(' or '[' found, use zero indent */
8298 curwin->w_cursor = realpos;
8300 return amount;
8302 #endif /* FEAT_LISP */
8304 void
8305 prepare_to_exit()
8307 #if defined(SIGHUP) && defined(SIG_IGN)
8308 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8309 * makes Vim exit and then handling SIGHUP causes various reentrance
8310 * problems. */
8311 signal(SIGHUP, SIG_IGN);
8312 #endif
8314 #ifdef FEAT_GUI
8315 if (gui.in_use)
8317 gui.dying = TRUE;
8318 out_trash(); /* trash any pending output */
8320 else
8321 #endif
8323 windgoto((int)Rows - 1, 0);
8326 * Switch terminal mode back now, so messages end up on the "normal"
8327 * screen (if there are two screens).
8329 settmode(TMODE_COOK);
8330 #ifdef WIN3264
8331 if (can_end_termcap_mode(FALSE) == TRUE)
8332 #endif
8333 stoptermcap();
8334 out_flush();
8339 * Preserve files and exit.
8340 * When called IObuff must contain a message.
8342 void
8343 preserve_exit()
8345 buf_T *buf;
8347 prepare_to_exit();
8349 /* Setting this will prevent free() calls. That avoids calling free()
8350 * recursively when free() was invoked with a bad pointer. */
8351 really_exiting = TRUE;
8353 out_str(IObuff);
8354 screen_start(); /* don't know where cursor is now */
8355 out_flush();
8357 ml_close_notmod(); /* close all not-modified buffers */
8359 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8361 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8363 OUT_STR(_("Vim: preserving files...\n"));
8364 screen_start(); /* don't know where cursor is now */
8365 out_flush();
8366 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8367 break;
8371 ml_close_all(FALSE); /* close all memfiles, without deleting */
8373 OUT_STR(_("Vim: Finished.\n"));
8375 getout(1);
8379 * return TRUE if "fname" exists.
8382 vim_fexists(fname)
8383 char_u *fname;
8385 struct stat st;
8387 if (mch_stat((char *)fname, &st))
8388 return FALSE;
8389 return TRUE;
8393 * Check for CTRL-C pressed, but only once in a while.
8394 * Should be used instead of ui_breakcheck() for functions that check for
8395 * each line in the file. Calling ui_breakcheck() each time takes too much
8396 * time, because it can be a system call.
8399 #ifndef BREAKCHECK_SKIP
8400 # ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8401 # define BREAKCHECK_SKIP 200
8402 # else
8403 # define BREAKCHECK_SKIP 32
8404 # endif
8405 #endif
8407 static int breakcheck_count = 0;
8409 void
8410 line_breakcheck()
8412 if (++breakcheck_count >= BREAKCHECK_SKIP)
8414 breakcheck_count = 0;
8415 ui_breakcheck();
8420 * Like line_breakcheck() but check 10 times less often.
8422 void
8423 fast_breakcheck()
8425 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8427 breakcheck_count = 0;
8428 ui_breakcheck();
8433 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8434 * 'wildignore'.
8435 * Returns OK or FAIL.
8438 expand_wildcards(num_pat, pat, num_file, file, flags)
8439 int num_pat; /* number of input patterns */
8440 char_u **pat; /* array of input patterns */
8441 int *num_file; /* resulting number of files */
8442 char_u ***file; /* array of resulting files */
8443 int flags; /* EW_DIR, etc. */
8445 int retval;
8446 int i, j;
8447 char_u *p;
8448 int non_suf_match; /* number without matching suffix */
8450 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8452 /* When keeping all matches, return here */
8453 if (flags & EW_KEEPALL)
8454 return retval;
8456 #ifdef FEAT_WILDIGN
8458 * Remove names that match 'wildignore'.
8460 if (*p_wig)
8462 char_u *ffname;
8464 /* check all files in (*file)[] */
8465 for (i = 0; i < *num_file; ++i)
8467 ffname = FullName_save((*file)[i], FALSE);
8468 if (ffname == NULL) /* out of memory */
8469 break;
8470 # ifdef VMS
8471 vms_remove_version(ffname);
8472 # endif
8473 if (match_file_list(p_wig, (*file)[i], ffname))
8475 /* remove this matching file from the list */
8476 vim_free((*file)[i]);
8477 for (j = i; j + 1 < *num_file; ++j)
8478 (*file)[j] = (*file)[j + 1];
8479 --*num_file;
8480 --i;
8482 vim_free(ffname);
8485 #endif
8488 * Move the names where 'suffixes' match to the end.
8490 if (*num_file > 1)
8492 non_suf_match = 0;
8493 for (i = 0; i < *num_file; ++i)
8495 if (!match_suffix((*file)[i]))
8498 * Move the name without matching suffix to the front
8499 * of the list.
8501 p = (*file)[i];
8502 for (j = i; j > non_suf_match; --j)
8503 (*file)[j] = (*file)[j - 1];
8504 (*file)[non_suf_match++] = p;
8509 return retval;
8513 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8516 match_suffix(fname)
8517 char_u *fname;
8519 int fnamelen, setsuflen;
8520 char_u *setsuf;
8521 #define MAXSUFLEN 30 /* maximum length of a file suffix */
8522 char_u suf_buf[MAXSUFLEN];
8524 fnamelen = (int)STRLEN(fname);
8525 setsuflen = 0;
8526 for (setsuf = p_su; *setsuf; )
8528 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
8529 if (fnamelen >= setsuflen
8530 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8531 (size_t)setsuflen) == 0)
8532 break;
8533 setsuflen = 0;
8535 return (setsuflen != 0);
8538 #if !defined(NO_EXPANDPATH) || defined(PROTO)
8540 # ifdef VIM_BACKTICK
8541 static int vim_backtick __ARGS((char_u *p));
8542 static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8543 # endif
8545 # if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8547 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8548 * it's shared between these systems.
8550 # if defined(DJGPP) || defined(PROTO)
8551 # define _cdecl /* DJGPP doesn't have this */
8552 # else
8553 # ifdef __BORLANDC__
8554 # define _cdecl _RTLENTRYF
8555 # endif
8556 # endif
8559 * comparison function for qsort in dos_expandpath()
8561 static int _cdecl
8562 pstrcmp(const void *a, const void *b)
8564 return (pathcmp(*(char **)a, *(char **)b, -1));
8567 # ifndef WIN3264
8568 static void
8569 namelowcpy(
8570 char_u *d,
8571 char_u *s)
8573 # ifdef DJGPP
8574 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8575 while (*s)
8576 *d++ = *s++;
8577 else
8578 # endif
8579 while (*s)
8580 *d++ = TOLOWER_LOC(*s++);
8581 *d = NUL;
8583 # endif
8586 * Recursively expand one path component into all matching files and/or
8587 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8588 * Return the number of matches found.
8589 * "path" has backslashes before chars that are not to be expanded, starting
8590 * at "path[wildoff]".
8591 * Return the number of matches found.
8592 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
8594 static int
8595 dos_expandpath(
8596 garray_T *gap,
8597 char_u *path,
8598 int wildoff,
8599 int flags, /* EW_* flags */
8600 int didstar) /* expanded "**" once already */
8602 char_u *buf;
8603 char_u *path_end;
8604 char_u *p, *s, *e;
8605 int start_len = gap->ga_len;
8606 char_u *pat;
8607 regmatch_T regmatch;
8608 int starts_with_dot;
8609 int matches;
8610 int len;
8611 int starstar = FALSE;
8612 static int stardepth = 0; /* depth for "**" expansion */
8613 #ifdef WIN3264
8614 WIN32_FIND_DATA fb;
8615 HANDLE hFind = (HANDLE)0;
8616 # ifdef FEAT_MBYTE
8617 WIN32_FIND_DATAW wfb;
8618 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8619 # endif
8620 #else
8621 struct ffblk fb;
8622 #endif
8623 char_u *matchname;
8624 int ok;
8626 /* Expanding "**" may take a long time, check for CTRL-C. */
8627 if (stardepth > 0)
8629 ui_breakcheck();
8630 if (got_int)
8631 return 0;
8634 /* make room for file name */
8635 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8636 if (buf == NULL)
8637 return 0;
8640 * Find the first part in the path name that contains a wildcard or a ~1.
8641 * Copy it into buf, including the preceding characters.
8643 p = buf;
8644 s = buf;
8645 e = NULL;
8646 path_end = path;
8647 while (*path_end != NUL)
8649 /* May ignore a wildcard that has a backslash before it; it will
8650 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8651 if (path_end >= path + wildoff && rem_backslash(path_end))
8652 *p++ = *path_end++;
8653 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8655 if (e != NULL)
8656 break;
8657 s = p + 1;
8659 else if (path_end >= path + wildoff
8660 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8661 e = p;
8662 #ifdef FEAT_MBYTE
8663 if (has_mbyte)
8665 len = (*mb_ptr2len)(path_end);
8666 STRNCPY(p, path_end, len);
8667 p += len;
8668 path_end += len;
8670 else
8671 #endif
8672 *p++ = *path_end++;
8674 e = p;
8675 *e = NUL;
8677 /* now we have one wildcard component between s and e */
8678 /* Remove backslashes between "wildoff" and the start of the wildcard
8679 * component. */
8680 for (p = buf + wildoff; p < s; ++p)
8681 if (rem_backslash(p))
8683 STRMOVE(p, p + 1);
8684 --e;
8685 --s;
8688 /* Check for "**" between "s" and "e". */
8689 for (p = s; p < e; ++p)
8690 if (p[0] == '*' && p[1] == '*')
8691 starstar = TRUE;
8693 starts_with_dot = (*s == '.');
8694 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8695 if (pat == NULL)
8697 vim_free(buf);
8698 return 0;
8701 /* compile the regexp into a program */
8702 regmatch.rm_ic = TRUE; /* Always ignore case */
8703 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8704 vim_free(pat);
8706 if (regmatch.regprog == NULL)
8708 vim_free(buf);
8709 return 0;
8712 /* remember the pattern or file name being looked for */
8713 matchname = vim_strsave(s);
8715 /* If "**" is by itself, this is the first time we encounter it and more
8716 * is following then find matches without any directory. */
8717 if (!didstar && stardepth < 100 && starstar && e - s == 2
8718 && *path_end == '/')
8720 STRCPY(s, path_end + 1);
8721 ++stardepth;
8722 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8723 --stardepth;
8726 /* Scan all files in the directory with "dir/ *.*" */
8727 STRCPY(s, "*.*");
8728 #ifdef WIN3264
8729 # ifdef FEAT_MBYTE
8730 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8732 /* The active codepage differs from 'encoding'. Attempt using the
8733 * wide function. If it fails because it is not implemented fall back
8734 * to the non-wide version (for Windows 98) */
8735 wn = enc_to_utf16(buf, NULL);
8736 if (wn != NULL)
8738 hFind = FindFirstFileW(wn, &wfb);
8739 if (hFind == INVALID_HANDLE_VALUE
8740 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8742 vim_free(wn);
8743 wn = NULL;
8748 if (wn == NULL)
8749 # endif
8750 hFind = FindFirstFile(buf, &fb);
8751 ok = (hFind != INVALID_HANDLE_VALUE);
8752 #else
8753 /* If we are expanding wildcards we try both files and directories */
8754 ok = (findfirst((char *)buf, &fb,
8755 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8756 #endif
8758 while (ok)
8760 #ifdef WIN3264
8761 # ifdef FEAT_MBYTE
8762 if (wn != NULL)
8763 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8764 else
8765 # endif
8766 p = (char_u *)fb.cFileName;
8767 #else
8768 p = (char_u *)fb.ff_name;
8769 #endif
8770 /* Ignore entries starting with a dot, unless when asked for. Accept
8771 * all entries found with "matchname". */
8772 if ((p[0] != '.' || starts_with_dot)
8773 && (matchname == NULL
8774 || vim_regexec(&regmatch, p, (colnr_T)0)))
8776 #ifdef WIN3264
8777 STRCPY(s, p);
8778 #else
8779 namelowcpy(s, p);
8780 #endif
8781 len = (int)STRLEN(buf);
8783 if (starstar && stardepth < 100)
8785 /* For "**" in the pattern first go deeper in the tree to
8786 * find matches. */
8787 STRCPY(buf + len, "/**");
8788 STRCPY(buf + len + 3, path_end);
8789 ++stardepth;
8790 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8791 --stardepth;
8794 STRCPY(buf + len, path_end);
8795 if (mch_has_exp_wildcard(path_end))
8797 /* need to expand another component of the path */
8798 /* remove backslashes for the remaining components only */
8799 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
8801 else
8803 /* no more wildcards, check if there is a match */
8804 /* remove backslashes for the remaining components only */
8805 if (*path_end != 0)
8806 backslash_halve(buf + len + 1);
8807 if (mch_getperm(buf) >= 0) /* add existing file */
8808 addfile(gap, buf, flags);
8812 #ifdef WIN3264
8813 # ifdef FEAT_MBYTE
8814 if (wn != NULL)
8816 vim_free(p);
8817 ok = FindNextFileW(hFind, &wfb);
8819 else
8820 # endif
8821 ok = FindNextFile(hFind, &fb);
8822 #else
8823 ok = (findnext(&fb) == 0);
8824 #endif
8826 /* If no more matches and no match was used, try expanding the name
8827 * itself. Finds the long name of a short filename. */
8828 if (!ok && matchname != NULL && gap->ga_len == start_len)
8830 STRCPY(s, matchname);
8831 #ifdef WIN3264
8832 FindClose(hFind);
8833 # ifdef FEAT_MBYTE
8834 if (wn != NULL)
8836 vim_free(wn);
8837 wn = enc_to_utf16(buf, NULL);
8838 if (wn != NULL)
8839 hFind = FindFirstFileW(wn, &wfb);
8841 if (wn == NULL)
8842 # endif
8843 hFind = FindFirstFile(buf, &fb);
8844 ok = (hFind != INVALID_HANDLE_VALUE);
8845 #else
8846 ok = (findfirst((char *)buf, &fb,
8847 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8848 #endif
8849 vim_free(matchname);
8850 matchname = NULL;
8854 #ifdef WIN3264
8855 FindClose(hFind);
8856 # ifdef FEAT_MBYTE
8857 vim_free(wn);
8858 # endif
8859 #endif
8860 vim_free(buf);
8861 vim_free(regmatch.regprog);
8862 vim_free(matchname);
8864 matches = gap->ga_len - start_len;
8865 if (matches > 0)
8866 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8867 sizeof(char_u *), pstrcmp);
8868 return matches;
8872 mch_expandpath(
8873 garray_T *gap,
8874 char_u *path,
8875 int flags) /* EW_* flags */
8877 return dos_expandpath(gap, path, 0, flags, FALSE);
8879 # endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8881 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8882 || defined(PROTO)
8884 * Unix style wildcard expansion code.
8885 * It's here because it's used both for Unix and Mac.
8887 static int pstrcmp __ARGS((const void *, const void *));
8889 static int
8890 pstrcmp(a, b)
8891 const void *a, *b;
8893 return (pathcmp(*(char **)a, *(char **)b, -1));
8897 * Recursively expand one path component into all matching files and/or
8898 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8899 * "path" has backslashes before chars that are not to be expanded, starting
8900 * at "path + wildoff".
8901 * Return the number of matches found.
8902 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8905 unix_expandpath(gap, path, wildoff, flags, didstar)
8906 garray_T *gap;
8907 char_u *path;
8908 int wildoff;
8909 int flags; /* EW_* flags */
8910 int didstar; /* expanded "**" once already */
8912 char_u *buf;
8913 char_u *path_end;
8914 char_u *p, *s, *e;
8915 int start_len = gap->ga_len;
8916 char_u *pat;
8917 regmatch_T regmatch;
8918 int starts_with_dot;
8919 int matches;
8920 int len;
8921 int starstar = FALSE;
8922 static int stardepth = 0; /* depth for "**" expansion */
8924 DIR *dirp;
8925 struct dirent *dp;
8927 /* Expanding "**" may take a long time, check for CTRL-C. */
8928 if (stardepth > 0)
8930 ui_breakcheck();
8931 if (got_int)
8932 return 0;
8935 /* make room for file name */
8936 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8937 if (buf == NULL)
8938 return 0;
8941 * Find the first part in the path name that contains a wildcard.
8942 * Copy it into "buf", including the preceding characters.
8944 p = buf;
8945 s = buf;
8946 e = NULL;
8947 path_end = path;
8948 while (*path_end != NUL)
8950 /* May ignore a wildcard that has a backslash before it; it will
8951 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8952 if (path_end >= path + wildoff && rem_backslash(path_end))
8953 *p++ = *path_end++;
8954 else if (*path_end == '/')
8956 if (e != NULL)
8957 break;
8958 s = p + 1;
8960 else if (path_end >= path + wildoff
8961 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
8962 e = p;
8963 #ifdef FEAT_MBYTE
8964 if (has_mbyte)
8966 len = (*mb_ptr2len)(path_end);
8967 STRNCPY(p, path_end, len);
8968 p += len;
8969 path_end += len;
8971 else
8972 #endif
8973 *p++ = *path_end++;
8975 e = p;
8976 *e = NUL;
8978 /* now we have one wildcard component between "s" and "e" */
8979 /* Remove backslashes between "wildoff" and the start of the wildcard
8980 * component. */
8981 for (p = buf + wildoff; p < s; ++p)
8982 if (rem_backslash(p))
8984 STRMOVE(p, p + 1);
8985 --e;
8986 --s;
8989 /* Check for "**" between "s" and "e". */
8990 for (p = s; p < e; ++p)
8991 if (p[0] == '*' && p[1] == '*')
8992 starstar = TRUE;
8994 /* convert the file pattern to a regexp pattern */
8995 starts_with_dot = (*s == '.');
8996 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8997 if (pat == NULL)
8999 vim_free(buf);
9000 return 0;
9003 /* compile the regexp into a program */
9004 #ifdef CASE_INSENSITIVE_FILENAME
9005 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9006 #else
9007 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9008 #endif
9009 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9010 vim_free(pat);
9012 if (regmatch.regprog == NULL)
9014 vim_free(buf);
9015 return 0;
9018 /* If "**" is by itself, this is the first time we encounter it and more
9019 * is following then find matches without any directory. */
9020 if (!didstar && stardepth < 100 && starstar && e - s == 2
9021 && *path_end == '/')
9023 STRCPY(s, path_end + 1);
9024 ++stardepth;
9025 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9026 --stardepth;
9029 /* open the directory for scanning */
9030 *s = NUL;
9031 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9033 /* Find all matching entries */
9034 if (dirp != NULL)
9036 for (;;)
9038 dp = readdir(dirp);
9039 if (dp == NULL)
9040 break;
9041 if ((dp->d_name[0] != '.' || starts_with_dot)
9042 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
9044 STRCPY(s, dp->d_name);
9045 len = STRLEN(buf);
9047 if (starstar && stardepth < 100)
9049 /* For "**" in the pattern first go deeper in the tree to
9050 * find matches. */
9051 STRCPY(buf + len, "/**");
9052 STRCPY(buf + len + 3, path_end);
9053 ++stardepth;
9054 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9055 --stardepth;
9058 STRCPY(buf + len, path_end);
9059 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9061 /* need to expand another component of the path */
9062 /* remove backslashes for the remaining components only */
9063 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9065 else
9067 /* no more wildcards, check if there is a match */
9068 /* remove backslashes for the remaining components only */
9069 if (*path_end != NUL)
9070 backslash_halve(buf + len + 1);
9071 if (mch_getperm(buf) >= 0) /* add existing file */
9073 #ifdef MACOS_CONVERT
9074 size_t precomp_len = STRLEN(buf)+1;
9075 char_u *precomp_buf =
9076 mac_precompose_path(buf, precomp_len, &precomp_len);
9078 if (precomp_buf)
9080 mch_memmove(buf, precomp_buf, precomp_len);
9081 vim_free(precomp_buf);
9083 #endif
9084 addfile(gap, buf, flags);
9090 closedir(dirp);
9093 vim_free(buf);
9094 vim_free(regmatch.regprog);
9096 matches = gap->ga_len - start_len;
9097 if (matches > 0)
9098 qsort(((char_u **)gap->ga_data) + start_len, matches,
9099 sizeof(char_u *), pstrcmp);
9100 return matches;
9102 #endif
9105 * Generic wildcard expansion code.
9107 * Characters in "pat" that should not be expanded must be preceded with a
9108 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9110 * Return FAIL when no single file was found. In this case "num_file" is not
9111 * set, and "file" may contain an error message.
9112 * Return OK when some files found. "num_file" is set to the number of
9113 * matches, "file" to the array of matches. Call FreeWild() later.
9116 gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9117 int num_pat; /* number of input patterns */
9118 char_u **pat; /* array of input patterns */
9119 int *num_file; /* resulting number of files */
9120 char_u ***file; /* array of resulting files */
9121 int flags; /* EW_* flags */
9123 int i;
9124 garray_T ga;
9125 char_u *p;
9126 static int recursive = FALSE;
9127 int add_pat;
9130 * expand_env() is called to expand things like "~user". If this fails,
9131 * it calls ExpandOne(), which brings us back here. In this case, always
9132 * call the machine specific expansion function, if possible. Otherwise,
9133 * return FAIL.
9135 if (recursive)
9136 #ifdef SPECIAL_WILDCHAR
9137 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9138 #else
9139 return FAIL;
9140 #endif
9142 #ifdef SPECIAL_WILDCHAR
9144 * If there are any special wildcard characters which we cannot handle
9145 * here, call machine specific function for all the expansion. This
9146 * avoids starting the shell for each argument separately.
9147 * For `=expr` do use the internal function.
9149 for (i = 0; i < num_pat; i++)
9151 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9152 # ifdef VIM_BACKTICK
9153 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9154 # endif
9156 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9158 #endif
9160 recursive = TRUE;
9163 * The matching file names are stored in a growarray. Init it empty.
9165 ga_init2(&ga, (int)sizeof(char_u *), 30);
9167 for (i = 0; i < num_pat; ++i)
9169 add_pat = -1;
9170 p = pat[i];
9172 #ifdef VIM_BACKTICK
9173 if (vim_backtick(p))
9174 add_pat = expand_backtick(&ga, p, flags);
9175 else
9176 #endif
9179 * First expand environment variables, "~/" and "~user/".
9181 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9183 p = expand_env_save_opt(p, TRUE);
9184 if (p == NULL)
9185 p = pat[i];
9186 #ifdef UNIX
9188 * On Unix, if expand_env() can't expand an environment
9189 * variable, use the shell to do that. Discard previously
9190 * found file names and start all over again.
9192 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9194 vim_free(p);
9195 ga_clear(&ga);
9196 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9197 flags);
9198 recursive = FALSE;
9199 return i;
9201 #endif
9205 * If there are wildcards: Expand file names and add each match to
9206 * the list. If there is no match, and EW_NOTFOUND is given, add
9207 * the pattern.
9208 * If there are no wildcards: Add the file name if it exists or
9209 * when EW_NOTFOUND is given.
9211 if (mch_has_exp_wildcard(p))
9212 add_pat = mch_expandpath(&ga, p, flags);
9215 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9217 char_u *t = backslash_halve_save(p);
9219 #if defined(MACOS_CLASSIC)
9220 slash_to_colon(t);
9221 #endif
9222 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9223 * "vim c:/" work. */
9224 if (flags & EW_NOTFOUND)
9225 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9226 else if (mch_getperm(t) >= 0)
9227 addfile(&ga, t, flags);
9228 vim_free(t);
9231 if (p != pat[i])
9232 vim_free(p);
9235 *num_file = ga.ga_len;
9236 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9238 recursive = FALSE;
9240 return (ga.ga_data != NULL) ? OK : FAIL;
9243 # ifdef VIM_BACKTICK
9246 * Return TRUE if we can expand this backtick thing here.
9248 static int
9249 vim_backtick(p)
9250 char_u *p;
9252 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9256 * Expand an item in `backticks` by executing it as a command.
9257 * Currently only works when pat[] starts and ends with a `.
9258 * Returns number of file names found.
9260 static int
9261 expand_backtick(gap, pat, flags)
9262 garray_T *gap;
9263 char_u *pat;
9264 int flags; /* EW_* flags */
9266 char_u *p;
9267 char_u *cmd;
9268 char_u *buffer;
9269 int cnt = 0;
9270 int i;
9272 /* Create the command: lop off the backticks. */
9273 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9274 if (cmd == NULL)
9275 return 0;
9277 #ifdef FEAT_EVAL
9278 if (*cmd == '=') /* `={expr}`: Expand expression */
9279 buffer = eval_to_string(cmd + 1, &p, TRUE);
9280 else
9281 #endif
9282 buffer = get_cmd_output(cmd, NULL,
9283 (flags & EW_SILENT) ? SHELL_SILENT : 0);
9284 vim_free(cmd);
9285 if (buffer == NULL)
9286 return 0;
9288 cmd = buffer;
9289 while (*cmd != NUL)
9291 cmd = skipwhite(cmd); /* skip over white space */
9292 p = cmd;
9293 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9294 ++p;
9295 /* add an entry if it is not empty */
9296 if (p > cmd)
9298 i = *p;
9299 *p = NUL;
9300 addfile(gap, cmd, flags);
9301 *p = i;
9302 ++cnt;
9304 cmd = p;
9305 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9306 ++cmd;
9309 vim_free(buffer);
9310 return cnt;
9312 # endif /* VIM_BACKTICK */
9315 * Add a file to a file list. Accepted flags:
9316 * EW_DIR add directories
9317 * EW_FILE add files
9318 * EW_EXEC add executable files
9319 * EW_NOTFOUND add even when it doesn't exist
9320 * EW_ADDSLASH add slash after directory name
9322 void
9323 addfile(gap, f, flags)
9324 garray_T *gap;
9325 char_u *f; /* filename */
9326 int flags;
9328 char_u *p;
9329 int isdir;
9331 /* if the file/dir doesn't exist, may not add it */
9332 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9333 return;
9335 #ifdef FNAME_ILLEGAL
9336 /* if the file/dir contains illegal characters, don't add it */
9337 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9338 return;
9339 #endif
9341 isdir = mch_isdir(f);
9342 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9343 return;
9345 /* If the file isn't executable, may not add it. Do accept directories. */
9346 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9347 return;
9349 /* Make room for another item in the file list. */
9350 if (ga_grow(gap, 1) == FAIL)
9351 return;
9353 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9354 if (p == NULL)
9355 return;
9357 STRCPY(p, f);
9358 #ifdef BACKSLASH_IN_FILENAME
9359 slash_adjust(p);
9360 #endif
9362 * Append a slash or backslash after directory names if none is present.
9364 #ifndef DONT_ADD_PATHSEP_TO_DIR
9365 if (isdir && (flags & EW_ADDSLASH))
9366 add_pathsep(p);
9367 #endif
9368 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
9370 #endif /* !NO_EXPANDPATH */
9372 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9374 #ifndef SEEK_SET
9375 # define SEEK_SET 0
9376 #endif
9377 #ifndef SEEK_END
9378 # define SEEK_END 2
9379 #endif
9382 * Get the stdout of an external command.
9383 * Returns an allocated string, or NULL for error.
9385 char_u *
9386 get_cmd_output(cmd, infile, flags)
9387 char_u *cmd;
9388 char_u *infile; /* optional input file name */
9389 int flags; /* can be SHELL_SILENT */
9391 char_u *tempname;
9392 char_u *command;
9393 char_u *buffer = NULL;
9394 int len;
9395 int i = 0;
9396 FILE *fd;
9398 if (check_restricted() || check_secure())
9399 return NULL;
9401 /* get a name for the temp file */
9402 if ((tempname = vim_tempname('o')) == NULL)
9404 EMSG(_(e_notmp));
9405 return NULL;
9408 /* Add the redirection stuff */
9409 command = make_filter_cmd(cmd, infile, tempname);
9410 if (command == NULL)
9411 goto done;
9414 * Call the shell to execute the command (errors are ignored).
9415 * Don't check timestamps here.
9417 ++no_check_timestamps;
9418 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9419 --no_check_timestamps;
9421 vim_free(command);
9424 * read the names from the file into memory
9426 # ifdef VMS
9427 /* created temporary file is not always readable as binary */
9428 fd = mch_fopen((char *)tempname, "r");
9429 # else
9430 fd = mch_fopen((char *)tempname, READBIN);
9431 # endif
9433 if (fd == NULL)
9435 EMSG2(_(e_notopen), tempname);
9436 goto done;
9439 fseek(fd, 0L, SEEK_END);
9440 len = ftell(fd); /* get size of temp file */
9441 fseek(fd, 0L, SEEK_SET);
9443 buffer = alloc(len + 1);
9444 if (buffer != NULL)
9445 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9446 fclose(fd);
9447 mch_remove(tempname);
9448 if (buffer == NULL)
9449 goto done;
9450 #ifdef VMS
9451 len = i; /* VMS doesn't give us what we asked for... */
9452 #endif
9453 if (i != len)
9455 EMSG2(_(e_notread), tempname);
9456 vim_free(buffer);
9457 buffer = NULL;
9459 else
9460 buffer[len] = '\0'; /* make sure the buffer is terminated */
9462 done:
9463 vim_free(tempname);
9464 return buffer;
9466 #endif
9469 * Free the list of files returned by expand_wildcards() or other expansion
9470 * functions.
9472 void
9473 FreeWild(count, files)
9474 int count;
9475 char_u **files;
9477 if (count <= 0 || files == NULL)
9478 return;
9479 #if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9481 * Is this still OK for when other functions than expand_wildcards() have
9482 * been used???
9484 _fnexplodefree((char **)files);
9485 #else
9486 while (count--)
9487 vim_free(files[count]);
9488 vim_free(files);
9489 #endif
9493 * return TRUE when need to go to Insert mode because of 'insertmode'.
9494 * Don't do this when still processing a command or a mapping.
9495 * Don't do this when inside a ":normal" command.
9498 goto_im()
9500 return (p_im && stuff_empty() && typebuf_typed());