merge changes from upstream
[MacVim/jjgod.git] / src / misc1.c
blobb67405fb40edff767aeb21babdfa91c9d38e9e22
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 #ifdef HAVE_FCNTL_H
18 # include <fcntl.h> /* for chdir() */
19 #endif
21 static char_u *vim_version_dir __ARGS((char_u *vimdir));
22 static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
23 static int copy_indent __ARGS((int size, char_u *src));
26 * Count the size (in window cells) of the indent in the current line.
28 int
29 get_indent()
31 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
35 * Count the size (in window cells) of the indent in line "lnum".
37 int
38 get_indent_lnum(lnum)
39 linenr_T lnum;
41 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
44 #if defined(FEAT_FOLDING) || defined(PROTO)
46 * Count the size (in window cells) of the indent in line "lnum" of buffer
47 * "buf".
49 int
50 get_indent_buf(buf, lnum)
51 buf_T *buf;
52 linenr_T lnum;
54 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
56 #endif
59 * count the size (in window cells) of the indent in line "ptr", with
60 * 'tabstop' at "ts"
62 int
63 get_indent_str(ptr, ts)
64 char_u *ptr;
65 int ts;
67 int count = 0;
69 for ( ; *ptr; ++ptr)
71 if (*ptr == TAB) /* count a tab for what it is worth */
72 count += ts - (count % ts);
73 else if (*ptr == ' ')
74 ++count; /* count a space for one */
75 else
76 break;
78 return count;
82 * Set the indent of the current line.
83 * Leaves the cursor on the first non-blank in the line.
84 * Caller must take care of undo.
85 * "flags":
86 * SIN_CHANGED: call changed_bytes() if the line was changed.
87 * SIN_INSERT: insert the indent in front of the line.
88 * SIN_UNDO: save line for undo before changing it.
89 * Returns TRUE if the line was changed.
91 int
92 set_indent(size, flags)
93 int size; /* measured in spaces */
94 int flags;
96 char_u *p;
97 char_u *newline;
98 char_u *oldline;
99 char_u *s;
100 int todo;
101 int ind_len; /* measured in characters */
102 int line_len;
103 int doit = FALSE;
104 int ind_done = 0; /* measured in spaces */
105 int tab_pad;
106 int retval = FALSE;
107 int orig_char_len = -1; /* number of initial whitespace chars when
108 'et' and 'pi' are both set */
111 * First check if there is anything to do and compute the number of
112 * characters needed for the indent.
114 todo = size;
115 ind_len = 0;
116 p = oldline = ml_get_curline();
118 /* Calculate the buffer size for the new indent, and check to see if it
119 * isn't already set */
121 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
122 * 'preserveindent' are set count the number of characters at the
123 * beginning of the line to be copied */
124 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
126 /* If 'preserveindent' is set then reuse as much as possible of
127 * the existing indent structure for the new indent */
128 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
130 ind_done = 0;
132 /* count as many characters as we can use */
133 while (todo > 0 && vim_iswhite(*p))
135 if (*p == TAB)
137 tab_pad = (int)curbuf->b_p_ts
138 - (ind_done % (int)curbuf->b_p_ts);
139 /* stop if this tab will overshoot the target */
140 if (todo < tab_pad)
141 break;
142 todo -= tab_pad;
143 ++ind_len;
144 ind_done += tab_pad;
146 else
148 --todo;
149 ++ind_len;
150 ++ind_done;
152 ++p;
155 /* Set initial number of whitespace chars to copy if we are
156 * preserving indent but expandtab is set */
157 if (curbuf->b_p_et)
158 orig_char_len = ind_len;
160 /* Fill to next tabstop with a tab, if possible */
161 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
162 if (todo >= tab_pad && orig_char_len == -1)
164 doit = TRUE;
165 todo -= tab_pad;
166 ++ind_len;
167 /* ind_done += tab_pad; */
171 /* count tabs required for indent */
172 while (todo >= (int)curbuf->b_p_ts)
174 if (*p != TAB)
175 doit = TRUE;
176 else
177 ++p;
178 todo -= (int)curbuf->b_p_ts;
179 ++ind_len;
180 /* ind_done += (int)curbuf->b_p_ts; */
183 /* count spaces required for indent */
184 while (todo > 0)
186 if (*p != ' ')
187 doit = TRUE;
188 else
189 ++p;
190 --todo;
191 ++ind_len;
192 /* ++ind_done; */
195 /* Return if the indent is OK already. */
196 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
197 return FALSE;
199 /* Allocate memory for the new line. */
200 if (flags & SIN_INSERT)
201 p = oldline;
202 else
203 p = skipwhite(p);
204 line_len = (int)STRLEN(p) + 1;
206 /* If 'preserveindent' and 'expandtab' are both set keep the original
207 * characters and allocate accordingly. We will fill the rest with spaces
208 * after the if (!curbuf->b_p_et) below. */
209 if (orig_char_len != -1)
211 newline = alloc(orig_char_len + size - ind_done + line_len);
212 if (newline == NULL)
213 return FALSE;
214 todo = size - ind_done;
215 ind_len = orig_char_len + todo; /* Set total length of indent in
216 * characters, which may have been
217 * undercounted until now */
218 p = oldline;
219 s = newline;
220 while (orig_char_len > 0)
222 *s++ = *p++;
223 orig_char_len--;
225 /* Skip over any additional white space (useful when newindent is less
226 * than old) */
227 while (vim_iswhite(*p))
228 (void)*p++;
231 else
233 todo = size;
234 newline = alloc(ind_len + line_len);
235 if (newline == NULL)
236 return FALSE;
237 s = newline;
240 /* Put the characters in the new line. */
241 /* if 'expandtab' isn't set: use TABs */
242 if (!curbuf->b_p_et)
244 /* If 'preserveindent' is set then reuse as much as possible of
245 * the existing indent structure for the new indent */
246 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
248 p = oldline;
249 ind_done = 0;
251 while (todo > 0 && vim_iswhite(*p))
253 if (*p == TAB)
255 tab_pad = (int)curbuf->b_p_ts
256 - (ind_done % (int)curbuf->b_p_ts);
257 /* stop if this tab will overshoot the target */
258 if (todo < tab_pad)
259 break;
260 todo -= tab_pad;
261 ind_done += tab_pad;
263 else
265 --todo;
266 ++ind_done;
268 *s++ = *p++;
271 /* Fill to next tabstop with a tab, if possible */
272 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
273 if (todo >= tab_pad)
275 *s++ = TAB;
276 todo -= tab_pad;
279 p = skipwhite(p);
282 while (todo >= (int)curbuf->b_p_ts)
284 *s++ = TAB;
285 todo -= (int)curbuf->b_p_ts;
288 while (todo > 0)
290 *s++ = ' ';
291 --todo;
293 mch_memmove(s, p, (size_t)line_len);
295 /* Replace the line (unless undo fails). */
296 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
298 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
299 if (flags & SIN_CHANGED)
300 changed_bytes(curwin->w_cursor.lnum, 0);
301 /* Correct saved cursor position if it's after the indent. */
302 if (saved_cursor.lnum == curwin->w_cursor.lnum
303 && saved_cursor.col >= (colnr_T)(p - oldline))
304 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
305 retval = TRUE;
307 else
308 vim_free(newline);
310 curwin->w_cursor.col = ind_len;
311 return retval;
315 * Copy the indent from ptr to the current line (and fill to size)
316 * Leaves the cursor on the first non-blank in the line.
317 * Returns TRUE if the line was changed.
319 static int
320 copy_indent(size, src)
321 int size;
322 char_u *src;
324 char_u *p = NULL;
325 char_u *line = NULL;
326 char_u *s;
327 int todo;
328 int ind_len;
329 int line_len = 0;
330 int tab_pad;
331 int ind_done;
332 int round;
334 /* Round 1: compute the number of characters needed for the indent
335 * Round 2: copy the characters. */
336 for (round = 1; round <= 2; ++round)
338 todo = size;
339 ind_len = 0;
340 ind_done = 0;
341 s = src;
343 /* Count/copy the usable portion of the source line */
344 while (todo > 0 && vim_iswhite(*s))
346 if (*s == TAB)
348 tab_pad = (int)curbuf->b_p_ts
349 - (ind_done % (int)curbuf->b_p_ts);
350 /* Stop if this tab will overshoot the target */
351 if (todo < tab_pad)
352 break;
353 todo -= tab_pad;
354 ind_done += tab_pad;
356 else
358 --todo;
359 ++ind_done;
361 ++ind_len;
362 if (p != NULL)
363 *p++ = *s;
364 ++s;
367 /* Fill to next tabstop with a tab, if possible */
368 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
369 if (todo >= tab_pad)
371 todo -= tab_pad;
372 ++ind_len;
373 if (p != NULL)
374 *p++ = TAB;
377 /* Add tabs required for indent */
378 while (todo >= (int)curbuf->b_p_ts)
380 todo -= (int)curbuf->b_p_ts;
381 ++ind_len;
382 if (p != NULL)
383 *p++ = TAB;
386 /* Count/add spaces required for indent */
387 while (todo > 0)
389 --todo;
390 ++ind_len;
391 if (p != NULL)
392 *p++ = ' ';
395 if (p == NULL)
397 /* Allocate memory for the result: the copied indent, new indent
398 * and the rest of the line. */
399 line_len = (int)STRLEN(ml_get_curline()) + 1;
400 line = alloc(ind_len + line_len);
401 if (line == NULL)
402 return FALSE;
403 p = line;
407 /* Append the original line */
408 mch_memmove(p, ml_get_curline(), (size_t)line_len);
410 /* Replace the line */
411 ml_replace(curwin->w_cursor.lnum, line, FALSE);
413 /* Put the cursor after the indent. */
414 curwin->w_cursor.col = ind_len;
415 return TRUE;
419 * Return the indent of the current line after a number. Return -1 if no
420 * number was found. Used for 'n' in 'formatoptions': numbered list.
421 * Since a pattern is used it can actually handle more than numbers.
424 get_number_indent(lnum)
425 linenr_T lnum;
427 colnr_T col;
428 pos_T pos;
429 regmmatch_T regmatch;
431 if (lnum > curbuf->b_ml.ml_line_count)
432 return -1;
433 pos.lnum = 0;
434 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
435 if (regmatch.regprog != NULL)
437 regmatch.rmm_ic = FALSE;
438 regmatch.rmm_maxcol = 0;
439 if (vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0))
441 pos.lnum = regmatch.endpos[0].lnum + lnum;
442 pos.col = regmatch.endpos[0].col;
443 #ifdef FEAT_VIRTUALEDIT
444 pos.coladd = 0;
445 #endif
447 vim_free(regmatch.regprog);
450 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
451 return -1;
452 getvcol(curwin, &pos, &col, NULL, NULL);
453 return (int)col;
456 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
458 static int cin_is_cinword __ARGS((char_u *line));
461 * Return TRUE if the string "line" starts with a word from 'cinwords'.
463 static int
464 cin_is_cinword(line)
465 char_u *line;
467 char_u *cinw;
468 char_u *cinw_buf;
469 int cinw_len;
470 int retval = FALSE;
471 int len;
473 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
474 cinw_buf = alloc((unsigned)cinw_len);
475 if (cinw_buf != NULL)
477 line = skipwhite(line);
478 for (cinw = curbuf->b_p_cinw; *cinw; )
480 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
481 if (STRNCMP(line, cinw_buf, len) == 0
482 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
484 retval = TRUE;
485 break;
488 vim_free(cinw_buf);
490 return retval;
492 #endif
495 * open_line: Add a new line below or above the current line.
497 * For VREPLACE mode, we only add a new line when we get to the end of the
498 * file, otherwise we just start replacing the next line.
500 * Caller must take care of undo. Since VREPLACE may affect any number of
501 * lines however, it may call u_save_cursor() again when starting to change a
502 * new line.
503 * "flags": OPENLINE_DELSPACES delete spaces after cursor
504 * OPENLINE_DO_COM format comments
505 * OPENLINE_KEEPTRAIL keep trailing spaces
506 * OPENLINE_MARKFIX adjust mark positions after the line break
508 * Return TRUE for success, FALSE for failure
511 open_line(dir, flags, old_indent)
512 int dir; /* FORWARD or BACKWARD */
513 int flags;
514 int old_indent; /* indent for after ^^D in Insert mode */
516 char_u *saved_line; /* copy of the original line */
517 char_u *next_line = NULL; /* copy of the next line */
518 char_u *p_extra = NULL; /* what goes to next line */
519 int less_cols = 0; /* less columns for mark in new line */
520 int less_cols_off = 0; /* columns to skip for mark adjust */
521 pos_T old_cursor; /* old cursor position */
522 int newcol = 0; /* new cursor column */
523 int newindent = 0; /* auto-indent of the new line */
524 int n;
525 int trunc_line = FALSE; /* truncate current line afterwards */
526 int retval = FALSE; /* return value, default is FAIL */
527 #ifdef FEAT_COMMENTS
528 int extra_len = 0; /* length of p_extra string */
529 int lead_len; /* length of comment leader */
530 char_u *lead_flags; /* position in 'comments' for comment leader */
531 char_u *leader = NULL; /* copy of comment leader */
532 #endif
533 char_u *allocated = NULL; /* allocated memory */
534 #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
535 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
536 char_u *p;
537 #endif
538 int saved_char = NUL; /* init for GCC */
539 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
540 pos_T *pos;
541 #endif
542 #ifdef FEAT_SMARTINDENT
543 int do_si = (!p_paste && curbuf->b_p_si
544 # ifdef FEAT_CINDENT
545 && !curbuf->b_p_cin
546 # endif
548 int no_si = FALSE; /* reset did_si afterwards */
549 int first_char = NUL; /* init for GCC */
550 #endif
551 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
552 int vreplace_mode;
553 #endif
554 int did_append; /* appended a new line */
555 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
558 * make a copy of the current line so we can mess with it
560 saved_line = vim_strsave(ml_get_curline());
561 if (saved_line == NULL) /* out of memory! */
562 return FALSE;
564 #ifdef FEAT_VREPLACE
565 if (State & VREPLACE_FLAG)
568 * With VREPLACE we make a copy of the next line, which we will be
569 * starting to replace. First make the new line empty and let vim play
570 * with the indenting and comment leader to its heart's content. Then
571 * we grab what it ended up putting on the new line, put back the
572 * original line, and call ins_char() to put each new character onto
573 * the line, replacing what was there before and pushing the right
574 * stuff onto the replace stack. -- webb.
576 if (curwin->w_cursor.lnum < orig_line_count)
577 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
578 else
579 next_line = vim_strsave((char_u *)"");
580 if (next_line == NULL) /* out of memory! */
581 goto theend;
584 * In VREPLACE mode, a NL replaces the rest of the line, and starts
585 * replacing the next line, so push all of the characters left on the
586 * line onto the replace stack. We'll push any other characters that
587 * might be replaced at the start of the next line (due to autoindent
588 * etc) a bit later.
590 replace_push(NUL); /* Call twice because BS over NL expects it */
591 replace_push(NUL);
592 p = saved_line + curwin->w_cursor.col;
593 while (*p != NUL)
594 replace_push(*p++);
595 saved_line[curwin->w_cursor.col] = NUL;
597 #endif
599 if ((State & INSERT)
600 #ifdef FEAT_VREPLACE
601 && !(State & VREPLACE_FLAG)
602 #endif
605 p_extra = saved_line + curwin->w_cursor.col;
606 #ifdef FEAT_SMARTINDENT
607 if (do_si) /* need first char after new line break */
609 p = skipwhite(p_extra);
610 first_char = *p;
612 #endif
613 #ifdef FEAT_COMMENTS
614 extra_len = (int)STRLEN(p_extra);
615 #endif
616 saved_char = *p_extra;
617 *p_extra = NUL;
620 u_clearline(); /* cannot do "U" command when adding lines */
621 #ifdef FEAT_SMARTINDENT
622 did_si = FALSE;
623 #endif
624 ai_col = 0;
627 * If we just did an auto-indent, then we didn't type anything on
628 * the prior line, and it should be truncated. Do this even if 'ai' is not
629 * set because automatically inserting a comment leader also sets did_ai.
631 if (dir == FORWARD && did_ai)
632 trunc_line = TRUE;
635 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
636 * indent to use for the new line.
638 if (curbuf->b_p_ai
639 #ifdef FEAT_SMARTINDENT
640 || do_si
641 #endif
645 * count white space on current line
647 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
648 if (newindent == 0)
649 newindent = old_indent; /* for ^^D command in insert mode */
651 #ifdef FEAT_SMARTINDENT
653 * Do smart indenting.
654 * In insert/replace mode (only when dir == FORWARD)
655 * we may move some text to the next line. If it starts with '{'
656 * don't add an indent. Fixes inserting a NL before '{' in line
657 * "if (condition) {"
659 if (!trunc_line && do_si && *saved_line != NUL
660 && (p_extra == NULL || first_char != '{'))
662 char_u *ptr;
663 char_u last_char;
665 old_cursor = curwin->w_cursor;
666 ptr = saved_line;
667 # ifdef FEAT_COMMENTS
668 if (flags & OPENLINE_DO_COM)
669 lead_len = get_leader_len(ptr, NULL, FALSE);
670 else
671 lead_len = 0;
672 # endif
673 if (dir == FORWARD)
676 * Skip preprocessor directives, unless they are
677 * recognised as comments.
679 if (
680 # ifdef FEAT_COMMENTS
681 lead_len == 0 &&
682 # endif
683 ptr[0] == '#')
685 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
686 ptr = ml_get(--curwin->w_cursor.lnum);
687 newindent = get_indent();
689 # ifdef FEAT_COMMENTS
690 if (flags & OPENLINE_DO_COM)
691 lead_len = get_leader_len(ptr, NULL, FALSE);
692 else
693 lead_len = 0;
694 if (lead_len > 0)
697 * This case gets the following right:
698 * \*
699 * * A comment (read '\' as '/').
700 * *\
701 * #define IN_THE_WAY
702 * This should line up here;
704 p = skipwhite(ptr);
705 if (p[0] == '/' && p[1] == '*')
706 p++;
707 if (p[0] == '*')
709 for (p++; *p; p++)
711 if (p[0] == '/' && p[-1] == '*')
714 * End of C comment, indent should line up
715 * with the line containing the start of
716 * the comment
718 curwin->w_cursor.col = (colnr_T)(p - ptr);
719 if ((pos = findmatch(NULL, NUL)) != NULL)
721 curwin->w_cursor.lnum = pos->lnum;
722 newindent = get_indent();
728 else /* Not a comment line */
729 # endif
731 /* Find last non-blank in line */
732 p = ptr + STRLEN(ptr) - 1;
733 while (p > ptr && vim_iswhite(*p))
734 --p;
735 last_char = *p;
738 * find the character just before the '{' or ';'
740 if (last_char == '{' || last_char == ';')
742 if (p > ptr)
743 --p;
744 while (p > ptr && vim_iswhite(*p))
745 --p;
748 * Try to catch lines that are split over multiple
749 * lines. eg:
750 * if (condition &&
751 * condition) {
752 * Should line up here!
755 if (*p == ')')
757 curwin->w_cursor.col = (colnr_T)(p - ptr);
758 if ((pos = findmatch(NULL, '(')) != NULL)
760 curwin->w_cursor.lnum = pos->lnum;
761 newindent = get_indent();
762 ptr = ml_get_curline();
766 * If last character is '{' do indent, without
767 * checking for "if" and the like.
769 if (last_char == '{')
771 did_si = TRUE; /* do indent */
772 no_si = TRUE; /* don't delete it when '{' typed */
775 * Look for "if" and the like, use 'cinwords'.
776 * Don't do this if the previous line ended in ';' or
777 * '}'.
779 else if (last_char != ';' && last_char != '}'
780 && cin_is_cinword(ptr))
781 did_si = TRUE;
784 else /* dir == BACKWARD */
787 * Skip preprocessor directives, unless they are
788 * recognised as comments.
790 if (
791 # ifdef FEAT_COMMENTS
792 lead_len == 0 &&
793 # endif
794 ptr[0] == '#')
796 int was_backslashed = FALSE;
798 while ((ptr[0] == '#' || was_backslashed) &&
799 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
801 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
802 was_backslashed = TRUE;
803 else
804 was_backslashed = FALSE;
805 ptr = ml_get(++curwin->w_cursor.lnum);
807 if (was_backslashed)
808 newindent = 0; /* Got to end of file */
809 else
810 newindent = get_indent();
812 p = skipwhite(ptr);
813 if (*p == '}') /* if line starts with '}': do indent */
814 did_si = TRUE;
815 else /* can delete indent when '{' typed */
816 can_si_back = TRUE;
818 curwin->w_cursor = old_cursor;
820 if (do_si)
821 can_si = TRUE;
822 #endif /* FEAT_SMARTINDENT */
824 did_ai = TRUE;
827 #ifdef FEAT_COMMENTS
829 * Find out if the current line starts with a comment leader.
830 * This may then be inserted in front of the new line.
832 end_comment_pending = NUL;
833 if (flags & OPENLINE_DO_COM)
834 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD);
835 else
836 lead_len = 0;
837 if (lead_len > 0)
839 char_u *lead_repl = NULL; /* replaces comment leader */
840 int lead_repl_len = 0; /* length of *lead_repl */
841 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
842 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
843 char_u *comment_end = NULL; /* where lead_end has been found */
844 int extra_space = FALSE; /* append extra space */
845 int current_flag;
846 int require_blank = FALSE; /* requires blank after middle */
847 char_u *p2;
850 * If the comment leader has the start, middle or end flag, it may not
851 * be used or may be replaced with the middle leader.
853 for (p = lead_flags; *p && *p != ':'; ++p)
855 if (*p == COM_BLANK)
857 require_blank = TRUE;
858 continue;
860 if (*p == COM_START || *p == COM_MIDDLE)
862 current_flag = *p;
863 if (*p == COM_START)
866 * Doing "O" on a start of comment does not insert leader.
868 if (dir == BACKWARD)
870 lead_len = 0;
871 break;
874 /* find start of middle part */
875 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
876 require_blank = FALSE;
880 * Isolate the strings of the middle and end leader.
882 while (*p && p[-1] != ':') /* find end of middle flags */
884 if (*p == COM_BLANK)
885 require_blank = TRUE;
886 ++p;
888 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
890 while (*p && p[-1] != ':') /* find end of end flags */
892 /* Check whether we allow automatic ending of comments */
893 if (*p == COM_AUTO_END)
894 end_comment_pending = -1; /* means we want to set it */
895 ++p;
897 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
899 if (end_comment_pending == -1) /* we can set it now */
900 end_comment_pending = lead_end[n - 1];
903 * If the end of the comment is in the same line, don't use
904 * the comment leader.
906 if (dir == FORWARD)
908 for (p = saved_line + lead_len; *p; ++p)
909 if (STRNCMP(p, lead_end, n) == 0)
911 comment_end = p;
912 lead_len = 0;
913 break;
918 * Doing "o" on a start of comment inserts the middle leader.
920 if (lead_len > 0)
922 if (current_flag == COM_START)
924 lead_repl = lead_middle;
925 lead_repl_len = (int)STRLEN(lead_middle);
929 * If we have hit RETURN immediately after the start
930 * comment leader, then put a space after the middle
931 * comment leader on the next line.
933 if (!vim_iswhite(saved_line[lead_len - 1])
934 && ((p_extra != NULL
935 && (int)curwin->w_cursor.col == lead_len)
936 || (p_extra == NULL
937 && saved_line[lead_len] == NUL)
938 || require_blank))
939 extra_space = TRUE;
941 break;
943 if (*p == COM_END)
946 * Doing "o" on the end of a comment does not insert leader.
947 * Remember where the end is, might want to use it to find the
948 * start (for C-comments).
950 if (dir == FORWARD)
952 comment_end = skipwhite(saved_line);
953 lead_len = 0;
954 break;
958 * Doing "O" on the end of a comment inserts the middle leader.
959 * Find the string for the middle leader, searching backwards.
961 while (p > curbuf->b_p_com && *p != ',')
962 --p;
963 for (lead_repl = p; lead_repl > curbuf->b_p_com
964 && lead_repl[-1] != ':'; --lead_repl)
966 lead_repl_len = (int)(p - lead_repl);
968 /* We can probably always add an extra space when doing "O" on
969 * the comment-end */
970 extra_space = TRUE;
972 /* Check whether we allow automatic ending of comments */
973 for (p2 = p; *p2 && *p2 != ':'; p2++)
975 if (*p2 == COM_AUTO_END)
976 end_comment_pending = -1; /* means we want to set it */
978 if (end_comment_pending == -1)
980 /* Find last character in end-comment string */
981 while (*p2 && *p2 != ',')
982 p2++;
983 end_comment_pending = p2[-1];
985 break;
987 if (*p == COM_FIRST)
990 * Comment leader for first line only: Don't repeat leader
991 * when using "O", blank out leader when using "o".
993 if (dir == BACKWARD)
994 lead_len = 0;
995 else
997 lead_repl = (char_u *)"";
998 lead_repl_len = 0;
1000 break;
1003 if (lead_len)
1005 /* allocate buffer (may concatenate p_exta later) */
1006 leader = alloc(lead_len + lead_repl_len + extra_space +
1007 extra_len + 1);
1008 allocated = leader; /* remember to free it later */
1010 if (leader == NULL)
1011 lead_len = 0;
1012 else
1014 vim_strncpy(leader, saved_line, lead_len);
1017 * Replace leader with lead_repl, right or left adjusted
1019 if (lead_repl != NULL)
1021 int c = 0;
1022 int off = 0;
1024 for (p = lead_flags; *p && *p != ':'; ++p)
1026 if (*p == COM_RIGHT || *p == COM_LEFT)
1027 c = *p;
1028 else if (VIM_ISDIGIT(*p) || *p == '-')
1029 off = getdigits(&p);
1031 if (c == COM_RIGHT) /* right adjusted leader */
1033 /* find last non-white in the leader to line up with */
1034 for (p = leader + lead_len - 1; p > leader
1035 && vim_iswhite(*p); --p)
1037 ++p;
1039 #ifdef FEAT_MBYTE
1040 /* Compute the length of the replaced characters in
1041 * screen characters, not bytes. */
1043 int repl_size = vim_strnsize(lead_repl,
1044 lead_repl_len);
1045 int old_size = 0;
1046 char_u *endp = p;
1047 int l;
1049 while (old_size < repl_size && p > leader)
1051 mb_ptr_back(leader, p);
1052 old_size += ptr2cells(p);
1054 l = lead_repl_len - (int)(endp - p);
1055 if (l != 0)
1056 mch_memmove(endp + l, endp,
1057 (size_t)((leader + lead_len) - endp));
1058 lead_len += l;
1060 #else
1061 if (p < leader + lead_repl_len)
1062 p = leader;
1063 else
1064 p -= lead_repl_len;
1065 #endif
1066 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1067 if (p + lead_repl_len > leader + lead_len)
1068 p[lead_repl_len] = NUL;
1070 /* blank-out any other chars from the old leader. */
1071 while (--p >= leader)
1073 #ifdef FEAT_MBYTE
1074 int l = mb_head_off(leader, p);
1076 if (l > 1)
1078 p -= l;
1079 if (ptr2cells(p) > 1)
1081 p[1] = ' ';
1082 --l;
1084 mch_memmove(p + 1, p + l + 1,
1085 (size_t)((leader + lead_len) - (p + l + 1)));
1086 lead_len -= l;
1087 *p = ' ';
1089 else
1090 #endif
1091 if (!vim_iswhite(*p))
1092 *p = ' ';
1095 else /* left adjusted leader */
1097 p = skipwhite(leader);
1098 #ifdef FEAT_MBYTE
1099 /* Compute the length of the replaced characters in
1100 * screen characters, not bytes. Move the part that is
1101 * not to be overwritten. */
1103 int repl_size = vim_strnsize(lead_repl,
1104 lead_repl_len);
1105 int i;
1106 int l;
1108 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1110 l = (*mb_ptr2len)(p + i);
1111 if (vim_strnsize(p, i + l) > repl_size)
1112 break;
1114 if (i != lead_repl_len)
1116 mch_memmove(p + lead_repl_len, p + i,
1117 (size_t)(lead_len - i - (leader - p)));
1118 lead_len += lead_repl_len - i;
1121 #endif
1122 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1124 /* Replace any remaining non-white chars in the old
1125 * leader by spaces. Keep Tabs, the indent must
1126 * remain the same. */
1127 for (p += lead_repl_len; p < leader + lead_len; ++p)
1128 if (!vim_iswhite(*p))
1130 /* Don't put a space before a TAB. */
1131 if (p + 1 < leader + lead_len && p[1] == TAB)
1133 --lead_len;
1134 mch_memmove(p, p + 1,
1135 (leader + lead_len) - p);
1137 else
1139 #ifdef FEAT_MBYTE
1140 int l = (*mb_ptr2len)(p);
1142 if (l > 1)
1144 if (ptr2cells(p) > 1)
1146 /* Replace a double-wide char with
1147 * two spaces */
1148 --l;
1149 *p++ = ' ';
1151 mch_memmove(p + 1, p + l,
1152 (leader + lead_len) - p);
1153 lead_len -= l - 1;
1155 #endif
1156 *p = ' ';
1159 *p = NUL;
1162 /* Recompute the indent, it may have changed. */
1163 if (curbuf->b_p_ai
1164 #ifdef FEAT_SMARTINDENT
1165 || do_si
1166 #endif
1168 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1170 /* Add the indent offset */
1171 if (newindent + off < 0)
1173 off = -newindent;
1174 newindent = 0;
1176 else
1177 newindent += off;
1179 /* Correct trailing spaces for the shift, so that
1180 * alignment remains equal. */
1181 while (off > 0 && lead_len > 0
1182 && leader[lead_len - 1] == ' ')
1184 /* Don't do it when there is a tab before the space */
1185 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1186 break;
1187 --lead_len;
1188 --off;
1191 /* If the leader ends in white space, don't add an
1192 * extra space */
1193 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1194 extra_space = FALSE;
1195 leader[lead_len] = NUL;
1198 if (extra_space)
1200 leader[lead_len++] = ' ';
1201 leader[lead_len] = NUL;
1204 newcol = lead_len;
1207 * if a new indent will be set below, remove the indent that
1208 * is in the comment leader
1210 if (newindent
1211 #ifdef FEAT_SMARTINDENT
1212 || did_si
1213 #endif
1216 while (lead_len && vim_iswhite(*leader))
1218 --lead_len;
1219 --newcol;
1220 ++leader;
1225 #ifdef FEAT_SMARTINDENT
1226 did_si = can_si = FALSE;
1227 #endif
1229 else if (comment_end != NULL)
1232 * We have finished a comment, so we don't use the leader.
1233 * If this was a C-comment and 'ai' or 'si' is set do a normal
1234 * indent to align with the line containing the start of the
1235 * comment.
1237 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1238 (curbuf->b_p_ai
1239 #ifdef FEAT_SMARTINDENT
1240 || do_si
1241 #endif
1244 old_cursor = curwin->w_cursor;
1245 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1246 if ((pos = findmatch(NULL, NUL)) != NULL)
1248 curwin->w_cursor.lnum = pos->lnum;
1249 newindent = get_indent();
1251 curwin->w_cursor = old_cursor;
1255 #endif
1257 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1258 if (p_extra != NULL)
1260 *p_extra = saved_char; /* restore char that NUL replaced */
1263 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1264 * non-blank.
1266 * When in REPLACE mode, put the deleted blanks on the replace stack,
1267 * preceded by a NUL, so they can be put back when a BS is entered.
1269 if (REPLACE_NORMAL(State))
1270 replace_push(NUL); /* end of extra blanks */
1271 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1273 while ((*p_extra == ' ' || *p_extra == '\t')
1274 #ifdef FEAT_MBYTE
1275 && (!enc_utf8
1276 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1277 #endif
1280 if (REPLACE_NORMAL(State))
1281 replace_push(*p_extra);
1282 ++p_extra;
1283 ++less_cols_off;
1286 if (*p_extra != NUL)
1287 did_ai = FALSE; /* append some text, don't truncate now */
1289 /* columns for marks adjusted for removed columns */
1290 less_cols = (int)(p_extra - saved_line);
1293 if (p_extra == NULL)
1294 p_extra = (char_u *)""; /* append empty line */
1296 #ifdef FEAT_COMMENTS
1297 /* concatenate leader and p_extra, if there is a leader */
1298 if (lead_len)
1300 STRCAT(leader, p_extra);
1301 p_extra = leader;
1302 did_ai = TRUE; /* So truncating blanks works with comments */
1303 less_cols -= lead_len;
1305 else
1306 end_comment_pending = NUL; /* turns out there was no leader */
1307 #endif
1309 old_cursor = curwin->w_cursor;
1310 if (dir == BACKWARD)
1311 --curwin->w_cursor.lnum;
1312 #ifdef FEAT_VREPLACE
1313 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1314 #endif
1316 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1317 == FAIL)
1318 goto theend;
1319 /* Postpone calling changed_lines(), because it would mess up folding
1320 * with markers. */
1321 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1322 did_append = TRUE;
1324 #ifdef FEAT_VREPLACE
1325 else
1328 * In VREPLACE mode we are starting to replace the next line.
1330 curwin->w_cursor.lnum++;
1331 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1333 /* In case we NL to a new line, BS to the previous one, and NL
1334 * again, we don't want to save the new line for undo twice.
1336 (void)u_save_cursor(); /* errors are ignored! */
1337 vr_lines_changed++;
1339 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1340 changed_bytes(curwin->w_cursor.lnum, 0);
1341 curwin->w_cursor.lnum--;
1342 did_append = FALSE;
1344 #endif
1346 if (newindent
1347 #ifdef FEAT_SMARTINDENT
1348 || did_si
1349 #endif
1352 ++curwin->w_cursor.lnum;
1353 #ifdef FEAT_SMARTINDENT
1354 if (did_si)
1356 if (p_sr)
1357 newindent -= newindent % (int)curbuf->b_p_sw;
1358 newindent += (int)curbuf->b_p_sw;
1360 #endif
1361 /* Copy the indent */
1362 if (curbuf->b_p_ci)
1364 (void)copy_indent(newindent, saved_line);
1367 * Set the 'preserveindent' option so that any further screwing
1368 * with the line doesn't entirely destroy our efforts to preserve
1369 * it. It gets restored at the function end.
1371 curbuf->b_p_pi = TRUE;
1373 else
1374 (void)set_indent(newindent, SIN_INSERT);
1375 less_cols -= curwin->w_cursor.col;
1377 ai_col = curwin->w_cursor.col;
1380 * In REPLACE mode, for each character in the new indent, there must
1381 * be a NUL on the replace stack, for when it is deleted with BS
1383 if (REPLACE_NORMAL(State))
1384 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1385 replace_push(NUL);
1386 newcol += curwin->w_cursor.col;
1387 #ifdef FEAT_SMARTINDENT
1388 if (no_si)
1389 did_si = FALSE;
1390 #endif
1393 #ifdef FEAT_COMMENTS
1395 * In REPLACE mode, for each character in the extra leader, there must be
1396 * a NUL on the replace stack, for when it is deleted with BS.
1398 if (REPLACE_NORMAL(State))
1399 while (lead_len-- > 0)
1400 replace_push(NUL);
1401 #endif
1403 curwin->w_cursor = old_cursor;
1405 if (dir == FORWARD)
1407 if (trunc_line || (State & INSERT))
1409 /* truncate current line at cursor */
1410 saved_line[curwin->w_cursor.col] = NUL;
1411 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1412 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1413 truncate_spaces(saved_line);
1414 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1415 saved_line = NULL;
1416 if (did_append)
1418 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1419 curwin->w_cursor.lnum + 1, 1L);
1420 did_append = FALSE;
1422 /* Move marks after the line break to the new line. */
1423 if (flags & OPENLINE_MARKFIX)
1424 mark_col_adjust(curwin->w_cursor.lnum,
1425 curwin->w_cursor.col + less_cols_off,
1426 1L, (long)-less_cols);
1428 else
1429 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1433 * Put the cursor on the new line. Careful: the scrollup() above may
1434 * have moved w_cursor, we must use old_cursor.
1436 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1438 if (did_append)
1439 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1441 curwin->w_cursor.col = newcol;
1442 #ifdef FEAT_VIRTUALEDIT
1443 curwin->w_cursor.coladd = 0;
1444 #endif
1446 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1448 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1449 * fixthisline() from doing it (via change_indent()) by telling it we're in
1450 * normal INSERT mode.
1452 if (State & VREPLACE_FLAG)
1454 vreplace_mode = State; /* So we know to put things right later */
1455 State = INSERT;
1457 else
1458 vreplace_mode = 0;
1459 #endif
1460 #ifdef FEAT_LISP
1462 * May do lisp indenting.
1464 if (!p_paste
1465 # ifdef FEAT_COMMENTS
1466 && leader == NULL
1467 # endif
1468 && curbuf->b_p_lisp
1469 && curbuf->b_p_ai)
1471 fixthisline(get_lisp_indent);
1472 p = ml_get_curline();
1473 ai_col = (colnr_T)(skipwhite(p) - p);
1475 #endif
1476 #ifdef FEAT_CINDENT
1478 * May do indenting after opening a new line.
1480 if (!p_paste
1481 && (curbuf->b_p_cin
1482 # ifdef FEAT_EVAL
1483 || *curbuf->b_p_inde != NUL
1484 # endif
1486 && in_cinkeys(dir == FORWARD
1487 ? KEY_OPEN_FORW
1488 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1490 do_c_expr_indent();
1491 p = ml_get_curline();
1492 ai_col = (colnr_T)(skipwhite(p) - p);
1494 #endif
1495 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1496 if (vreplace_mode != 0)
1497 State = vreplace_mode;
1498 #endif
1500 #ifdef FEAT_VREPLACE
1502 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1503 * original line, and inserts the new stuff char by char, pushing old stuff
1504 * onto the replace stack (via ins_char()).
1506 if (State & VREPLACE_FLAG)
1508 /* Put new line in p_extra */
1509 p_extra = vim_strsave(ml_get_curline());
1510 if (p_extra == NULL)
1511 goto theend;
1513 /* Put back original line */
1514 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1516 /* Insert new stuff into line again */
1517 curwin->w_cursor.col = 0;
1518 #ifdef FEAT_VIRTUALEDIT
1519 curwin->w_cursor.coladd = 0;
1520 #endif
1521 ins_bytes(p_extra); /* will call changed_bytes() */
1522 vim_free(p_extra);
1523 next_line = NULL;
1525 #endif
1527 retval = TRUE; /* success! */
1528 theend:
1529 curbuf->b_p_pi = saved_pi;
1530 vim_free(saved_line);
1531 vim_free(next_line);
1532 vim_free(allocated);
1533 return retval;
1536 #if defined(FEAT_COMMENTS) || defined(PROTO)
1538 * get_leader_len() returns the length of the prefix of the given string
1539 * which introduces a comment. If this string is not a comment then 0 is
1540 * returned.
1541 * When "flags" is not NULL, it is set to point to the flags of the recognized
1542 * comment leader.
1543 * "backward" must be true for the "O" command.
1546 get_leader_len(line, flags, backward)
1547 char_u *line;
1548 char_u **flags;
1549 int backward;
1551 int i, j;
1552 int got_com = FALSE;
1553 int found_one;
1554 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1555 char_u *string; /* pointer to comment string */
1556 char_u *list;
1558 i = 0;
1559 while (vim_iswhite(line[i])) /* leading white space is ignored */
1560 ++i;
1563 * Repeat to match several nested comment strings.
1565 while (line[i])
1568 * scan through the 'comments' option for a match
1570 found_one = FALSE;
1571 for (list = curbuf->b_p_com; *list; )
1574 * Get one option part into part_buf[]. Advance list to next one.
1575 * put string at start of string.
1577 if (!got_com && flags != NULL) /* remember where flags started */
1578 *flags = list;
1579 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1580 string = vim_strchr(part_buf, ':');
1581 if (string == NULL) /* missing ':', ignore this part */
1582 continue;
1583 *string++ = NUL; /* isolate flags from string */
1586 * When already found a nested comment, only accept further
1587 * nested comments.
1589 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1590 continue;
1592 /* When 'O' flag used don't use for "O" command */
1593 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1594 continue;
1597 * Line contents and string must match.
1598 * When string starts with white space, must have some white space
1599 * (but the amount does not need to match, there might be a mix of
1600 * TABs and spaces).
1602 if (vim_iswhite(string[0]))
1604 if (i == 0 || !vim_iswhite(line[i - 1]))
1605 continue;
1606 while (vim_iswhite(string[0]))
1607 ++string;
1609 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1611 if (string[j] != NUL)
1612 continue;
1615 * When 'b' flag used, there must be white space or an
1616 * end-of-line after the string in the line.
1618 if (vim_strchr(part_buf, COM_BLANK) != NULL
1619 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1620 continue;
1623 * We have found a match, stop searching.
1625 i += j;
1626 got_com = TRUE;
1627 found_one = TRUE;
1628 break;
1632 * No match found, stop scanning.
1634 if (!found_one)
1635 break;
1638 * Include any trailing white space.
1640 while (vim_iswhite(line[i]))
1641 ++i;
1644 * If this comment doesn't nest, stop here.
1646 if (vim_strchr(part_buf, COM_NEST) == NULL)
1647 break;
1649 return (got_com ? i : 0);
1651 #endif
1654 * Return the number of window lines occupied by buffer line "lnum".
1657 plines(lnum)
1658 linenr_T lnum;
1660 return plines_win(curwin, lnum, TRUE);
1664 plines_win(wp, lnum, winheight)
1665 win_T *wp;
1666 linenr_T lnum;
1667 int winheight; /* when TRUE limit to window height */
1669 #if defined(FEAT_DIFF) || defined(PROTO)
1670 /* Check for filler lines above this buffer line. When folded the result
1671 * is one line anyway. */
1672 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1676 plines_nofill(lnum)
1677 linenr_T lnum;
1679 return plines_win_nofill(curwin, lnum, TRUE);
1683 plines_win_nofill(wp, lnum, winheight)
1684 win_T *wp;
1685 linenr_T lnum;
1686 int winheight; /* when TRUE limit to window height */
1688 #endif
1689 int lines;
1691 if (!wp->w_p_wrap)
1692 return 1;
1694 #ifdef FEAT_VERTSPLIT
1695 if (wp->w_width == 0)
1696 return 1;
1697 #endif
1699 #ifdef FEAT_FOLDING
1700 /* A folded lines is handled just like an empty line. */
1701 /* NOTE: Caller must handle lines that are MAYBE folded. */
1702 if (lineFolded(wp, lnum) == TRUE)
1703 return 1;
1704 #endif
1706 lines = plines_win_nofold(wp, lnum);
1707 if (winheight > 0 && lines > wp->w_height)
1708 return (int)wp->w_height;
1709 return lines;
1713 * Return number of window lines physical line "lnum" will occupy in window
1714 * "wp". Does not care about folding, 'wrap' or 'diff'.
1717 plines_win_nofold(wp, lnum)
1718 win_T *wp;
1719 linenr_T lnum;
1721 char_u *s;
1722 long col;
1723 int width;
1725 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1726 if (*s == NUL) /* empty line */
1727 return 1;
1728 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1731 * If list mode is on, then the '$' at the end of the line may take up one
1732 * extra column.
1734 if (wp->w_p_list && lcs_eol != NUL)
1735 col += 1;
1738 * Add column offset for 'number' and 'foldcolumn'.
1740 width = W_WIDTH(wp) - win_col_off(wp);
1741 if (width <= 0)
1742 return 32000;
1743 if (col <= width)
1744 return 1;
1745 col -= width;
1746 width += win_col_off2(wp);
1747 return (col + (width - 1)) / width + 1;
1751 * Like plines_win(), but only reports the number of physical screen lines
1752 * used from the start of the line to the given column number.
1755 plines_win_col(wp, lnum, column)
1756 win_T *wp;
1757 linenr_T lnum;
1758 long column;
1760 long col;
1761 char_u *s;
1762 int lines = 0;
1763 int width;
1765 #ifdef FEAT_DIFF
1766 /* Check for filler lines above this buffer line. When folded the result
1767 * is one line anyway. */
1768 lines = diff_check_fill(wp, lnum);
1769 #endif
1771 if (!wp->w_p_wrap)
1772 return lines + 1;
1774 #ifdef FEAT_VERTSPLIT
1775 if (wp->w_width == 0)
1776 return lines + 1;
1777 #endif
1779 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1781 col = 0;
1782 while (*s != NUL && --column >= 0)
1784 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
1785 mb_ptr_adv(s);
1789 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1790 * INSERT mode, then col must be adjusted so that it represents the last
1791 * screen position of the TAB. This only fixes an error when the TAB wraps
1792 * from one screen line to the next (when 'columns' is not a multiple of
1793 * 'ts') -- webb.
1795 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1796 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1799 * Add column offset for 'number', 'foldcolumn', etc.
1801 width = W_WIDTH(wp) - win_col_off(wp);
1802 if (width <= 0)
1803 return 9999;
1805 lines += 1;
1806 if (col > width)
1807 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1808 return lines;
1812 plines_m_win(wp, first, last)
1813 win_T *wp;
1814 linenr_T first, last;
1816 int count = 0;
1818 while (first <= last)
1820 #ifdef FEAT_FOLDING
1821 int x;
1823 /* Check if there are any really folded lines, but also included lines
1824 * that are maybe folded. */
1825 x = foldedCount(wp, first, NULL);
1826 if (x > 0)
1828 ++count; /* count 1 for "+-- folded" line */
1829 first += x;
1831 else
1832 #endif
1834 #ifdef FEAT_DIFF
1835 if (first == wp->w_topline)
1836 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1837 else
1838 #endif
1839 count += plines_win(wp, first, TRUE);
1840 ++first;
1843 return (count);
1846 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1848 * Insert string "p" at the cursor position. Stops at a NUL byte.
1849 * Handles Replace mode and multi-byte characters.
1851 void
1852 ins_bytes(p)
1853 char_u *p;
1855 ins_bytes_len(p, (int)STRLEN(p));
1857 #endif
1859 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1860 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1862 * Insert string "p" with length "len" at the cursor position.
1863 * Handles Replace mode and multi-byte characters.
1865 void
1866 ins_bytes_len(p, len)
1867 char_u *p;
1868 int len;
1870 int i;
1871 # ifdef FEAT_MBYTE
1872 int n;
1874 for (i = 0; i < len; i += n)
1876 n = (*mb_ptr2len)(p + i);
1877 ins_char_bytes(p + i, n);
1879 # else
1880 for (i = 0; i < len; ++i)
1881 ins_char(p[i]);
1882 # endif
1884 #endif
1887 * Insert or replace a single character at the cursor position.
1888 * When in REPLACE or VREPLACE mode, replace any existing character.
1889 * Caller must have prepared for undo.
1890 * For multi-byte characters we get the whole character, the caller must
1891 * convert bytes to a character.
1893 void
1894 ins_char(c)
1895 int c;
1897 #if defined(FEAT_MBYTE) || defined(PROTO)
1898 char_u buf[MB_MAXBYTES];
1899 int n;
1901 n = (*mb_char2bytes)(c, buf);
1903 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1904 * Happens for CTRL-Vu9900. */
1905 if (buf[0] == 0)
1906 buf[0] = '\n';
1908 ins_char_bytes(buf, n);
1911 void
1912 ins_char_bytes(buf, charlen)
1913 char_u *buf;
1914 int charlen;
1916 int c = buf[0];
1917 int l, j;
1918 #endif
1919 int newlen; /* nr of bytes inserted */
1920 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1921 char_u *p;
1922 char_u *newp;
1923 char_u *oldp;
1924 int linelen; /* length of old line including NUL */
1925 colnr_T col;
1926 linenr_T lnum = curwin->w_cursor.lnum;
1927 int i;
1929 #ifdef FEAT_VIRTUALEDIT
1930 /* Break tabs if needed. */
1931 if (virtual_active() && curwin->w_cursor.coladd > 0)
1932 coladvance_force(getviscol());
1933 #endif
1935 col = curwin->w_cursor.col;
1936 oldp = ml_get(lnum);
1937 linelen = (int)STRLEN(oldp) + 1;
1939 /* The lengths default to the values for when not replacing. */
1940 oldlen = 0;
1941 #ifdef FEAT_MBYTE
1942 newlen = charlen;
1943 #else
1944 newlen = 1;
1945 #endif
1947 if (State & REPLACE_FLAG)
1949 #ifdef FEAT_VREPLACE
1950 if (State & VREPLACE_FLAG)
1952 colnr_T new_vcol = 0; /* init for GCC */
1953 colnr_T vcol;
1954 int old_list;
1955 #ifndef FEAT_MBYTE
1956 char_u buf[2];
1957 #endif
1960 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1961 * Returns the old value of list, so when finished,
1962 * curwin->w_p_list should be set back to this.
1964 old_list = curwin->w_p_list;
1965 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
1966 curwin->w_p_list = FALSE;
1969 * In virtual replace mode each character may replace one or more
1970 * characters (zero if it's a TAB). Count the number of bytes to
1971 * be deleted to make room for the new character, counting screen
1972 * cells. May result in adding spaces to fill a gap.
1974 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
1975 #ifndef FEAT_MBYTE
1976 buf[0] = c;
1977 buf[1] = NUL;
1978 #endif
1979 new_vcol = vcol + chartabsize(buf, vcol);
1980 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
1982 vcol += chartabsize(oldp + col + oldlen, vcol);
1983 /* Don't need to remove a TAB that takes us to the right
1984 * position. */
1985 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
1986 break;
1987 #ifdef FEAT_MBYTE
1988 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
1989 #else
1990 ++oldlen;
1991 #endif
1992 /* Deleted a bit too much, insert spaces. */
1993 if (vcol > new_vcol)
1994 newlen += vcol - new_vcol;
1996 curwin->w_p_list = old_list;
1998 else
1999 #endif
2000 if (oldp[col] != NUL)
2002 /* normal replace */
2003 #ifdef FEAT_MBYTE
2004 oldlen = (*mb_ptr2len)(oldp + col);
2005 #else
2006 oldlen = 1;
2007 #endif
2011 /* Push the replaced bytes onto the replace stack, so that they can be
2012 * put back when BS is used. The bytes of a multi-byte character are
2013 * done the other way around, so that the first byte is popped off
2014 * first (it tells the byte length of the character). */
2015 replace_push(NUL);
2016 for (i = 0; i < oldlen; ++i)
2018 #ifdef FEAT_MBYTE
2019 l = (*mb_ptr2len)(oldp + col + i) - 1;
2020 for (j = l; j >= 0; --j)
2021 replace_push(oldp[col + i + j]);
2022 i += l;
2023 #else
2024 replace_push(oldp[col + i]);
2025 #endif
2029 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2030 if (newp == NULL)
2031 return;
2033 /* Copy bytes before the cursor. */
2034 if (col > 0)
2035 mch_memmove(newp, oldp, (size_t)col);
2037 /* Copy bytes after the changed character(s). */
2038 p = newp + col;
2039 mch_memmove(p + newlen, oldp + col + oldlen,
2040 (size_t)(linelen - col - oldlen));
2042 /* Insert or overwrite the new character. */
2043 #ifdef FEAT_MBYTE
2044 mch_memmove(p, buf, charlen);
2045 i = charlen;
2046 #else
2047 *p = c;
2048 i = 1;
2049 #endif
2051 /* Fill with spaces when necessary. */
2052 while (i < newlen)
2053 p[i++] = ' ';
2055 /* Replace the line in the buffer. */
2056 ml_replace(lnum, newp, FALSE);
2058 /* mark the buffer as changed and prepare for displaying */
2059 changed_bytes(lnum, col);
2062 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2063 * show the match for right parens and braces.
2065 if (p_sm && (State & INSERT)
2066 && msg_silent == 0
2067 #ifdef FEAT_MBYTE
2068 && charlen == 1
2069 #endif
2070 #ifdef FEAT_INS_EXPAND
2071 && !ins_compl_active()
2072 #endif
2074 showmatch(c);
2076 #ifdef FEAT_RIGHTLEFT
2077 if (!p_ri || (State & REPLACE_FLAG))
2078 #endif
2080 /* Normal insert: move cursor right */
2081 #ifdef FEAT_MBYTE
2082 curwin->w_cursor.col += charlen;
2083 #else
2084 ++curwin->w_cursor.col;
2085 #endif
2088 * TODO: should try to update w_row here, to avoid recomputing it later.
2093 * Insert a string at the cursor position.
2094 * Note: Does NOT handle Replace mode.
2095 * Caller must have prepared for undo.
2097 void
2098 ins_str(s)
2099 char_u *s;
2101 char_u *oldp, *newp;
2102 int newlen = (int)STRLEN(s);
2103 int oldlen;
2104 colnr_T col;
2105 linenr_T lnum = curwin->w_cursor.lnum;
2107 #ifdef FEAT_VIRTUALEDIT
2108 if (virtual_active() && curwin->w_cursor.coladd > 0)
2109 coladvance_force(getviscol());
2110 #endif
2112 col = curwin->w_cursor.col;
2113 oldp = ml_get(lnum);
2114 oldlen = (int)STRLEN(oldp);
2116 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2117 if (newp == NULL)
2118 return;
2119 if (col > 0)
2120 mch_memmove(newp, oldp, (size_t)col);
2121 mch_memmove(newp + col, s, (size_t)newlen);
2122 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2123 ml_replace(lnum, newp, FALSE);
2124 changed_bytes(lnum, col);
2125 curwin->w_cursor.col += newlen;
2129 * Delete one character under the cursor.
2130 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2131 * Caller must have prepared for undo.
2133 * return FAIL for failure, OK otherwise
2136 del_char(fixpos)
2137 int fixpos;
2139 #ifdef FEAT_MBYTE
2140 if (has_mbyte)
2142 /* Make sure the cursor is at the start of a character. */
2143 mb_adjust_cursor();
2144 if (*ml_get_cursor() == NUL)
2145 return FAIL;
2146 return del_chars(1L, fixpos);
2148 #endif
2149 return del_bytes(1L, fixpos, TRUE);
2152 #if defined(FEAT_MBYTE) || defined(PROTO)
2154 * Like del_bytes(), but delete characters instead of bytes.
2157 del_chars(count, fixpos)
2158 long count;
2159 int fixpos;
2161 long bytes = 0;
2162 long i;
2163 char_u *p;
2164 int l;
2166 p = ml_get_cursor();
2167 for (i = 0; i < count && *p != NUL; ++i)
2169 l = (*mb_ptr2len)(p);
2170 bytes += l;
2171 p += l;
2173 return del_bytes(bytes, fixpos, TRUE);
2175 #endif
2178 * Delete "count" bytes under the cursor.
2179 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2180 * Caller must have prepared for undo.
2182 * return FAIL for failure, OK otherwise
2184 /*ARGSUSED*/
2186 del_bytes(count, fixpos_arg, use_delcombine)
2187 long count;
2188 int fixpos_arg;
2189 int use_delcombine; /* 'delcombine' option applies */
2191 char_u *oldp, *newp;
2192 colnr_T oldlen;
2193 linenr_T lnum = curwin->w_cursor.lnum;
2194 colnr_T col = curwin->w_cursor.col;
2195 int was_alloced;
2196 long movelen;
2197 int fixpos = fixpos_arg;
2199 oldp = ml_get(lnum);
2200 oldlen = (int)STRLEN(oldp);
2203 * Can't do anything when the cursor is on the NUL after the line.
2205 if (col >= oldlen)
2206 return FAIL;
2208 #ifdef FEAT_MBYTE
2209 /* If 'delcombine' is set and deleting (less than) one character, only
2210 * delete the last combining character. */
2211 if (p_deco && use_delcombine && enc_utf8
2212 && utfc_ptr2len(oldp + col) >= count)
2214 int cc[MAX_MCO];
2215 int n;
2217 (void)utfc_ptr2char(oldp + col, cc);
2218 if (cc[0] != NUL)
2220 /* Find the last composing char, there can be several. */
2221 n = col;
2224 col = n;
2225 count = utf_ptr2len(oldp + n);
2226 n += count;
2227 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2228 fixpos = 0;
2231 #endif
2234 * When count is too big, reduce it.
2236 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2237 if (movelen <= 1)
2240 * If we just took off the last character of a non-blank line, and
2241 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2242 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2244 if (col > 0 && fixpos && restart_edit == 0
2245 #ifdef FEAT_VIRTUALEDIT
2246 && (ve_flags & VE_ONEMORE) == 0
2247 #endif
2250 --curwin->w_cursor.col;
2251 #ifdef FEAT_VIRTUALEDIT
2252 curwin->w_cursor.coladd = 0;
2253 #endif
2254 #ifdef FEAT_MBYTE
2255 if (has_mbyte)
2256 curwin->w_cursor.col -=
2257 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2258 #endif
2260 count = oldlen - col;
2261 movelen = 1;
2265 * If the old line has been allocated the deletion can be done in the
2266 * existing line. Otherwise a new line has to be allocated
2268 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
2269 #ifdef FEAT_NETBEANS_INTG
2270 if (was_alloced && usingNetbeans)
2271 netbeans_removed(curbuf, lnum, col, count);
2272 /* else is handled by ml_replace() */
2273 #endif
2274 if (was_alloced)
2275 newp = oldp; /* use same allocated memory */
2276 else
2277 { /* need to allocate a new line */
2278 newp = alloc((unsigned)(oldlen + 1 - count));
2279 if (newp == NULL)
2280 return FAIL;
2281 mch_memmove(newp, oldp, (size_t)col);
2283 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2284 if (!was_alloced)
2285 ml_replace(lnum, newp, FALSE);
2287 /* mark the buffer as changed and prepare for displaying */
2288 changed_bytes(lnum, curwin->w_cursor.col);
2290 return OK;
2294 * Delete from cursor to end of line.
2295 * Caller must have prepared for undo.
2297 * return FAIL for failure, OK otherwise
2300 truncate_line(fixpos)
2301 int fixpos; /* if TRUE fix the cursor position when done */
2303 char_u *newp;
2304 linenr_T lnum = curwin->w_cursor.lnum;
2305 colnr_T col = curwin->w_cursor.col;
2307 if (col == 0)
2308 newp = vim_strsave((char_u *)"");
2309 else
2310 newp = vim_strnsave(ml_get(lnum), col);
2312 if (newp == NULL)
2313 return FAIL;
2315 ml_replace(lnum, newp, FALSE);
2317 /* mark the buffer as changed and prepare for displaying */
2318 changed_bytes(lnum, curwin->w_cursor.col);
2321 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2323 if (fixpos && curwin->w_cursor.col > 0)
2324 --curwin->w_cursor.col;
2326 return OK;
2330 * Delete "nlines" lines at the cursor.
2331 * Saves the lines for undo first if "undo" is TRUE.
2333 void
2334 del_lines(nlines, undo)
2335 long nlines; /* number of lines to delete */
2336 int undo; /* if TRUE, prepare for undo */
2338 long n;
2340 if (nlines <= 0)
2341 return;
2343 /* save the deleted lines for undo */
2344 if (undo && u_savedel(curwin->w_cursor.lnum, nlines) == FAIL)
2345 return;
2347 for (n = 0; n < nlines; )
2349 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2350 break;
2352 ml_delete(curwin->w_cursor.lnum, TRUE);
2353 ++n;
2355 /* If we delete the last line in the file, stop */
2356 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
2357 break;
2359 /* adjust marks, mark the buffer as changed and prepare for displaying */
2360 deleted_lines_mark(curwin->w_cursor.lnum, n);
2362 curwin->w_cursor.col = 0;
2363 check_cursor_lnum();
2367 gchar_pos(pos)
2368 pos_T *pos;
2370 char_u *ptr = ml_get_pos(pos);
2372 #ifdef FEAT_MBYTE
2373 if (has_mbyte)
2374 return (*mb_ptr2char)(ptr);
2375 #endif
2376 return (int)*ptr;
2380 gchar_cursor()
2382 #ifdef FEAT_MBYTE
2383 if (has_mbyte)
2384 return (*mb_ptr2char)(ml_get_cursor());
2385 #endif
2386 return (int)*ml_get_cursor();
2390 * Write a character at the current cursor position.
2391 * It is directly written into the block.
2393 void
2394 pchar_cursor(c)
2395 int c;
2397 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2398 + curwin->w_cursor.col) = c;
2401 #if 0 /* not used */
2403 * Put *pos at end of current buffer
2405 void
2406 goto_endofbuf(pos)
2407 pos_T *pos;
2409 char_u *p;
2411 pos->lnum = curbuf->b_ml.ml_line_count;
2412 pos->col = 0;
2413 p = ml_get(pos->lnum);
2414 while (*p++)
2415 ++pos->col;
2417 #endif
2420 * When extra == 0: Return TRUE if the cursor is before or on the first
2421 * non-blank in the line.
2422 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2423 * the line.
2426 inindent(extra)
2427 int extra;
2429 char_u *ptr;
2430 colnr_T col;
2432 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2433 ++ptr;
2434 if (col >= curwin->w_cursor.col + extra)
2435 return TRUE;
2436 else
2437 return FALSE;
2441 * Skip to next part of an option argument: Skip space and comma.
2443 char_u *
2444 skip_to_option_part(p)
2445 char_u *p;
2447 if (*p == ',')
2448 ++p;
2449 while (*p == ' ')
2450 ++p;
2451 return p;
2455 * changed() is called when something in the current buffer is changed.
2457 * Most often called through changed_bytes() and changed_lines(), which also
2458 * mark the area of the display to be redrawn.
2460 void
2461 changed()
2463 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2464 /* The text of the preediting area is inserted, but this doesn't
2465 * mean a change of the buffer yet. That is delayed until the
2466 * text is committed. (this means preedit becomes empty) */
2467 if (im_is_preediting() && !xim_changed_while_preediting)
2468 return;
2469 xim_changed_while_preediting = FALSE;
2470 #endif
2472 if (!curbuf->b_changed)
2474 int save_msg_scroll = msg_scroll;
2476 /* Give a warning about changing a read-only file. This may also
2477 * check-out the file, thus change "curbuf"! */
2478 change_warning(0);
2480 /* Create a swap file if that is wanted.
2481 * Don't do this for "nofile" and "nowrite" buffer types. */
2482 if (curbuf->b_may_swap
2483 #ifdef FEAT_QUICKFIX
2484 && !bt_dontwrite(curbuf)
2485 #endif
2488 ml_open_file(curbuf);
2490 /* The ml_open_file() can cause an ATTENTION message.
2491 * Wait two seconds, to make sure the user reads this unexpected
2492 * message. Since we could be anywhere, call wait_return() now,
2493 * and don't let the emsg() set msg_scroll. */
2494 if (need_wait_return && emsg_silent == 0)
2496 out_flush();
2497 ui_delay(2000L, TRUE);
2498 wait_return(TRUE);
2499 msg_scroll = save_msg_scroll;
2502 curbuf->b_changed = TRUE;
2503 ml_setflags(curbuf);
2504 #ifdef FEAT_WINDOWS
2505 check_status(curbuf);
2506 redraw_tabline = TRUE;
2507 #endif
2508 #ifdef FEAT_TITLE
2509 need_maketitle = TRUE; /* set window title later */
2510 #endif
2512 ++curbuf->b_changedtick;
2515 static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2516 static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
2517 static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2520 * Changed bytes within a single line for the current buffer.
2521 * - marks the windows on this buffer to be redisplayed
2522 * - marks the buffer changed by calling changed()
2523 * - invalidates cached values
2525 void
2526 changed_bytes(lnum, col)
2527 linenr_T lnum;
2528 colnr_T col;
2530 changedOneline(curbuf, lnum);
2531 changed_common(lnum, col, lnum + 1, 0L);
2533 #ifdef FEAT_DIFF
2534 /* Diff highlighting in other diff windows may need to be updated too. */
2535 if (curwin->w_p_diff)
2537 win_T *wp;
2538 linenr_T wlnum;
2540 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2541 if (wp->w_p_diff && wp != curwin)
2543 redraw_win_later(wp, VALID);
2544 wlnum = diff_lnum_win(lnum, wp);
2545 if (wlnum > 0)
2546 changedOneline(wp->w_buffer, wlnum);
2549 #endif
2552 static void
2553 changedOneline(buf, lnum)
2554 buf_T *buf;
2555 linenr_T lnum;
2557 if (buf->b_mod_set)
2559 /* find the maximum area that must be redisplayed */
2560 if (lnum < buf->b_mod_top)
2561 buf->b_mod_top = lnum;
2562 else if (lnum >= buf->b_mod_bot)
2563 buf->b_mod_bot = lnum + 1;
2565 else
2567 /* set the area that must be redisplayed to one line */
2568 buf->b_mod_set = TRUE;
2569 buf->b_mod_top = lnum;
2570 buf->b_mod_bot = lnum + 1;
2571 buf->b_mod_xlines = 0;
2576 * Appended "count" lines below line "lnum" in the current buffer.
2577 * Must be called AFTER the change and after mark_adjust().
2578 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2580 void
2581 appended_lines(lnum, count)
2582 linenr_T lnum;
2583 long count;
2585 changed_lines(lnum + 1, 0, lnum + 1, count);
2589 * Like appended_lines(), but adjust marks first.
2591 void
2592 appended_lines_mark(lnum, count)
2593 linenr_T lnum;
2594 long count;
2596 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2597 changed_lines(lnum + 1, 0, lnum + 1, count);
2601 * Deleted "count" lines at line "lnum" in the current buffer.
2602 * Must be called AFTER the change and after mark_adjust().
2603 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2605 void
2606 deleted_lines(lnum, count)
2607 linenr_T lnum;
2608 long count;
2610 changed_lines(lnum, 0, lnum + count, -count);
2614 * Like deleted_lines(), but adjust marks first.
2616 void
2617 deleted_lines_mark(lnum, count)
2618 linenr_T lnum;
2619 long count;
2621 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2622 changed_lines(lnum, 0, lnum + count, -count);
2626 * Changed lines for the current buffer.
2627 * Must be called AFTER the change and after mark_adjust().
2628 * - mark the buffer changed by calling changed()
2629 * - mark the windows on this buffer to be redisplayed
2630 * - invalidate cached values
2631 * "lnum" is the first line that needs displaying, "lnume" the first line
2632 * below the changed lines (BEFORE the change).
2633 * When only inserting lines, "lnum" and "lnume" are equal.
2634 * Takes care of calling changed() and updating b_mod_*.
2636 void
2637 changed_lines(lnum, col, lnume, xtra)
2638 linenr_T lnum; /* first line with change */
2639 colnr_T col; /* column in first line with change */
2640 linenr_T lnume; /* line below last changed line */
2641 long xtra; /* number of extra lines (negative when deleting) */
2643 changed_lines_buf(curbuf, lnum, lnume, xtra);
2645 #ifdef FEAT_DIFF
2646 if (xtra == 0 && curwin->w_p_diff)
2648 /* When the number of lines doesn't change then mark_adjust() isn't
2649 * called and other diff buffers still need to be marked for
2650 * displaying. */
2651 win_T *wp;
2652 linenr_T wlnum;
2654 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2655 if (wp->w_p_diff && wp != curwin)
2657 redraw_win_later(wp, VALID);
2658 wlnum = diff_lnum_win(lnum, wp);
2659 if (wlnum > 0)
2660 changed_lines_buf(wp->w_buffer, wlnum,
2661 lnume - lnum + wlnum, 0L);
2664 #endif
2666 changed_common(lnum, col, lnume, xtra);
2669 static void
2670 changed_lines_buf(buf, lnum, lnume, xtra)
2671 buf_T *buf;
2672 linenr_T lnum; /* first line with change */
2673 linenr_T lnume; /* line below last changed line */
2674 long xtra; /* number of extra lines (negative when deleting) */
2676 if (buf->b_mod_set)
2678 /* find the maximum area that must be redisplayed */
2679 if (lnum < buf->b_mod_top)
2680 buf->b_mod_top = lnum;
2681 if (lnum < buf->b_mod_bot)
2683 /* adjust old bot position for xtra lines */
2684 buf->b_mod_bot += xtra;
2685 if (buf->b_mod_bot < lnum)
2686 buf->b_mod_bot = lnum;
2688 if (lnume + xtra > buf->b_mod_bot)
2689 buf->b_mod_bot = lnume + xtra;
2690 buf->b_mod_xlines += xtra;
2692 else
2694 /* set the area that must be redisplayed */
2695 buf->b_mod_set = TRUE;
2696 buf->b_mod_top = lnum;
2697 buf->b_mod_bot = lnume + xtra;
2698 buf->b_mod_xlines = xtra;
2702 static void
2703 changed_common(lnum, col, lnume, xtra)
2704 linenr_T lnum;
2705 colnr_T col;
2706 linenr_T lnume;
2707 long xtra;
2709 win_T *wp;
2710 int i;
2711 #ifdef FEAT_JUMPLIST
2712 int cols;
2713 pos_T *p;
2714 int add;
2715 #endif
2717 /* mark the buffer as modified */
2718 changed();
2720 /* set the '. mark */
2721 if (!cmdmod.keepjumps)
2723 curbuf->b_last_change.lnum = lnum;
2724 curbuf->b_last_change.col = col;
2726 #ifdef FEAT_JUMPLIST
2727 /* Create a new entry if a new undo-able change was started or we
2728 * don't have an entry yet. */
2729 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2731 if (curbuf->b_changelistlen == 0)
2732 add = TRUE;
2733 else
2735 /* Don't create a new entry when the line number is the same
2736 * as the last one and the column is not too far away. Avoids
2737 * creating many entries for typing "xxxxx". */
2738 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2739 if (p->lnum != lnum)
2740 add = TRUE;
2741 else
2743 cols = comp_textwidth(FALSE);
2744 if (cols == 0)
2745 cols = 79;
2746 add = (p->col + cols < col || col + cols < p->col);
2749 if (add)
2751 /* This is the first of a new sequence of undo-able changes
2752 * and it's at some distance of the last change. Use a new
2753 * position in the changelist. */
2754 curbuf->b_new_change = FALSE;
2756 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2758 /* changelist is full: remove oldest entry */
2759 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2760 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2761 sizeof(pos_T) * (JUMPLISTSIZE - 1));
2762 FOR_ALL_WINDOWS(wp)
2764 /* Correct position in changelist for other windows on
2765 * this buffer. */
2766 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2767 --wp->w_changelistidx;
2770 FOR_ALL_WINDOWS(wp)
2772 /* For other windows, if the position in the changelist is
2773 * at the end it stays at the end. */
2774 if (wp->w_buffer == curbuf
2775 && wp->w_changelistidx == curbuf->b_changelistlen)
2776 ++wp->w_changelistidx;
2778 ++curbuf->b_changelistlen;
2781 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2782 curbuf->b_last_change;
2783 /* The current window is always after the last change, so that "g,"
2784 * takes you back to it. */
2785 curwin->w_changelistidx = curbuf->b_changelistlen;
2786 #endif
2789 FOR_ALL_WINDOWS(wp)
2791 if (wp->w_buffer == curbuf)
2793 /* Mark this window to be redrawn later. */
2794 if (wp->w_redr_type < VALID)
2795 wp->w_redr_type = VALID;
2797 /* Check if a change in the buffer has invalidated the cached
2798 * values for the cursor. */
2799 #ifdef FEAT_FOLDING
2801 * Update the folds for this window. Can't postpone this, because
2802 * a following operator might work on the whole fold: ">>dd".
2804 foldUpdate(wp, lnum, lnume + xtra - 1);
2806 /* The change may cause lines above or below the change to become
2807 * included in a fold. Set lnum/lnume to the first/last line that
2808 * might be displayed differently.
2809 * Set w_cline_folded here as an efficient way to update it when
2810 * inserting lines just above a closed fold. */
2811 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2812 if (wp->w_cursor.lnum == lnum)
2813 wp->w_cline_folded = i;
2814 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2815 if (wp->w_cursor.lnum == lnume)
2816 wp->w_cline_folded = i;
2818 /* If the changed line is in a range of previously folded lines,
2819 * compare with the first line in that range. */
2820 if (wp->w_cursor.lnum <= lnum)
2822 i = find_wl_entry(wp, lnum);
2823 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2824 changed_line_abv_curs_win(wp);
2826 #endif
2828 if (wp->w_cursor.lnum > lnum)
2829 changed_line_abv_curs_win(wp);
2830 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2831 changed_cline_bef_curs_win(wp);
2832 if (wp->w_botline >= lnum)
2834 /* Assume that botline doesn't change (inserted lines make
2835 * other lines scroll down below botline). */
2836 approximate_botline_win(wp);
2839 /* Check if any w_lines[] entries have become invalid.
2840 * For entries below the change: Correct the lnums for
2841 * inserted/deleted lines. Makes it possible to stop displaying
2842 * after the change. */
2843 for (i = 0; i < wp->w_lines_valid; ++i)
2844 if (wp->w_lines[i].wl_valid)
2846 if (wp->w_lines[i].wl_lnum >= lnum)
2848 if (wp->w_lines[i].wl_lnum < lnume)
2850 /* line included in change */
2851 wp->w_lines[i].wl_valid = FALSE;
2853 else if (xtra != 0)
2855 /* line below change */
2856 wp->w_lines[i].wl_lnum += xtra;
2857 #ifdef FEAT_FOLDING
2858 wp->w_lines[i].wl_lastlnum += xtra;
2859 #endif
2862 #ifdef FEAT_FOLDING
2863 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2865 /* change somewhere inside this range of folded lines,
2866 * may need to be redrawn */
2867 wp->w_lines[i].wl_valid = FALSE;
2869 #endif
2874 /* Call update_screen() later, which checks out what needs to be redrawn,
2875 * since it notices b_mod_set and then uses b_mod_*. */
2876 if (must_redraw < VALID)
2877 must_redraw = VALID;
2879 #ifdef FEAT_AUTOCMD
2880 /* when the cursor line is changed always trigger CursorMoved */
2881 if (lnum <= curwin->w_cursor.lnum
2882 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
2883 last_cursormoved.lnum = 0;
2884 #endif
2888 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2890 void
2891 unchanged(buf, ff)
2892 buf_T *buf;
2893 int ff; /* also reset 'fileformat' */
2895 if (buf->b_changed || (ff && file_ff_differs(buf)))
2897 buf->b_changed = 0;
2898 ml_setflags(buf);
2899 if (ff)
2900 save_file_ff(buf);
2901 #ifdef FEAT_WINDOWS
2902 check_status(buf);
2903 redraw_tabline = TRUE;
2904 #endif
2905 #ifdef FEAT_TITLE
2906 need_maketitle = TRUE; /* set window title later */
2907 #endif
2909 ++buf->b_changedtick;
2910 #ifdef FEAT_NETBEANS_INTG
2911 netbeans_unmodified(buf);
2912 #endif
2915 #if defined(FEAT_WINDOWS) || defined(PROTO)
2917 * check_status: called when the status bars for the buffer 'buf'
2918 * need to be updated
2920 void
2921 check_status(buf)
2922 buf_T *buf;
2924 win_T *wp;
2926 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2927 if (wp->w_buffer == buf && wp->w_status_height)
2929 wp->w_redr_status = TRUE;
2930 if (must_redraw < VALID)
2931 must_redraw = VALID;
2934 #endif
2937 * If the file is readonly, give a warning message with the first change.
2938 * Don't do this for autocommands.
2939 * Don't use emsg(), because it flushes the macro buffer.
2940 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
2941 * will be TRUE.
2943 void
2944 change_warning(col)
2945 int col; /* column for message; non-zero when in insert
2946 mode and 'showmode' is on */
2948 if (curbuf->b_did_warn == FALSE
2949 && curbufIsChanged() == 0
2950 #ifdef FEAT_AUTOCMD
2951 && !autocmd_busy
2952 #endif
2953 && curbuf->b_p_ro)
2955 #ifdef FEAT_AUTOCMD
2956 ++curbuf_lock;
2957 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
2958 --curbuf_lock;
2959 if (!curbuf->b_p_ro)
2960 return;
2961 #endif
2963 * Do what msg() does, but with a column offset if the warning should
2964 * be after the mode message.
2966 msg_start();
2967 if (msg_row == Rows - 1)
2968 msg_col = col;
2969 msg_source(hl_attr(HLF_W));
2970 MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
2971 hl_attr(HLF_W) | MSG_HIST);
2972 msg_clr_eos();
2973 (void)msg_end();
2974 if (msg_silent == 0 && !silent_mode)
2976 out_flush();
2977 ui_delay(1000L, TRUE); /* give the user time to think about it */
2979 curbuf->b_did_warn = TRUE;
2980 redraw_cmdline = FALSE; /* don't redraw and erase the message */
2981 if (msg_row < Rows - 1)
2982 showmode();
2987 * Ask for a reply from the user, a 'y' or a 'n'.
2988 * No other characters are accepted, the message is repeated until a valid
2989 * reply is entered or CTRL-C is hit.
2990 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
2991 * from any buffers but directly from the user.
2993 * return the 'y' or 'n'
2996 ask_yesno(str, direct)
2997 char_u *str;
2998 int direct;
3000 int r = ' ';
3001 int save_State = State;
3003 if (exiting) /* put terminal in raw mode for this question */
3004 settmode(TMODE_RAW);
3005 ++no_wait_return;
3006 #ifdef USE_ON_FLY_SCROLL
3007 dont_scroll = TRUE; /* disallow scrolling here */
3008 #endif
3009 State = CONFIRM; /* mouse behaves like with :confirm */
3010 #ifdef FEAT_MOUSE
3011 setmouse(); /* disables mouse for xterm */
3012 #endif
3013 ++no_mapping;
3014 ++allow_keys; /* no mapping here, but recognize keys */
3016 while (r != 'y' && r != 'n')
3018 /* same highlighting as for wait_return */
3019 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3020 if (direct)
3021 r = get_keystroke();
3022 else
3023 r = safe_vgetc();
3024 if (r == Ctrl_C || r == ESC)
3025 r = 'n';
3026 msg_putchar(r); /* show what you typed */
3027 out_flush();
3029 --no_wait_return;
3030 State = save_State;
3031 #ifdef FEAT_MOUSE
3032 setmouse();
3033 #endif
3034 --no_mapping;
3035 --allow_keys;
3037 return r;
3041 * Get a key stroke directly from the user.
3042 * Ignores mouse clicks and scrollbar events, except a click for the left
3043 * button (used at the more prompt).
3044 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3045 * Disadvantage: typeahead is ignored.
3046 * Translates the interrupt character for unix to ESC.
3049 get_keystroke()
3051 #define CBUFLEN 151
3052 char_u buf[CBUFLEN];
3053 int len = 0;
3054 int n;
3055 int save_mapped_ctrl_c = mapped_ctrl_c;
3056 int waited = 0;
3058 mapped_ctrl_c = FALSE; /* mappings are not used here */
3059 for (;;)
3061 cursor_on();
3062 out_flush();
3064 /* First time: blocking wait. Second time: wait up to 100ms for a
3065 * terminal code to complete. Leave some room for check_termcode() to
3066 * insert a key code into (max 5 chars plus NUL). And
3067 * fix_input_buffer() can triple the number of bytes. */
3068 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3069 len == 0 ? -1L : 100L, 0);
3070 if (n > 0)
3072 /* Replace zero and CSI by a special key code. */
3073 n = fix_input_buffer(buf + len, n, FALSE);
3074 len += n;
3075 waited = 0;
3077 else if (len > 0)
3078 ++waited; /* keep track of the waiting time */
3080 /* Incomplete termcode and not timed out yet: get more characters */
3081 if ((n = check_termcode(1, buf, len)) < 0
3082 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
3083 continue;
3085 /* found a termcode: adjust length */
3086 if (n > 0)
3087 len = n;
3088 if (len == 0) /* nothing typed yet */
3089 continue;
3091 /* Handle modifier and/or special key code. */
3092 n = buf[0];
3093 if (n == K_SPECIAL)
3095 n = TO_SPECIAL(buf[1], buf[2]);
3096 if (buf[1] == KS_MODIFIER
3097 || n == K_IGNORE
3098 #ifdef FEAT_MOUSE
3099 || n == K_LEFTMOUSE_NM
3100 || n == K_LEFTDRAG
3101 || n == K_LEFTRELEASE
3102 || n == K_LEFTRELEASE_NM
3103 || n == K_MIDDLEMOUSE
3104 || n == K_MIDDLEDRAG
3105 || n == K_MIDDLERELEASE
3106 || n == K_RIGHTMOUSE
3107 || n == K_RIGHTDRAG
3108 || n == K_RIGHTRELEASE
3109 || n == K_MOUSEDOWN
3110 || n == K_MOUSEUP
3111 || n == K_X1MOUSE
3112 || n == K_X1DRAG
3113 || n == K_X1RELEASE
3114 || n == K_X2MOUSE
3115 || n == K_X2DRAG
3116 || n == K_X2RELEASE
3117 # ifdef FEAT_GUI
3118 || n == K_VER_SCROLLBAR
3119 || n == K_HOR_SCROLLBAR
3120 # endif
3121 #endif
3124 if (buf[1] == KS_MODIFIER)
3125 mod_mask = buf[2];
3126 len -= 3;
3127 if (len > 0)
3128 mch_memmove(buf, buf + 3, (size_t)len);
3129 continue;
3131 break;
3133 #ifdef FEAT_MBYTE
3134 if (has_mbyte)
3136 if (MB_BYTE2LEN(n) > len)
3137 continue; /* more bytes to get */
3138 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3139 n = (*mb_ptr2char)(buf);
3141 #endif
3142 #ifdef UNIX
3143 if (n == intr_char)
3144 n = ESC;
3145 #endif
3146 break;
3149 mapped_ctrl_c = save_mapped_ctrl_c;
3150 return n;
3154 * Get a number from the user.
3155 * When "mouse_used" is not NULL allow using the mouse.
3158 get_number(colon, mouse_used)
3159 int colon; /* allow colon to abort */
3160 int *mouse_used;
3162 int n = 0;
3163 int c;
3164 int typed = 0;
3166 if (mouse_used != NULL)
3167 *mouse_used = FALSE;
3169 /* When not printing messages, the user won't know what to type, return a
3170 * zero (as if CR was hit). */
3171 if (msg_silent != 0)
3172 return 0;
3174 #ifdef USE_ON_FLY_SCROLL
3175 dont_scroll = TRUE; /* disallow scrolling here */
3176 #endif
3177 ++no_mapping;
3178 ++allow_keys; /* no mapping here, but recognize keys */
3179 for (;;)
3181 windgoto(msg_row, msg_col);
3182 c = safe_vgetc();
3183 if (VIM_ISDIGIT(c))
3185 n = n * 10 + c - '0';
3186 msg_putchar(c);
3187 ++typed;
3189 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3191 if (typed > 0)
3193 MSG_PUTS("\b \b");
3194 --typed;
3196 n /= 10;
3198 #ifdef FEAT_MOUSE
3199 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3201 *mouse_used = TRUE;
3202 n = mouse_row + 1;
3203 break;
3205 #endif
3206 else if (n == 0 && c == ':' && colon)
3208 stuffcharReadbuff(':');
3209 if (!exmode_active)
3210 cmdline_row = msg_row;
3211 skip_redraw = TRUE; /* skip redraw once */
3212 do_redraw = FALSE;
3213 break;
3215 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3216 break;
3218 --no_mapping;
3219 --allow_keys;
3220 return n;
3224 * Ask the user to enter a number.
3225 * When "mouse_used" is not NULL allow using the mouse and in that case return
3226 * the line number.
3229 prompt_for_number(mouse_used)
3230 int *mouse_used;
3232 int i;
3233 int save_cmdline_row;
3234 int save_State;
3236 /* When using ":silent" assume that <CR> was entered. */
3237 if (mouse_used != NULL)
3238 MSG_PUTS(_("Type number or click with mouse (<Enter> cancels): "));
3239 else
3240 MSG_PUTS(_("Choice number (<Enter> cancels): "));
3242 /* Set the state such that text can be selected/copied/pasted and we still
3243 * get mouse events. */
3244 save_cmdline_row = cmdline_row;
3245 cmdline_row = 0;
3246 save_State = State;
3247 State = CMDLINE;
3249 i = get_number(TRUE, mouse_used);
3250 if (KeyTyped)
3252 /* don't call wait_return() now */
3253 /* msg_putchar('\n'); */
3254 cmdline_row = msg_row - 1;
3255 need_wait_return = FALSE;
3256 msg_didany = FALSE;
3258 else
3259 cmdline_row = save_cmdline_row;
3260 State = save_State;
3262 return i;
3265 void
3266 msgmore(n)
3267 long n;
3269 long pn;
3271 if (global_busy /* no messages now, wait until global is finished */
3272 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3273 return;
3275 /* We don't want to overwrite another important message, but do overwrite
3276 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3277 * then "put" reports the last action. */
3278 if (keep_msg != NULL && !keep_msg_more)
3279 return;
3281 if (n > 0)
3282 pn = n;
3283 else
3284 pn = -n;
3286 if (pn > p_report)
3288 if (pn == 1)
3290 if (n > 0)
3291 STRCPY(msg_buf, _("1 more line"));
3292 else
3293 STRCPY(msg_buf, _("1 line less"));
3295 else
3297 if (n > 0)
3298 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3299 else
3300 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3302 if (got_int)
3303 STRCAT(msg_buf, _(" (Interrupted)"));
3304 if (msg(msg_buf))
3306 set_keep_msg(msg_buf, 0);
3307 keep_msg_more = TRUE;
3313 * flush map and typeahead buffers and give a warning for an error
3315 void
3316 beep_flush()
3318 if (emsg_silent == 0)
3320 flush_buffers(FALSE);
3321 vim_beep();
3326 * give a warning for an error
3328 void
3329 vim_beep()
3331 if (emsg_silent == 0)
3333 if (p_vb
3334 #ifdef FEAT_GUI
3335 /* While the GUI is starting up the termcap is set for the GUI
3336 * but the output still goes to a terminal. */
3337 && !(gui.in_use && gui.starting)
3338 #endif
3341 out_str(T_VB);
3343 else
3345 #ifdef MSDOS
3347 * The number of beeps outputted is reduced to avoid having to wait
3348 * for all the beeps to finish. This is only a problem on systems
3349 * where the beeps don't overlap.
3351 if (beep_count == 0 || beep_count == 10)
3353 out_char(BELL);
3354 beep_count = 1;
3356 else
3357 ++beep_count;
3358 #else
3359 out_char(BELL);
3360 #endif
3363 /* When 'verbose' is set and we are sourcing a script or executing a
3364 * function give the user a hint where the beep comes from. */
3365 if (vim_strchr(p_debug, 'e') != NULL)
3367 msg_source(hl_attr(HLF_W));
3368 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3374 * To get the "real" home directory:
3375 * - get value of $HOME
3376 * For Unix:
3377 * - go to that directory
3378 * - do mch_dirname() to get the real name of that directory.
3379 * This also works with mounts and links.
3380 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3382 static char_u *homedir = NULL;
3384 void
3385 init_homedir()
3387 char_u *var;
3389 /* In case we are called a second time (when 'encoding' changes). */
3390 vim_free(homedir);
3391 homedir = NULL;
3393 #ifdef VMS
3394 var = mch_getenv((char_u *)"SYS$LOGIN");
3395 #else
3396 var = mch_getenv((char_u *)"HOME");
3397 #endif
3399 if (var != NULL && *var == NUL) /* empty is same as not set */
3400 var = NULL;
3402 #ifdef WIN3264
3404 * Weird but true: $HOME may contain an indirect reference to another
3405 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3406 * when $HOME is being set.
3408 if (var != NULL && *var == '%')
3410 char_u *p;
3411 char_u *exp;
3413 p = vim_strchr(var + 1, '%');
3414 if (p != NULL)
3416 vim_strncpy(NameBuff, var + 1, p - (var + 1));
3417 exp = mch_getenv(NameBuff);
3418 if (exp != NULL && *exp != NUL
3419 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3421 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
3422 var = NameBuff;
3423 /* Also set $HOME, it's needed for _viminfo. */
3424 vim_setenv((char_u *)"HOME", NameBuff);
3430 * Typically, $HOME is not defined on Windows, unless the user has
3431 * specifically defined it for Vim's sake. However, on Windows NT
3432 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3433 * each user. Try constructing $HOME from these.
3435 if (var == NULL)
3437 char_u *homedrive, *homepath;
3439 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3440 homepath = mch_getenv((char_u *)"HOMEPATH");
3441 if (homedrive != NULL && homepath != NULL
3442 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3444 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3445 if (NameBuff[0] != NUL)
3447 var = NameBuff;
3448 /* Also set $HOME, it's needed for _viminfo. */
3449 vim_setenv((char_u *)"HOME", NameBuff);
3454 # if defined(FEAT_MBYTE)
3455 if (enc_utf8 && var != NULL)
3457 int len;
3458 char_u *pp;
3460 /* Convert from active codepage to UTF-8. Other conversions are
3461 * not done, because they would fail for non-ASCII characters. */
3462 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
3463 if (pp != NULL)
3465 homedir = pp;
3466 return;
3469 # endif
3470 #endif
3472 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3474 * Default home dir is C:/
3475 * Best assumption we can make in such a situation.
3477 if (var == NULL)
3478 var = "C:/";
3479 #endif
3480 if (var != NULL)
3482 #ifdef UNIX
3484 * Change to the directory and get the actual path. This resolves
3485 * links. Don't do it when we can't return.
3487 if (mch_dirname(NameBuff, MAXPATHL) == OK
3488 && mch_chdir((char *)NameBuff) == 0)
3490 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3491 var = IObuff;
3492 if (mch_chdir((char *)NameBuff) != 0)
3493 EMSG(_(e_prev_dir));
3495 #endif
3496 homedir = vim_strsave(var);
3500 #if defined(EXITFREE) || defined(PROTO)
3501 void
3502 free_homedir()
3504 vim_free(homedir);
3506 #endif
3509 * Call expand_env() and store the result in an allocated string.
3510 * This is not very memory efficient, this expects the result to be freed
3511 * again soon.
3513 char_u *
3514 expand_env_save(src)
3515 char_u *src;
3517 return expand_env_save_opt(src, FALSE);
3521 * Idem, but when "one" is TRUE handle the string as one file name, only
3522 * expand "~" at the start.
3524 char_u *
3525 expand_env_save_opt(src, one)
3526 char_u *src;
3527 int one;
3529 char_u *p;
3531 p = alloc(MAXPATHL);
3532 if (p != NULL)
3533 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3534 return p;
3538 * Expand environment variable with path name.
3539 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3540 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
3541 * If anything fails no expansion is done and dst equals src.
3543 void
3544 expand_env(src, dst, dstlen)
3545 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3546 char_u *dst; /* where to put the result */
3547 int dstlen; /* maximum length of the result */
3549 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
3552 void
3553 expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
3554 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
3555 char_u *dst; /* where to put the result */
3556 int dstlen; /* maximum length of the result */
3557 int esc; /* escape spaces in expanded variables */
3558 int one; /* "srcp" is one file name */
3559 char_u *startstr; /* start again after this (can be NULL) */
3561 char_u *src;
3562 char_u *tail;
3563 int c;
3564 char_u *var;
3565 int copy_char;
3566 int mustfree; /* var was allocated, need to free it later */
3567 int at_start = TRUE; /* at start of a name */
3568 int startstr_len = 0;
3570 if (startstr != NULL)
3571 startstr_len = (int)STRLEN(startstr);
3573 src = skipwhite(srcp);
3574 --dstlen; /* leave one char space for "\," */
3575 while (*src && dstlen > 0)
3577 copy_char = TRUE;
3578 if ((*src == '$'
3579 #ifdef VMS
3580 && at_start
3581 #endif
3583 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3584 || *src == '%'
3585 #endif
3586 || (*src == '~' && at_start))
3588 mustfree = FALSE;
3591 * The variable name is copied into dst temporarily, because it may
3592 * be a string in read-only memory and a NUL needs to be appended.
3594 if (*src != '~') /* environment var */
3596 tail = src + 1;
3597 var = dst;
3598 c = dstlen - 1;
3600 #ifdef UNIX
3601 /* Unix has ${var-name} type environment vars */
3602 if (*tail == '{' && !vim_isIDc('{'))
3604 tail++; /* ignore '{' */
3605 while (c-- > 0 && *tail && *tail != '}')
3606 *var++ = *tail++;
3608 else
3609 #endif
3611 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3612 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3613 || (*src == '%' && *tail != '%')
3614 #endif
3617 #ifdef OS2 /* env vars only in uppercase */
3618 *var++ = TOUPPER_LOC(*tail);
3619 tail++; /* toupper() may be a macro! */
3620 #else
3621 *var++ = *tail++;
3622 #endif
3626 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3627 # ifdef UNIX
3628 if (src[1] == '{' && *tail != '}')
3629 # else
3630 if (*src == '%' && *tail != '%')
3631 # endif
3632 var = NULL;
3633 else
3635 # ifdef UNIX
3636 if (src[1] == '{')
3637 # else
3638 if (*src == '%')
3639 #endif
3640 ++tail;
3641 #endif
3642 *var = NUL;
3643 var = vim_getenv(dst, &mustfree);
3644 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3646 #endif
3648 /* home directory */
3649 else if ( src[1] == NUL
3650 || vim_ispathsep(src[1])
3651 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3653 var = homedir;
3654 tail = src + 1;
3656 else /* user directory */
3658 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3660 * Copy ~user to dst[], so we can put a NUL after it.
3662 tail = src;
3663 var = dst;
3664 c = dstlen - 1;
3665 while ( c-- > 0
3666 && *tail
3667 && vim_isfilec(*tail)
3668 && !vim_ispathsep(*tail))
3669 *var++ = *tail++;
3670 *var = NUL;
3671 # ifdef UNIX
3673 * If the system supports getpwnam(), use it.
3674 * Otherwise, or if getpwnam() fails, the shell is used to
3675 * expand ~user. This is slower and may fail if the shell
3676 * does not support ~user (old versions of /bin/sh).
3678 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3680 struct passwd *pw;
3682 /* Note: memory allocated by getpwnam() is never freed.
3683 * Calling endpwent() apparently doesn't help. */
3684 pw = getpwnam((char *)dst + 1);
3685 if (pw != NULL)
3686 var = (char_u *)pw->pw_dir;
3687 else
3688 var = NULL;
3690 if (var == NULL)
3691 # endif
3693 expand_T xpc;
3695 ExpandInit(&xpc);
3696 xpc.xp_context = EXPAND_FILES;
3697 var = ExpandOne(&xpc, dst, NULL,
3698 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
3699 mustfree = TRUE;
3702 # else /* !UNIX, thus VMS */
3704 * USER_HOME is a comma-separated list of
3705 * directories to search for the user account in.
3708 char_u test[MAXPATHL], paths[MAXPATHL];
3709 char_u *path, *next_path, *ptr;
3710 struct stat st;
3712 STRCPY(paths, USER_HOME);
3713 next_path = paths;
3714 while (*next_path)
3716 for (path = next_path; *next_path && *next_path != ',';
3717 next_path++);
3718 if (*next_path)
3719 *next_path++ = NUL;
3720 STRCPY(test, path);
3721 STRCAT(test, "/");
3722 STRCAT(test, dst + 1);
3723 if (mch_stat(test, &st) == 0)
3725 var = alloc(STRLEN(test) + 1);
3726 STRCPY(var, test);
3727 mustfree = TRUE;
3728 break;
3732 # endif /* UNIX */
3733 #else
3734 /* cannot expand user's home directory, so don't try */
3735 var = NULL;
3736 tail = (char_u *)""; /* for gcc */
3737 #endif /* UNIX || VMS */
3740 #ifdef BACKSLASH_IN_FILENAME
3741 /* If 'shellslash' is set change backslashes to forward slashes.
3742 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3743 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3745 char_u *p = vim_strsave(var);
3747 if (p != NULL)
3749 if (mustfree)
3750 vim_free(var);
3751 var = p;
3752 mustfree = TRUE;
3753 forward_slash(var);
3756 #endif
3758 /* If "var" contains white space, escape it with a backslash.
3759 * Required for ":e ~/tt" when $HOME includes a space. */
3760 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3762 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3764 if (p != NULL)
3766 if (mustfree)
3767 vim_free(var);
3768 var = p;
3769 mustfree = TRUE;
3773 if (var != NULL && *var != NUL
3774 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3776 STRCPY(dst, var);
3777 dstlen -= (int)STRLEN(var);
3778 c = (int)STRLEN(var);
3779 /* if var[] ends in a path separator and tail[] starts
3780 * with it, skip a character */
3781 if (*var != NUL && after_pathsep(dst, dst + c)
3782 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3783 && dst[-1] != ':'
3784 #endif
3785 && vim_ispathsep(*tail))
3786 ++tail;
3787 dst += c;
3788 src = tail;
3789 copy_char = FALSE;
3791 if (mustfree)
3792 vim_free(var);
3795 if (copy_char) /* copy at least one char */
3798 * Recognize the start of a new name, for '~'.
3799 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3800 * ":edit foo ~ foo".
3802 at_start = FALSE;
3803 if (src[0] == '\\' && src[1] != NUL)
3805 *dst++ = *src++;
3806 --dstlen;
3808 else if ((src[0] == ' ' || src[0] == ',') && !one)
3809 at_start = TRUE;
3810 *dst++ = *src++;
3811 --dstlen;
3813 if (startstr != NULL && src - startstr_len >= srcp
3814 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3815 at_start = TRUE;
3818 *dst = NUL;
3822 * Vim's version of getenv().
3823 * Special handling of $HOME, $VIM and $VIMRUNTIME.
3824 * Also does ACP to 'enc' conversion for Win32.
3826 char_u *
3827 vim_getenv(name, mustfree)
3828 char_u *name;
3829 int *mustfree; /* set to TRUE when returned is allocated */
3831 char_u *p;
3832 char_u *pend;
3833 int vimruntime;
3835 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3836 /* use "C:/" when $HOME is not set */
3837 if (STRCMP(name, "HOME") == 0)
3838 return homedir;
3839 #endif
3841 p = mch_getenv(name);
3842 if (p != NULL && *p == NUL) /* empty is the same as not set */
3843 p = NULL;
3845 if (p != NULL)
3847 #if defined(FEAT_MBYTE) && defined(WIN3264)
3848 if (enc_utf8)
3850 int len;
3851 char_u *pp;
3853 /* Convert from active codepage to UTF-8. Other conversions are
3854 * not done, because they would fail for non-ASCII characters. */
3855 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
3856 if (pp != NULL)
3858 p = pp;
3859 *mustfree = TRUE;
3862 #endif
3863 return p;
3866 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3867 if (!vimruntime && STRCMP(name, "VIM") != 0)
3868 return NULL;
3871 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3872 * Don't do this when default_vimruntime_dir is non-empty.
3874 if (vimruntime
3875 #ifdef HAVE_PATHDEF
3876 && *default_vimruntime_dir == NUL
3877 #endif
3880 p = mch_getenv((char_u *)"VIM");
3881 if (p != NULL && *p == NUL) /* empty is the same as not set */
3882 p = NULL;
3883 if (p != NULL)
3885 p = vim_version_dir(p);
3886 if (p != NULL)
3887 *mustfree = TRUE;
3888 else
3889 p = mch_getenv((char_u *)"VIM");
3891 #if defined(FEAT_MBYTE) && defined(WIN3264)
3892 if (enc_utf8)
3894 int len;
3895 char_u *pp;
3897 /* Convert from active codepage to UTF-8. Other conversions
3898 * are not done, because they would fail for non-ASCII
3899 * characters. */
3900 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
3901 if (pp != NULL)
3903 if (mustfree)
3904 vim_free(p);
3905 p = pp;
3906 *mustfree = TRUE;
3909 #endif
3914 * When expanding $VIM or $VIMRUNTIME fails, try using:
3915 * - the directory name from 'helpfile' (unless it contains '$')
3916 * - the executable name from argv[0]
3918 if (p == NULL)
3920 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3921 p = p_hf;
3922 #ifdef USE_EXE_NAME
3924 * Use the name of the executable, obtained from argv[0].
3926 else
3927 p = exe_name;
3928 #endif
3929 if (p != NULL)
3931 /* remove the file name */
3932 pend = gettail(p);
3934 /* remove "doc/" from 'helpfile', if present */
3935 if (p == p_hf)
3936 pend = remove_tail(p, pend, (char_u *)"doc");
3938 #ifdef USE_EXE_NAME
3939 # ifdef MACOS_X
3940 /* remove "MacOS" from exe_name and add "Resources/vim" */
3941 if (p == exe_name)
3943 char_u *pend1;
3944 char_u *pnew;
3946 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
3947 if (pend1 != pend)
3949 pnew = alloc((unsigned)(pend1 - p) + 15);
3950 if (pnew != NULL)
3952 STRNCPY(pnew, p, (pend1 - p));
3953 STRCPY(pnew + (pend1 - p), "Resources/vim");
3954 p = pnew;
3955 pend = p + STRLEN(p);
3959 # endif
3960 /* remove "src/" from exe_name, if present */
3961 if (p == exe_name)
3962 pend = remove_tail(p, pend, (char_u *)"src");
3963 #endif
3965 /* for $VIM, remove "runtime/" or "vim54/", if present */
3966 if (!vimruntime)
3968 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
3969 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
3972 /* remove trailing path separator */
3973 #ifndef MACOS_CLASSIC
3974 /* With MacOS path (with colons) the final colon is required */
3975 /* to avoid confusion between absoulute and relative path */
3976 if (pend > p && after_pathsep(p, pend))
3977 --pend;
3978 #endif
3980 #ifdef MACOS_X
3981 if (p == exe_name || p == p_hf)
3982 #endif
3983 /* check that the result is a directory name */
3984 p = vim_strnsave(p, (int)(pend - p));
3986 if (p != NULL && !mch_isdir(p))
3988 vim_free(p);
3989 p = NULL;
3991 else
3993 #ifdef USE_EXE_NAME
3994 /* may add "/vim54" or "/runtime" if it exists */
3995 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
3997 vim_free(p);
3998 p = pend;
4000 #endif
4001 *mustfree = TRUE;
4006 #ifdef HAVE_PATHDEF
4007 /* When there is a pathdef.c file we can use default_vim_dir and
4008 * default_vimruntime_dir */
4009 if (p == NULL)
4011 /* Only use default_vimruntime_dir when it is not empty */
4012 if (vimruntime && *default_vimruntime_dir != NUL)
4014 p = default_vimruntime_dir;
4015 *mustfree = FALSE;
4017 else if (*default_vim_dir != NUL)
4019 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4020 *mustfree = TRUE;
4021 else
4023 p = default_vim_dir;
4024 *mustfree = FALSE;
4028 #endif
4031 * Set the environment variable, so that the new value can be found fast
4032 * next time, and others can also use it (e.g. Perl).
4034 if (p != NULL)
4036 if (vimruntime)
4038 vim_setenv((char_u *)"VIMRUNTIME", p);
4039 didset_vimruntime = TRUE;
4040 #ifdef FEAT_GETTEXT
4042 char_u *buf = concat_str(p, (char_u *)"/lang");
4044 if (buf != NULL)
4046 bindtextdomain(VIMPACKAGE, (char *)buf);
4047 vim_free(buf);
4050 #endif
4052 else
4054 vim_setenv((char_u *)"VIM", p);
4055 didset_vim = TRUE;
4058 return p;
4062 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4063 * Return NULL if not, return its name in allocated memory otherwise.
4065 static char_u *
4066 vim_version_dir(vimdir)
4067 char_u *vimdir;
4069 char_u *p;
4071 if (vimdir == NULL || *vimdir == NUL)
4072 return NULL;
4073 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4074 if (p != NULL && mch_isdir(p))
4075 return p;
4076 vim_free(p);
4077 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4078 if (p != NULL && mch_isdir(p))
4079 return p;
4080 vim_free(p);
4081 return NULL;
4085 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4086 * the length of "name/". Otherwise return "pend".
4088 static char_u *
4089 remove_tail(p, pend, name)
4090 char_u *p;
4091 char_u *pend;
4092 char_u *name;
4094 int len = (int)STRLEN(name) + 1;
4095 char_u *newend = pend - len;
4097 if (newend >= p
4098 && fnamencmp(newend, name, len - 1) == 0
4099 && (newend == p || after_pathsep(p, newend)))
4100 return newend;
4101 return pend;
4105 * Our portable version of setenv.
4107 void
4108 vim_setenv(name, val)
4109 char_u *name;
4110 char_u *val;
4112 #ifdef HAVE_SETENV
4113 mch_setenv((char *)name, (char *)val, 1);
4114 #else
4115 char_u *envbuf;
4118 * Putenv does not copy the string, it has to remain
4119 * valid. The allocated memory will never be freed.
4121 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4122 if (envbuf != NULL)
4124 sprintf((char *)envbuf, "%s=%s", name, val);
4125 putenv((char *)envbuf);
4127 #endif
4130 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4132 * Function given to ExpandGeneric() to obtain an environment variable name.
4134 /*ARGSUSED*/
4135 char_u *
4136 get_env_name(xp, idx)
4137 expand_T *xp;
4138 int idx;
4140 # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4142 * No environ[] on the Amiga and on the Mac (using MPW).
4144 return NULL;
4145 # else
4146 # ifndef __WIN32__
4147 /* Borland C++ 5.2 has this in a header file. */
4148 extern char **environ;
4149 # endif
4150 # define ENVNAMELEN 100
4151 static char_u name[ENVNAMELEN];
4152 char_u *str;
4153 int n;
4155 str = (char_u *)environ[idx];
4156 if (str == NULL)
4157 return NULL;
4159 for (n = 0; n < ENVNAMELEN - 1; ++n)
4161 if (str[n] == '=' || str[n] == NUL)
4162 break;
4163 name[n] = str[n];
4165 name[n] = NUL;
4166 return name;
4167 # endif
4169 #endif
4172 * Replace home directory by "~" in each space or comma separated file name in
4173 * 'src'.
4174 * If anything fails (except when out of space) dst equals src.
4176 void
4177 home_replace(buf, src, dst, dstlen, one)
4178 buf_T *buf; /* when not NULL, check for help files */
4179 char_u *src; /* input file name */
4180 char_u *dst; /* where to put the result */
4181 int dstlen; /* maximum length of the result */
4182 int one; /* if TRUE, only replace one file name, include
4183 spaces and commas in the file name. */
4185 size_t dirlen = 0, envlen = 0;
4186 size_t len;
4187 char_u *homedir_env;
4188 char_u *p;
4190 if (src == NULL)
4192 *dst = NUL;
4193 return;
4197 * If the file is a help file, remove the path completely.
4199 if (buf != NULL && buf->b_help)
4201 STRCPY(dst, gettail(src));
4202 return;
4206 * We check both the value of the $HOME environment variable and the
4207 * "real" home directory.
4209 if (homedir != NULL)
4210 dirlen = STRLEN(homedir);
4212 #ifdef VMS
4213 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4214 #else
4215 homedir_env = mch_getenv((char_u *)"HOME");
4216 #endif
4218 if (homedir_env != NULL && *homedir_env == NUL)
4219 homedir_env = NULL;
4220 if (homedir_env != NULL)
4221 envlen = STRLEN(homedir_env);
4223 if (!one)
4224 src = skipwhite(src);
4225 while (*src && dstlen > 0)
4228 * Here we are at the beginning of a file name.
4229 * First, check to see if the beginning of the file name matches
4230 * $HOME or the "real" home directory. Check that there is a '/'
4231 * after the match (so that if e.g. the file is "/home/pieter/bla",
4232 * and the home directory is "/home/piet", the file does not end up
4233 * as "~er/bla" (which would seem to indicate the file "bla" in user
4234 * er's home directory)).
4236 p = homedir;
4237 len = dirlen;
4238 for (;;)
4240 if ( len
4241 && fnamencmp(src, p, len) == 0
4242 && (vim_ispathsep(src[len])
4243 || (!one && (src[len] == ',' || src[len] == ' '))
4244 || src[len] == NUL))
4246 src += len;
4247 if (--dstlen > 0)
4248 *dst++ = '~';
4251 * If it's just the home directory, add "/".
4253 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4254 *dst++ = '/';
4255 break;
4257 if (p == homedir_env)
4258 break;
4259 p = homedir_env;
4260 len = envlen;
4263 /* if (!one) skip to separator: space or comma */
4264 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4265 *dst++ = *src++;
4266 /* skip separator */
4267 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4268 *dst++ = *src++;
4270 /* if (dstlen == 0) out of space, what to do??? */
4272 *dst = NUL;
4276 * Like home_replace, store the replaced string in allocated memory.
4277 * When something fails, NULL is returned.
4279 char_u *
4280 home_replace_save(buf, src)
4281 buf_T *buf; /* when not NULL, check for help files */
4282 char_u *src; /* input file name */
4284 char_u *dst;
4285 unsigned len;
4287 len = 3; /* space for "~/" and trailing NUL */
4288 if (src != NULL) /* just in case */
4289 len += (unsigned)STRLEN(src);
4290 dst = alloc(len);
4291 if (dst != NULL)
4292 home_replace(buf, src, dst, len, TRUE);
4293 return dst;
4297 * Compare two file names and return:
4298 * FPC_SAME if they both exist and are the same file.
4299 * FPC_SAMEX if they both don't exist and have the same file name.
4300 * FPC_DIFF if they both exist and are different files.
4301 * FPC_NOTX if they both don't exist.
4302 * FPC_DIFFX if one of them doesn't exist.
4303 * For the first name environment variables are expanded
4306 fullpathcmp(s1, s2, checkname)
4307 char_u *s1, *s2;
4308 int checkname; /* when both don't exist, check file names */
4310 #ifdef UNIX
4311 char_u exp1[MAXPATHL];
4312 char_u full1[MAXPATHL];
4313 char_u full2[MAXPATHL];
4314 struct stat st1, st2;
4315 int r1, r2;
4317 expand_env(s1, exp1, MAXPATHL);
4318 r1 = mch_stat((char *)exp1, &st1);
4319 r2 = mch_stat((char *)s2, &st2);
4320 if (r1 != 0 && r2 != 0)
4322 /* if mch_stat() doesn't work, may compare the names */
4323 if (checkname)
4325 if (fnamecmp(exp1, s2) == 0)
4326 return FPC_SAMEX;
4327 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4328 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4329 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4330 return FPC_SAMEX;
4332 return FPC_NOTX;
4334 if (r1 != 0 || r2 != 0)
4335 return FPC_DIFFX;
4336 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4337 return FPC_SAME;
4338 return FPC_DIFF;
4339 #else
4340 char_u *exp1; /* expanded s1 */
4341 char_u *full1; /* full path of s1 */
4342 char_u *full2; /* full path of s2 */
4343 int retval = FPC_DIFF;
4344 int r1, r2;
4346 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4347 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4349 full1 = exp1 + MAXPATHL;
4350 full2 = full1 + MAXPATHL;
4352 expand_env(s1, exp1, MAXPATHL);
4353 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4354 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4356 /* If vim_FullName() fails, the file probably doesn't exist. */
4357 if (r1 != OK && r2 != OK)
4359 if (checkname && fnamecmp(exp1, s2) == 0)
4360 retval = FPC_SAMEX;
4361 else
4362 retval = FPC_NOTX;
4364 else if (r1 != OK || r2 != OK)
4365 retval = FPC_DIFFX;
4366 else if (fnamecmp(full1, full2))
4367 retval = FPC_DIFF;
4368 else
4369 retval = FPC_SAME;
4370 vim_free(exp1);
4372 return retval;
4373 #endif
4377 * Get the tail of a path: the file name.
4378 * Fail safe: never returns NULL.
4380 char_u *
4381 gettail(fname)
4382 char_u *fname;
4384 char_u *p1, *p2;
4386 if (fname == NULL)
4387 return (char_u *)"";
4388 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4390 if (vim_ispathsep(*p2))
4391 p1 = p2 + 1;
4392 mb_ptr_adv(p2);
4394 return p1;
4398 * Get pointer to tail of "fname", including path separators. Putting a NUL
4399 * here leaves the directory name. Takes care of "c:/" and "//".
4400 * Always returns a valid pointer.
4402 char_u *
4403 gettail_sep(fname)
4404 char_u *fname;
4406 char_u *p;
4407 char_u *t;
4409 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4410 t = gettail(fname);
4411 while (t > p && after_pathsep(fname, t))
4412 --t;
4413 #ifdef VMS
4414 /* path separator is part of the path */
4415 ++t;
4416 #endif
4417 return t;
4421 * get the next path component (just after the next path separator).
4423 char_u *
4424 getnextcomp(fname)
4425 char_u *fname;
4427 while (*fname && !vim_ispathsep(*fname))
4428 mb_ptr_adv(fname);
4429 if (*fname)
4430 ++fname;
4431 return fname;
4435 * Get a pointer to one character past the head of a path name.
4436 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4437 * If there is no head, path is returned.
4439 char_u *
4440 get_past_head(path)
4441 char_u *path;
4443 char_u *retval;
4445 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4446 /* may skip "c:" */
4447 if (isalpha(path[0]) && path[1] == ':')
4448 retval = path + 2;
4449 else
4450 retval = path;
4451 #else
4452 # if defined(AMIGA)
4453 /* may skip "label:" */
4454 retval = vim_strchr(path, ':');
4455 if (retval == NULL)
4456 retval = path;
4457 # else /* Unix */
4458 retval = path;
4459 # endif
4460 #endif
4462 while (vim_ispathsep(*retval))
4463 ++retval;
4465 return retval;
4469 * return TRUE if 'c' is a path separator.
4472 vim_ispathsep(c)
4473 int c;
4475 #ifdef RISCOS
4476 return (c == '.' || c == ':');
4477 #else
4478 # ifdef UNIX
4479 return (c == '/'); /* UNIX has ':' inside file names */
4480 # else
4481 # ifdef BACKSLASH_IN_FILENAME
4482 return (c == ':' || c == '/' || c == '\\');
4483 # else
4484 # ifdef VMS
4485 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4486 return (c == ':' || c == '[' || c == ']' || c == '/'
4487 || c == '<' || c == '>' || c == '"' );
4488 # else /* Amiga */
4489 return (c == ':' || c == '/');
4490 # endif /* VMS */
4491 # endif
4492 # endif
4493 #endif /* RISC OS */
4496 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
4498 * return TRUE if 'c' is a path list separator.
4501 vim_ispathlistsep(c)
4502 int c;
4504 #ifdef UNIX
4505 return (c == ':');
4506 #else
4507 return (c == ';'); /* might not be right for every system... */
4508 #endif
4510 #endif
4512 #if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4513 || defined(FEAT_EVAL) || defined(PROTO)
4515 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4516 * It's done in-place.
4518 void
4519 shorten_dir(str)
4520 char_u *str;
4522 char_u *tail, *s, *d;
4523 int skip = FALSE;
4525 tail = gettail(str);
4526 d = str;
4527 for (s = str; ; ++s)
4529 if (s >= tail) /* copy the whole tail */
4531 *d++ = *s;
4532 if (*s == NUL)
4533 break;
4535 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4537 *d++ = *s;
4538 skip = FALSE;
4540 else if (!skip)
4542 *d++ = *s; /* copy next char */
4543 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4544 skip = TRUE;
4545 # ifdef FEAT_MBYTE
4546 if (has_mbyte)
4548 int l = mb_ptr2len(s);
4550 while (--l > 0)
4551 *d++ = *++s;
4553 # endif
4557 #endif
4560 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4561 * Also returns TRUE if there is no directory name.
4562 * "fname" must be writable!.
4565 dir_of_file_exists(fname)
4566 char_u *fname;
4568 char_u *p;
4569 int c;
4570 int retval;
4572 p = gettail_sep(fname);
4573 if (p == fname)
4574 return TRUE;
4575 c = *p;
4576 *p = NUL;
4577 retval = mch_isdir(fname);
4578 *p = c;
4579 return retval;
4582 #if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4583 || defined(PROTO)
4585 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4588 vim_fnamecmp(x, y)
4589 char_u *x, *y;
4591 return vim_fnamencmp(x, y, MAXPATHL);
4595 vim_fnamencmp(x, y, len)
4596 char_u *x, *y;
4597 size_t len;
4599 while (len > 0 && *x && *y)
4601 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4602 && !(*x == '/' && *y == '\\')
4603 && !(*x == '\\' && *y == '/'))
4604 break;
4605 ++x;
4606 ++y;
4607 --len;
4609 if (len == 0)
4610 return 0;
4611 return (*x - *y);
4613 #endif
4616 * Concatenate file names fname1 and fname2 into allocated memory.
4617 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
4619 char_u *
4620 concat_fnames(fname1, fname2, sep)
4621 char_u *fname1;
4622 char_u *fname2;
4623 int sep;
4625 char_u *dest;
4627 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4628 if (dest != NULL)
4630 STRCPY(dest, fname1);
4631 if (sep)
4632 add_pathsep(dest);
4633 STRCAT(dest, fname2);
4635 return dest;
4638 #if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4640 * Concatenate two strings and return the result in allocated memory.
4641 * Returns NULL when out of memory.
4643 char_u *
4644 concat_str(str1, str2)
4645 char_u *str1;
4646 char_u *str2;
4648 char_u *dest;
4649 size_t l = STRLEN(str1);
4651 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4652 if (dest != NULL)
4654 STRCPY(dest, str1);
4655 STRCPY(dest + l, str2);
4657 return dest;
4659 #endif
4662 * Add a path separator to a file name, unless it already ends in a path
4663 * separator.
4665 void
4666 add_pathsep(p)
4667 char_u *p;
4669 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
4670 STRCAT(p, PATHSEPSTR);
4674 * FullName_save - Make an allocated copy of a full file name.
4675 * Returns NULL when out of memory.
4677 char_u *
4678 FullName_save(fname, force)
4679 char_u *fname;
4680 int force; /* force expansion, even when it already looks
4681 like a full path name */
4683 char_u *buf;
4684 char_u *new_fname = NULL;
4686 if (fname == NULL)
4687 return NULL;
4689 buf = alloc((unsigned)MAXPATHL);
4690 if (buf != NULL)
4692 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4693 new_fname = vim_strsave(buf);
4694 else
4695 new_fname = vim_strsave(fname);
4696 vim_free(buf);
4698 return new_fname;
4701 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4703 static char_u *skip_string __ARGS((char_u *p));
4706 * Find the start of a comment, not knowing if we are in a comment right now.
4707 * Search starts at w_cursor.lnum and goes backwards.
4709 pos_T *
4710 find_start_comment(ind_maxcomment) /* XXX */
4711 int ind_maxcomment;
4713 pos_T *pos;
4714 char_u *line;
4715 char_u *p;
4716 int cur_maxcomment = ind_maxcomment;
4718 for (;;)
4720 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4721 if (pos == NULL)
4722 break;
4725 * Check if the comment start we found is inside a string.
4726 * If it is then restrict the search to below this line and try again.
4728 line = ml_get(pos->lnum);
4729 for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
4730 p = skip_string(p);
4731 if ((unsigned)(p - line) <= pos->col)
4732 break;
4733 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4734 if (cur_maxcomment <= 0)
4736 pos = NULL;
4737 break;
4740 return pos;
4744 * Skip to the end of a "string" and a 'c' character.
4745 * If there is no string or character, return argument unmodified.
4747 static char_u *
4748 skip_string(p)
4749 char_u *p;
4751 int i;
4754 * We loop, because strings may be concatenated: "date""time".
4756 for ( ; ; ++p)
4758 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4760 if (!p[1]) /* ' at end of line */
4761 break;
4762 i = 2;
4763 if (p[1] == '\\') /* '\n' or '\000' */
4765 ++i;
4766 while (vim_isdigit(p[i - 1])) /* '\000' */
4767 ++i;
4769 if (p[i] == '\'') /* check for trailing ' */
4771 p += i;
4772 continue;
4775 else if (p[0] == '"') /* start of string */
4777 for (++p; p[0]; ++p)
4779 if (p[0] == '\\' && p[1] != NUL)
4780 ++p;
4781 else if (p[0] == '"') /* end of string */
4782 break;
4784 if (p[0] == '"')
4785 continue;
4787 break; /* no string found */
4789 if (!*p)
4790 --p; /* backup from NUL */
4791 return p;
4793 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
4795 #if defined(FEAT_CINDENT) || defined(PROTO)
4798 * Do C or expression indenting on the current line.
4800 void
4801 do_c_expr_indent()
4803 # ifdef FEAT_EVAL
4804 if (*curbuf->b_p_inde != NUL)
4805 fixthisline(get_expr_indent);
4806 else
4807 # endif
4808 fixthisline(get_c_indent);
4812 * Functions for C-indenting.
4813 * Most of this originally comes from Eric Fischer.
4816 * Below "XXX" means that this function may unlock the current line.
4819 static char_u *cin_skipcomment __ARGS((char_u *));
4820 static int cin_nocode __ARGS((char_u *));
4821 static pos_T *find_line_comment __ARGS((void));
4822 static int cin_islabel_skip __ARGS((char_u **));
4823 static int cin_isdefault __ARGS((char_u *));
4824 static char_u *after_label __ARGS((char_u *l));
4825 static int get_indent_nolabel __ARGS((linenr_T lnum));
4826 static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4827 static int cin_first_id_amount __ARGS((void));
4828 static int cin_get_equal_amount __ARGS((linenr_T lnum));
4829 static int cin_ispreproc __ARGS((char_u *));
4830 static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4831 static int cin_iscomment __ARGS((char_u *));
4832 static int cin_islinecomment __ARGS((char_u *));
4833 static int cin_isterminated __ARGS((char_u *, int, int));
4834 static int cin_isinit __ARGS((void));
4835 static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4836 static int cin_isif __ARGS((char_u *));
4837 static int cin_iselse __ARGS((char_u *));
4838 static int cin_isdo __ARGS((char_u *));
4839 static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
4840 static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
4841 static int cin_isbreak __ARGS((char_u *));
4842 static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
4843 static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
4844 static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4845 static int cin_skip2pos __ARGS((pos_T *trypos));
4846 static pos_T *find_start_brace __ARGS((int));
4847 static pos_T *find_match_paren __ARGS((int, int));
4848 static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4849 static int find_last_paren __ARGS((char_u *l, int start, int end));
4850 static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4852 static int ind_hash_comment = 0; /* # starts a comment */
4855 * Skip over white space and C comments within the line.
4856 * Also skip over Perl/shell comments if desired.
4858 static char_u *
4859 cin_skipcomment(s)
4860 char_u *s;
4862 while (*s)
4864 char_u *prev_s = s;
4866 s = skipwhite(s);
4868 /* Perl/shell # comment comment continues until eol. Require a space
4869 * before # to avoid recognizing $#array. */
4870 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
4872 s += STRLEN(s);
4873 break;
4875 if (*s != '/')
4876 break;
4877 ++s;
4878 if (*s == '/') /* slash-slash comment continues till eol */
4880 s += STRLEN(s);
4881 break;
4883 if (*s != '*')
4884 break;
4885 for (++s; *s; ++s) /* skip slash-star comment */
4886 if (s[0] == '*' && s[1] == '/')
4888 s += 2;
4889 break;
4892 return s;
4896 * Return TRUE if there there is no code at *s. White space and comments are
4897 * not considered code.
4899 static int
4900 cin_nocode(s)
4901 char_u *s;
4903 return *cin_skipcomment(s) == NUL;
4907 * Check previous lines for a "//" line comment, skipping over blank lines.
4909 static pos_T *
4910 find_line_comment() /* XXX */
4912 static pos_T pos;
4913 char_u *line;
4914 char_u *p;
4916 pos = curwin->w_cursor;
4917 while (--pos.lnum > 0)
4919 line = ml_get(pos.lnum);
4920 p = skipwhite(line);
4921 if (cin_islinecomment(p))
4923 pos.col = (int)(p - line);
4924 return &pos;
4926 if (*p != NUL)
4927 break;
4929 return NULL;
4933 * Check if string matches "label:"; move to character after ':' if true.
4935 static int
4936 cin_islabel_skip(s)
4937 char_u **s;
4939 if (!vim_isIDc(**s)) /* need at least one ID character */
4940 return FALSE;
4942 while (vim_isIDc(**s))
4943 (*s)++;
4945 *s = cin_skipcomment(*s);
4947 /* "::" is not a label, it's C++ */
4948 return (**s == ':' && *++*s != ':');
4952 * Recognize a label: "label:".
4953 * Note: curwin->w_cursor must be where we are looking for the label.
4956 cin_islabel(ind_maxcomment) /* XXX */
4957 int ind_maxcomment;
4959 char_u *s;
4961 s = cin_skipcomment(ml_get_curline());
4964 * Exclude "default" from labels, since it should be indented
4965 * like a switch label. Same for C++ scope declarations.
4967 if (cin_isdefault(s))
4968 return FALSE;
4969 if (cin_isscopedecl(s))
4970 return FALSE;
4972 if (cin_islabel_skip(&s))
4975 * Only accept a label if the previous line is terminated or is a case
4976 * label.
4978 pos_T cursor_save;
4979 pos_T *trypos;
4980 char_u *line;
4982 cursor_save = curwin->w_cursor;
4983 while (curwin->w_cursor.lnum > 1)
4985 --curwin->w_cursor.lnum;
4988 * If we're in a comment now, skip to the start of the comment.
4990 curwin->w_cursor.col = 0;
4991 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
4992 curwin->w_cursor = *trypos;
4994 line = ml_get_curline();
4995 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
4996 continue;
4997 if (*(line = cin_skipcomment(line)) == NUL)
4998 continue;
5000 curwin->w_cursor = cursor_save;
5001 if (cin_isterminated(line, TRUE, FALSE)
5002 || cin_isscopedecl(line)
5003 || cin_iscase(line)
5004 || (cin_islabel_skip(&line) && cin_nocode(line)))
5005 return TRUE;
5006 return FALSE;
5008 curwin->w_cursor = cursor_save;
5009 return TRUE; /* label at start of file??? */
5011 return FALSE;
5015 * Recognize structure initialization and enumerations.
5016 * Q&D-Implementation:
5017 * check for "=" at end or "[typedef] enum" at beginning of line.
5019 static int
5020 cin_isinit(void)
5022 char_u *s;
5024 s = cin_skipcomment(ml_get_curline());
5026 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5027 s = cin_skipcomment(s + 7);
5029 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5030 return TRUE;
5032 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5033 return TRUE;
5035 return FALSE;
5039 * Recognize a switch label: "case .*:" or "default:".
5042 cin_iscase(s)
5043 char_u *s;
5045 s = cin_skipcomment(s);
5046 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5048 for (s += 4; *s; ++s)
5050 s = cin_skipcomment(s);
5051 if (*s == ':')
5053 if (s[1] == ':') /* skip over "::" for C++ */
5054 ++s;
5055 else
5056 return TRUE;
5058 if (*s == '\'' && s[1] && s[2] == '\'')
5059 s += 2; /* skip over '.' */
5060 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5061 return FALSE; /* stop at comment */
5062 else if (*s == '"')
5063 return FALSE; /* stop at string */
5065 return FALSE;
5068 if (cin_isdefault(s))
5069 return TRUE;
5070 return FALSE;
5074 * Recognize a "default" switch label.
5076 static int
5077 cin_isdefault(s)
5078 char_u *s;
5080 return (STRNCMP(s, "default", 7) == 0
5081 && *(s = cin_skipcomment(s + 7)) == ':'
5082 && s[1] != ':');
5086 * Recognize a "public/private/proctected" scope declaration label.
5089 cin_isscopedecl(s)
5090 char_u *s;
5092 int i;
5094 s = cin_skipcomment(s);
5095 if (STRNCMP(s, "public", 6) == 0)
5096 i = 6;
5097 else if (STRNCMP(s, "protected", 9) == 0)
5098 i = 9;
5099 else if (STRNCMP(s, "private", 7) == 0)
5100 i = 7;
5101 else
5102 return FALSE;
5103 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5107 * Return a pointer to the first non-empty non-comment character after a ':'.
5108 * Return NULL if not found.
5109 * case 234: a = b;
5112 static char_u *
5113 after_label(l)
5114 char_u *l;
5116 for ( ; *l; ++l)
5118 if (*l == ':')
5120 if (l[1] == ':') /* skip over "::" for C++ */
5121 ++l;
5122 else if (!cin_iscase(l + 1))
5123 break;
5125 else if (*l == '\'' && l[1] && l[2] == '\'')
5126 l += 2; /* skip over 'x' */
5128 if (*l == NUL)
5129 return NULL;
5130 l = cin_skipcomment(l + 1);
5131 if (*l == NUL)
5132 return NULL;
5133 return l;
5137 * Get indent of line "lnum", skipping a label.
5138 * Return 0 if there is nothing after the label.
5140 static int
5141 get_indent_nolabel(lnum) /* XXX */
5142 linenr_T lnum;
5144 char_u *l;
5145 pos_T fp;
5146 colnr_T col;
5147 char_u *p;
5149 l = ml_get(lnum);
5150 p = after_label(l);
5151 if (p == NULL)
5152 return 0;
5154 fp.col = (colnr_T)(p - l);
5155 fp.lnum = lnum;
5156 getvcol(curwin, &fp, &col, NULL, NULL);
5157 return (int)col;
5161 * Find indent for line "lnum", ignoring any case or jump label.
5162 * Also return a pointer to the text (after the label) in "pp".
5163 * label: if (asdf && asdfasdf)
5166 static int
5167 skip_label(lnum, pp, ind_maxcomment)
5168 linenr_T lnum;
5169 char_u **pp;
5170 int ind_maxcomment;
5172 char_u *l;
5173 int amount;
5174 pos_T cursor_save;
5176 cursor_save = curwin->w_cursor;
5177 curwin->w_cursor.lnum = lnum;
5178 l = ml_get_curline();
5179 /* XXX */
5180 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5182 amount = get_indent_nolabel(lnum);
5183 l = after_label(ml_get_curline());
5184 if (l == NULL) /* just in case */
5185 l = ml_get_curline();
5187 else
5189 amount = get_indent();
5190 l = ml_get_curline();
5192 *pp = l;
5194 curwin->w_cursor = cursor_save;
5195 return amount;
5199 * Return the indent of the first variable name after a type in a declaration.
5200 * int a, indent of "a"
5201 * static struct foo b, indent of "b"
5202 * enum bla c, indent of "c"
5203 * Returns zero when it doesn't look like a declaration.
5205 static int
5206 cin_first_id_amount()
5208 char_u *line, *p, *s;
5209 int len;
5210 pos_T fp;
5211 colnr_T col;
5213 line = ml_get_curline();
5214 p = skipwhite(line);
5215 len = (int)(skiptowhite(p) - p);
5216 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5218 p = skipwhite(p + 6);
5219 len = (int)(skiptowhite(p) - p);
5221 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5222 p = skipwhite(p + 6);
5223 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5224 p = skipwhite(p + 4);
5225 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5226 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5228 s = skipwhite(p + len);
5229 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5230 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5231 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5232 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5233 p = s;
5235 for (len = 0; vim_isIDc(p[len]); ++len)
5237 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5238 return 0;
5240 p = skipwhite(p + len);
5241 fp.lnum = curwin->w_cursor.lnum;
5242 fp.col = (colnr_T)(p - line);
5243 getvcol(curwin, &fp, &col, NULL, NULL);
5244 return (int)col;
5248 * Return the indent of the first non-blank after an equal sign.
5249 * char *foo = "here";
5250 * Return zero if no (useful) equal sign found.
5251 * Return -1 if the line above "lnum" ends in a backslash.
5252 * foo = "asdf\
5253 * asdf\
5254 * here";
5256 static int
5257 cin_get_equal_amount(lnum)
5258 linenr_T lnum;
5260 char_u *line;
5261 char_u *s;
5262 colnr_T col;
5263 pos_T fp;
5265 if (lnum > 1)
5267 line = ml_get(lnum - 1);
5268 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5269 return -1;
5272 line = s = ml_get(lnum);
5273 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5275 if (cin_iscomment(s)) /* ignore comments */
5276 s = cin_skipcomment(s);
5277 else
5278 ++s;
5280 if (*s != '=')
5281 return 0;
5283 s = skipwhite(s + 1);
5284 if (cin_nocode(s))
5285 return 0;
5287 if (*s == '"') /* nice alignment for continued strings */
5288 ++s;
5290 fp.lnum = lnum;
5291 fp.col = (colnr_T)(s - line);
5292 getvcol(curwin, &fp, &col, NULL, NULL);
5293 return (int)col;
5297 * Recognize a preprocessor statement: Any line that starts with '#'.
5299 static int
5300 cin_ispreproc(s)
5301 char_u *s;
5303 s = skipwhite(s);
5304 if (*s == '#')
5305 return TRUE;
5306 return FALSE;
5310 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5311 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5312 * start and return the line in "*pp".
5314 static int
5315 cin_ispreproc_cont(pp, lnump)
5316 char_u **pp;
5317 linenr_T *lnump;
5319 char_u *line = *pp;
5320 linenr_T lnum = *lnump;
5321 int retval = FALSE;
5323 for (;;)
5325 if (cin_ispreproc(line))
5327 retval = TRUE;
5328 *lnump = lnum;
5329 break;
5331 if (lnum == 1)
5332 break;
5333 line = ml_get(--lnum);
5334 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5335 break;
5338 if (lnum != *lnump)
5339 *pp = ml_get(*lnump);
5340 return retval;
5344 * Recognize the start of a C or C++ comment.
5346 static int
5347 cin_iscomment(p)
5348 char_u *p;
5350 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5354 * Recognize the start of a "//" comment.
5356 static int
5357 cin_islinecomment(p)
5358 char_u *p;
5360 return (p[0] == '/' && p[1] == '/');
5364 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5365 * Don't consider "} else" a terminated line.
5366 * Return the character terminating the line (ending char's have precedence if
5367 * both apply in order to determine initializations).
5369 static int
5370 cin_isterminated(s, incl_open, incl_comma)
5371 char_u *s;
5372 int incl_open; /* include '{' at the end as terminator */
5373 int incl_comma; /* recognize a trailing comma */
5375 char_u found_start = 0;
5377 s = cin_skipcomment(s);
5379 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5380 found_start = *s;
5382 while (*s)
5384 /* skip over comments, "" strings and 'c'haracters */
5385 s = skip_string(cin_skipcomment(s));
5386 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5387 || (incl_comma && *s == ','))
5388 && cin_nocode(s + 1))
5389 return *s;
5391 if (*s)
5392 s++;
5394 return found_start;
5398 * Recognize the basic picture of a function declaration -- it needs to
5399 * have an open paren somewhere and a close paren at the end of the line and
5400 * no semicolons anywhere.
5401 * When a line ends in a comma we continue looking in the next line.
5402 * "sp" points to a string with the line. When looking at other lines it must
5403 * be restored to the line. When it's NULL fetch lines here.
5404 * "lnum" is where we start looking.
5406 static int
5407 cin_isfuncdecl(sp, first_lnum)
5408 char_u **sp;
5409 linenr_T first_lnum;
5411 char_u *s;
5412 linenr_T lnum = first_lnum;
5413 int retval = FALSE;
5415 if (sp == NULL)
5416 s = ml_get(lnum);
5417 else
5418 s = *sp;
5420 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5422 if (cin_iscomment(s)) /* ignore comments */
5423 s = cin_skipcomment(s);
5424 else
5425 ++s;
5427 if (*s != '(')
5428 return FALSE; /* ';', ' or " before any () or no '(' */
5430 while (*s && *s != ';' && *s != '\'' && *s != '"')
5432 if (*s == ')' && cin_nocode(s + 1))
5434 /* ')' at the end: may have found a match
5435 * Check for he previous line not to end in a backslash:
5436 * #if defined(x) && \
5437 * defined(y)
5439 lnum = first_lnum - 1;
5440 s = ml_get(lnum);
5441 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5442 retval = TRUE;
5443 goto done;
5445 if (*s == ',' && cin_nocode(s + 1))
5447 /* ',' at the end: continue looking in the next line */
5448 if (lnum >= curbuf->b_ml.ml_line_count)
5449 break;
5451 s = ml_get(++lnum);
5453 else if (cin_iscomment(s)) /* ignore comments */
5454 s = cin_skipcomment(s);
5455 else
5456 ++s;
5459 done:
5460 if (lnum != first_lnum && sp != NULL)
5461 *sp = ml_get(first_lnum);
5463 return retval;
5466 static int
5467 cin_isif(p)
5468 char_u *p;
5470 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5473 static int
5474 cin_iselse(p)
5475 char_u *p;
5477 if (*p == '}') /* accept "} else" */
5478 p = cin_skipcomment(p + 1);
5479 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5482 static int
5483 cin_isdo(p)
5484 char_u *p;
5486 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5490 * Check if this is a "while" that should have a matching "do".
5491 * We only accept a "while (condition) ;", with only white space between the
5492 * ')' and ';'. The condition may be spread over several lines.
5494 static int
5495 cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5496 char_u *p;
5497 linenr_T lnum;
5498 int ind_maxparen;
5500 pos_T cursor_save;
5501 pos_T *trypos;
5502 int retval = FALSE;
5504 p = cin_skipcomment(p);
5505 if (*p == '}') /* accept "} while (cond);" */
5506 p = cin_skipcomment(p + 1);
5507 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5509 cursor_save = curwin->w_cursor;
5510 curwin->w_cursor.lnum = lnum;
5511 curwin->w_cursor.col = 0;
5512 p = ml_get_curline();
5513 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5515 ++p;
5516 ++curwin->w_cursor.col;
5518 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5519 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5520 retval = TRUE;
5521 curwin->w_cursor = cursor_save;
5523 return retval;
5527 * Return TRUE if we are at the end of a do-while.
5528 * do
5529 * nothing;
5530 * while (foo
5531 * && bar); <-- here
5532 * Adjust the cursor to the line with "while".
5534 static int
5535 cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5536 int terminated;
5537 int ind_maxparen;
5538 int ind_maxcomment;
5540 char_u *line;
5541 char_u *p;
5542 char_u *s;
5543 pos_T *trypos;
5544 int i;
5546 if (terminated != ';') /* there must be a ';' at the end */
5547 return FALSE;
5549 p = line = ml_get_curline();
5550 while (*p != NUL)
5552 p = cin_skipcomment(p);
5553 if (*p == ')')
5555 s = skipwhite(p + 1);
5556 if (*s == ';' && cin_nocode(s + 1))
5558 /* Found ");" at end of the line, now check there is "while"
5559 * before the matching '('. XXX */
5560 i = (int)(p - line);
5561 curwin->w_cursor.col = i;
5562 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5563 if (trypos != NULL)
5565 s = cin_skipcomment(ml_get(trypos->lnum));
5566 if (*s == '}') /* accept "} while (cond);" */
5567 s = cin_skipcomment(s + 1);
5568 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5570 curwin->w_cursor.lnum = trypos->lnum;
5571 return TRUE;
5575 /* Searching may have made "line" invalid, get it again. */
5576 line = ml_get_curline();
5577 p = line + i;
5580 if (*p != NUL)
5581 ++p;
5583 return FALSE;
5586 static int
5587 cin_isbreak(p)
5588 char_u *p;
5590 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5594 * Find the position of a C++ base-class declaration or
5595 * constructor-initialization. eg:
5597 * class MyClass :
5598 * baseClass <-- here
5599 * class MyClass : public baseClass,
5600 * anotherBaseClass <-- here (should probably lineup ??)
5601 * MyClass::MyClass(...) :
5602 * baseClass(...) <-- here (constructor-initialization)
5604 * This is a lot of guessing. Watch out for "cond ? func() : foo".
5606 static int
5607 cin_is_cpp_baseclass(col)
5608 colnr_T *col; /* return: column to align with */
5610 char_u *s;
5611 int class_or_struct, lookfor_ctor_init, cpp_base_class;
5612 linenr_T lnum = curwin->w_cursor.lnum;
5613 char_u *line = ml_get_curline();
5615 *col = 0;
5617 s = skipwhite(line);
5618 if (*s == '#') /* skip #define FOO x ? (x) : x */
5619 return FALSE;
5620 s = cin_skipcomment(s);
5621 if (*s == NUL)
5622 return FALSE;
5624 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5626 /* Search for a line starting with '#', empty, ending in ';' or containing
5627 * '{' or '}' and start below it. This handles the following situations:
5628 * a = cond ?
5629 * func() :
5630 * asdf;
5631 * func::foo()
5632 * : something
5633 * {}
5634 * Foo::Foo (int one, int two)
5635 * : something(4),
5636 * somethingelse(3)
5637 * {}
5639 while (lnum > 1)
5641 line = ml_get(lnum - 1);
5642 s = skipwhite(line);
5643 if (*s == '#' || *s == NUL)
5644 break;
5645 while (*s != NUL)
5647 s = cin_skipcomment(s);
5648 if (*s == '{' || *s == '}'
5649 || (*s == ';' && cin_nocode(s + 1)))
5650 break;
5651 if (*s != NUL)
5652 ++s;
5654 if (*s != NUL)
5655 break;
5656 --lnum;
5659 line = ml_get(lnum);
5660 s = cin_skipcomment(line);
5661 for (;;)
5663 if (*s == NUL)
5665 if (lnum == curwin->w_cursor.lnum)
5666 break;
5667 /* Continue in the cursor line. */
5668 line = ml_get(++lnum);
5669 s = cin_skipcomment(line);
5670 if (*s == NUL)
5671 continue;
5674 if (s[0] == ':')
5676 if (s[1] == ':')
5678 /* skip double colon. It can't be a constructor
5679 * initialization any more */
5680 lookfor_ctor_init = FALSE;
5681 s = cin_skipcomment(s + 2);
5683 else if (lookfor_ctor_init || class_or_struct)
5685 /* we have something found, that looks like the start of
5686 * cpp-base-class-declaration or contructor-initialization */
5687 cpp_base_class = TRUE;
5688 lookfor_ctor_init = class_or_struct = FALSE;
5689 *col = 0;
5690 s = cin_skipcomment(s + 1);
5692 else
5693 s = cin_skipcomment(s + 1);
5695 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5696 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5698 class_or_struct = TRUE;
5699 lookfor_ctor_init = FALSE;
5701 if (*s == 'c')
5702 s = cin_skipcomment(s + 5);
5703 else
5704 s = cin_skipcomment(s + 6);
5706 else
5708 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5710 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5712 else if (s[0] == ')')
5714 /* Constructor-initialization is assumed if we come across
5715 * something like "):" */
5716 class_or_struct = FALSE;
5717 lookfor_ctor_init = TRUE;
5719 else if (s[0] == '?')
5721 /* Avoid seeing '() :' after '?' as constructor init. */
5722 return FALSE;
5724 else if (!vim_isIDc(s[0]))
5726 /* if it is not an identifier, we are wrong */
5727 class_or_struct = FALSE;
5728 lookfor_ctor_init = FALSE;
5730 else if (*col == 0)
5732 /* it can't be a constructor-initialization any more */
5733 lookfor_ctor_init = FALSE;
5735 /* the first statement starts here: lineup with this one... */
5736 if (cpp_base_class)
5737 *col = (colnr_T)(s - line);
5740 /* When the line ends in a comma don't align with it. */
5741 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5742 *col = 0;
5744 s = cin_skipcomment(s + 1);
5748 return cpp_base_class;
5751 static int
5752 get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5753 int col;
5754 int ind_maxparen;
5755 int ind_maxcomment;
5756 int ind_cpp_baseclass;
5758 int amount;
5759 colnr_T vcol;
5760 pos_T *trypos;
5762 if (col == 0)
5764 amount = get_indent();
5765 if (find_last_paren(ml_get_curline(), '(', ')')
5766 && (trypos = find_match_paren(ind_maxparen,
5767 ind_maxcomment)) != NULL)
5768 amount = get_indent_lnum(trypos->lnum); /* XXX */
5769 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5770 amount += ind_cpp_baseclass;
5772 else
5774 curwin->w_cursor.col = col;
5775 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5776 amount = (int)vcol;
5778 if (amount < ind_cpp_baseclass)
5779 amount = ind_cpp_baseclass;
5780 return amount;
5784 * Return TRUE if string "s" ends with the string "find", possibly followed by
5785 * white space and comments. Skip strings and comments.
5786 * Ignore "ignore" after "find" if it's not NULL.
5788 static int
5789 cin_ends_in(s, find, ignore)
5790 char_u *s;
5791 char_u *find;
5792 char_u *ignore;
5794 char_u *p = s;
5795 char_u *r;
5796 int len = (int)STRLEN(find);
5798 while (*p != NUL)
5800 p = cin_skipcomment(p);
5801 if (STRNCMP(p, find, len) == 0)
5803 r = skipwhite(p + len);
5804 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5805 r = skipwhite(r + STRLEN(ignore));
5806 if (cin_nocode(r))
5807 return TRUE;
5809 if (*p != NUL)
5810 ++p;
5812 return FALSE;
5816 * Skip strings, chars and comments until at or past "trypos".
5817 * Return the column found.
5819 static int
5820 cin_skip2pos(trypos)
5821 pos_T *trypos;
5823 char_u *line;
5824 char_u *p;
5826 p = line = ml_get(trypos->lnum);
5827 while (*p && (colnr_T)(p - line) < trypos->col)
5829 if (cin_iscomment(p))
5830 p = cin_skipcomment(p);
5831 else
5833 p = skip_string(p);
5834 ++p;
5837 return (int)(p - line);
5841 * Find the '{' at the start of the block we are in.
5842 * Return NULL if no match found.
5843 * Ignore a '{' that is in a comment, makes indenting the next three lines
5844 * work. */
5845 /* foo() */
5846 /* { */
5847 /* } */
5849 static pos_T *
5850 find_start_brace(ind_maxcomment) /* XXX */
5851 int ind_maxcomment;
5853 pos_T cursor_save;
5854 pos_T *trypos;
5855 pos_T *pos;
5856 static pos_T pos_copy;
5858 cursor_save = curwin->w_cursor;
5859 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5861 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5862 trypos = &pos_copy;
5863 curwin->w_cursor = *trypos;
5864 pos = NULL;
5865 /* ignore the { if it's in a // or / * * / comment */
5866 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5867 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5868 break;
5869 if (pos != NULL)
5870 curwin->w_cursor.lnum = pos->lnum;
5872 curwin->w_cursor = cursor_save;
5873 return trypos;
5877 * Find the matching '(', failing if it is in a comment.
5878 * Return NULL of no match found.
5880 static pos_T *
5881 find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5882 int ind_maxparen;
5883 int ind_maxcomment;
5885 pos_T cursor_save;
5886 pos_T *trypos;
5887 static pos_T pos_copy;
5889 cursor_save = curwin->w_cursor;
5890 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5892 /* check if the ( is in a // comment */
5893 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5894 trypos = NULL;
5895 else
5897 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5898 trypos = &pos_copy;
5899 curwin->w_cursor = *trypos;
5900 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5901 trypos = NULL;
5904 curwin->w_cursor = cursor_save;
5905 return trypos;
5909 * Return ind_maxparen corrected for the difference in line number between the
5910 * cursor position and "startpos". This makes sure that searching for a
5911 * matching paren above the cursor line doesn't find a match because of
5912 * looking a few lines further.
5914 static int
5915 corr_ind_maxparen(ind_maxparen, startpos)
5916 int ind_maxparen;
5917 pos_T *startpos;
5919 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5921 if (n > 0 && n < ind_maxparen / 2)
5922 return ind_maxparen - (int)n;
5923 return ind_maxparen;
5927 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5928 * line "l".
5930 static int
5931 find_last_paren(l, start, end)
5932 char_u *l;
5933 int start, end;
5935 int i;
5936 int retval = FALSE;
5937 int open_count = 0;
5939 curwin->w_cursor.col = 0; /* default is start of line */
5941 for (i = 0; l[i]; i++)
5943 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5944 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5945 if (l[i] == start)
5946 ++open_count;
5947 else if (l[i] == end)
5949 if (open_count > 0)
5950 --open_count;
5951 else
5953 curwin->w_cursor.col = i;
5954 retval = TRUE;
5958 return retval;
5962 get_c_indent()
5965 * spaces from a block's opening brace the prevailing indent for that
5966 * block should be
5968 int ind_level = curbuf->b_p_sw;
5971 * spaces from the edge of the line an open brace that's at the end of a
5972 * line is imagined to be.
5974 int ind_open_imag = 0;
5977 * spaces from the prevailing indent for a line that is not precededof by
5978 * an opening brace.
5980 int ind_no_brace = 0;
5983 * column where the first { of a function should be located }
5985 int ind_first_open = 0;
5988 * spaces from the prevailing indent a leftmost open brace should be
5989 * located
5991 int ind_open_extra = 0;
5994 * spaces from the matching open brace (real location for one at the left
5995 * edge; imaginary location from one that ends a line) the matching close
5996 * brace should be located
5998 int ind_close_extra = 0;
6001 * spaces from the edge of the line an open brace sitting in the leftmost
6002 * column is imagined to be
6004 int ind_open_left_imag = 0;
6007 * spaces from the switch() indent a "case xx" label should be located
6009 int ind_case = curbuf->b_p_sw;
6012 * spaces from the "case xx:" code after a switch() should be located
6014 int ind_case_code = curbuf->b_p_sw;
6017 * lineup break at end of case in switch() with case label
6019 int ind_case_break = 0;
6022 * spaces from the class declaration indent a scope declaration label
6023 * should be located
6025 int ind_scopedecl = curbuf->b_p_sw;
6028 * spaces from the scope declaration label code should be located
6030 int ind_scopedecl_code = curbuf->b_p_sw;
6033 * amount K&R-style parameters should be indented
6035 int ind_param = curbuf->b_p_sw;
6038 * amount a function type spec should be indented
6040 int ind_func_type = curbuf->b_p_sw;
6043 * amount a cpp base class declaration or constructor initialization
6044 * should be indented
6046 int ind_cpp_baseclass = curbuf->b_p_sw;
6049 * additional spaces beyond the prevailing indent a continuation line
6050 * should be located
6052 int ind_continuation = curbuf->b_p_sw;
6055 * spaces from the indent of the line with an unclosed parentheses
6057 int ind_unclosed = curbuf->b_p_sw * 2;
6060 * spaces from the indent of the line with an unclosed parentheses, which
6061 * itself is also unclosed
6063 int ind_unclosed2 = curbuf->b_p_sw;
6066 * suppress ignoring spaces from the indent of a line starting with an
6067 * unclosed parentheses.
6069 int ind_unclosed_noignore = 0;
6072 * If the opening paren is the last nonwhite character on the line, and
6073 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6074 * context (for very long lines).
6076 int ind_unclosed_wrapped = 0;
6079 * suppress ignoring white space when lining up with the character after
6080 * an unclosed parentheses.
6082 int ind_unclosed_whiteok = 0;
6085 * indent a closing parentheses under the line start of the matching
6086 * opening parentheses.
6088 int ind_matching_paren = 0;
6091 * indent a closing parentheses under the previous line.
6093 int ind_paren_prev = 0;
6096 * Extra indent for comments.
6098 int ind_comment = 0;
6101 * spaces from the comment opener when there is nothing after it.
6103 int ind_in_comment = 3;
6106 * boolean: if non-zero, use ind_in_comment even if there is something
6107 * after the comment opener.
6109 int ind_in_comment2 = 0;
6112 * max lines to search for an open paren
6114 int ind_maxparen = 20;
6117 * max lines to search for an open comment
6119 int ind_maxcomment = 70;
6122 * handle braces for java code
6124 int ind_java = 0;
6127 * handle blocked cases correctly
6129 int ind_keep_case_label = 0;
6131 pos_T cur_curpos;
6132 int amount;
6133 int scope_amount;
6134 int cur_amount = MAXCOL;
6135 colnr_T col;
6136 char_u *theline;
6137 char_u *linecopy;
6138 pos_T *trypos;
6139 pos_T *tryposBrace = NULL;
6140 pos_T our_paren_pos;
6141 char_u *start;
6142 int start_brace;
6143 #define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
6144 #define BRACE_AT_START 2 /* '{' is at start of line */
6145 #define BRACE_AT_END 3 /* '{' is at end of line */
6146 linenr_T ourscope;
6147 char_u *l;
6148 char_u *look;
6149 char_u terminated;
6150 int lookfor;
6151 #define LOOKFOR_INITIAL 0
6152 #define LOOKFOR_IF 1
6153 #define LOOKFOR_DO 2
6154 #define LOOKFOR_CASE 3
6155 #define LOOKFOR_ANY 4
6156 #define LOOKFOR_TERM 5
6157 #define LOOKFOR_UNTERM 6
6158 #define LOOKFOR_SCOPEDECL 7
6159 #define LOOKFOR_NOBREAK 8
6160 #define LOOKFOR_CPP_BASECLASS 9
6161 #define LOOKFOR_ENUM_OR_INIT 10
6163 int whilelevel;
6164 linenr_T lnum;
6165 char_u *options;
6166 int fraction = 0; /* init for GCC */
6167 int divider;
6168 int n;
6169 int iscase;
6170 int lookfor_break;
6171 int cont_amount = 0; /* amount for continuation line */
6173 for (options = curbuf->b_p_cino; *options; )
6175 l = options++;
6176 if (*options == '-')
6177 ++options;
6178 n = getdigits(&options);
6179 divider = 0;
6180 if (*options == '.') /* ".5s" means a fraction */
6182 fraction = atol((char *)++options);
6183 while (VIM_ISDIGIT(*options))
6185 ++options;
6186 if (divider)
6187 divider *= 10;
6188 else
6189 divider = 10;
6192 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6194 if (n == 0 && fraction == 0)
6195 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6196 else
6198 n *= curbuf->b_p_sw;
6199 if (divider)
6200 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6202 ++options;
6204 if (l[1] == '-')
6205 n = -n;
6206 /* When adding an entry here, also update the default 'cinoptions' in
6207 * doc/indent.txt, and add explanation for it! */
6208 switch (*l)
6210 case '>': ind_level = n; break;
6211 case 'e': ind_open_imag = n; break;
6212 case 'n': ind_no_brace = n; break;
6213 case 'f': ind_first_open = n; break;
6214 case '{': ind_open_extra = n; break;
6215 case '}': ind_close_extra = n; break;
6216 case '^': ind_open_left_imag = n; break;
6217 case ':': ind_case = n; break;
6218 case '=': ind_case_code = n; break;
6219 case 'b': ind_case_break = n; break;
6220 case 'p': ind_param = n; break;
6221 case 't': ind_func_type = n; break;
6222 case '/': ind_comment = n; break;
6223 case 'c': ind_in_comment = n; break;
6224 case 'C': ind_in_comment2 = n; break;
6225 case 'i': ind_cpp_baseclass = n; break;
6226 case '+': ind_continuation = n; break;
6227 case '(': ind_unclosed = n; break;
6228 case 'u': ind_unclosed2 = n; break;
6229 case 'U': ind_unclosed_noignore = n; break;
6230 case 'W': ind_unclosed_wrapped = n; break;
6231 case 'w': ind_unclosed_whiteok = n; break;
6232 case 'm': ind_matching_paren = n; break;
6233 case 'M': ind_paren_prev = n; break;
6234 case ')': ind_maxparen = n; break;
6235 case '*': ind_maxcomment = n; break;
6236 case 'g': ind_scopedecl = n; break;
6237 case 'h': ind_scopedecl_code = n; break;
6238 case 'j': ind_java = n; break;
6239 case 'l': ind_keep_case_label = n; break;
6240 case '#': ind_hash_comment = n; break;
6244 /* remember where the cursor was when we started */
6245 cur_curpos = curwin->w_cursor;
6247 /* Get a copy of the current contents of the line.
6248 * This is required, because only the most recent line obtained with
6249 * ml_get is valid! */
6250 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6251 if (linecopy == NULL)
6252 return 0;
6255 * In insert mode and the cursor is on a ')' truncate the line at the
6256 * cursor position. We don't want to line up with the matching '(' when
6257 * inserting new stuff.
6258 * For unknown reasons the cursor might be past the end of the line, thus
6259 * check for that.
6261 if ((State & INSERT)
6262 && curwin->w_cursor.col < STRLEN(linecopy)
6263 && linecopy[curwin->w_cursor.col] == ')')
6264 linecopy[curwin->w_cursor.col] = NUL;
6266 theline = skipwhite(linecopy);
6268 /* move the cursor to the start of the line */
6270 curwin->w_cursor.col = 0;
6273 * #defines and so on always go at the left when included in 'cinkeys'.
6275 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6277 amount = 0;
6281 * Is it a non-case label? Then that goes at the left margin too.
6283 else if (cin_islabel(ind_maxcomment)) /* XXX */
6285 amount = 0;
6289 * If we're inside a "//" comment and there is a "//" comment in a
6290 * previous line, lineup with that one.
6292 else if (cin_islinecomment(theline)
6293 && (trypos = find_line_comment()) != NULL) /* XXX */
6295 /* find how indented the line beginning the comment is */
6296 getvcol(curwin, trypos, &col, NULL, NULL);
6297 amount = col;
6301 * If we're inside a comment and not looking at the start of the
6302 * comment, try using the 'comments' option.
6304 else if (!cin_iscomment(theline)
6305 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6307 int lead_start_len = 2;
6308 int lead_middle_len = 1;
6309 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6310 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6311 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6312 char_u *p;
6313 int start_align = 0;
6314 int start_off = 0;
6315 int done = FALSE;
6317 /* find how indented the line beginning the comment is */
6318 getvcol(curwin, trypos, &col, NULL, NULL);
6319 amount = col;
6321 p = curbuf->b_p_com;
6322 while (*p != NUL)
6324 int align = 0;
6325 int off = 0;
6326 int what = 0;
6328 while (*p != NUL && *p != ':')
6330 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6331 what = *p++;
6332 else if (*p == COM_LEFT || *p == COM_RIGHT)
6333 align = *p++;
6334 else if (VIM_ISDIGIT(*p) || *p == '-')
6335 off = getdigits(&p);
6336 else
6337 ++p;
6340 if (*p == ':')
6341 ++p;
6342 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6343 if (what == COM_START)
6345 STRCPY(lead_start, lead_end);
6346 lead_start_len = (int)STRLEN(lead_start);
6347 start_off = off;
6348 start_align = align;
6350 else if (what == COM_MIDDLE)
6352 STRCPY(lead_middle, lead_end);
6353 lead_middle_len = (int)STRLEN(lead_middle);
6355 else if (what == COM_END)
6357 /* If our line starts with the middle comment string, line it
6358 * up with the comment opener per the 'comments' option. */
6359 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6360 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6362 done = TRUE;
6363 if (curwin->w_cursor.lnum > 1)
6365 /* If the start comment string matches in the previous
6366 * line, use the indent of that line pluss offset. If
6367 * the middle comment string matches in the previous
6368 * line, use the indent of that line. XXX */
6369 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6370 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6371 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6372 else if (STRNCMP(look, lead_middle,
6373 lead_middle_len) == 0)
6375 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6376 break;
6378 /* If the start comment string doesn't match with the
6379 * start of the comment, skip this entry. XXX */
6380 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6381 lead_start, lead_start_len) != 0)
6382 continue;
6384 if (start_off != 0)
6385 amount += start_off;
6386 else if (start_align == COM_RIGHT)
6387 amount += vim_strsize(lead_start)
6388 - vim_strsize(lead_middle);
6389 break;
6392 /* If our line starts with the end comment string, line it up
6393 * with the middle comment */
6394 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6395 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6397 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6398 /* XXX */
6399 if (off != 0)
6400 amount += off;
6401 else if (align == COM_RIGHT)
6402 amount += vim_strsize(lead_start)
6403 - vim_strsize(lead_middle);
6404 done = TRUE;
6405 break;
6410 /* If our line starts with an asterisk, line up with the
6411 * asterisk in the comment opener; otherwise, line up
6412 * with the first character of the comment text.
6414 if (done)
6416 else if (theline[0] == '*')
6417 amount += 1;
6418 else
6421 * If we are more than one line away from the comment opener, take
6422 * the indent of the previous non-empty line. If 'cino' has "CO"
6423 * and we are just below the comment opener and there are any
6424 * white characters after it line up with the text after it;
6425 * otherwise, add the amount specified by "c" in 'cino'
6427 amount = -1;
6428 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6430 if (linewhite(lnum)) /* skip blank lines */
6431 continue;
6432 amount = get_indent_lnum(lnum); /* XXX */
6433 break;
6435 if (amount == -1) /* use the comment opener */
6437 if (!ind_in_comment2)
6439 start = ml_get(trypos->lnum);
6440 look = start + trypos->col + 2; /* skip / and * */
6441 if (*look != NUL) /* if something after it */
6442 trypos->col = (colnr_T)(skipwhite(look) - start);
6444 getvcol(curwin, trypos, &col, NULL, NULL);
6445 amount = col;
6446 if (ind_in_comment2 || *look == NUL)
6447 amount += ind_in_comment;
6453 * Are we inside parentheses or braces?
6454 */ /* XXX */
6455 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6456 && ind_java == 0)
6457 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6458 || trypos != NULL)
6460 if (trypos != NULL && tryposBrace != NULL)
6462 /* Both an unmatched '(' and '{' is found. Use the one which is
6463 * closer to the current cursor position, set the other to NULL. */
6464 if (trypos->lnum != tryposBrace->lnum
6465 ? trypos->lnum < tryposBrace->lnum
6466 : trypos->col < tryposBrace->col)
6467 trypos = NULL;
6468 else
6469 tryposBrace = NULL;
6472 if (trypos != NULL)
6475 * If the matching paren is more than one line away, use the indent of
6476 * a previous non-empty line that matches the same paren.
6478 if (theline[0] == ')' && ind_paren_prev)
6480 /* Line up with the start of the matching paren line. */
6481 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6483 else
6485 amount = -1;
6486 our_paren_pos = *trypos;
6487 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
6489 l = skipwhite(ml_get(lnum));
6490 if (cin_nocode(l)) /* skip comment lines */
6491 continue;
6492 if (cin_ispreproc_cont(&l, &lnum))
6493 continue; /* ignore #define, #if, etc. */
6494 curwin->w_cursor.lnum = lnum;
6496 /* Skip a comment. XXX */
6497 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6499 lnum = trypos->lnum + 1;
6500 continue;
6503 /* XXX */
6504 if ((trypos = find_match_paren(
6505 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6506 ind_maxcomment)) != NULL
6507 && trypos->lnum == our_paren_pos.lnum
6508 && trypos->col == our_paren_pos.col)
6510 amount = get_indent_lnum(lnum); /* XXX */
6512 if (theline[0] == ')')
6514 if (our_paren_pos.lnum != lnum
6515 && cur_amount > amount)
6516 cur_amount = amount;
6517 amount = -1;
6519 break;
6525 * Line up with line where the matching paren is. XXX
6526 * If the line starts with a '(' or the indent for unclosed
6527 * parentheses is zero, line up with the unclosed parentheses.
6529 if (amount == -1)
6531 int ignore_paren_col = 0;
6533 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
6534 look = skipwhite(look);
6535 if (*look == '(')
6537 linenr_T save_lnum = curwin->w_cursor.lnum;
6538 char_u *line;
6539 int look_col;
6541 /* Ignore a '(' in front of the line that has a match before
6542 * our matching '('. */
6543 curwin->w_cursor.lnum = our_paren_pos.lnum;
6544 line = ml_get_curline();
6545 look_col = (int)(look - line);
6546 curwin->w_cursor.col = look_col + 1;
6547 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6548 != NULL
6549 && trypos->lnum == our_paren_pos.lnum
6550 && trypos->col < our_paren_pos.col)
6551 ignore_paren_col = trypos->col + 1;
6553 curwin->w_cursor.lnum = save_lnum;
6554 look = ml_get(our_paren_pos.lnum) + look_col;
6556 if (theline[0] == ')' || ind_unclosed == 0
6557 || (!ind_unclosed_noignore && *look == '('
6558 && ignore_paren_col == 0))
6561 * If we're looking at a close paren, line up right there;
6562 * otherwise, line up with the next (non-white) character.
6563 * When ind_unclosed_wrapped is set and the matching paren is
6564 * the last nonwhite character of the line, use either the
6565 * indent of the current line or the indentation of the next
6566 * outer paren and add ind_unclosed_wrapped (for very long
6567 * lines).
6569 if (theline[0] != ')')
6571 cur_amount = MAXCOL;
6572 l = ml_get(our_paren_pos.lnum);
6573 if (ind_unclosed_wrapped
6574 && cin_ends_in(l, (char_u *)"(", NULL))
6576 /* look for opening unmatched paren, indent one level
6577 * for each additional level */
6578 n = 1;
6579 for (col = 0; col < our_paren_pos.col; ++col)
6581 switch (l[col])
6583 case '(':
6584 case '{': ++n;
6585 break;
6587 case ')':
6588 case '}': if (n > 1)
6589 --n;
6590 break;
6594 our_paren_pos.col = 0;
6595 amount += n * ind_unclosed_wrapped;
6597 else if (ind_unclosed_whiteok)
6598 our_paren_pos.col++;
6599 else
6601 col = our_paren_pos.col + 1;
6602 while (vim_iswhite(l[col]))
6603 col++;
6604 if (l[col] != NUL) /* In case of trailing space */
6605 our_paren_pos.col = col;
6606 else
6607 our_paren_pos.col++;
6612 * Find how indented the paren is, or the character after it
6613 * if we did the above "if".
6615 if (our_paren_pos.col > 0)
6617 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6618 if (cur_amount > (int)col)
6619 cur_amount = col;
6623 if (theline[0] == ')' && ind_matching_paren)
6625 /* Line up with the start of the matching paren line. */
6627 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
6628 && *look == '(' && ignore_paren_col == 0))
6630 if (cur_amount != MAXCOL)
6631 amount = cur_amount;
6633 else
6635 /* Add ind_unclosed2 for each '(' before our matching one, but
6636 * ignore (void) before the line (ignore_paren_col). */
6637 col = our_paren_pos.col;
6638 while ((int)our_paren_pos.col > ignore_paren_col)
6640 --our_paren_pos.col;
6641 switch (*ml_get_pos(&our_paren_pos))
6643 case '(': amount += ind_unclosed2;
6644 col = our_paren_pos.col;
6645 break;
6646 case ')': amount -= ind_unclosed2;
6647 col = MAXCOL;
6648 break;
6652 /* Use ind_unclosed once, when the first '(' is not inside
6653 * braces */
6654 if (col == MAXCOL)
6655 amount += ind_unclosed;
6656 else
6658 curwin->w_cursor.lnum = our_paren_pos.lnum;
6659 curwin->w_cursor.col = col;
6660 if ((trypos = find_match_paren(ind_maxparen,
6661 ind_maxcomment)) != NULL)
6662 amount += ind_unclosed2;
6663 else
6664 amount += ind_unclosed;
6667 * For a line starting with ')' use the minimum of the two
6668 * positions, to avoid giving it more indent than the previous
6669 * lines:
6670 * func_long_name( if (x
6671 * arg && yy
6672 * ) ^ not here ) ^ not here
6674 if (cur_amount < amount)
6675 amount = cur_amount;
6679 /* add extra indent for a comment */
6680 if (cin_iscomment(theline))
6681 amount += ind_comment;
6685 * Are we at least inside braces, then?
6687 else
6689 trypos = tryposBrace;
6691 ourscope = trypos->lnum;
6692 start = ml_get(ourscope);
6695 * Now figure out how indented the line is in general.
6696 * If the brace was at the start of the line, we use that;
6697 * otherwise, check out the indentation of the line as
6698 * a whole and then add the "imaginary indent" to that.
6700 look = skipwhite(start);
6701 if (*look == '{')
6703 getvcol(curwin, trypos, &col, NULL, NULL);
6704 amount = col;
6705 if (*start == '{')
6706 start_brace = BRACE_IN_COL0;
6707 else
6708 start_brace = BRACE_AT_START;
6710 else
6713 * that opening brace might have been on a continuation
6714 * line. if so, find the start of the line.
6716 curwin->w_cursor.lnum = ourscope;
6719 * position the cursor over the rightmost paren, so that
6720 * matching it will take us back to the start of the line.
6722 lnum = ourscope;
6723 if (find_last_paren(start, '(', ')')
6724 && (trypos = find_match_paren(ind_maxparen,
6725 ind_maxcomment)) != NULL)
6726 lnum = trypos->lnum;
6729 * It could have been something like
6730 * case 1: if (asdf &&
6731 * ldfd) {
6734 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6735 amount = get_indent();
6736 else
6737 amount = skip_label(lnum, &l, ind_maxcomment);
6739 start_brace = BRACE_AT_END;
6743 * if we're looking at a closing brace, that's where
6744 * we want to be. otherwise, add the amount of room
6745 * that an indent is supposed to be.
6747 if (theline[0] == '}')
6750 * they may want closing braces to line up with something
6751 * other than the open brace. indulge them, if so.
6753 amount += ind_close_extra;
6755 else
6758 * If we're looking at an "else", try to find an "if"
6759 * to match it with.
6760 * If we're looking at a "while", try to find a "do"
6761 * to match it with.
6763 lookfor = LOOKFOR_INITIAL;
6764 if (cin_iselse(theline))
6765 lookfor = LOOKFOR_IF;
6766 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6767 /* XXX */
6768 lookfor = LOOKFOR_DO;
6769 if (lookfor != LOOKFOR_INITIAL)
6771 curwin->w_cursor.lnum = cur_curpos.lnum;
6772 if (find_match(lookfor, ourscope, ind_maxparen,
6773 ind_maxcomment) == OK)
6775 amount = get_indent(); /* XXX */
6776 goto theend;
6781 * We get here if we are not on an "while-of-do" or "else" (or
6782 * failed to find a matching "if").
6783 * Search backwards for something to line up with.
6784 * First set amount for when we don't find anything.
6788 * if the '{' is _really_ at the left margin, use the imaginary
6789 * location of a left-margin brace. Otherwise, correct the
6790 * location for ind_open_extra.
6793 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6795 amount = ind_open_left_imag;
6797 else
6799 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6800 amount += ind_open_imag;
6801 else
6803 /* Compensate for adding ind_open_extra later. */
6804 amount -= ind_open_extra;
6805 if (amount < 0)
6806 amount = 0;
6810 lookfor_break = FALSE;
6812 if (cin_iscase(theline)) /* it's a switch() label */
6814 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6815 amount += ind_case;
6817 else if (cin_isscopedecl(theline)) /* private:, ... */
6819 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6820 amount += ind_scopedecl;
6822 else
6824 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6825 lookfor_break = TRUE;
6827 lookfor = LOOKFOR_INITIAL;
6828 amount += ind_level; /* ind_level from start of block */
6830 scope_amount = amount;
6831 whilelevel = 0;
6834 * Search backwards. If we find something we recognize, line up
6835 * with that.
6837 * if we're looking at an open brace, indent
6838 * the usual amount relative to the conditional
6839 * that opens the block.
6841 curwin->w_cursor = cur_curpos;
6842 for (;;)
6844 curwin->w_cursor.lnum--;
6845 curwin->w_cursor.col = 0;
6848 * If we went all the way back to the start of our scope, line
6849 * up with it.
6851 if (curwin->w_cursor.lnum <= ourscope)
6853 /* we reached end of scope:
6854 * if looking for a enum or structure initialization
6855 * go further back:
6856 * if it is an initializer (enum xxx or xxx =), then
6857 * don't add ind_continuation, otherwise it is a variable
6858 * declaration:
6859 * int x,
6860 * here; <-- add ind_continuation
6862 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6864 if (curwin->w_cursor.lnum == 0
6865 || curwin->w_cursor.lnum
6866 < ourscope - ind_maxparen)
6868 /* nothing found (abuse ind_maxparen as limit)
6869 * assume terminated line (i.e. a variable
6870 * initialization) */
6871 if (cont_amount > 0)
6872 amount = cont_amount;
6873 else
6874 amount += ind_continuation;
6875 break;
6878 l = ml_get_curline();
6881 * If we're in a comment now, skip to the start of the
6882 * comment.
6884 trypos = find_start_comment(ind_maxcomment);
6885 if (trypos != NULL)
6887 curwin->w_cursor.lnum = trypos->lnum + 1;
6888 continue;
6892 * Skip preprocessor directives and blank lines.
6894 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6895 continue;
6897 if (cin_nocode(l))
6898 continue;
6900 terminated = cin_isterminated(l, FALSE, TRUE);
6903 * If we are at top level and the line looks like a
6904 * function declaration, we are done
6905 * (it's a variable declaration).
6907 if (start_brace != BRACE_IN_COL0
6908 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6910 /* if the line is terminated with another ','
6911 * it is a continued variable initialization.
6912 * don't add extra indent.
6913 * TODO: does not work, if a function
6914 * declaration is split over multiple lines:
6915 * cin_isfuncdecl returns FALSE then.
6917 if (terminated == ',')
6918 break;
6920 /* if it es a enum declaration or an assignment,
6921 * we are done.
6923 if (terminated != ';' && cin_isinit())
6924 break;
6926 /* nothing useful found */
6927 if (terminated == 0 || terminated == '{')
6928 continue;
6931 if (terminated != ';')
6933 /* Skip parens and braces. Position the cursor
6934 * over the rightmost paren, so that matching it
6935 * will take us back to the start of the line.
6936 */ /* XXX */
6937 trypos = NULL;
6938 if (find_last_paren(l, '(', ')'))
6939 trypos = find_match_paren(ind_maxparen,
6940 ind_maxcomment);
6942 if (trypos == NULL && find_last_paren(l, '{', '}'))
6943 trypos = find_start_brace(ind_maxcomment);
6945 if (trypos != NULL)
6947 curwin->w_cursor.lnum = trypos->lnum + 1;
6948 continue;
6952 /* it's a variable declaration, add indentation
6953 * like in
6954 * int a,
6955 * b;
6957 if (cont_amount > 0)
6958 amount = cont_amount;
6959 else
6960 amount += ind_continuation;
6962 else if (lookfor == LOOKFOR_UNTERM)
6964 if (cont_amount > 0)
6965 amount = cont_amount;
6966 else
6967 amount += ind_continuation;
6969 else if (lookfor != LOOKFOR_TERM
6970 && lookfor != LOOKFOR_CPP_BASECLASS)
6972 amount = scope_amount;
6973 if (theline[0] == '{')
6974 amount += ind_open_extra;
6976 break;
6980 * If we're in a comment now, skip to the start of the comment.
6981 */ /* XXX */
6982 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6984 curwin->w_cursor.lnum = trypos->lnum + 1;
6985 continue;
6988 l = ml_get_curline();
6991 * If this is a switch() label, may line up relative to that.
6992 * If this is a C++ scope declaration, do the same.
6994 iscase = cin_iscase(l);
6995 if (iscase || cin_isscopedecl(l))
6997 /* we are only looking for cpp base class
6998 * declaration/initialization any longer */
6999 if (lookfor == LOOKFOR_CPP_BASECLASS)
7000 break;
7002 /* When looking for a "do" we are not interested in
7003 * labels. */
7004 if (whilelevel > 0)
7005 continue;
7008 * case xx:
7009 * c = 99 + <- this indent plus continuation
7010 *-> here;
7012 if (lookfor == LOOKFOR_UNTERM
7013 || lookfor == LOOKFOR_ENUM_OR_INIT)
7015 if (cont_amount > 0)
7016 amount = cont_amount;
7017 else
7018 amount += ind_continuation;
7019 break;
7023 * case xx: <- line up with this case
7024 * x = 333;
7025 * case yy:
7027 if ( (iscase && lookfor == LOOKFOR_CASE)
7028 || (iscase && lookfor_break)
7029 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7032 * Check that this case label is not for another
7033 * switch()
7034 */ /* XXX */
7035 if ((trypos = find_start_brace(ind_maxcomment)) ==
7036 NULL || trypos->lnum == ourscope)
7038 amount = get_indent(); /* XXX */
7039 break;
7041 continue;
7044 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7047 * case xx: if (cond) <- line up with this if
7048 * y = y + 1;
7049 * -> s = 99;
7051 * case xx:
7052 * if (cond) <- line up with this line
7053 * y = y + 1;
7054 * -> s = 99;
7056 if (lookfor == LOOKFOR_TERM)
7058 if (n)
7059 amount = n;
7061 if (!lookfor_break)
7062 break;
7066 * case xx: x = x + 1; <- line up with this x
7067 * -> y = y + 1;
7069 * case xx: if (cond) <- line up with this if
7070 * -> y = y + 1;
7072 if (n)
7074 amount = n;
7075 l = after_label(ml_get_curline());
7076 if (l != NULL && cin_is_cinword(l))
7078 if (theline[0] == '{')
7079 amount += ind_open_extra;
7080 else
7081 amount += ind_level + ind_no_brace;
7083 break;
7087 * Try to get the indent of a statement before the switch
7088 * label. If nothing is found, line up relative to the
7089 * switch label.
7090 * break; <- may line up with this line
7091 * case xx:
7092 * -> y = 1;
7094 scope_amount = get_indent() + (iscase /* XXX */
7095 ? ind_case_code : ind_scopedecl_code);
7096 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7097 continue;
7101 * Looking for a switch() label or C++ scope declaration,
7102 * ignore other lines, skip {}-blocks.
7104 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7106 if (find_last_paren(l, '{', '}') && (trypos =
7107 find_start_brace(ind_maxcomment)) != NULL)
7108 curwin->w_cursor.lnum = trypos->lnum + 1;
7109 continue;
7113 * Ignore jump labels with nothing after them.
7115 if (cin_islabel(ind_maxcomment))
7117 l = after_label(ml_get_curline());
7118 if (l == NULL || cin_nocode(l))
7119 continue;
7123 * Ignore #defines, #if, etc.
7124 * Ignore comment and empty lines.
7125 * (need to get the line again, cin_islabel() may have
7126 * unlocked it)
7128 l = ml_get_curline();
7129 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7130 || cin_nocode(l))
7131 continue;
7134 * Are we at the start of a cpp base class declaration or
7135 * constructor initialization?
7136 */ /* XXX */
7137 n = FALSE;
7138 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7140 n = cin_is_cpp_baseclass(&col);
7141 l = ml_get_curline();
7143 if (n)
7145 if (lookfor == LOOKFOR_UNTERM)
7147 if (cont_amount > 0)
7148 amount = cont_amount;
7149 else
7150 amount += ind_continuation;
7152 else if (theline[0] == '{')
7154 /* Need to find start of the declaration. */
7155 lookfor = LOOKFOR_UNTERM;
7156 ind_continuation = 0;
7157 continue;
7159 else
7160 /* XXX */
7161 amount = get_baseclass_amount(col, ind_maxparen,
7162 ind_maxcomment, ind_cpp_baseclass);
7163 break;
7165 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7167 /* only look, whether there is a cpp base class
7168 * declaration or initialization before the opening brace.
7170 if (cin_isterminated(l, TRUE, FALSE))
7171 break;
7172 else
7173 continue;
7177 * What happens next depends on the line being terminated.
7178 * If terminated with a ',' only consider it terminating if
7179 * there is another unterminated statement behind, eg:
7180 * 123,
7181 * sizeof
7182 * here
7183 * Otherwise check whether it is a enumeration or structure
7184 * initialisation (not indented) or a variable declaration
7185 * (indented).
7187 terminated = cin_isterminated(l, FALSE, TRUE);
7189 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7190 && terminated == ','))
7193 * if we're in the middle of a paren thing,
7194 * go back to the line that starts it so
7195 * we can get the right prevailing indent
7196 * if ( foo &&
7197 * bar )
7200 * position the cursor over the rightmost paren, so that
7201 * matching it will take us back to the start of the line.
7203 (void)find_last_paren(l, '(', ')');
7204 trypos = find_match_paren(
7205 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7206 ind_maxcomment);
7209 * If we are looking for ',', we also look for matching
7210 * braces.
7212 if (trypos == NULL && terminated == ','
7213 && find_last_paren(l, '{', '}'))
7214 trypos = find_start_brace(ind_maxcomment);
7216 if (trypos != NULL)
7219 * Check if we are on a case label now. This is
7220 * handled above.
7221 * case xx: if ( asdf &&
7222 * asdf)
7224 curwin->w_cursor.lnum = trypos->lnum;
7225 l = ml_get_curline();
7226 if (cin_iscase(l) || cin_isscopedecl(l))
7228 ++curwin->w_cursor.lnum;
7229 continue;
7234 * Skip over continuation lines to find the one to get the
7235 * indent from
7236 * char *usethis = "bla\
7237 * bla",
7238 * here;
7240 if (terminated == ',')
7242 while (curwin->w_cursor.lnum > 1)
7244 l = ml_get(curwin->w_cursor.lnum - 1);
7245 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7246 break;
7247 --curwin->w_cursor.lnum;
7252 * Get indent and pointer to text for current line,
7253 * ignoring any jump label. XXX
7255 cur_amount = skip_label(curwin->w_cursor.lnum,
7256 &l, ind_maxcomment);
7259 * If this is just above the line we are indenting, and it
7260 * starts with a '{', line it up with this line.
7261 * while (not)
7262 * -> {
7265 if (terminated != ',' && lookfor != LOOKFOR_TERM
7266 && theline[0] == '{')
7268 amount = cur_amount;
7270 * Only add ind_open_extra when the current line
7271 * doesn't start with a '{', which must have a match
7272 * in the same line (scope is the same). Probably:
7273 * { 1, 2 },
7274 * -> { 3, 4 }
7276 if (*skipwhite(l) != '{')
7277 amount += ind_open_extra;
7279 if (ind_cpp_baseclass)
7281 /* have to look back, whether it is a cpp base
7282 * class declaration or initialization */
7283 lookfor = LOOKFOR_CPP_BASECLASS;
7284 continue;
7286 break;
7290 * Check if we are after an "if", "while", etc.
7291 * Also allow " } else".
7293 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7296 * Found an unterminated line after an if (), line up
7297 * with the last one.
7298 * if (cond)
7299 * 100 +
7300 * -> here;
7302 if (lookfor == LOOKFOR_UNTERM
7303 || lookfor == LOOKFOR_ENUM_OR_INIT)
7305 if (cont_amount > 0)
7306 amount = cont_amount;
7307 else
7308 amount += ind_continuation;
7309 break;
7313 * If this is just above the line we are indenting, we
7314 * are finished.
7315 * while (not)
7316 * -> here;
7317 * Otherwise this indent can be used when the line
7318 * before this is terminated.
7319 * yyy;
7320 * if (stat)
7321 * while (not)
7322 * xxx;
7323 * -> here;
7325 amount = cur_amount;
7326 if (theline[0] == '{')
7327 amount += ind_open_extra;
7328 if (lookfor != LOOKFOR_TERM)
7330 amount += ind_level + ind_no_brace;
7331 break;
7335 * Special trick: when expecting the while () after a
7336 * do, line up with the while()
7337 * do
7338 * x = 1;
7339 * -> here
7341 l = skipwhite(ml_get_curline());
7342 if (cin_isdo(l))
7344 if (whilelevel == 0)
7345 break;
7346 --whilelevel;
7350 * When searching for a terminated line, don't use the
7351 * one between the "if" and the "else".
7352 * Need to use the scope of this "else". XXX
7353 * If whilelevel != 0 continue looking for a "do {".
7355 if (cin_iselse(l)
7356 && whilelevel == 0
7357 && ((trypos = find_start_brace(ind_maxcomment))
7358 == NULL
7359 || find_match(LOOKFOR_IF, trypos->lnum,
7360 ind_maxparen, ind_maxcomment) == FAIL))
7361 break;
7365 * If we're below an unterminated line that is not an
7366 * "if" or something, we may line up with this line or
7367 * add something for a continuation line, depending on
7368 * the line before this one.
7370 else
7373 * Found two unterminated lines on a row, line up with
7374 * the last one.
7375 * c = 99 +
7376 * 100 +
7377 * -> here;
7379 if (lookfor == LOOKFOR_UNTERM)
7381 /* When line ends in a comma add extra indent */
7382 if (terminated == ',')
7383 amount += ind_continuation;
7384 break;
7387 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7389 /* Found two lines ending in ',', lineup with the
7390 * lowest one, but check for cpp base class
7391 * declaration/initialization, if it is an
7392 * opening brace or we are looking just for
7393 * enumerations/initializations. */
7394 if (terminated == ',')
7396 if (ind_cpp_baseclass == 0)
7397 break;
7399 lookfor = LOOKFOR_CPP_BASECLASS;
7400 continue;
7403 /* Ignore unterminated lines in between, but
7404 * reduce indent. */
7405 if (amount > cur_amount)
7406 amount = cur_amount;
7408 else
7411 * Found first unterminated line on a row, may
7412 * line up with this line, remember its indent
7413 * 100 +
7414 * -> here;
7416 amount = cur_amount;
7419 * If previous line ends in ',', check whether we
7420 * are in an initialization or enum
7421 * struct xxx =
7423 * sizeof a,
7424 * 124 };
7425 * or a normal possible continuation line.
7426 * but only, of no other statement has been found
7427 * yet.
7429 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7431 lookfor = LOOKFOR_ENUM_OR_INIT;
7432 cont_amount = cin_first_id_amount();
7434 else
7436 if (lookfor == LOOKFOR_INITIAL
7437 && *l != NUL
7438 && l[STRLEN(l) - 1] == '\\')
7439 /* XXX */
7440 cont_amount = cin_get_equal_amount(
7441 curwin->w_cursor.lnum);
7442 if (lookfor != LOOKFOR_TERM)
7443 lookfor = LOOKFOR_UNTERM;
7450 * Check if we are after a while (cond);
7451 * If so: Ignore until the matching "do".
7453 /* XXX */
7454 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7455 ind_maxcomment))
7458 * Found an unterminated line after a while ();, line up
7459 * with the last one.
7460 * while (cond);
7461 * 100 + <- line up with this one
7462 * -> here;
7464 if (lookfor == LOOKFOR_UNTERM
7465 || lookfor == LOOKFOR_ENUM_OR_INIT)
7467 if (cont_amount > 0)
7468 amount = cont_amount;
7469 else
7470 amount += ind_continuation;
7471 break;
7474 if (whilelevel == 0)
7476 lookfor = LOOKFOR_TERM;
7477 amount = get_indent(); /* XXX */
7478 if (theline[0] == '{')
7479 amount += ind_open_extra;
7481 ++whilelevel;
7485 * We are after a "normal" statement.
7486 * If we had another statement we can stop now and use the
7487 * indent of that other statement.
7488 * Otherwise the indent of the current statement may be used,
7489 * search backwards for the next "normal" statement.
7491 else
7494 * Skip single break line, if before a switch label. It
7495 * may be lined up with the case label.
7497 if (lookfor == LOOKFOR_NOBREAK
7498 && cin_isbreak(skipwhite(ml_get_curline())))
7500 lookfor = LOOKFOR_ANY;
7501 continue;
7505 * Handle "do {" line.
7507 if (whilelevel > 0)
7509 l = cin_skipcomment(ml_get_curline());
7510 if (cin_isdo(l))
7512 amount = get_indent(); /* XXX */
7513 --whilelevel;
7514 continue;
7519 * Found a terminated line above an unterminated line. Add
7520 * the amount for a continuation line.
7521 * x = 1;
7522 * y = foo +
7523 * -> here;
7524 * or
7525 * int x = 1;
7526 * int foo,
7527 * -> here;
7529 if (lookfor == LOOKFOR_UNTERM
7530 || lookfor == LOOKFOR_ENUM_OR_INIT)
7532 if (cont_amount > 0)
7533 amount = cont_amount;
7534 else
7535 amount += ind_continuation;
7536 break;
7540 * Found a terminated line above a terminated line or "if"
7541 * etc. line. Use the amount of the line below us.
7542 * x = 1; x = 1;
7543 * if (asdf) y = 2;
7544 * while (asdf) ->here;
7545 * here;
7546 * ->foo;
7548 if (lookfor == LOOKFOR_TERM)
7550 if (!lookfor_break && whilelevel == 0)
7551 break;
7555 * First line above the one we're indenting is terminated.
7556 * To know what needs to be done look further backward for
7557 * a terminated line.
7559 else
7562 * position the cursor over the rightmost paren, so
7563 * that matching it will take us back to the start of
7564 * the line. Helps for:
7565 * func(asdr,
7566 * asdfasdf);
7567 * here;
7569 term_again:
7570 l = ml_get_curline();
7571 if (find_last_paren(l, '(', ')')
7572 && (trypos = find_match_paren(ind_maxparen,
7573 ind_maxcomment)) != NULL)
7576 * Check if we are on a case label now. This is
7577 * handled above.
7578 * case xx: if ( asdf &&
7579 * asdf)
7581 curwin->w_cursor.lnum = trypos->lnum;
7582 l = ml_get_curline();
7583 if (cin_iscase(l) || cin_isscopedecl(l))
7585 ++curwin->w_cursor.lnum;
7586 continue;
7590 /* When aligning with the case statement, don't align
7591 * with a statement after it.
7592 * case 1: { <-- don't use this { position
7593 * stat;
7595 * case 2:
7596 * stat;
7599 iscase = (ind_keep_case_label && cin_iscase(l));
7602 * Get indent and pointer to text for current line,
7603 * ignoring any jump label.
7605 amount = skip_label(curwin->w_cursor.lnum,
7606 &l, ind_maxcomment);
7608 if (theline[0] == '{')
7609 amount += ind_open_extra;
7610 /* See remark above: "Only add ind_open_extra.." */
7611 l = skipwhite(l);
7612 if (*l == '{')
7613 amount -= ind_open_extra;
7614 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7617 * When a terminated line starts with "else" skip to
7618 * the matching "if":
7619 * else 3;
7620 * indent this;
7621 * Need to use the scope of this "else". XXX
7622 * If whilelevel != 0 continue looking for a "do {".
7624 if (lookfor == LOOKFOR_TERM
7625 && *l != '}'
7626 && cin_iselse(l)
7627 && whilelevel == 0)
7629 if ((trypos = find_start_brace(ind_maxcomment))
7630 == NULL
7631 || find_match(LOOKFOR_IF, trypos->lnum,
7632 ind_maxparen, ind_maxcomment) == FAIL)
7633 break;
7634 continue;
7638 * If we're at the end of a block, skip to the start of
7639 * that block.
7641 curwin->w_cursor.col = 0;
7642 if (*cin_skipcomment(l) == '}'
7643 && (trypos = find_start_brace(ind_maxcomment))
7644 != NULL) /* XXX */
7646 curwin->w_cursor.lnum = trypos->lnum;
7647 /* if not "else {" check for terminated again */
7648 /* but skip block for "} else {" */
7649 l = cin_skipcomment(ml_get_curline());
7650 if (*l == '}' || !cin_iselse(l))
7651 goto term_again;
7652 ++curwin->w_cursor.lnum;
7660 /* add extra indent for a comment */
7661 if (cin_iscomment(theline))
7662 amount += ind_comment;
7666 * ok -- we're not inside any sort of structure at all!
7668 * this means we're at the top level, and everything should
7669 * basically just match where the previous line is, except
7670 * for the lines immediately following a function declaration,
7671 * which are K&R-style parameters and need to be indented.
7673 else
7676 * if our line starts with an open brace, forget about any
7677 * prevailing indent and make sure it looks like the start
7678 * of a function
7681 if (theline[0] == '{')
7683 amount = ind_first_open;
7687 * If the NEXT line is a function declaration, the current
7688 * line needs to be indented as a function type spec.
7689 * Don't do this if the current line looks like a comment
7690 * or if the current line is terminated, ie. ends in ';'.
7692 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7693 && !cin_nocode(theline)
7694 && !cin_ends_in(theline, (char_u *)":", NULL)
7695 && !cin_ends_in(theline, (char_u *)",", NULL)
7696 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7697 && !cin_isterminated(theline, FALSE, TRUE))
7699 amount = ind_func_type;
7701 else
7703 amount = 0;
7704 curwin->w_cursor = cur_curpos;
7706 /* search backwards until we find something we recognize */
7708 while (curwin->w_cursor.lnum > 1)
7710 curwin->w_cursor.lnum--;
7711 curwin->w_cursor.col = 0;
7713 l = ml_get_curline();
7716 * If we're in a comment now, skip to the start of the comment.
7717 */ /* XXX */
7718 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7720 curwin->w_cursor.lnum = trypos->lnum + 1;
7721 continue;
7725 * Are we at the start of a cpp base class declaration or
7726 * constructor initialization?
7727 */ /* XXX */
7728 n = FALSE;
7729 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7731 n = cin_is_cpp_baseclass(&col);
7732 l = ml_get_curline();
7734 if (n)
7736 /* XXX */
7737 amount = get_baseclass_amount(col, ind_maxparen,
7738 ind_maxcomment, ind_cpp_baseclass);
7739 break;
7743 * Skip preprocessor directives and blank lines.
7745 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7746 continue;
7748 if (cin_nocode(l))
7749 continue;
7752 * If the previous line ends in ',', use one level of
7753 * indentation:
7754 * int foo,
7755 * bar;
7756 * do this before checking for '}' in case of eg.
7757 * enum foobar
7759 * ...
7760 * } foo,
7761 * bar;
7763 n = 0;
7764 if (cin_ends_in(l, (char_u *)",", NULL)
7765 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7767 /* take us back to opening paren */
7768 if (find_last_paren(l, '(', ')')
7769 && (trypos = find_match_paren(ind_maxparen,
7770 ind_maxcomment)) != NULL)
7771 curwin->w_cursor.lnum = trypos->lnum;
7773 /* For a line ending in ',' that is a continuation line go
7774 * back to the first line with a backslash:
7775 * char *foo = "bla\
7776 * bla",
7777 * here;
7779 while (n == 0 && curwin->w_cursor.lnum > 1)
7781 l = ml_get(curwin->w_cursor.lnum - 1);
7782 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7783 break;
7784 --curwin->w_cursor.lnum;
7787 amount = get_indent(); /* XXX */
7789 if (amount == 0)
7790 amount = cin_first_id_amount();
7791 if (amount == 0)
7792 amount = ind_continuation;
7793 break;
7797 * If the line looks like a function declaration, and we're
7798 * not in a comment, put it the left margin.
7800 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7801 break;
7802 l = ml_get_curline();
7805 * Finding the closing '}' of a previous function. Put
7806 * current line at the left margin. For when 'cino' has "fs".
7808 if (*skipwhite(l) == '}')
7809 break;
7811 /* (matching {)
7812 * If the previous line ends on '};' (maybe followed by
7813 * comments) align at column 0. For example:
7814 * char *string_array[] = { "foo",
7815 * / * x * / "b};ar" }; / * foobar * /
7817 if (cin_ends_in(l, (char_u *)"};", NULL))
7818 break;
7821 * If the PREVIOUS line is a function declaration, the current
7822 * line (and the ones that follow) needs to be indented as
7823 * parameters.
7825 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7827 amount = ind_param;
7828 break;
7832 * If the previous line ends in ';' and the line before the
7833 * previous line ends in ',' or '\', ident to column zero:
7834 * int foo,
7835 * bar;
7836 * indent_to_0 here;
7838 if (cin_ends_in(l, (char_u *)";", NULL))
7840 l = ml_get(curwin->w_cursor.lnum - 1);
7841 if (cin_ends_in(l, (char_u *)",", NULL)
7842 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7843 break;
7844 l = ml_get_curline();
7848 * Doesn't look like anything interesting -- so just
7849 * use the indent of this line.
7851 * Position the cursor over the rightmost paren, so that
7852 * matching it will take us back to the start of the line.
7854 find_last_paren(l, '(', ')');
7856 if ((trypos = find_match_paren(ind_maxparen,
7857 ind_maxcomment)) != NULL)
7858 curwin->w_cursor.lnum = trypos->lnum;
7859 amount = get_indent(); /* XXX */
7860 break;
7863 /* add extra indent for a comment */
7864 if (cin_iscomment(theline))
7865 amount += ind_comment;
7867 /* add extra indent if the previous line ended in a backslash:
7868 * "asdfasdf\
7869 * here";
7870 * char *foo = "asdf\
7871 * here";
7873 if (cur_curpos.lnum > 1)
7875 l = ml_get(cur_curpos.lnum - 1);
7876 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7878 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7879 if (cur_amount > 0)
7880 amount = cur_amount;
7881 else if (cur_amount == 0)
7882 amount += ind_continuation;
7888 theend:
7889 /* put the cursor back where it belongs */
7890 curwin->w_cursor = cur_curpos;
7892 vim_free(linecopy);
7894 if (amount < 0)
7895 return 0;
7896 return amount;
7899 static int
7900 find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7901 int lookfor;
7902 linenr_T ourscope;
7903 int ind_maxparen;
7904 int ind_maxcomment;
7906 char_u *look;
7907 pos_T *theirscope;
7908 char_u *mightbeif;
7909 int elselevel;
7910 int whilelevel;
7912 if (lookfor == LOOKFOR_IF)
7914 elselevel = 1;
7915 whilelevel = 0;
7917 else
7919 elselevel = 0;
7920 whilelevel = 1;
7923 curwin->w_cursor.col = 0;
7925 while (curwin->w_cursor.lnum > ourscope + 1)
7927 curwin->w_cursor.lnum--;
7928 curwin->w_cursor.col = 0;
7930 look = cin_skipcomment(ml_get_curline());
7931 if (cin_iselse(look)
7932 || cin_isif(look)
7933 || cin_isdo(look) /* XXX */
7934 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7937 * if we've gone outside the braces entirely,
7938 * we must be out of scope...
7940 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7941 if (theirscope == NULL)
7942 break;
7945 * and if the brace enclosing this is further
7946 * back than the one enclosing the else, we're
7947 * out of luck too.
7949 if (theirscope->lnum < ourscope)
7950 break;
7953 * and if they're enclosed in a *deeper* brace,
7954 * then we can ignore it because it's in a
7955 * different scope...
7957 if (theirscope->lnum > ourscope)
7958 continue;
7961 * if it was an "else" (that's not an "else if")
7962 * then we need to go back to another if, so
7963 * increment elselevel
7965 look = cin_skipcomment(ml_get_curline());
7966 if (cin_iselse(look))
7968 mightbeif = cin_skipcomment(look + 4);
7969 if (!cin_isif(mightbeif))
7970 ++elselevel;
7971 continue;
7975 * if it was a "while" then we need to go back to
7976 * another "do", so increment whilelevel. XXX
7978 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7980 ++whilelevel;
7981 continue;
7984 /* If it's an "if" decrement elselevel */
7985 look = cin_skipcomment(ml_get_curline());
7986 if (cin_isif(look))
7988 elselevel--;
7990 * When looking for an "if" ignore "while"s that
7991 * get in the way.
7993 if (elselevel == 0 && lookfor == LOOKFOR_IF)
7994 whilelevel = 0;
7997 /* If it's a "do" decrement whilelevel */
7998 if (cin_isdo(look))
7999 whilelevel--;
8002 * if we've used up all the elses, then
8003 * this must be the if that we want!
8004 * match the indent level of that if.
8006 if (elselevel <= 0 && whilelevel <= 0)
8008 return OK;
8012 return FAIL;
8015 # if defined(FEAT_EVAL) || defined(PROTO)
8017 * Get indent level from 'indentexpr'.
8020 get_expr_indent()
8022 int indent;
8023 pos_T pos;
8024 int save_State;
8025 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8026 OPT_LOCAL);
8028 pos = curwin->w_cursor;
8029 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
8030 if (use_sandbox)
8031 ++sandbox;
8032 ++textlock;
8033 indent = eval_to_number(curbuf->b_p_inde);
8034 if (use_sandbox)
8035 --sandbox;
8036 --textlock;
8038 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8039 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8040 * command. */
8041 save_State = State;
8042 State = INSERT;
8043 curwin->w_cursor = pos;
8044 check_cursor();
8045 State = save_State;
8047 /* If there is an error, just keep the current indent. */
8048 if (indent < 0)
8049 indent = get_indent();
8051 return indent;
8053 # endif
8055 #endif /* FEAT_CINDENT */
8057 #if defined(FEAT_LISP) || defined(PROTO)
8059 static int lisp_match __ARGS((char_u *p));
8061 static int
8062 lisp_match(p)
8063 char_u *p;
8065 char_u buf[LSIZE];
8066 int len;
8067 char_u *word = p_lispwords;
8069 while (*word != NUL)
8071 (void)copy_option_part(&word, buf, LSIZE, ",");
8072 len = (int)STRLEN(buf);
8073 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8074 return TRUE;
8076 return FALSE;
8080 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8081 * The incompatible newer method is quite a bit better at indenting
8082 * code in lisp-like languages than the traditional one; it's still
8083 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8085 * TODO:
8086 * Findmatch() should be adapted for lisp, also to make showmatch
8087 * work correctly: now (v5.3) it seems all C/C++ oriented:
8088 * - it does not recognize the #\( and #\) notations as character literals
8089 * - it doesn't know about comments starting with a semicolon
8090 * - it incorrectly interprets '(' as a character literal
8091 * All this messes up get_lisp_indent in some rare cases.
8092 * Update from Sergey Khorev:
8093 * I tried to fix the first two issues.
8096 get_lisp_indent()
8098 pos_T *pos, realpos, paren;
8099 int amount;
8100 char_u *that;
8101 colnr_T col;
8102 colnr_T firsttry;
8103 int parencount, quotecount;
8104 int vi_lisp;
8106 /* Set vi_lisp to use the vi-compatible method */
8107 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8109 realpos = curwin->w_cursor;
8110 curwin->w_cursor.col = 0;
8112 if ((pos = findmatch(NULL, '(')) == NULL)
8113 pos = findmatch(NULL, '[');
8114 else
8116 paren = *pos;
8117 pos = findmatch(NULL, '[');
8118 if (pos == NULL || ltp(pos, &paren))
8119 pos = &paren;
8121 if (pos != NULL)
8123 /* Extra trick: Take the indent of the first previous non-white
8124 * line that is at the same () level. */
8125 amount = -1;
8126 parencount = 0;
8128 while (--curwin->w_cursor.lnum >= pos->lnum)
8130 if (linewhite(curwin->w_cursor.lnum))
8131 continue;
8132 for (that = ml_get_curline(); *that != NUL; ++that)
8134 if (*that == ';')
8136 while (*(that + 1) != NUL)
8137 ++that;
8138 continue;
8140 if (*that == '\\')
8142 if (*(that + 1) != NUL)
8143 ++that;
8144 continue;
8146 if (*that == '"' && *(that + 1) != NUL)
8148 while (*++that && *that != '"')
8150 /* skipping escaped characters in the string */
8151 if (*that == '\\')
8153 if (*++that == NUL)
8154 break;
8155 if (that[1] == NUL)
8157 ++that;
8158 break;
8163 if (*that == '(' || *that == '[')
8164 ++parencount;
8165 else if (*that == ')' || *that == ']')
8166 --parencount;
8168 if (parencount == 0)
8170 amount = get_indent();
8171 break;
8175 if (amount == -1)
8177 curwin->w_cursor.lnum = pos->lnum;
8178 curwin->w_cursor.col = pos->col;
8179 col = pos->col;
8181 that = ml_get_curline();
8183 if (vi_lisp && get_indent() == 0)
8184 amount = 2;
8185 else
8187 amount = 0;
8188 while (*that && col)
8190 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8191 col--;
8195 * Some keywords require "body" indenting rules (the
8196 * non-standard-lisp ones are Scheme special forms):
8198 * (let ((a 1)) instead (let ((a 1))
8199 * (...)) of (...))
8202 if (!vi_lisp && (*that == '(' || *that == '[')
8203 && lisp_match(that + 1))
8204 amount += 2;
8205 else
8207 that++;
8208 amount++;
8209 firsttry = amount;
8211 while (vim_iswhite(*that))
8213 amount += lbr_chartabsize(that, (colnr_T)amount);
8214 ++that;
8217 if (*that && *that != ';') /* not a comment line */
8219 /* test *that != '(' to accomodate first let/do
8220 * argument if it is more than one line */
8221 if (!vi_lisp && *that != '(' && *that != '[')
8222 firsttry++;
8224 parencount = 0;
8225 quotecount = 0;
8227 if (vi_lisp
8228 || (*that != '"'
8229 && *that != '\''
8230 && *that != '#'
8231 && (*that < '0' || *that > '9')))
8233 while (*that
8234 && (!vim_iswhite(*that)
8235 || quotecount
8236 || parencount)
8237 && (!((*that == '(' || *that == '[')
8238 && !quotecount
8239 && !parencount
8240 && vi_lisp)))
8242 if (*that == '"')
8243 quotecount = !quotecount;
8244 if ((*that == '(' || *that == '[')
8245 && !quotecount)
8246 ++parencount;
8247 if ((*that == ')' || *that == ']')
8248 && !quotecount)
8249 --parencount;
8250 if (*that == '\\' && *(that+1) != NUL)
8251 amount += lbr_chartabsize_adv(&that,
8252 (colnr_T)amount);
8253 amount += lbr_chartabsize_adv(&that,
8254 (colnr_T)amount);
8257 while (vim_iswhite(*that))
8259 amount += lbr_chartabsize(that, (colnr_T)amount);
8260 that++;
8262 if (!*that || *that == ';')
8263 amount = firsttry;
8269 else
8270 amount = 0; /* no matching '(' or '[' found, use zero indent */
8272 curwin->w_cursor = realpos;
8274 return amount;
8276 #endif /* FEAT_LISP */
8278 void
8279 prepare_to_exit()
8281 #if defined(SIGHUP) && defined(SIG_IGN)
8282 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8283 * makes Vim exit and then handling SIGHUP causes various reentrance
8284 * problems. */
8285 signal(SIGHUP, SIG_IGN);
8286 #endif
8288 #ifdef FEAT_GUI
8289 if (gui.in_use)
8291 gui.dying = TRUE;
8292 out_trash(); /* trash any pending output */
8294 else
8295 #endif
8297 windgoto((int)Rows - 1, 0);
8300 * Switch terminal mode back now, so messages end up on the "normal"
8301 * screen (if there are two screens).
8303 settmode(TMODE_COOK);
8304 #ifdef WIN3264
8305 if (can_end_termcap_mode(FALSE) == TRUE)
8306 #endif
8307 stoptermcap();
8308 out_flush();
8313 * Preserve files and exit.
8314 * When called IObuff must contain a message.
8316 void
8317 preserve_exit()
8319 buf_T *buf;
8321 prepare_to_exit();
8323 /* Setting this will prevent free() calls. That avoids calling free()
8324 * recursively when free() was invoked with a bad pointer. */
8325 really_exiting = TRUE;
8327 out_str(IObuff);
8328 screen_start(); /* don't know where cursor is now */
8329 out_flush();
8331 ml_close_notmod(); /* close all not-modified buffers */
8333 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8335 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8337 OUT_STR(_("Vim: preserving files...\n"));
8338 screen_start(); /* don't know where cursor is now */
8339 out_flush();
8340 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8341 break;
8345 ml_close_all(FALSE); /* close all memfiles, without deleting */
8347 OUT_STR(_("Vim: Finished.\n"));
8349 getout(1);
8353 * return TRUE if "fname" exists.
8356 vim_fexists(fname)
8357 char_u *fname;
8359 struct stat st;
8361 if (mch_stat((char *)fname, &st))
8362 return FALSE;
8363 return TRUE;
8367 * Check for CTRL-C pressed, but only once in a while.
8368 * Should be used instead of ui_breakcheck() for functions that check for
8369 * each line in the file. Calling ui_breakcheck() each time takes too much
8370 * time, because it can be a system call.
8373 #ifndef BREAKCHECK_SKIP
8374 # ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8375 # define BREAKCHECK_SKIP 200
8376 # else
8377 # define BREAKCHECK_SKIP 32
8378 # endif
8379 #endif
8381 static int breakcheck_count = 0;
8383 void
8384 line_breakcheck()
8386 if (++breakcheck_count >= BREAKCHECK_SKIP)
8388 breakcheck_count = 0;
8389 ui_breakcheck();
8394 * Like line_breakcheck() but check 10 times less often.
8396 void
8397 fast_breakcheck()
8399 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8401 breakcheck_count = 0;
8402 ui_breakcheck();
8407 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8408 * 'wildignore'.
8409 * Returns OK or FAIL.
8412 expand_wildcards(num_pat, pat, num_file, file, flags)
8413 int num_pat; /* number of input patterns */
8414 char_u **pat; /* array of input patterns */
8415 int *num_file; /* resulting number of files */
8416 char_u ***file; /* array of resulting files */
8417 int flags; /* EW_DIR, etc. */
8419 int retval;
8420 int i, j;
8421 char_u *p;
8422 int non_suf_match; /* number without matching suffix */
8424 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8426 /* When keeping all matches, return here */
8427 if (flags & EW_KEEPALL)
8428 return retval;
8430 #ifdef FEAT_WILDIGN
8432 * Remove names that match 'wildignore'.
8434 if (*p_wig)
8436 char_u *ffname;
8438 /* check all files in (*file)[] */
8439 for (i = 0; i < *num_file; ++i)
8441 ffname = FullName_save((*file)[i], FALSE);
8442 if (ffname == NULL) /* out of memory */
8443 break;
8444 # ifdef VMS
8445 vms_remove_version(ffname);
8446 # endif
8447 if (match_file_list(p_wig, (*file)[i], ffname))
8449 /* remove this matching file from the list */
8450 vim_free((*file)[i]);
8451 for (j = i; j + 1 < *num_file; ++j)
8452 (*file)[j] = (*file)[j + 1];
8453 --*num_file;
8454 --i;
8456 vim_free(ffname);
8459 #endif
8462 * Move the names where 'suffixes' match to the end.
8464 if (*num_file > 1)
8466 non_suf_match = 0;
8467 for (i = 0; i < *num_file; ++i)
8469 if (!match_suffix((*file)[i]))
8472 * Move the name without matching suffix to the front
8473 * of the list.
8475 p = (*file)[i];
8476 for (j = i; j > non_suf_match; --j)
8477 (*file)[j] = (*file)[j - 1];
8478 (*file)[non_suf_match++] = p;
8483 return retval;
8487 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8490 match_suffix(fname)
8491 char_u *fname;
8493 int fnamelen, setsuflen;
8494 char_u *setsuf;
8495 #define MAXSUFLEN 30 /* maximum length of a file suffix */
8496 char_u suf_buf[MAXSUFLEN];
8498 fnamelen = (int)STRLEN(fname);
8499 setsuflen = 0;
8500 for (setsuf = p_su; *setsuf; )
8502 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
8503 if (fnamelen >= setsuflen
8504 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8505 (size_t)setsuflen) == 0)
8506 break;
8507 setsuflen = 0;
8509 return (setsuflen != 0);
8512 #if !defined(NO_EXPANDPATH) || defined(PROTO)
8514 # ifdef VIM_BACKTICK
8515 static int vim_backtick __ARGS((char_u *p));
8516 static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8517 # endif
8519 # if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8521 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8522 * it's shared between these systems.
8524 # if defined(DJGPP) || defined(PROTO)
8525 # define _cdecl /* DJGPP doesn't have this */
8526 # else
8527 # ifdef __BORLANDC__
8528 # define _cdecl _RTLENTRYF
8529 # endif
8530 # endif
8533 * comparison function for qsort in dos_expandpath()
8535 static int _cdecl
8536 pstrcmp(const void *a, const void *b)
8538 return (pathcmp(*(char **)a, *(char **)b, -1));
8541 # ifndef WIN3264
8542 static void
8543 namelowcpy(
8544 char_u *d,
8545 char_u *s)
8547 # ifdef DJGPP
8548 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8549 while (*s)
8550 *d++ = *s++;
8551 else
8552 # endif
8553 while (*s)
8554 *d++ = TOLOWER_LOC(*s++);
8555 *d = NUL;
8557 # endif
8560 * Recursively expand one path component into all matching files and/or
8561 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8562 * Return the number of matches found.
8563 * "path" has backslashes before chars that are not to be expanded, starting
8564 * at "path[wildoff]".
8565 * Return the number of matches found.
8566 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
8568 static int
8569 dos_expandpath(
8570 garray_T *gap,
8571 char_u *path,
8572 int wildoff,
8573 int flags, /* EW_* flags */
8574 int didstar) /* expanded "**" once already */
8576 char_u *buf;
8577 char_u *path_end;
8578 char_u *p, *s, *e;
8579 int start_len = gap->ga_len;
8580 char_u *pat;
8581 regmatch_T regmatch;
8582 int starts_with_dot;
8583 int matches;
8584 int len;
8585 int starstar = FALSE;
8586 static int stardepth = 0; /* depth for "**" expansion */
8587 #ifdef WIN3264
8588 WIN32_FIND_DATA fb;
8589 HANDLE hFind = (HANDLE)0;
8590 # ifdef FEAT_MBYTE
8591 WIN32_FIND_DATAW wfb;
8592 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8593 # endif
8594 #else
8595 struct ffblk fb;
8596 #endif
8597 char_u *matchname;
8598 int ok;
8600 /* Expanding "**" may take a long time, check for CTRL-C. */
8601 if (stardepth > 0)
8603 ui_breakcheck();
8604 if (got_int)
8605 return 0;
8608 /* make room for file name */
8609 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8610 if (buf == NULL)
8611 return 0;
8614 * Find the first part in the path name that contains a wildcard or a ~1.
8615 * Copy it into buf, including the preceding characters.
8617 p = buf;
8618 s = buf;
8619 e = NULL;
8620 path_end = path;
8621 while (*path_end != NUL)
8623 /* May ignore a wildcard that has a backslash before it; it will
8624 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8625 if (path_end >= path + wildoff && rem_backslash(path_end))
8626 *p++ = *path_end++;
8627 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8629 if (e != NULL)
8630 break;
8631 s = p + 1;
8633 else if (path_end >= path + wildoff
8634 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8635 e = p;
8636 #ifdef FEAT_MBYTE
8637 if (has_mbyte)
8639 len = (*mb_ptr2len)(path_end);
8640 STRNCPY(p, path_end, len);
8641 p += len;
8642 path_end += len;
8644 else
8645 #endif
8646 *p++ = *path_end++;
8648 e = p;
8649 *e = NUL;
8651 /* now we have one wildcard component between s and e */
8652 /* Remove backslashes between "wildoff" and the start of the wildcard
8653 * component. */
8654 for (p = buf + wildoff; p < s; ++p)
8655 if (rem_backslash(p))
8657 mch_memmove(p, p + 1, STRLEN(p));
8658 --e;
8659 --s;
8662 /* Check for "**" between "s" and "e". */
8663 for (p = s; p < e; ++p)
8664 if (p[0] == '*' && p[1] == '*')
8665 starstar = TRUE;
8667 starts_with_dot = (*s == '.');
8668 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8669 if (pat == NULL)
8671 vim_free(buf);
8672 return 0;
8675 /* compile the regexp into a program */
8676 regmatch.rm_ic = TRUE; /* Always ignore case */
8677 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8678 vim_free(pat);
8680 if (regmatch.regprog == NULL)
8682 vim_free(buf);
8683 return 0;
8686 /* remember the pattern or file name being looked for */
8687 matchname = vim_strsave(s);
8689 /* If "**" is by itself, this is the first time we encounter it and more
8690 * is following then find matches without any directory. */
8691 if (!didstar && stardepth < 100 && starstar && e - s == 2
8692 && *path_end == '/')
8694 STRCPY(s, path_end + 1);
8695 ++stardepth;
8696 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8697 --stardepth;
8700 /* Scan all files in the directory with "dir/ *.*" */
8701 STRCPY(s, "*.*");
8702 #ifdef WIN3264
8703 # ifdef FEAT_MBYTE
8704 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8706 /* The active codepage differs from 'encoding'. Attempt using the
8707 * wide function. If it fails because it is not implemented fall back
8708 * to the non-wide version (for Windows 98) */
8709 wn = enc_to_ucs2(buf, NULL);
8710 if (wn != NULL)
8712 hFind = FindFirstFileW(wn, &wfb);
8713 if (hFind == INVALID_HANDLE_VALUE
8714 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8716 vim_free(wn);
8717 wn = NULL;
8722 if (wn == NULL)
8723 # endif
8724 hFind = FindFirstFile(buf, &fb);
8725 ok = (hFind != INVALID_HANDLE_VALUE);
8726 #else
8727 /* If we are expanding wildcards we try both files and directories */
8728 ok = (findfirst((char *)buf, &fb,
8729 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8730 #endif
8732 while (ok)
8734 #ifdef WIN3264
8735 # ifdef FEAT_MBYTE
8736 if (wn != NULL)
8737 p = ucs2_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8738 else
8739 # endif
8740 p = (char_u *)fb.cFileName;
8741 #else
8742 p = (char_u *)fb.ff_name;
8743 #endif
8744 /* Ignore entries starting with a dot, unless when asked for. Accept
8745 * all entries found with "matchname". */
8746 if ((p[0] != '.' || starts_with_dot)
8747 && (matchname == NULL
8748 || vim_regexec(&regmatch, p, (colnr_T)0)))
8750 #ifdef WIN3264
8751 STRCPY(s, p);
8752 #else
8753 namelowcpy(s, p);
8754 #endif
8755 len = (int)STRLEN(buf);
8757 if (starstar && stardepth < 100)
8759 /* For "**" in the pattern first go deeper in the tree to
8760 * find matches. */
8761 STRCPY(buf + len, "/**");
8762 STRCPY(buf + len + 3, path_end);
8763 ++stardepth;
8764 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8765 --stardepth;
8768 STRCPY(buf + len, path_end);
8769 if (mch_has_exp_wildcard(path_end))
8771 /* need to expand another component of the path */
8772 /* remove backslashes for the remaining components only */
8773 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
8775 else
8777 /* no more wildcards, check if there is a match */
8778 /* remove backslashes for the remaining components only */
8779 if (*path_end != 0)
8780 backslash_halve(buf + len + 1);
8781 if (mch_getperm(buf) >= 0) /* add existing file */
8782 addfile(gap, buf, flags);
8786 #ifdef WIN3264
8787 # ifdef FEAT_MBYTE
8788 if (wn != NULL)
8790 vim_free(p);
8791 ok = FindNextFileW(hFind, &wfb);
8793 else
8794 # endif
8795 ok = FindNextFile(hFind, &fb);
8796 #else
8797 ok = (findnext(&fb) == 0);
8798 #endif
8800 /* If no more matches and no match was used, try expanding the name
8801 * itself. Finds the long name of a short filename. */
8802 if (!ok && matchname != NULL && gap->ga_len == start_len)
8804 STRCPY(s, matchname);
8805 #ifdef WIN3264
8806 FindClose(hFind);
8807 # ifdef FEAT_MBYTE
8808 if (wn != NULL)
8810 vim_free(wn);
8811 wn = enc_to_ucs2(buf, NULL);
8812 if (wn != NULL)
8813 hFind = FindFirstFileW(wn, &wfb);
8815 if (wn == NULL)
8816 # endif
8817 hFind = FindFirstFile(buf, &fb);
8818 ok = (hFind != INVALID_HANDLE_VALUE);
8819 #else
8820 ok = (findfirst((char *)buf, &fb,
8821 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8822 #endif
8823 vim_free(matchname);
8824 matchname = NULL;
8828 #ifdef WIN3264
8829 FindClose(hFind);
8830 # ifdef FEAT_MBYTE
8831 vim_free(wn);
8832 # endif
8833 #endif
8834 vim_free(buf);
8835 vim_free(regmatch.regprog);
8836 vim_free(matchname);
8838 matches = gap->ga_len - start_len;
8839 if (matches > 0)
8840 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8841 sizeof(char_u *), pstrcmp);
8842 return matches;
8846 mch_expandpath(
8847 garray_T *gap,
8848 char_u *path,
8849 int flags) /* EW_* flags */
8851 return dos_expandpath(gap, path, 0, flags, FALSE);
8853 # endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8855 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8856 || defined(PROTO)
8858 * Unix style wildcard expansion code.
8859 * It's here because it's used both for Unix and Mac.
8861 static int pstrcmp __ARGS((const void *, const void *));
8863 static int
8864 pstrcmp(a, b)
8865 const void *a, *b;
8867 return (pathcmp(*(char **)a, *(char **)b, -1));
8871 * Recursively expand one path component into all matching files and/or
8872 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8873 * "path" has backslashes before chars that are not to be expanded, starting
8874 * at "path + wildoff".
8875 * Return the number of matches found.
8876 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8879 unix_expandpath(gap, path, wildoff, flags, didstar)
8880 garray_T *gap;
8881 char_u *path;
8882 int wildoff;
8883 int flags; /* EW_* flags */
8884 int didstar; /* expanded "**" once already */
8886 char_u *buf;
8887 char_u *path_end;
8888 char_u *p, *s, *e;
8889 int start_len = gap->ga_len;
8890 char_u *pat;
8891 regmatch_T regmatch;
8892 int starts_with_dot;
8893 int matches;
8894 int len;
8895 int starstar = FALSE;
8896 static int stardepth = 0; /* depth for "**" expansion */
8898 DIR *dirp;
8899 struct dirent *dp;
8901 /* Expanding "**" may take a long time, check for CTRL-C. */
8902 if (stardepth > 0)
8904 ui_breakcheck();
8905 if (got_int)
8906 return 0;
8909 /* make room for file name */
8910 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8911 if (buf == NULL)
8912 return 0;
8915 * Find the first part in the path name that contains a wildcard.
8916 * Copy it into "buf", including the preceding characters.
8918 p = buf;
8919 s = buf;
8920 e = NULL;
8921 path_end = path;
8922 while (*path_end != NUL)
8924 /* May ignore a wildcard that has a backslash before it; it will
8925 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8926 if (path_end >= path + wildoff && rem_backslash(path_end))
8927 *p++ = *path_end++;
8928 else if (*path_end == '/')
8930 if (e != NULL)
8931 break;
8932 s = p + 1;
8934 else if (path_end >= path + wildoff
8935 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
8936 e = p;
8937 #ifdef FEAT_MBYTE
8938 if (has_mbyte)
8940 len = (*mb_ptr2len)(path_end);
8941 STRNCPY(p, path_end, len);
8942 p += len;
8943 path_end += len;
8945 else
8946 #endif
8947 *p++ = *path_end++;
8949 e = p;
8950 *e = NUL;
8952 /* now we have one wildcard component between "s" and "e" */
8953 /* Remove backslashes between "wildoff" and the start of the wildcard
8954 * component. */
8955 for (p = buf + wildoff; p < s; ++p)
8956 if (rem_backslash(p))
8958 mch_memmove(p, p + 1, STRLEN(p));
8959 --e;
8960 --s;
8963 /* Check for "**" between "s" and "e". */
8964 for (p = s; p < e; ++p)
8965 if (p[0] == '*' && p[1] == '*')
8966 starstar = TRUE;
8968 /* convert the file pattern to a regexp pattern */
8969 starts_with_dot = (*s == '.');
8970 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8971 if (pat == NULL)
8973 vim_free(buf);
8974 return 0;
8977 /* compile the regexp into a program */
8978 #ifdef CASE_INSENSITIVE_FILENAME
8979 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
8980 #else
8981 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
8982 #endif
8983 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8984 vim_free(pat);
8986 if (regmatch.regprog == NULL)
8988 vim_free(buf);
8989 return 0;
8992 /* If "**" is by itself, this is the first time we encounter it and more
8993 * is following then find matches without any directory. */
8994 if (!didstar && stardepth < 100 && starstar && e - s == 2
8995 && *path_end == '/')
8997 STRCPY(s, path_end + 1);
8998 ++stardepth;
8999 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9000 --stardepth;
9003 /* open the directory for scanning */
9004 *s = NUL;
9005 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9007 /* Find all matching entries */
9008 if (dirp != NULL)
9010 for (;;)
9012 dp = readdir(dirp);
9013 if (dp == NULL)
9014 break;
9015 if ((dp->d_name[0] != '.' || starts_with_dot)
9016 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
9018 STRCPY(s, dp->d_name);
9019 len = STRLEN(buf);
9021 if (starstar && stardepth < 100)
9023 /* For "**" in the pattern first go deeper in the tree to
9024 * find matches. */
9025 STRCPY(buf + len, "/**");
9026 STRCPY(buf + len + 3, path_end);
9027 ++stardepth;
9028 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9029 --stardepth;
9032 STRCPY(buf + len, path_end);
9033 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9035 /* need to expand another component of the path */
9036 /* remove backslashes for the remaining components only */
9037 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9039 else
9041 /* no more wildcards, check if there is a match */
9042 /* remove backslashes for the remaining components only */
9043 if (*path_end != NUL)
9044 backslash_halve(buf + len + 1);
9045 if (mch_getperm(buf) >= 0) /* add existing file */
9047 #ifdef MACOS_CONVERT
9048 size_t precomp_len = STRLEN(buf)+1;
9049 char_u *precomp_buf =
9050 mac_precompose_path(buf, precomp_len, &precomp_len);
9052 if (precomp_buf)
9054 mch_memmove(buf, precomp_buf, precomp_len);
9055 vim_free(precomp_buf);
9057 #endif
9058 addfile(gap, buf, flags);
9064 closedir(dirp);
9067 vim_free(buf);
9068 vim_free(regmatch.regprog);
9070 matches = gap->ga_len - start_len;
9071 if (matches > 0)
9072 qsort(((char_u **)gap->ga_data) + start_len, matches,
9073 sizeof(char_u *), pstrcmp);
9074 return matches;
9076 #endif
9079 * Generic wildcard expansion code.
9081 * Characters in "pat" that should not be expanded must be preceded with a
9082 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9084 * Return FAIL when no single file was found. In this case "num_file" is not
9085 * set, and "file" may contain an error message.
9086 * Return OK when some files found. "num_file" is set to the number of
9087 * matches, "file" to the array of matches. Call FreeWild() later.
9090 gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9091 int num_pat; /* number of input patterns */
9092 char_u **pat; /* array of input patterns */
9093 int *num_file; /* resulting number of files */
9094 char_u ***file; /* array of resulting files */
9095 int flags; /* EW_* flags */
9097 int i;
9098 garray_T ga;
9099 char_u *p;
9100 static int recursive = FALSE;
9101 int add_pat;
9104 * expand_env() is called to expand things like "~user". If this fails,
9105 * it calls ExpandOne(), which brings us back here. In this case, always
9106 * call the machine specific expansion function, if possible. Otherwise,
9107 * return FAIL.
9109 if (recursive)
9110 #ifdef SPECIAL_WILDCHAR
9111 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9112 #else
9113 return FAIL;
9114 #endif
9116 #ifdef SPECIAL_WILDCHAR
9118 * If there are any special wildcard characters which we cannot handle
9119 * here, call machine specific function for all the expansion. This
9120 * avoids starting the shell for each argument separately.
9121 * For `=expr` do use the internal function.
9123 for (i = 0; i < num_pat; i++)
9125 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9126 # ifdef VIM_BACKTICK
9127 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9128 # endif
9130 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9132 #endif
9134 recursive = TRUE;
9137 * The matching file names are stored in a growarray. Init it empty.
9139 ga_init2(&ga, (int)sizeof(char_u *), 30);
9141 for (i = 0; i < num_pat; ++i)
9143 add_pat = -1;
9144 p = pat[i];
9146 #ifdef VIM_BACKTICK
9147 if (vim_backtick(p))
9148 add_pat = expand_backtick(&ga, p, flags);
9149 else
9150 #endif
9153 * First expand environment variables, "~/" and "~user/".
9155 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9157 p = expand_env_save_opt(p, TRUE);
9158 if (p == NULL)
9159 p = pat[i];
9160 #ifdef UNIX
9162 * On Unix, if expand_env() can't expand an environment
9163 * variable, use the shell to do that. Discard previously
9164 * found file names and start all over again.
9166 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9168 vim_free(p);
9169 ga_clear(&ga);
9170 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9171 flags);
9172 recursive = FALSE;
9173 return i;
9175 #endif
9179 * If there are wildcards: Expand file names and add each match to
9180 * the list. If there is no match, and EW_NOTFOUND is given, add
9181 * the pattern.
9182 * If there are no wildcards: Add the file name if it exists or
9183 * when EW_NOTFOUND is given.
9185 if (mch_has_exp_wildcard(p))
9186 add_pat = mch_expandpath(&ga, p, flags);
9189 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9191 char_u *t = backslash_halve_save(p);
9193 #if defined(MACOS_CLASSIC)
9194 slash_to_colon(t);
9195 #endif
9196 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9197 * "vim c:/" work. */
9198 if (flags & EW_NOTFOUND)
9199 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9200 else if (mch_getperm(t) >= 0)
9201 addfile(&ga, t, flags);
9202 vim_free(t);
9205 if (p != pat[i])
9206 vim_free(p);
9209 *num_file = ga.ga_len;
9210 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9212 recursive = FALSE;
9214 return (ga.ga_data != NULL) ? OK : FAIL;
9217 # ifdef VIM_BACKTICK
9220 * Return TRUE if we can expand this backtick thing here.
9222 static int
9223 vim_backtick(p)
9224 char_u *p;
9226 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9230 * Expand an item in `backticks` by executing it as a command.
9231 * Currently only works when pat[] starts and ends with a `.
9232 * Returns number of file names found.
9234 static int
9235 expand_backtick(gap, pat, flags)
9236 garray_T *gap;
9237 char_u *pat;
9238 int flags; /* EW_* flags */
9240 char_u *p;
9241 char_u *cmd;
9242 char_u *buffer;
9243 int cnt = 0;
9244 int i;
9246 /* Create the command: lop off the backticks. */
9247 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9248 if (cmd == NULL)
9249 return 0;
9251 #ifdef FEAT_EVAL
9252 if (*cmd == '=') /* `={expr}`: Expand expression */
9253 buffer = eval_to_string(cmd + 1, &p, TRUE);
9254 else
9255 #endif
9256 buffer = get_cmd_output(cmd, NULL,
9257 (flags & EW_SILENT) ? SHELL_SILENT : 0);
9258 vim_free(cmd);
9259 if (buffer == NULL)
9260 return 0;
9262 cmd = buffer;
9263 while (*cmd != NUL)
9265 cmd = skipwhite(cmd); /* skip over white space */
9266 p = cmd;
9267 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9268 ++p;
9269 /* add an entry if it is not empty */
9270 if (p > cmd)
9272 i = *p;
9273 *p = NUL;
9274 addfile(gap, cmd, flags);
9275 *p = i;
9276 ++cnt;
9278 cmd = p;
9279 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9280 ++cmd;
9283 vim_free(buffer);
9284 return cnt;
9286 # endif /* VIM_BACKTICK */
9289 * Add a file to a file list. Accepted flags:
9290 * EW_DIR add directories
9291 * EW_FILE add files
9292 * EW_EXEC add executable files
9293 * EW_NOTFOUND add even when it doesn't exist
9294 * EW_ADDSLASH add slash after directory name
9296 void
9297 addfile(gap, f, flags)
9298 garray_T *gap;
9299 char_u *f; /* filename */
9300 int flags;
9302 char_u *p;
9303 int isdir;
9305 /* if the file/dir doesn't exist, may not add it */
9306 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9307 return;
9309 #ifdef FNAME_ILLEGAL
9310 /* if the file/dir contains illegal characters, don't add it */
9311 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9312 return;
9313 #endif
9315 isdir = mch_isdir(f);
9316 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9317 return;
9319 /* If the file isn't executable, may not add it. Do accept directories. */
9320 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9321 return;
9323 /* Make room for another item in the file list. */
9324 if (ga_grow(gap, 1) == FAIL)
9325 return;
9327 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9328 if (p == NULL)
9329 return;
9331 STRCPY(p, f);
9332 #ifdef BACKSLASH_IN_FILENAME
9333 slash_adjust(p);
9334 #endif
9336 * Append a slash or backslash after directory names if none is present.
9338 #ifndef DONT_ADD_PATHSEP_TO_DIR
9339 if (isdir && (flags & EW_ADDSLASH))
9340 add_pathsep(p);
9341 #endif
9342 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
9344 #endif /* !NO_EXPANDPATH */
9346 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9348 #ifndef SEEK_SET
9349 # define SEEK_SET 0
9350 #endif
9351 #ifndef SEEK_END
9352 # define SEEK_END 2
9353 #endif
9356 * Get the stdout of an external command.
9357 * Returns an allocated string, or NULL for error.
9359 char_u *
9360 get_cmd_output(cmd, infile, flags)
9361 char_u *cmd;
9362 char_u *infile; /* optional input file name */
9363 int flags; /* can be SHELL_SILENT */
9365 char_u *tempname;
9366 char_u *command;
9367 char_u *buffer = NULL;
9368 int len;
9369 int i = 0;
9370 FILE *fd;
9372 if (check_restricted() || check_secure())
9373 return NULL;
9375 /* get a name for the temp file */
9376 if ((tempname = vim_tempname('o')) == NULL)
9378 EMSG(_(e_notmp));
9379 return NULL;
9382 /* Add the redirection stuff */
9383 command = make_filter_cmd(cmd, infile, tempname);
9384 if (command == NULL)
9385 goto done;
9388 * Call the shell to execute the command (errors are ignored).
9389 * Don't check timestamps here.
9391 ++no_check_timestamps;
9392 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9393 --no_check_timestamps;
9395 vim_free(command);
9398 * read the names from the file into memory
9400 # ifdef VMS
9401 /* created temporary file is not always readable as binary */
9402 fd = mch_fopen((char *)tempname, "r");
9403 # else
9404 fd = mch_fopen((char *)tempname, READBIN);
9405 # endif
9407 if (fd == NULL)
9409 EMSG2(_(e_notopen), tempname);
9410 goto done;
9413 fseek(fd, 0L, SEEK_END);
9414 len = ftell(fd); /* get size of temp file */
9415 fseek(fd, 0L, SEEK_SET);
9417 buffer = alloc(len + 1);
9418 if (buffer != NULL)
9419 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9420 fclose(fd);
9421 mch_remove(tempname);
9422 if (buffer == NULL)
9423 goto done;
9424 #ifdef VMS
9425 len = i; /* VMS doesn't give us what we asked for... */
9426 #endif
9427 if (i != len)
9429 EMSG2(_(e_notread), tempname);
9430 vim_free(buffer);
9431 buffer = NULL;
9433 else
9434 buffer[len] = '\0'; /* make sure the buffer is terminated */
9436 done:
9437 vim_free(tempname);
9438 return buffer;
9440 #endif
9443 * Free the list of files returned by expand_wildcards() or other expansion
9444 * functions.
9446 void
9447 FreeWild(count, files)
9448 int count;
9449 char_u **files;
9451 if (count <= 0 || files == NULL)
9452 return;
9453 #if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9455 * Is this still OK for when other functions than expand_wildcards() have
9456 * been used???
9458 _fnexplodefree((char **)files);
9459 #else
9460 while (count--)
9461 vim_free(files[count]);
9462 vim_free(files);
9463 #endif
9467 * return TRUE when need to go to Insert mode because of 'insertmode'.
9468 * Don't do this when still processing a command or a mapping.
9469 * Don't do this when inside a ":normal" command.
9472 goto_im()
9474 return (p_im && stuff_empty() && typebuf_typed());