Merged from the latest developing branch.
[MacVim/jjgod.git] / src / misc1.c
blobd9505046b7e317047d5947b6a91183a8004da1e3
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 = 0; /* number of initial whitespace chars when
108 'et' and 'pi' are both set */
111 * First check if there is anything to do and compute the number of
112 * characters needed for the indent.
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 == 0)
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 != 0)
211 newline = alloc(orig_char_len + size - ind_done + line_len);
212 if (newline == NULL)
213 return FALSE;
214 p = oldline;
215 s = newline;
216 while (orig_char_len > 0)
218 *s++ = *p++;
219 orig_char_len--;
221 /* Skip over any additional white space (useful when newindent is less
222 * than old) */
223 while (vim_iswhite(*p))
224 (void)*p++;
225 todo = size - ind_done;
226 ind_len += todo; /* Set total length of indent in characters,
227 * which may have been undercounted until now */
230 else
232 todo = size;
233 newline = alloc(ind_len + line_len);
234 if (newline == NULL)
235 return FALSE;
236 s = newline;
239 /* Put the characters in the new line. */
240 /* if 'expandtab' isn't set: use TABs */
241 if (!curbuf->b_p_et)
243 /* If 'preserveindent' is set then reuse as much as possible of
244 * the existing indent structure for the new indent */
245 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
247 p = oldline;
248 ind_done = 0;
250 while (todo > 0 && vim_iswhite(*p))
252 if (*p == TAB)
254 tab_pad = (int)curbuf->b_p_ts
255 - (ind_done % (int)curbuf->b_p_ts);
256 /* stop if this tab will overshoot the target */
257 if (todo < tab_pad)
258 break;
259 todo -= tab_pad;
260 ind_done += tab_pad;
262 else
264 --todo;
265 ++ind_done;
267 *s++ = *p++;
270 /* Fill to next tabstop with a tab, if possible */
271 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
272 if (todo >= tab_pad)
274 *s++ = TAB;
275 todo -= tab_pad;
278 p = skipwhite(p);
281 while (todo >= (int)curbuf->b_p_ts)
283 *s++ = TAB;
284 todo -= (int)curbuf->b_p_ts;
287 while (todo > 0)
289 *s++ = ' ';
290 --todo;
292 mch_memmove(s, p, (size_t)line_len);
294 /* Replace the line (unless undo fails). */
295 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
297 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
298 if (flags & SIN_CHANGED)
299 changed_bytes(curwin->w_cursor.lnum, 0);
300 /* Correct saved cursor position if it's after the indent. */
301 if (saved_cursor.lnum == curwin->w_cursor.lnum
302 && saved_cursor.col >= (colnr_T)(p - oldline))
303 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
304 retval = TRUE;
306 else
307 vim_free(newline);
309 curwin->w_cursor.col = ind_len;
310 return retval;
314 * Copy the indent from ptr to the current line (and fill to size)
315 * Leaves the cursor on the first non-blank in the line.
316 * Returns TRUE if the line was changed.
318 static int
319 copy_indent(size, src)
320 int size;
321 char_u *src;
323 char_u *p = NULL;
324 char_u *line = NULL;
325 char_u *s;
326 int todo;
327 int ind_len;
328 int line_len = 0;
329 int tab_pad;
330 int ind_done;
331 int round;
333 /* Round 1: compute the number of characters needed for the indent
334 * Round 2: copy the characters. */
335 for (round = 1; round <= 2; ++round)
337 todo = size;
338 ind_len = 0;
339 ind_done = 0;
340 s = src;
342 /* Count/copy the usable portion of the source line */
343 while (todo > 0 && vim_iswhite(*s))
345 if (*s == TAB)
347 tab_pad = (int)curbuf->b_p_ts
348 - (ind_done % (int)curbuf->b_p_ts);
349 /* Stop if this tab will overshoot the target */
350 if (todo < tab_pad)
351 break;
352 todo -= tab_pad;
353 ind_done += tab_pad;
355 else
357 --todo;
358 ++ind_done;
360 ++ind_len;
361 if (p != NULL)
362 *p++ = *s;
363 ++s;
366 /* Fill to next tabstop with a tab, if possible */
367 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
368 if (todo >= tab_pad)
370 todo -= tab_pad;
371 ++ind_len;
372 if (p != NULL)
373 *p++ = TAB;
376 /* Add tabs required for indent */
377 while (todo >= (int)curbuf->b_p_ts)
379 todo -= (int)curbuf->b_p_ts;
380 ++ind_len;
381 if (p != NULL)
382 *p++ = TAB;
385 /* Count/add spaces required for indent */
386 while (todo > 0)
388 --todo;
389 ++ind_len;
390 if (p != NULL)
391 *p++ = ' ';
394 if (p == NULL)
396 /* Allocate memory for the result: the copied indent, new indent
397 * and the rest of the line. */
398 line_len = (int)STRLEN(ml_get_curline()) + 1;
399 line = alloc(ind_len + line_len);
400 if (line == NULL)
401 return FALSE;
402 p = line;
406 /* Append the original line */
407 mch_memmove(p, ml_get_curline(), (size_t)line_len);
409 /* Replace the line */
410 ml_replace(curwin->w_cursor.lnum, line, FALSE);
412 /* Put the cursor after the indent. */
413 curwin->w_cursor.col = ind_len;
414 return TRUE;
418 * Return the indent of the current line after a number. Return -1 if no
419 * number was found. Used for 'n' in 'formatoptions': numbered list.
420 * Since a pattern is used it can actually handle more than numbers.
423 get_number_indent(lnum)
424 linenr_T lnum;
426 colnr_T col;
427 pos_T pos;
428 regmmatch_T regmatch;
430 if (lnum > curbuf->b_ml.ml_line_count)
431 return -1;
432 pos.lnum = 0;
433 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
434 if (regmatch.regprog != NULL)
436 regmatch.rmm_ic = FALSE;
437 regmatch.rmm_maxcol = 0;
438 if (vim_regexec_multi(&regmatch, curwin, curbuf, lnum, (colnr_T)0))
440 pos.lnum = regmatch.endpos[0].lnum + lnum;
441 pos.col = regmatch.endpos[0].col;
442 #ifdef FEAT_VIRTUALEDIT
443 pos.coladd = 0;
444 #endif
446 vim_free(regmatch.regprog);
449 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
450 return -1;
451 getvcol(curwin, &pos, &col, NULL, NULL);
452 return (int)col;
455 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
457 static int cin_is_cinword __ARGS((char_u *line));
460 * Return TRUE if the string "line" starts with a word from 'cinwords'.
462 static int
463 cin_is_cinword(line)
464 char_u *line;
466 char_u *cinw;
467 char_u *cinw_buf;
468 int cinw_len;
469 int retval = FALSE;
470 int len;
472 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
473 cinw_buf = alloc((unsigned)cinw_len);
474 if (cinw_buf != NULL)
476 line = skipwhite(line);
477 for (cinw = curbuf->b_p_cinw; *cinw; )
479 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
480 if (STRNCMP(line, cinw_buf, len) == 0
481 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
483 retval = TRUE;
484 break;
487 vim_free(cinw_buf);
489 return retval;
491 #endif
494 * open_line: Add a new line below or above the current line.
496 * For VREPLACE mode, we only add a new line when we get to the end of the
497 * file, otherwise we just start replacing the next line.
499 * Caller must take care of undo. Since VREPLACE may affect any number of
500 * lines however, it may call u_save_cursor() again when starting to change a
501 * new line.
502 * "flags": OPENLINE_DELSPACES delete spaces after cursor
503 * OPENLINE_DO_COM format comments
504 * OPENLINE_KEEPTRAIL keep trailing spaces
505 * OPENLINE_MARKFIX adjust mark positions after the line break
507 * Return TRUE for success, FALSE for failure
510 open_line(dir, flags, old_indent)
511 int dir; /* FORWARD or BACKWARD */
512 int flags;
513 int old_indent; /* indent for after ^^D in Insert mode */
515 char_u *saved_line; /* copy of the original line */
516 char_u *next_line = NULL; /* copy of the next line */
517 char_u *p_extra = NULL; /* what goes to next line */
518 int less_cols = 0; /* less columns for mark in new line */
519 int less_cols_off = 0; /* columns to skip for mark adjust */
520 pos_T old_cursor; /* old cursor position */
521 int newcol = 0; /* new cursor column */
522 int newindent = 0; /* auto-indent of the new line */
523 int n;
524 int trunc_line = FALSE; /* truncate current line afterwards */
525 int retval = FALSE; /* return value, default is FAIL */
526 #ifdef FEAT_COMMENTS
527 int extra_len = 0; /* length of p_extra string */
528 int lead_len; /* length of comment leader */
529 char_u *lead_flags; /* position in 'comments' for comment leader */
530 char_u *leader = NULL; /* copy of comment leader */
531 #endif
532 char_u *allocated = NULL; /* allocated memory */
533 #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
534 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
535 char_u *p;
536 #endif
537 int saved_char = NUL; /* init for GCC */
538 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
539 pos_T *pos;
540 #endif
541 #ifdef FEAT_SMARTINDENT
542 int do_si = (!p_paste && curbuf->b_p_si
543 # ifdef FEAT_CINDENT
544 && !curbuf->b_p_cin
545 # endif
547 int no_si = FALSE; /* reset did_si afterwards */
548 int first_char = NUL; /* init for GCC */
549 #endif
550 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
551 int vreplace_mode;
552 #endif
553 int did_append; /* appended a new line */
554 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
557 * make a copy of the current line so we can mess with it
559 saved_line = vim_strsave(ml_get_curline());
560 if (saved_line == NULL) /* out of memory! */
561 return FALSE;
563 #ifdef FEAT_VREPLACE
564 if (State & VREPLACE_FLAG)
567 * With VREPLACE we make a copy of the next line, which we will be
568 * starting to replace. First make the new line empty and let vim play
569 * with the indenting and comment leader to its heart's content. Then
570 * we grab what it ended up putting on the new line, put back the
571 * original line, and call ins_char() to put each new character onto
572 * the line, replacing what was there before and pushing the right
573 * stuff onto the replace stack. -- webb.
575 if (curwin->w_cursor.lnum < orig_line_count)
576 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
577 else
578 next_line = vim_strsave((char_u *)"");
579 if (next_line == NULL) /* out of memory! */
580 goto theend;
583 * In VREPLACE mode, a NL replaces the rest of the line, and starts
584 * replacing the next line, so push all of the characters left on the
585 * line onto the replace stack. We'll push any other characters that
586 * might be replaced at the start of the next line (due to autoindent
587 * etc) a bit later.
589 replace_push(NUL); /* Call twice because BS over NL expects it */
590 replace_push(NUL);
591 p = saved_line + curwin->w_cursor.col;
592 while (*p != NUL)
593 replace_push(*p++);
594 saved_line[curwin->w_cursor.col] = NUL;
596 #endif
598 if ((State & INSERT)
599 #ifdef FEAT_VREPLACE
600 && !(State & VREPLACE_FLAG)
601 #endif
604 p_extra = saved_line + curwin->w_cursor.col;
605 #ifdef FEAT_SMARTINDENT
606 if (do_si) /* need first char after new line break */
608 p = skipwhite(p_extra);
609 first_char = *p;
611 #endif
612 #ifdef FEAT_COMMENTS
613 extra_len = (int)STRLEN(p_extra);
614 #endif
615 saved_char = *p_extra;
616 *p_extra = NUL;
619 u_clearline(); /* cannot do "U" command when adding lines */
620 #ifdef FEAT_SMARTINDENT
621 did_si = FALSE;
622 #endif
623 ai_col = 0;
626 * If we just did an auto-indent, then we didn't type anything on
627 * the prior line, and it should be truncated. Do this even if 'ai' is not
628 * set because automatically inserting a comment leader also sets did_ai.
630 if (dir == FORWARD && did_ai)
631 trunc_line = TRUE;
634 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
635 * indent to use for the new line.
637 if (curbuf->b_p_ai
638 #ifdef FEAT_SMARTINDENT
639 || do_si
640 #endif
644 * count white space on current line
646 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
647 if (newindent == 0)
648 newindent = old_indent; /* for ^^D command in insert mode */
650 #ifdef FEAT_SMARTINDENT
652 * Do smart indenting.
653 * In insert/replace mode (only when dir == FORWARD)
654 * we may move some text to the next line. If it starts with '{'
655 * don't add an indent. Fixes inserting a NL before '{' in line
656 * "if (condition) {"
658 if (!trunc_line && do_si && *saved_line != NUL
659 && (p_extra == NULL || first_char != '{'))
661 char_u *ptr;
662 char_u last_char;
664 old_cursor = curwin->w_cursor;
665 ptr = saved_line;
666 # ifdef FEAT_COMMENTS
667 if (flags & OPENLINE_DO_COM)
668 lead_len = get_leader_len(ptr, NULL, FALSE);
669 else
670 lead_len = 0;
671 # endif
672 if (dir == FORWARD)
675 * Skip preprocessor directives, unless they are
676 * recognised as comments.
678 if (
679 # ifdef FEAT_COMMENTS
680 lead_len == 0 &&
681 # endif
682 ptr[0] == '#')
684 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
685 ptr = ml_get(--curwin->w_cursor.lnum);
686 newindent = get_indent();
688 # ifdef FEAT_COMMENTS
689 if (flags & OPENLINE_DO_COM)
690 lead_len = get_leader_len(ptr, NULL, FALSE);
691 else
692 lead_len = 0;
693 if (lead_len > 0)
696 * This case gets the following right:
697 * \*
698 * * A comment (read '\' as '/').
699 * *\
700 * #define IN_THE_WAY
701 * This should line up here;
703 p = skipwhite(ptr);
704 if (p[0] == '/' && p[1] == '*')
705 p++;
706 if (p[0] == '*')
708 for (p++; *p; p++)
710 if (p[0] == '/' && p[-1] == '*')
713 * End of C comment, indent should line up
714 * with the line containing the start of
715 * the comment
717 curwin->w_cursor.col = (colnr_T)(p - ptr);
718 if ((pos = findmatch(NULL, NUL)) != NULL)
720 curwin->w_cursor.lnum = pos->lnum;
721 newindent = get_indent();
727 else /* Not a comment line */
728 # endif
730 /* Find last non-blank in line */
731 p = ptr + STRLEN(ptr) - 1;
732 while (p > ptr && vim_iswhite(*p))
733 --p;
734 last_char = *p;
737 * find the character just before the '{' or ';'
739 if (last_char == '{' || last_char == ';')
741 if (p > ptr)
742 --p;
743 while (p > ptr && vim_iswhite(*p))
744 --p;
747 * Try to catch lines that are split over multiple
748 * lines. eg:
749 * if (condition &&
750 * condition) {
751 * Should line up here!
754 if (*p == ')')
756 curwin->w_cursor.col = (colnr_T)(p - ptr);
757 if ((pos = findmatch(NULL, '(')) != NULL)
759 curwin->w_cursor.lnum = pos->lnum;
760 newindent = get_indent();
761 ptr = ml_get_curline();
765 * If last character is '{' do indent, without
766 * checking for "if" and the like.
768 if (last_char == '{')
770 did_si = TRUE; /* do indent */
771 no_si = TRUE; /* don't delete it when '{' typed */
774 * Look for "if" and the like, use 'cinwords'.
775 * Don't do this if the previous line ended in ';' or
776 * '}'.
778 else if (last_char != ';' && last_char != '}'
779 && cin_is_cinword(ptr))
780 did_si = TRUE;
783 else /* dir == BACKWARD */
786 * Skip preprocessor directives, unless they are
787 * recognised as comments.
789 if (
790 # ifdef FEAT_COMMENTS
791 lead_len == 0 &&
792 # endif
793 ptr[0] == '#')
795 int was_backslashed = FALSE;
797 while ((ptr[0] == '#' || was_backslashed) &&
798 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
800 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
801 was_backslashed = TRUE;
802 else
803 was_backslashed = FALSE;
804 ptr = ml_get(++curwin->w_cursor.lnum);
806 if (was_backslashed)
807 newindent = 0; /* Got to end of file */
808 else
809 newindent = get_indent();
811 p = skipwhite(ptr);
812 if (*p == '}') /* if line starts with '}': do indent */
813 did_si = TRUE;
814 else /* can delete indent when '{' typed */
815 can_si_back = TRUE;
817 curwin->w_cursor = old_cursor;
819 if (do_si)
820 can_si = TRUE;
821 #endif /* FEAT_SMARTINDENT */
823 did_ai = TRUE;
826 #ifdef FEAT_COMMENTS
828 * Find out if the current line starts with a comment leader.
829 * This may then be inserted in front of the new line.
831 end_comment_pending = NUL;
832 if (flags & OPENLINE_DO_COM)
833 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD);
834 else
835 lead_len = 0;
836 if (lead_len > 0)
838 char_u *lead_repl = NULL; /* replaces comment leader */
839 int lead_repl_len = 0; /* length of *lead_repl */
840 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
841 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
842 char_u *comment_end = NULL; /* where lead_end has been found */
843 int extra_space = FALSE; /* append extra space */
844 int current_flag;
845 int require_blank = FALSE; /* requires blank after middle */
846 char_u *p2;
849 * If the comment leader has the start, middle or end flag, it may not
850 * be used or may be replaced with the middle leader.
852 for (p = lead_flags; *p && *p != ':'; ++p)
854 if (*p == COM_BLANK)
856 require_blank = TRUE;
857 continue;
859 if (*p == COM_START || *p == COM_MIDDLE)
861 current_flag = *p;
862 if (*p == COM_START)
865 * Doing "O" on a start of comment does not insert leader.
867 if (dir == BACKWARD)
869 lead_len = 0;
870 break;
873 /* find start of middle part */
874 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
875 require_blank = FALSE;
879 * Isolate the strings of the middle and end leader.
881 while (*p && p[-1] != ':') /* find end of middle flags */
883 if (*p == COM_BLANK)
884 require_blank = TRUE;
885 ++p;
887 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
889 while (*p && p[-1] != ':') /* find end of end flags */
891 /* Check whether we allow automatic ending of comments */
892 if (*p == COM_AUTO_END)
893 end_comment_pending = -1; /* means we want to set it */
894 ++p;
896 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
898 if (end_comment_pending == -1) /* we can set it now */
899 end_comment_pending = lead_end[n - 1];
902 * If the end of the comment is in the same line, don't use
903 * the comment leader.
905 if (dir == FORWARD)
907 for (p = saved_line + lead_len; *p; ++p)
908 if (STRNCMP(p, lead_end, n) == 0)
910 comment_end = p;
911 lead_len = 0;
912 break;
917 * Doing "o" on a start of comment inserts the middle leader.
919 if (lead_len > 0)
921 if (current_flag == COM_START)
923 lead_repl = lead_middle;
924 lead_repl_len = (int)STRLEN(lead_middle);
928 * If we have hit RETURN immediately after the start
929 * comment leader, then put a space after the middle
930 * comment leader on the next line.
932 if (!vim_iswhite(saved_line[lead_len - 1])
933 && ((p_extra != NULL
934 && (int)curwin->w_cursor.col == lead_len)
935 || (p_extra == NULL
936 && saved_line[lead_len] == NUL)
937 || require_blank))
938 extra_space = TRUE;
940 break;
942 if (*p == COM_END)
945 * Doing "o" on the end of a comment does not insert leader.
946 * Remember where the end is, might want to use it to find the
947 * start (for C-comments).
949 if (dir == FORWARD)
951 comment_end = skipwhite(saved_line);
952 lead_len = 0;
953 break;
957 * Doing "O" on the end of a comment inserts the middle leader.
958 * Find the string for the middle leader, searching backwards.
960 while (p > curbuf->b_p_com && *p != ',')
961 --p;
962 for (lead_repl = p; lead_repl > curbuf->b_p_com
963 && lead_repl[-1] != ':'; --lead_repl)
965 lead_repl_len = (int)(p - lead_repl);
967 /* We can probably always add an extra space when doing "O" on
968 * the comment-end */
969 extra_space = TRUE;
971 /* Check whether we allow automatic ending of comments */
972 for (p2 = p; *p2 && *p2 != ':'; p2++)
974 if (*p2 == COM_AUTO_END)
975 end_comment_pending = -1; /* means we want to set it */
977 if (end_comment_pending == -1)
979 /* Find last character in end-comment string */
980 while (*p2 && *p2 != ',')
981 p2++;
982 end_comment_pending = p2[-1];
984 break;
986 if (*p == COM_FIRST)
989 * Comment leader for first line only: Don't repeat leader
990 * when using "O", blank out leader when using "o".
992 if (dir == BACKWARD)
993 lead_len = 0;
994 else
996 lead_repl = (char_u *)"";
997 lead_repl_len = 0;
999 break;
1002 if (lead_len)
1004 /* allocate buffer (may concatenate p_exta later) */
1005 leader = alloc(lead_len + lead_repl_len + extra_space +
1006 extra_len + 1);
1007 allocated = leader; /* remember to free it later */
1009 if (leader == NULL)
1010 lead_len = 0;
1011 else
1013 vim_strncpy(leader, saved_line, lead_len);
1016 * Replace leader with lead_repl, right or left adjusted
1018 if (lead_repl != NULL)
1020 int c = 0;
1021 int off = 0;
1023 for (p = lead_flags; *p && *p != ':'; ++p)
1025 if (*p == COM_RIGHT || *p == COM_LEFT)
1026 c = *p;
1027 else if (VIM_ISDIGIT(*p) || *p == '-')
1028 off = getdigits(&p);
1030 if (c == COM_RIGHT) /* right adjusted leader */
1032 /* find last non-white in the leader to line up with */
1033 for (p = leader + lead_len - 1; p > leader
1034 && vim_iswhite(*p); --p)
1036 ++p;
1038 #ifdef FEAT_MBYTE
1039 /* Compute the length of the replaced characters in
1040 * screen characters, not bytes. */
1042 int repl_size = vim_strnsize(lead_repl,
1043 lead_repl_len);
1044 int old_size = 0;
1045 char_u *endp = p;
1046 int l;
1048 while (old_size < repl_size && p > leader)
1050 mb_ptr_back(leader, p);
1051 old_size += ptr2cells(p);
1053 l = lead_repl_len - (int)(endp - p);
1054 if (l != 0)
1055 mch_memmove(endp + l, endp,
1056 (size_t)((leader + lead_len) - endp));
1057 lead_len += l;
1059 #else
1060 if (p < leader + lead_repl_len)
1061 p = leader;
1062 else
1063 p -= lead_repl_len;
1064 #endif
1065 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1066 if (p + lead_repl_len > leader + lead_len)
1067 p[lead_repl_len] = NUL;
1069 /* blank-out any other chars from the old leader. */
1070 while (--p >= leader)
1072 #ifdef FEAT_MBYTE
1073 int l = mb_head_off(leader, p);
1075 if (l > 1)
1077 p -= l;
1078 if (ptr2cells(p) > 1)
1080 p[1] = ' ';
1081 --l;
1083 mch_memmove(p + 1, p + l + 1,
1084 (size_t)((leader + lead_len) - (p + l + 1)));
1085 lead_len -= l;
1086 *p = ' ';
1088 else
1089 #endif
1090 if (!vim_iswhite(*p))
1091 *p = ' ';
1094 else /* left adjusted leader */
1096 p = skipwhite(leader);
1097 #ifdef FEAT_MBYTE
1098 /* Compute the length of the replaced characters in
1099 * screen characters, not bytes. Move the part that is
1100 * not to be overwritten. */
1102 int repl_size = vim_strnsize(lead_repl,
1103 lead_repl_len);
1104 int i;
1105 int l;
1107 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1109 l = (*mb_ptr2len)(p + i);
1110 if (vim_strnsize(p, i + l) > repl_size)
1111 break;
1113 if (i != lead_repl_len)
1115 mch_memmove(p + lead_repl_len, p + i,
1116 (size_t)(lead_len - i - (leader - p)));
1117 lead_len += lead_repl_len - i;
1120 #endif
1121 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1123 /* Replace any remaining non-white chars in the old
1124 * leader by spaces. Keep Tabs, the indent must
1125 * remain the same. */
1126 for (p += lead_repl_len; p < leader + lead_len; ++p)
1127 if (!vim_iswhite(*p))
1129 /* Don't put a space before a TAB. */
1130 if (p + 1 < leader + lead_len && p[1] == TAB)
1132 --lead_len;
1133 mch_memmove(p, p + 1,
1134 (leader + lead_len) - p);
1136 else
1138 #ifdef FEAT_MBYTE
1139 int l = (*mb_ptr2len)(p);
1141 if (l > 1)
1143 if (ptr2cells(p) > 1)
1145 /* Replace a double-wide char with
1146 * two spaces */
1147 --l;
1148 *p++ = ' ';
1150 mch_memmove(p + 1, p + l,
1151 (leader + lead_len) - p);
1152 lead_len -= l - 1;
1154 #endif
1155 *p = ' ';
1158 *p = NUL;
1161 /* Recompute the indent, it may have changed. */
1162 if (curbuf->b_p_ai
1163 #ifdef FEAT_SMARTINDENT
1164 || do_si
1165 #endif
1167 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1169 /* Add the indent offset */
1170 if (newindent + off < 0)
1172 off = -newindent;
1173 newindent = 0;
1175 else
1176 newindent += off;
1178 /* Correct trailing spaces for the shift, so that
1179 * alignment remains equal. */
1180 while (off > 0 && lead_len > 0
1181 && leader[lead_len - 1] == ' ')
1183 /* Don't do it when there is a tab before the space */
1184 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1185 break;
1186 --lead_len;
1187 --off;
1190 /* If the leader ends in white space, don't add an
1191 * extra space */
1192 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1193 extra_space = FALSE;
1194 leader[lead_len] = NUL;
1197 if (extra_space)
1199 leader[lead_len++] = ' ';
1200 leader[lead_len] = NUL;
1203 newcol = lead_len;
1206 * if a new indent will be set below, remove the indent that
1207 * is in the comment leader
1209 if (newindent
1210 #ifdef FEAT_SMARTINDENT
1211 || did_si
1212 #endif
1215 while (lead_len && vim_iswhite(*leader))
1217 --lead_len;
1218 --newcol;
1219 ++leader;
1224 #ifdef FEAT_SMARTINDENT
1225 did_si = can_si = FALSE;
1226 #endif
1228 else if (comment_end != NULL)
1231 * We have finished a comment, so we don't use the leader.
1232 * If this was a C-comment and 'ai' or 'si' is set do a normal
1233 * indent to align with the line containing the start of the
1234 * comment.
1236 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1237 (curbuf->b_p_ai
1238 #ifdef FEAT_SMARTINDENT
1239 || do_si
1240 #endif
1243 old_cursor = curwin->w_cursor;
1244 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1245 if ((pos = findmatch(NULL, NUL)) != NULL)
1247 curwin->w_cursor.lnum = pos->lnum;
1248 newindent = get_indent();
1250 curwin->w_cursor = old_cursor;
1254 #endif
1256 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1257 if (p_extra != NULL)
1259 *p_extra = saved_char; /* restore char that NUL replaced */
1262 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1263 * non-blank.
1265 * When in REPLACE mode, put the deleted blanks on the replace stack,
1266 * preceded by a NUL, so they can be put back when a BS is entered.
1268 if (REPLACE_NORMAL(State))
1269 replace_push(NUL); /* end of extra blanks */
1270 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1272 while ((*p_extra == ' ' || *p_extra == '\t')
1273 #ifdef FEAT_MBYTE
1274 && (!enc_utf8
1275 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1276 #endif
1279 if (REPLACE_NORMAL(State))
1280 replace_push(*p_extra);
1281 ++p_extra;
1282 ++less_cols_off;
1285 if (*p_extra != NUL)
1286 did_ai = FALSE; /* append some text, don't truncate now */
1288 /* columns for marks adjusted for removed columns */
1289 less_cols = (int)(p_extra - saved_line);
1292 if (p_extra == NULL)
1293 p_extra = (char_u *)""; /* append empty line */
1295 #ifdef FEAT_COMMENTS
1296 /* concatenate leader and p_extra, if there is a leader */
1297 if (lead_len)
1299 STRCAT(leader, p_extra);
1300 p_extra = leader;
1301 did_ai = TRUE; /* So truncating blanks works with comments */
1302 less_cols -= lead_len;
1304 else
1305 end_comment_pending = NUL; /* turns out there was no leader */
1306 #endif
1308 old_cursor = curwin->w_cursor;
1309 if (dir == BACKWARD)
1310 --curwin->w_cursor.lnum;
1311 #ifdef FEAT_VREPLACE
1312 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1313 #endif
1315 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1316 == FAIL)
1317 goto theend;
1318 /* Postpone calling changed_lines(), because it would mess up folding
1319 * with markers. */
1320 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1321 did_append = TRUE;
1323 #ifdef FEAT_VREPLACE
1324 else
1327 * In VREPLACE mode we are starting to replace the next line.
1329 curwin->w_cursor.lnum++;
1330 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1332 /* In case we NL to a new line, BS to the previous one, and NL
1333 * again, we don't want to save the new line for undo twice.
1335 (void)u_save_cursor(); /* errors are ignored! */
1336 vr_lines_changed++;
1338 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1339 changed_bytes(curwin->w_cursor.lnum, 0);
1340 curwin->w_cursor.lnum--;
1341 did_append = FALSE;
1343 #endif
1345 if (newindent
1346 #ifdef FEAT_SMARTINDENT
1347 || did_si
1348 #endif
1351 ++curwin->w_cursor.lnum;
1352 #ifdef FEAT_SMARTINDENT
1353 if (did_si)
1355 if (p_sr)
1356 newindent -= newindent % (int)curbuf->b_p_sw;
1357 newindent += (int)curbuf->b_p_sw;
1359 #endif
1360 /* Copy the indent */
1361 if (curbuf->b_p_ci)
1363 (void)copy_indent(newindent, saved_line);
1366 * Set the 'preserveindent' option so that any further screwing
1367 * with the line doesn't entirely destroy our efforts to preserve
1368 * it. It gets restored at the function end.
1370 curbuf->b_p_pi = TRUE;
1372 else
1373 (void)set_indent(newindent, SIN_INSERT);
1374 less_cols -= curwin->w_cursor.col;
1376 ai_col = curwin->w_cursor.col;
1379 * In REPLACE mode, for each character in the new indent, there must
1380 * be a NUL on the replace stack, for when it is deleted with BS
1382 if (REPLACE_NORMAL(State))
1383 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1384 replace_push(NUL);
1385 newcol += curwin->w_cursor.col;
1386 #ifdef FEAT_SMARTINDENT
1387 if (no_si)
1388 did_si = FALSE;
1389 #endif
1392 #ifdef FEAT_COMMENTS
1394 * In REPLACE mode, for each character in the extra leader, there must be
1395 * a NUL on the replace stack, for when it is deleted with BS.
1397 if (REPLACE_NORMAL(State))
1398 while (lead_len-- > 0)
1399 replace_push(NUL);
1400 #endif
1402 curwin->w_cursor = old_cursor;
1404 if (dir == FORWARD)
1406 if (trunc_line || (State & INSERT))
1408 /* truncate current line at cursor */
1409 saved_line[curwin->w_cursor.col] = NUL;
1410 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1411 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1412 truncate_spaces(saved_line);
1413 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1414 saved_line = NULL;
1415 if (did_append)
1417 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1418 curwin->w_cursor.lnum + 1, 1L);
1419 did_append = FALSE;
1421 /* Move marks after the line break to the new line. */
1422 if (flags & OPENLINE_MARKFIX)
1423 mark_col_adjust(curwin->w_cursor.lnum,
1424 curwin->w_cursor.col + less_cols_off,
1425 1L, (long)-less_cols);
1427 else
1428 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1432 * Put the cursor on the new line. Careful: the scrollup() above may
1433 * have moved w_cursor, we must use old_cursor.
1435 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1437 if (did_append)
1438 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1440 curwin->w_cursor.col = newcol;
1441 #ifdef FEAT_VIRTUALEDIT
1442 curwin->w_cursor.coladd = 0;
1443 #endif
1445 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1447 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1448 * fixthisline() from doing it (via change_indent()) by telling it we're in
1449 * normal INSERT mode.
1451 if (State & VREPLACE_FLAG)
1453 vreplace_mode = State; /* So we know to put things right later */
1454 State = INSERT;
1456 else
1457 vreplace_mode = 0;
1458 #endif
1459 #ifdef FEAT_LISP
1461 * May do lisp indenting.
1463 if (!p_paste
1464 # ifdef FEAT_COMMENTS
1465 && leader == NULL
1466 # endif
1467 && curbuf->b_p_lisp
1468 && curbuf->b_p_ai)
1470 fixthisline(get_lisp_indent);
1471 p = ml_get_curline();
1472 ai_col = (colnr_T)(skipwhite(p) - p);
1474 #endif
1475 #ifdef FEAT_CINDENT
1477 * May do indenting after opening a new line.
1479 if (!p_paste
1480 && (curbuf->b_p_cin
1481 # ifdef FEAT_EVAL
1482 || *curbuf->b_p_inde != NUL
1483 # endif
1485 && in_cinkeys(dir == FORWARD
1486 ? KEY_OPEN_FORW
1487 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1489 do_c_expr_indent();
1490 p = ml_get_curline();
1491 ai_col = (colnr_T)(skipwhite(p) - p);
1493 #endif
1494 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1495 if (vreplace_mode != 0)
1496 State = vreplace_mode;
1497 #endif
1499 #ifdef FEAT_VREPLACE
1501 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1502 * original line, and inserts the new stuff char by char, pushing old stuff
1503 * onto the replace stack (via ins_char()).
1505 if (State & VREPLACE_FLAG)
1507 /* Put new line in p_extra */
1508 p_extra = vim_strsave(ml_get_curline());
1509 if (p_extra == NULL)
1510 goto theend;
1512 /* Put back original line */
1513 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1515 /* Insert new stuff into line again */
1516 curwin->w_cursor.col = 0;
1517 #ifdef FEAT_VIRTUALEDIT
1518 curwin->w_cursor.coladd = 0;
1519 #endif
1520 ins_bytes(p_extra); /* will call changed_bytes() */
1521 vim_free(p_extra);
1522 next_line = NULL;
1524 #endif
1526 retval = TRUE; /* success! */
1527 theend:
1528 curbuf->b_p_pi = saved_pi;
1529 vim_free(saved_line);
1530 vim_free(next_line);
1531 vim_free(allocated);
1532 return retval;
1535 #if defined(FEAT_COMMENTS) || defined(PROTO)
1537 * get_leader_len() returns the length of the prefix of the given string
1538 * which introduces a comment. If this string is not a comment then 0 is
1539 * returned.
1540 * When "flags" is not NULL, it is set to point to the flags of the recognized
1541 * comment leader.
1542 * "backward" must be true for the "O" command.
1545 get_leader_len(line, flags, backward)
1546 char_u *line;
1547 char_u **flags;
1548 int backward;
1550 int i, j;
1551 int got_com = FALSE;
1552 int found_one;
1553 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1554 char_u *string; /* pointer to comment string */
1555 char_u *list;
1557 i = 0;
1558 while (vim_iswhite(line[i])) /* leading white space is ignored */
1559 ++i;
1562 * Repeat to match several nested comment strings.
1564 while (line[i])
1567 * scan through the 'comments' option for a match
1569 found_one = FALSE;
1570 for (list = curbuf->b_p_com; *list; )
1573 * Get one option part into part_buf[]. Advance list to next one.
1574 * put string at start of string.
1576 if (!got_com && flags != NULL) /* remember where flags started */
1577 *flags = list;
1578 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1579 string = vim_strchr(part_buf, ':');
1580 if (string == NULL) /* missing ':', ignore this part */
1581 continue;
1582 *string++ = NUL; /* isolate flags from string */
1585 * When already found a nested comment, only accept further
1586 * nested comments.
1588 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1589 continue;
1591 /* When 'O' flag used don't use for "O" command */
1592 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1593 continue;
1596 * Line contents and string must match.
1597 * When string starts with white space, must have some white space
1598 * (but the amount does not need to match, there might be a mix of
1599 * TABs and spaces).
1601 if (vim_iswhite(string[0]))
1603 if (i == 0 || !vim_iswhite(line[i - 1]))
1604 continue;
1605 while (vim_iswhite(string[0]))
1606 ++string;
1608 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1610 if (string[j] != NUL)
1611 continue;
1614 * When 'b' flag used, there must be white space or an
1615 * end-of-line after the string in the line.
1617 if (vim_strchr(part_buf, COM_BLANK) != NULL
1618 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1619 continue;
1622 * We have found a match, stop searching.
1624 i += j;
1625 got_com = TRUE;
1626 found_one = TRUE;
1627 break;
1631 * No match found, stop scanning.
1633 if (!found_one)
1634 break;
1637 * Include any trailing white space.
1639 while (vim_iswhite(line[i]))
1640 ++i;
1643 * If this comment doesn't nest, stop here.
1645 if (vim_strchr(part_buf, COM_NEST) == NULL)
1646 break;
1648 return (got_com ? i : 0);
1650 #endif
1653 * Return the number of window lines occupied by buffer line "lnum".
1656 plines(lnum)
1657 linenr_T lnum;
1659 return plines_win(curwin, lnum, TRUE);
1663 plines_win(wp, lnum, winheight)
1664 win_T *wp;
1665 linenr_T lnum;
1666 int winheight; /* when TRUE limit to window height */
1668 #if defined(FEAT_DIFF) || defined(PROTO)
1669 /* Check for filler lines above this buffer line. When folded the result
1670 * is one line anyway. */
1671 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1675 plines_nofill(lnum)
1676 linenr_T lnum;
1678 return plines_win_nofill(curwin, lnum, TRUE);
1682 plines_win_nofill(wp, lnum, winheight)
1683 win_T *wp;
1684 linenr_T lnum;
1685 int winheight; /* when TRUE limit to window height */
1687 #endif
1688 int lines;
1690 if (!wp->w_p_wrap)
1691 return 1;
1693 #ifdef FEAT_VERTSPLIT
1694 if (wp->w_width == 0)
1695 return 1;
1696 #endif
1698 #ifdef FEAT_FOLDING
1699 /* A folded lines is handled just like an empty line. */
1700 /* NOTE: Caller must handle lines that are MAYBE folded. */
1701 if (lineFolded(wp, lnum) == TRUE)
1702 return 1;
1703 #endif
1705 lines = plines_win_nofold(wp, lnum);
1706 if (winheight > 0 && lines > wp->w_height)
1707 return (int)wp->w_height;
1708 return lines;
1712 * Return number of window lines physical line "lnum" will occupy in window
1713 * "wp". Does not care about folding, 'wrap' or 'diff'.
1716 plines_win_nofold(wp, lnum)
1717 win_T *wp;
1718 linenr_T lnum;
1720 char_u *s;
1721 long col;
1722 int width;
1724 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1725 if (*s == NUL) /* empty line */
1726 return 1;
1727 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1730 * If list mode is on, then the '$' at the end of the line may take up one
1731 * extra column.
1733 if (wp->w_p_list && lcs_eol != NUL)
1734 col += 1;
1737 * Add column offset for 'number' and 'foldcolumn'.
1739 width = W_WIDTH(wp) - win_col_off(wp);
1740 if (width <= 0)
1741 return 32000;
1742 if (col <= width)
1743 return 1;
1744 col -= width;
1745 width += win_col_off2(wp);
1746 return (col + (width - 1)) / width + 1;
1750 * Like plines_win(), but only reports the number of physical screen lines
1751 * used from the start of the line to the given column number.
1754 plines_win_col(wp, lnum, column)
1755 win_T *wp;
1756 linenr_T lnum;
1757 long column;
1759 long col;
1760 char_u *s;
1761 int lines = 0;
1762 int width;
1764 #ifdef FEAT_DIFF
1765 /* Check for filler lines above this buffer line. When folded the result
1766 * is one line anyway. */
1767 lines = diff_check_fill(wp, lnum);
1768 #endif
1770 if (!wp->w_p_wrap)
1771 return lines + 1;
1773 #ifdef FEAT_VERTSPLIT
1774 if (wp->w_width == 0)
1775 return lines + 1;
1776 #endif
1778 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1780 col = 0;
1781 while (*s != NUL && --column >= 0)
1783 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
1784 mb_ptr_adv(s);
1788 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1789 * INSERT mode, then col must be adjusted so that it represents the last
1790 * screen position of the TAB. This only fixes an error when the TAB wraps
1791 * from one screen line to the next (when 'columns' is not a multiple of
1792 * 'ts') -- webb.
1794 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1795 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1798 * Add column offset for 'number', 'foldcolumn', etc.
1800 width = W_WIDTH(wp) - win_col_off(wp);
1801 if (width <= 0)
1802 return 9999;
1804 lines += 1;
1805 if (col > width)
1806 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1807 return lines;
1811 plines_m_win(wp, first, last)
1812 win_T *wp;
1813 linenr_T first, last;
1815 int count = 0;
1817 while (first <= last)
1819 #ifdef FEAT_FOLDING
1820 int x;
1822 /* Check if there are any really folded lines, but also included lines
1823 * that are maybe folded. */
1824 x = foldedCount(wp, first, NULL);
1825 if (x > 0)
1827 ++count; /* count 1 for "+-- folded" line */
1828 first += x;
1830 else
1831 #endif
1833 #ifdef FEAT_DIFF
1834 if (first == wp->w_topline)
1835 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1836 else
1837 #endif
1838 count += plines_win(wp, first, TRUE);
1839 ++first;
1842 return (count);
1845 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1847 * Insert string "p" at the cursor position. Stops at a NUL byte.
1848 * Handles Replace mode and multi-byte characters.
1850 void
1851 ins_bytes(p)
1852 char_u *p;
1854 ins_bytes_len(p, (int)STRLEN(p));
1856 #endif
1858 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1859 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1861 * Insert string "p" with length "len" at the cursor position.
1862 * Handles Replace mode and multi-byte characters.
1864 void
1865 ins_bytes_len(p, len)
1866 char_u *p;
1867 int len;
1869 int i;
1870 # ifdef FEAT_MBYTE
1871 int n;
1873 for (i = 0; i < len; i += n)
1875 n = (*mb_ptr2len)(p + i);
1876 ins_char_bytes(p + i, n);
1878 # else
1879 for (i = 0; i < len; ++i)
1880 ins_char(p[i]);
1881 # endif
1883 #endif
1886 * Insert or replace a single character at the cursor position.
1887 * When in REPLACE or VREPLACE mode, replace any existing character.
1888 * Caller must have prepared for undo.
1889 * For multi-byte characters we get the whole character, the caller must
1890 * convert bytes to a character.
1892 void
1893 ins_char(c)
1894 int c;
1896 #if defined(FEAT_MBYTE) || defined(PROTO)
1897 char_u buf[MB_MAXBYTES];
1898 int n;
1900 n = (*mb_char2bytes)(c, buf);
1902 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1903 * Happens for CTRL-Vu9900. */
1904 if (buf[0] == 0)
1905 buf[0] = '\n';
1907 ins_char_bytes(buf, n);
1910 void
1911 ins_char_bytes(buf, charlen)
1912 char_u *buf;
1913 int charlen;
1915 int c = buf[0];
1916 int l, j;
1917 #endif
1918 int newlen; /* nr of bytes inserted */
1919 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1920 char_u *p;
1921 char_u *newp;
1922 char_u *oldp;
1923 int linelen; /* length of old line including NUL */
1924 colnr_T col;
1925 linenr_T lnum = curwin->w_cursor.lnum;
1926 int i;
1928 #ifdef FEAT_VIRTUALEDIT
1929 /* Break tabs if needed. */
1930 if (virtual_active() && curwin->w_cursor.coladd > 0)
1931 coladvance_force(getviscol());
1932 #endif
1934 col = curwin->w_cursor.col;
1935 oldp = ml_get(lnum);
1936 linelen = (int)STRLEN(oldp) + 1;
1938 /* The lengths default to the values for when not replacing. */
1939 oldlen = 0;
1940 #ifdef FEAT_MBYTE
1941 newlen = charlen;
1942 #else
1943 newlen = 1;
1944 #endif
1946 if (State & REPLACE_FLAG)
1948 #ifdef FEAT_VREPLACE
1949 if (State & VREPLACE_FLAG)
1951 colnr_T new_vcol = 0; /* init for GCC */
1952 colnr_T vcol;
1953 int old_list;
1954 #ifndef FEAT_MBYTE
1955 char_u buf[2];
1956 #endif
1959 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1960 * Returns the old value of list, so when finished,
1961 * curwin->w_p_list should be set back to this.
1963 old_list = curwin->w_p_list;
1964 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
1965 curwin->w_p_list = FALSE;
1968 * In virtual replace mode each character may replace one or more
1969 * characters (zero if it's a TAB). Count the number of bytes to
1970 * be deleted to make room for the new character, counting screen
1971 * cells. May result in adding spaces to fill a gap.
1973 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
1974 #ifndef FEAT_MBYTE
1975 buf[0] = c;
1976 buf[1] = NUL;
1977 #endif
1978 new_vcol = vcol + chartabsize(buf, vcol);
1979 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
1981 vcol += chartabsize(oldp + col + oldlen, vcol);
1982 /* Don't need to remove a TAB that takes us to the right
1983 * position. */
1984 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
1985 break;
1986 #ifdef FEAT_MBYTE
1987 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
1988 #else
1989 ++oldlen;
1990 #endif
1991 /* Deleted a bit too much, insert spaces. */
1992 if (vcol > new_vcol)
1993 newlen += vcol - new_vcol;
1995 curwin->w_p_list = old_list;
1997 else
1998 #endif
1999 if (oldp[col] != NUL)
2001 /* normal replace */
2002 #ifdef FEAT_MBYTE
2003 oldlen = (*mb_ptr2len)(oldp + col);
2004 #else
2005 oldlen = 1;
2006 #endif
2010 /* Push the replaced bytes onto the replace stack, so that they can be
2011 * put back when BS is used. The bytes of a multi-byte character are
2012 * done the other way around, so that the first byte is popped off
2013 * first (it tells the byte length of the character). */
2014 replace_push(NUL);
2015 for (i = 0; i < oldlen; ++i)
2017 #ifdef FEAT_MBYTE
2018 l = (*mb_ptr2len)(oldp + col + i) - 1;
2019 for (j = l; j >= 0; --j)
2020 replace_push(oldp[col + i + j]);
2021 i += l;
2022 #else
2023 replace_push(oldp[col + i]);
2024 #endif
2028 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2029 if (newp == NULL)
2030 return;
2032 /* Copy bytes before the cursor. */
2033 if (col > 0)
2034 mch_memmove(newp, oldp, (size_t)col);
2036 /* Copy bytes after the changed character(s). */
2037 p = newp + col;
2038 mch_memmove(p + newlen, oldp + col + oldlen,
2039 (size_t)(linelen - col - oldlen));
2041 /* Insert or overwrite the new character. */
2042 #ifdef FEAT_MBYTE
2043 mch_memmove(p, buf, charlen);
2044 i = charlen;
2045 #else
2046 *p = c;
2047 i = 1;
2048 #endif
2050 /* Fill with spaces when necessary. */
2051 while (i < newlen)
2052 p[i++] = ' ';
2054 /* Replace the line in the buffer. */
2055 ml_replace(lnum, newp, FALSE);
2057 /* mark the buffer as changed and prepare for displaying */
2058 changed_bytes(lnum, col);
2061 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2062 * show the match for right parens and braces.
2064 if (p_sm && (State & INSERT)
2065 && msg_silent == 0
2066 #ifdef FEAT_MBYTE
2067 && charlen == 1
2068 #endif
2069 #ifdef FEAT_INS_EXPAND
2070 && !ins_compl_active()
2071 #endif
2073 showmatch(c);
2075 #ifdef FEAT_RIGHTLEFT
2076 if (!p_ri || (State & REPLACE_FLAG))
2077 #endif
2079 /* Normal insert: move cursor right */
2080 #ifdef FEAT_MBYTE
2081 curwin->w_cursor.col += charlen;
2082 #else
2083 ++curwin->w_cursor.col;
2084 #endif
2087 * TODO: should try to update w_row here, to avoid recomputing it later.
2092 * Insert a string at the cursor position.
2093 * Note: Does NOT handle Replace mode.
2094 * Caller must have prepared for undo.
2096 void
2097 ins_str(s)
2098 char_u *s;
2100 char_u *oldp, *newp;
2101 int newlen = (int)STRLEN(s);
2102 int oldlen;
2103 colnr_T col;
2104 linenr_T lnum = curwin->w_cursor.lnum;
2106 #ifdef FEAT_VIRTUALEDIT
2107 if (virtual_active() && curwin->w_cursor.coladd > 0)
2108 coladvance_force(getviscol());
2109 #endif
2111 col = curwin->w_cursor.col;
2112 oldp = ml_get(lnum);
2113 oldlen = (int)STRLEN(oldp);
2115 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2116 if (newp == NULL)
2117 return;
2118 if (col > 0)
2119 mch_memmove(newp, oldp, (size_t)col);
2120 mch_memmove(newp + col, s, (size_t)newlen);
2121 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2122 ml_replace(lnum, newp, FALSE);
2123 changed_bytes(lnum, col);
2124 curwin->w_cursor.col += newlen;
2128 * Delete one character under the cursor.
2129 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2130 * Caller must have prepared for undo.
2132 * return FAIL for failure, OK otherwise
2135 del_char(fixpos)
2136 int fixpos;
2138 #ifdef FEAT_MBYTE
2139 if (has_mbyte)
2141 /* Make sure the cursor is at the start of a character. */
2142 mb_adjust_cursor();
2143 if (*ml_get_cursor() == NUL)
2144 return FAIL;
2145 return del_chars(1L, fixpos);
2147 #endif
2148 return del_bytes(1L, fixpos, TRUE);
2151 #if defined(FEAT_MBYTE) || defined(PROTO)
2153 * Like del_bytes(), but delete characters instead of bytes.
2156 del_chars(count, fixpos)
2157 long count;
2158 int fixpos;
2160 long bytes = 0;
2161 long i;
2162 char_u *p;
2163 int l;
2165 p = ml_get_cursor();
2166 for (i = 0; i < count && *p != NUL; ++i)
2168 l = (*mb_ptr2len)(p);
2169 bytes += l;
2170 p += l;
2172 return del_bytes(bytes, fixpos, TRUE);
2174 #endif
2177 * Delete "count" bytes under the cursor.
2178 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2179 * Caller must have prepared for undo.
2181 * return FAIL for failure, OK otherwise
2183 /*ARGSUSED*/
2185 del_bytes(count, fixpos_arg, use_delcombine)
2186 long count;
2187 int fixpos_arg;
2188 int use_delcombine; /* 'delcombine' option applies */
2190 char_u *oldp, *newp;
2191 colnr_T oldlen;
2192 linenr_T lnum = curwin->w_cursor.lnum;
2193 colnr_T col = curwin->w_cursor.col;
2194 int was_alloced;
2195 long movelen;
2196 int fixpos = fixpos_arg;
2198 oldp = ml_get(lnum);
2199 oldlen = (int)STRLEN(oldp);
2202 * Can't do anything when the cursor is on the NUL after the line.
2204 if (col >= oldlen)
2205 return FAIL;
2207 #ifdef FEAT_MBYTE
2208 /* If 'delcombine' is set and deleting (less than) one character, only
2209 * delete the last combining character. */
2210 if (p_deco && use_delcombine && enc_utf8
2211 && utfc_ptr2len(oldp + col) >= count)
2213 int cc[MAX_MCO];
2214 int n;
2216 (void)utfc_ptr2char(oldp + col, cc);
2217 if (cc[0] != NUL)
2219 /* Find the last composing char, there can be several. */
2220 n = col;
2223 col = n;
2224 count = utf_ptr2len(oldp + n);
2225 n += count;
2226 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2227 fixpos = 0;
2230 #endif
2233 * When count is too big, reduce it.
2235 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2236 if (movelen <= 1)
2239 * If we just took off the last character of a non-blank line, and
2240 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2241 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2243 if (col > 0 && fixpos && restart_edit == 0
2244 #ifdef FEAT_VIRTUALEDIT
2245 && (ve_flags & VE_ONEMORE) == 0
2246 #endif
2249 --curwin->w_cursor.col;
2250 #ifdef FEAT_VIRTUALEDIT
2251 curwin->w_cursor.coladd = 0;
2252 #endif
2253 #ifdef FEAT_MBYTE
2254 if (has_mbyte)
2255 curwin->w_cursor.col -=
2256 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2257 #endif
2259 count = oldlen - col;
2260 movelen = 1;
2264 * If the old line has been allocated the deletion can be done in the
2265 * existing line. Otherwise a new line has to be allocated
2267 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
2268 #ifdef FEAT_NETBEANS_INTG
2269 if (was_alloced && usingNetbeans)
2270 netbeans_removed(curbuf, lnum, col, count);
2271 /* else is handled by ml_replace() */
2272 #endif
2273 if (was_alloced)
2274 newp = oldp; /* use same allocated memory */
2275 else
2276 { /* need to allocate a new line */
2277 newp = alloc((unsigned)(oldlen + 1 - count));
2278 if (newp == NULL)
2279 return FAIL;
2280 mch_memmove(newp, oldp, (size_t)col);
2282 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2283 if (!was_alloced)
2284 ml_replace(lnum, newp, FALSE);
2286 /* mark the buffer as changed and prepare for displaying */
2287 changed_bytes(lnum, curwin->w_cursor.col);
2289 return OK;
2293 * Delete from cursor to end of line.
2294 * Caller must have prepared for undo.
2296 * return FAIL for failure, OK otherwise
2299 truncate_line(fixpos)
2300 int fixpos; /* if TRUE fix the cursor position when done */
2302 char_u *newp;
2303 linenr_T lnum = curwin->w_cursor.lnum;
2304 colnr_T col = curwin->w_cursor.col;
2306 if (col == 0)
2307 newp = vim_strsave((char_u *)"");
2308 else
2309 newp = vim_strnsave(ml_get(lnum), col);
2311 if (newp == NULL)
2312 return FAIL;
2314 ml_replace(lnum, newp, FALSE);
2316 /* mark the buffer as changed and prepare for displaying */
2317 changed_bytes(lnum, curwin->w_cursor.col);
2320 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2322 if (fixpos && curwin->w_cursor.col > 0)
2323 --curwin->w_cursor.col;
2325 return OK;
2329 * Delete "nlines" lines at the cursor.
2330 * Saves the lines for undo first if "undo" is TRUE.
2332 void
2333 del_lines(nlines, undo)
2334 long nlines; /* number of lines to delete */
2335 int undo; /* if TRUE, prepare for undo */
2337 long n;
2339 if (nlines <= 0)
2340 return;
2342 /* save the deleted lines for undo */
2343 if (undo && u_savedel(curwin->w_cursor.lnum, nlines) == FAIL)
2344 return;
2346 for (n = 0; n < nlines; )
2348 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2349 break;
2351 ml_delete(curwin->w_cursor.lnum, TRUE);
2352 ++n;
2354 /* If we delete the last line in the file, stop */
2355 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
2356 break;
2358 /* adjust marks, mark the buffer as changed and prepare for displaying */
2359 deleted_lines_mark(curwin->w_cursor.lnum, n);
2361 curwin->w_cursor.col = 0;
2362 check_cursor_lnum();
2366 gchar_pos(pos)
2367 pos_T *pos;
2369 char_u *ptr = ml_get_pos(pos);
2371 #ifdef FEAT_MBYTE
2372 if (has_mbyte)
2373 return (*mb_ptr2char)(ptr);
2374 #endif
2375 return (int)*ptr;
2379 gchar_cursor()
2381 #ifdef FEAT_MBYTE
2382 if (has_mbyte)
2383 return (*mb_ptr2char)(ml_get_cursor());
2384 #endif
2385 return (int)*ml_get_cursor();
2389 * Write a character at the current cursor position.
2390 * It is directly written into the block.
2392 void
2393 pchar_cursor(c)
2394 int c;
2396 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2397 + curwin->w_cursor.col) = c;
2400 #if 0 /* not used */
2402 * Put *pos at end of current buffer
2404 void
2405 goto_endofbuf(pos)
2406 pos_T *pos;
2408 char_u *p;
2410 pos->lnum = curbuf->b_ml.ml_line_count;
2411 pos->col = 0;
2412 p = ml_get(pos->lnum);
2413 while (*p++)
2414 ++pos->col;
2416 #endif
2419 * When extra == 0: Return TRUE if the cursor is before or on the first
2420 * non-blank in the line.
2421 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2422 * the line.
2425 inindent(extra)
2426 int extra;
2428 char_u *ptr;
2429 colnr_T col;
2431 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2432 ++ptr;
2433 if (col >= curwin->w_cursor.col + extra)
2434 return TRUE;
2435 else
2436 return FALSE;
2440 * Skip to next part of an option argument: Skip space and comma.
2442 char_u *
2443 skip_to_option_part(p)
2444 char_u *p;
2446 if (*p == ',')
2447 ++p;
2448 while (*p == ' ')
2449 ++p;
2450 return p;
2454 * changed() is called when something in the current buffer is changed.
2456 * Most often called through changed_bytes() and changed_lines(), which also
2457 * mark the area of the display to be redrawn.
2459 void
2460 changed()
2462 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2463 /* The text of the preediting area is inserted, but this doesn't
2464 * mean a change of the buffer yet. That is delayed until the
2465 * text is committed. (this means preedit becomes empty) */
2466 if (im_is_preediting() && !xim_changed_while_preediting)
2467 return;
2468 xim_changed_while_preediting = FALSE;
2469 #endif
2471 if (!curbuf->b_changed)
2473 int save_msg_scroll = msg_scroll;
2475 /* Give a warning about changing a read-only file. This may also
2476 * check-out the file, thus change "curbuf"! */
2477 change_warning(0);
2479 /* Create a swap file if that is wanted.
2480 * Don't do this for "nofile" and "nowrite" buffer types. */
2481 if (curbuf->b_may_swap
2482 #ifdef FEAT_QUICKFIX
2483 && !bt_dontwrite(curbuf)
2484 #endif
2487 ml_open_file(curbuf);
2489 /* The ml_open_file() can cause an ATTENTION message.
2490 * Wait two seconds, to make sure the user reads this unexpected
2491 * message. Since we could be anywhere, call wait_return() now,
2492 * and don't let the emsg() set msg_scroll. */
2493 if (need_wait_return && emsg_silent == 0)
2495 out_flush();
2496 ui_delay(2000L, TRUE);
2497 wait_return(TRUE);
2498 msg_scroll = save_msg_scroll;
2501 curbuf->b_changed = TRUE;
2502 ml_setflags(curbuf);
2503 #ifdef FEAT_WINDOWS
2504 check_status(curbuf);
2505 redraw_tabline = TRUE;
2506 #endif
2507 #ifdef FEAT_TITLE
2508 need_maketitle = TRUE; /* set window title later */
2509 #endif
2511 ++curbuf->b_changedtick;
2514 static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2515 static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
2516 static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2519 * Changed bytes within a single line for the current buffer.
2520 * - marks the windows on this buffer to be redisplayed
2521 * - marks the buffer changed by calling changed()
2522 * - invalidates cached values
2524 void
2525 changed_bytes(lnum, col)
2526 linenr_T lnum;
2527 colnr_T col;
2529 changedOneline(curbuf, lnum);
2530 changed_common(lnum, col, lnum + 1, 0L);
2532 #ifdef FEAT_DIFF
2533 /* Diff highlighting in other diff windows may need to be updated too. */
2534 if (curwin->w_p_diff)
2536 win_T *wp;
2537 linenr_T wlnum;
2539 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2540 if (wp->w_p_diff && wp != curwin)
2542 redraw_win_later(wp, VALID);
2543 wlnum = diff_lnum_win(lnum, wp);
2544 if (wlnum > 0)
2545 changedOneline(wp->w_buffer, wlnum);
2548 #endif
2551 static void
2552 changedOneline(buf, lnum)
2553 buf_T *buf;
2554 linenr_T lnum;
2556 if (buf->b_mod_set)
2558 /* find the maximum area that must be redisplayed */
2559 if (lnum < buf->b_mod_top)
2560 buf->b_mod_top = lnum;
2561 else if (lnum >= buf->b_mod_bot)
2562 buf->b_mod_bot = lnum + 1;
2564 else
2566 /* set the area that must be redisplayed to one line */
2567 buf->b_mod_set = TRUE;
2568 buf->b_mod_top = lnum;
2569 buf->b_mod_bot = lnum + 1;
2570 buf->b_mod_xlines = 0;
2575 * Appended "count" lines below line "lnum" in the current buffer.
2576 * Must be called AFTER the change and after mark_adjust().
2577 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2579 void
2580 appended_lines(lnum, count)
2581 linenr_T lnum;
2582 long count;
2584 changed_lines(lnum + 1, 0, lnum + 1, count);
2588 * Like appended_lines(), but adjust marks first.
2590 void
2591 appended_lines_mark(lnum, count)
2592 linenr_T lnum;
2593 long count;
2595 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2596 changed_lines(lnum + 1, 0, lnum + 1, count);
2600 * Deleted "count" lines at line "lnum" in the current buffer.
2601 * Must be called AFTER the change and after mark_adjust().
2602 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2604 void
2605 deleted_lines(lnum, count)
2606 linenr_T lnum;
2607 long count;
2609 changed_lines(lnum, 0, lnum + count, -count);
2613 * Like deleted_lines(), but adjust marks first.
2615 void
2616 deleted_lines_mark(lnum, count)
2617 linenr_T lnum;
2618 long count;
2620 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2621 changed_lines(lnum, 0, lnum + count, -count);
2625 * Changed lines for the current buffer.
2626 * Must be called AFTER the change and after mark_adjust().
2627 * - mark the buffer changed by calling changed()
2628 * - mark the windows on this buffer to be redisplayed
2629 * - invalidate cached values
2630 * "lnum" is the first line that needs displaying, "lnume" the first line
2631 * below the changed lines (BEFORE the change).
2632 * When only inserting lines, "lnum" and "lnume" are equal.
2633 * Takes care of calling changed() and updating b_mod_*.
2635 void
2636 changed_lines(lnum, col, lnume, xtra)
2637 linenr_T lnum; /* first line with change */
2638 colnr_T col; /* column in first line with change */
2639 linenr_T lnume; /* line below last changed line */
2640 long xtra; /* number of extra lines (negative when deleting) */
2642 changed_lines_buf(curbuf, lnum, lnume, xtra);
2644 #ifdef FEAT_DIFF
2645 if (xtra == 0 && curwin->w_p_diff)
2647 /* When the number of lines doesn't change then mark_adjust() isn't
2648 * called and other diff buffers still need to be marked for
2649 * displaying. */
2650 win_T *wp;
2651 linenr_T wlnum;
2653 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2654 if (wp->w_p_diff && wp != curwin)
2656 redraw_win_later(wp, VALID);
2657 wlnum = diff_lnum_win(lnum, wp);
2658 if (wlnum > 0)
2659 changed_lines_buf(wp->w_buffer, wlnum,
2660 lnume - lnum + wlnum, 0L);
2663 #endif
2665 changed_common(lnum, col, lnume, xtra);
2668 static void
2669 changed_lines_buf(buf, lnum, lnume, xtra)
2670 buf_T *buf;
2671 linenr_T lnum; /* first line with change */
2672 linenr_T lnume; /* line below last changed line */
2673 long xtra; /* number of extra lines (negative when deleting) */
2675 if (buf->b_mod_set)
2677 /* find the maximum area that must be redisplayed */
2678 if (lnum < buf->b_mod_top)
2679 buf->b_mod_top = lnum;
2680 if (lnum < buf->b_mod_bot)
2682 /* adjust old bot position for xtra lines */
2683 buf->b_mod_bot += xtra;
2684 if (buf->b_mod_bot < lnum)
2685 buf->b_mod_bot = lnum;
2687 if (lnume + xtra > buf->b_mod_bot)
2688 buf->b_mod_bot = lnume + xtra;
2689 buf->b_mod_xlines += xtra;
2691 else
2693 /* set the area that must be redisplayed */
2694 buf->b_mod_set = TRUE;
2695 buf->b_mod_top = lnum;
2696 buf->b_mod_bot = lnume + xtra;
2697 buf->b_mod_xlines = xtra;
2701 static void
2702 changed_common(lnum, col, lnume, xtra)
2703 linenr_T lnum;
2704 colnr_T col;
2705 linenr_T lnume;
2706 long xtra;
2708 win_T *wp;
2709 int i;
2710 #ifdef FEAT_JUMPLIST
2711 int cols;
2712 pos_T *p;
2713 int add;
2714 #endif
2716 /* mark the buffer as modified */
2717 changed();
2719 /* set the '. mark */
2720 if (!cmdmod.keepjumps)
2722 curbuf->b_last_change.lnum = lnum;
2723 curbuf->b_last_change.col = col;
2725 #ifdef FEAT_JUMPLIST
2726 /* Create a new entry if a new undo-able change was started or we
2727 * don't have an entry yet. */
2728 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2730 if (curbuf->b_changelistlen == 0)
2731 add = TRUE;
2732 else
2734 /* Don't create a new entry when the line number is the same
2735 * as the last one and the column is not too far away. Avoids
2736 * creating many entries for typing "xxxxx". */
2737 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2738 if (p->lnum != lnum)
2739 add = TRUE;
2740 else
2742 cols = comp_textwidth(FALSE);
2743 if (cols == 0)
2744 cols = 79;
2745 add = (p->col + cols < col || col + cols < p->col);
2748 if (add)
2750 /* This is the first of a new sequence of undo-able changes
2751 * and it's at some distance of the last change. Use a new
2752 * position in the changelist. */
2753 curbuf->b_new_change = FALSE;
2755 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2757 /* changelist is full: remove oldest entry */
2758 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2759 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2760 sizeof(pos_T) * (JUMPLISTSIZE - 1));
2761 FOR_ALL_WINDOWS(wp)
2763 /* Correct position in changelist for other windows on
2764 * this buffer. */
2765 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2766 --wp->w_changelistidx;
2769 FOR_ALL_WINDOWS(wp)
2771 /* For other windows, if the position in the changelist is
2772 * at the end it stays at the end. */
2773 if (wp->w_buffer == curbuf
2774 && wp->w_changelistidx == curbuf->b_changelistlen)
2775 ++wp->w_changelistidx;
2777 ++curbuf->b_changelistlen;
2780 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2781 curbuf->b_last_change;
2782 /* The current window is always after the last change, so that "g,"
2783 * takes you back to it. */
2784 curwin->w_changelistidx = curbuf->b_changelistlen;
2785 #endif
2788 FOR_ALL_WINDOWS(wp)
2790 if (wp->w_buffer == curbuf)
2792 /* Mark this window to be redrawn later. */
2793 if (wp->w_redr_type < VALID)
2794 wp->w_redr_type = VALID;
2796 /* Check if a change in the buffer has invalidated the cached
2797 * values for the cursor. */
2798 #ifdef FEAT_FOLDING
2800 * Update the folds for this window. Can't postpone this, because
2801 * a following operator might work on the whole fold: ">>dd".
2803 foldUpdate(wp, lnum, lnume + xtra - 1);
2805 /* The change may cause lines above or below the change to become
2806 * included in a fold. Set lnum/lnume to the first/last line that
2807 * might be displayed differently.
2808 * Set w_cline_folded here as an efficient way to update it when
2809 * inserting lines just above a closed fold. */
2810 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2811 if (wp->w_cursor.lnum == lnum)
2812 wp->w_cline_folded = i;
2813 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2814 if (wp->w_cursor.lnum == lnume)
2815 wp->w_cline_folded = i;
2817 /* If the changed line is in a range of previously folded lines,
2818 * compare with the first line in that range. */
2819 if (wp->w_cursor.lnum <= lnum)
2821 i = find_wl_entry(wp, lnum);
2822 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2823 changed_line_abv_curs_win(wp);
2825 #endif
2827 if (wp->w_cursor.lnum > lnum)
2828 changed_line_abv_curs_win(wp);
2829 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2830 changed_cline_bef_curs_win(wp);
2831 if (wp->w_botline >= lnum)
2833 /* Assume that botline doesn't change (inserted lines make
2834 * other lines scroll down below botline). */
2835 approximate_botline_win(wp);
2838 /* Check if any w_lines[] entries have become invalid.
2839 * For entries below the change: Correct the lnums for
2840 * inserted/deleted lines. Makes it possible to stop displaying
2841 * after the change. */
2842 for (i = 0; i < wp->w_lines_valid; ++i)
2843 if (wp->w_lines[i].wl_valid)
2845 if (wp->w_lines[i].wl_lnum >= lnum)
2847 if (wp->w_lines[i].wl_lnum < lnume)
2849 /* line included in change */
2850 wp->w_lines[i].wl_valid = FALSE;
2852 else if (xtra != 0)
2854 /* line below change */
2855 wp->w_lines[i].wl_lnum += xtra;
2856 #ifdef FEAT_FOLDING
2857 wp->w_lines[i].wl_lastlnum += xtra;
2858 #endif
2861 #ifdef FEAT_FOLDING
2862 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2864 /* change somewhere inside this range of folded lines,
2865 * may need to be redrawn */
2866 wp->w_lines[i].wl_valid = FALSE;
2868 #endif
2873 /* Call update_screen() later, which checks out what needs to be redrawn,
2874 * since it notices b_mod_set and then uses b_mod_*. */
2875 if (must_redraw < VALID)
2876 must_redraw = VALID;
2878 #ifdef FEAT_AUTOCMD
2879 /* when the cursor line is changed always trigger CursorMoved */
2880 if (lnum <= curwin->w_cursor.lnum
2881 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
2882 last_cursormoved.lnum = 0;
2883 #endif
2887 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2889 void
2890 unchanged(buf, ff)
2891 buf_T *buf;
2892 int ff; /* also reset 'fileformat' */
2894 if (buf->b_changed || (ff && file_ff_differs(buf)))
2896 buf->b_changed = 0;
2897 ml_setflags(buf);
2898 if (ff)
2899 save_file_ff(buf);
2900 #ifdef FEAT_WINDOWS
2901 check_status(buf);
2902 redraw_tabline = TRUE;
2903 #endif
2904 #ifdef FEAT_TITLE
2905 need_maketitle = TRUE; /* set window title later */
2906 #endif
2908 ++buf->b_changedtick;
2909 #ifdef FEAT_NETBEANS_INTG
2910 netbeans_unmodified(buf);
2911 #endif
2914 #if defined(FEAT_WINDOWS) || defined(PROTO)
2916 * check_status: called when the status bars for the buffer 'buf'
2917 * need to be updated
2919 void
2920 check_status(buf)
2921 buf_T *buf;
2923 win_T *wp;
2925 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2926 if (wp->w_buffer == buf && wp->w_status_height)
2928 wp->w_redr_status = TRUE;
2929 if (must_redraw < VALID)
2930 must_redraw = VALID;
2933 #endif
2936 * If the file is readonly, give a warning message with the first change.
2937 * Don't do this for autocommands.
2938 * Don't use emsg(), because it flushes the macro buffer.
2939 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
2940 * will be TRUE.
2942 void
2943 change_warning(col)
2944 int col; /* column for message; non-zero when in insert
2945 mode and 'showmode' is on */
2947 if (curbuf->b_did_warn == FALSE
2948 && curbufIsChanged() == 0
2949 #ifdef FEAT_AUTOCMD
2950 && !autocmd_busy
2951 #endif
2952 && curbuf->b_p_ro)
2954 #ifdef FEAT_AUTOCMD
2955 ++curbuf_lock;
2956 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
2957 --curbuf_lock;
2958 if (!curbuf->b_p_ro)
2959 return;
2960 #endif
2962 * Do what msg() does, but with a column offset if the warning should
2963 * be after the mode message.
2965 msg_start();
2966 if (msg_row == Rows - 1)
2967 msg_col = col;
2968 msg_source(hl_attr(HLF_W));
2969 MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
2970 hl_attr(HLF_W) | MSG_HIST);
2971 msg_clr_eos();
2972 (void)msg_end();
2973 if (msg_silent == 0 && !silent_mode)
2975 out_flush();
2976 ui_delay(1000L, TRUE); /* give the user time to think about it */
2978 curbuf->b_did_warn = TRUE;
2979 redraw_cmdline = FALSE; /* don't redraw and erase the message */
2980 if (msg_row < Rows - 1)
2981 showmode();
2986 * Ask for a reply from the user, a 'y' or a 'n'.
2987 * No other characters are accepted, the message is repeated until a valid
2988 * reply is entered or CTRL-C is hit.
2989 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
2990 * from any buffers but directly from the user.
2992 * return the 'y' or 'n'
2995 ask_yesno(str, direct)
2996 char_u *str;
2997 int direct;
2999 int r = ' ';
3000 int save_State = State;
3002 if (exiting) /* put terminal in raw mode for this question */
3003 settmode(TMODE_RAW);
3004 ++no_wait_return;
3005 #ifdef USE_ON_FLY_SCROLL
3006 dont_scroll = TRUE; /* disallow scrolling here */
3007 #endif
3008 State = CONFIRM; /* mouse behaves like with :confirm */
3009 #ifdef FEAT_MOUSE
3010 setmouse(); /* disables mouse for xterm */
3011 #endif
3012 ++no_mapping;
3013 ++allow_keys; /* no mapping here, but recognize keys */
3015 while (r != 'y' && r != 'n')
3017 /* same highlighting as for wait_return */
3018 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3019 if (direct)
3020 r = get_keystroke();
3021 else
3022 r = safe_vgetc();
3023 if (r == Ctrl_C || r == ESC)
3024 r = 'n';
3025 msg_putchar(r); /* show what you typed */
3026 out_flush();
3028 --no_wait_return;
3029 State = save_State;
3030 #ifdef FEAT_MOUSE
3031 setmouse();
3032 #endif
3033 --no_mapping;
3034 --allow_keys;
3036 return r;
3040 * Get a key stroke directly from the user.
3041 * Ignores mouse clicks and scrollbar events, except a click for the left
3042 * button (used at the more prompt).
3043 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3044 * Disadvantage: typeahead is ignored.
3045 * Translates the interrupt character for unix to ESC.
3048 get_keystroke()
3050 #define CBUFLEN 151
3051 char_u buf[CBUFLEN];
3052 int len = 0;
3053 int n;
3054 int save_mapped_ctrl_c = mapped_ctrl_c;
3055 int waited = 0;
3057 mapped_ctrl_c = FALSE; /* mappings are not used here */
3058 for (;;)
3060 cursor_on();
3061 out_flush();
3063 /* First time: blocking wait. Second time: wait up to 100ms for a
3064 * terminal code to complete. Leave some room for check_termcode() to
3065 * insert a key code into (max 5 chars plus NUL). And
3066 * fix_input_buffer() can triple the number of bytes. */
3067 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3068 len == 0 ? -1L : 100L, 0);
3069 if (n > 0)
3071 /* Replace zero and CSI by a special key code. */
3072 n = fix_input_buffer(buf + len, n, FALSE);
3073 len += n;
3074 waited = 0;
3076 else if (len > 0)
3077 ++waited; /* keep track of the waiting time */
3079 /* Incomplete termcode and not timed out yet: get more characters */
3080 if ((n = check_termcode(1, buf, len)) < 0
3081 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
3082 continue;
3084 /* found a termcode: adjust length */
3085 if (n > 0)
3086 len = n;
3087 if (len == 0) /* nothing typed yet */
3088 continue;
3090 /* Handle modifier and/or special key code. */
3091 n = buf[0];
3092 if (n == K_SPECIAL)
3094 n = TO_SPECIAL(buf[1], buf[2]);
3095 if (buf[1] == KS_MODIFIER
3096 || n == K_IGNORE
3097 #ifdef FEAT_MOUSE
3098 || n == K_LEFTMOUSE_NM
3099 || n == K_LEFTDRAG
3100 || n == K_LEFTRELEASE
3101 || n == K_LEFTRELEASE_NM
3102 || n == K_MIDDLEMOUSE
3103 || n == K_MIDDLEDRAG
3104 || n == K_MIDDLERELEASE
3105 || n == K_RIGHTMOUSE
3106 || n == K_RIGHTDRAG
3107 || n == K_RIGHTRELEASE
3108 || n == K_MOUSEDOWN
3109 || n == K_MOUSEUP
3110 || n == K_X1MOUSE
3111 || n == K_X1DRAG
3112 || n == K_X1RELEASE
3113 || n == K_X2MOUSE
3114 || n == K_X2DRAG
3115 || n == K_X2RELEASE
3116 # ifdef FEAT_GUI
3117 || n == K_VER_SCROLLBAR
3118 || n == K_HOR_SCROLLBAR
3119 # endif
3120 #endif
3123 if (buf[1] == KS_MODIFIER)
3124 mod_mask = buf[2];
3125 len -= 3;
3126 if (len > 0)
3127 mch_memmove(buf, buf + 3, (size_t)len);
3128 continue;
3130 break;
3132 #ifdef FEAT_MBYTE
3133 if (has_mbyte)
3135 if (MB_BYTE2LEN(n) > len)
3136 continue; /* more bytes to get */
3137 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3138 n = (*mb_ptr2char)(buf);
3140 #endif
3141 #ifdef UNIX
3142 if (n == intr_char)
3143 n = ESC;
3144 #endif
3145 break;
3148 mapped_ctrl_c = save_mapped_ctrl_c;
3149 return n;
3153 * Get a number from the user.
3154 * When "mouse_used" is not NULL allow using the mouse.
3157 get_number(colon, mouse_used)
3158 int colon; /* allow colon to abort */
3159 int *mouse_used;
3161 int n = 0;
3162 int c;
3163 int typed = 0;
3165 if (mouse_used != NULL)
3166 *mouse_used = FALSE;
3168 /* When not printing messages, the user won't know what to type, return a
3169 * zero (as if CR was hit). */
3170 if (msg_silent != 0)
3171 return 0;
3173 #ifdef USE_ON_FLY_SCROLL
3174 dont_scroll = TRUE; /* disallow scrolling here */
3175 #endif
3176 ++no_mapping;
3177 ++allow_keys; /* no mapping here, but recognize keys */
3178 for (;;)
3180 windgoto(msg_row, msg_col);
3181 c = safe_vgetc();
3182 if (VIM_ISDIGIT(c))
3184 n = n * 10 + c - '0';
3185 msg_putchar(c);
3186 ++typed;
3188 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3190 if (typed > 0)
3192 MSG_PUTS("\b \b");
3193 --typed;
3195 n /= 10;
3197 #ifdef FEAT_MOUSE
3198 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3200 *mouse_used = TRUE;
3201 n = mouse_row + 1;
3202 break;
3204 #endif
3205 else if (n == 0 && c == ':' && colon)
3207 stuffcharReadbuff(':');
3208 if (!exmode_active)
3209 cmdline_row = msg_row;
3210 skip_redraw = TRUE; /* skip redraw once */
3211 do_redraw = FALSE;
3212 break;
3214 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3215 break;
3217 --no_mapping;
3218 --allow_keys;
3219 return n;
3223 * Ask the user to enter a number.
3224 * When "mouse_used" is not NULL allow using the mouse and in that case return
3225 * the line number.
3228 prompt_for_number(mouse_used)
3229 int *mouse_used;
3231 int i;
3232 int save_cmdline_row;
3233 int save_State;
3235 /* When using ":silent" assume that <CR> was entered. */
3236 if (mouse_used != NULL)
3237 MSG_PUTS(_("Type number or click with mouse (<Enter> cancels): "));
3238 else
3239 MSG_PUTS(_("Choice number (<Enter> cancels): "));
3241 /* Set the state such that text can be selected/copied/pasted and we still
3242 * get mouse events. */
3243 save_cmdline_row = cmdline_row;
3244 cmdline_row = 0;
3245 save_State = State;
3246 State = CMDLINE;
3248 i = get_number(TRUE, mouse_used);
3249 if (KeyTyped)
3251 /* don't call wait_return() now */
3252 /* msg_putchar('\n'); */
3253 cmdline_row = msg_row - 1;
3254 need_wait_return = FALSE;
3255 msg_didany = FALSE;
3257 else
3258 cmdline_row = save_cmdline_row;
3259 State = save_State;
3261 return i;
3264 void
3265 msgmore(n)
3266 long n;
3268 long pn;
3270 if (global_busy /* no messages now, wait until global is finished */
3271 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3272 return;
3274 /* We don't want to overwrite another important message, but do overwrite
3275 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3276 * then "put" reports the last action. */
3277 if (keep_msg != NULL && !keep_msg_more)
3278 return;
3280 if (n > 0)
3281 pn = n;
3282 else
3283 pn = -n;
3285 if (pn > p_report)
3287 if (pn == 1)
3289 if (n > 0)
3290 STRCPY(msg_buf, _("1 more line"));
3291 else
3292 STRCPY(msg_buf, _("1 line less"));
3294 else
3296 if (n > 0)
3297 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3298 else
3299 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3301 if (got_int)
3302 STRCAT(msg_buf, _(" (Interrupted)"));
3303 if (msg(msg_buf))
3305 set_keep_msg(msg_buf, 0);
3306 keep_msg_more = TRUE;
3312 * flush map and typeahead buffers and give a warning for an error
3314 void
3315 beep_flush()
3317 if (emsg_silent == 0)
3319 flush_buffers(FALSE);
3320 vim_beep();
3325 * give a warning for an error
3327 void
3328 vim_beep()
3330 if (emsg_silent == 0)
3332 if (p_vb
3333 #ifdef FEAT_GUI
3334 /* While the GUI is starting up the termcap is set for the GUI
3335 * but the output still goes to a terminal. */
3336 && !(gui.in_use && gui.starting)
3337 #endif
3340 out_str(T_VB);
3342 else
3344 #ifdef MSDOS
3346 * The number of beeps outputted is reduced to avoid having to wait
3347 * for all the beeps to finish. This is only a problem on systems
3348 * where the beeps don't overlap.
3350 if (beep_count == 0 || beep_count == 10)
3352 out_char(BELL);
3353 beep_count = 1;
3355 else
3356 ++beep_count;
3357 #else
3358 out_char(BELL);
3359 #endif
3362 /* When 'verbose' is set and we are sourcing a script or executing a
3363 * function give the user a hint where the beep comes from. */
3364 if (vim_strchr(p_debug, 'e') != NULL)
3366 msg_source(hl_attr(HLF_W));
3367 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3373 * To get the "real" home directory:
3374 * - get value of $HOME
3375 * For Unix:
3376 * - go to that directory
3377 * - do mch_dirname() to get the real name of that directory.
3378 * This also works with mounts and links.
3379 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3381 static char_u *homedir = NULL;
3383 void
3384 init_homedir()
3386 char_u *var;
3388 /* In case we are called a second time (when 'encoding' changes). */
3389 vim_free(homedir);
3390 homedir = NULL;
3392 #ifdef VMS
3393 var = mch_getenv((char_u *)"SYS$LOGIN");
3394 #else
3395 var = mch_getenv((char_u *)"HOME");
3396 #endif
3398 if (var != NULL && *var == NUL) /* empty is same as not set */
3399 var = NULL;
3401 #ifdef WIN3264
3403 * Weird but true: $HOME may contain an indirect reference to another
3404 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3405 * when $HOME is being set.
3407 if (var != NULL && *var == '%')
3409 char_u *p;
3410 char_u *exp;
3412 p = vim_strchr(var + 1, '%');
3413 if (p != NULL)
3415 vim_strncpy(NameBuff, var + 1, p - (var + 1));
3416 exp = mch_getenv(NameBuff);
3417 if (exp != NULL && *exp != NUL
3418 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3420 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
3421 var = NameBuff;
3422 /* Also set $HOME, it's needed for _viminfo. */
3423 vim_setenv((char_u *)"HOME", NameBuff);
3429 * Typically, $HOME is not defined on Windows, unless the user has
3430 * specifically defined it for Vim's sake. However, on Windows NT
3431 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3432 * each user. Try constructing $HOME from these.
3434 if (var == NULL)
3436 char_u *homedrive, *homepath;
3438 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3439 homepath = mch_getenv((char_u *)"HOMEPATH");
3440 if (homedrive != NULL && homepath != NULL
3441 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3443 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3444 if (NameBuff[0] != NUL)
3446 var = NameBuff;
3447 /* Also set $HOME, it's needed for _viminfo. */
3448 vim_setenv((char_u *)"HOME", NameBuff);
3453 # if defined(FEAT_MBYTE)
3454 if (enc_utf8 && var != NULL)
3456 int len;
3457 char_u *pp;
3459 /* Convert from active codepage to UTF-8. Other conversions are
3460 * not done, because they would fail for non-ASCII characters. */
3461 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
3462 if (pp != NULL)
3464 homedir = pp;
3465 return;
3468 # endif
3469 #endif
3471 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3473 * Default home dir is C:/
3474 * Best assumption we can make in such a situation.
3476 if (var == NULL)
3477 var = "C:/";
3478 #endif
3479 if (var != NULL)
3481 #ifdef UNIX
3483 * Change to the directory and get the actual path. This resolves
3484 * links. Don't do it when we can't return.
3486 if (mch_dirname(NameBuff, MAXPATHL) == OK
3487 && mch_chdir((char *)NameBuff) == 0)
3489 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3490 var = IObuff;
3491 if (mch_chdir((char *)NameBuff) != 0)
3492 EMSG(_(e_prev_dir));
3494 #endif
3495 homedir = vim_strsave(var);
3499 #if defined(EXITFREE) || defined(PROTO)
3500 void
3501 free_homedir()
3503 vim_free(homedir);
3505 #endif
3508 * Expand environment variable with path name.
3509 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3510 * Skips over "\ ", "\~" and "\$".
3511 * If anything fails no expansion is done and dst equals src.
3513 void
3514 expand_env(src, dst, dstlen)
3515 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3516 char_u *dst; /* where to put the result */
3517 int dstlen; /* maximum length of the result */
3519 expand_env_esc(src, dst, dstlen, FALSE, NULL);
3522 void
3523 expand_env_esc(srcp, dst, dstlen, esc, startstr)
3524 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
3525 char_u *dst; /* where to put the result */
3526 int dstlen; /* maximum length of the result */
3527 int esc; /* escape spaces in expanded variables */
3528 char_u *startstr; /* start again after this (can be NULL) */
3530 char_u *src;
3531 char_u *tail;
3532 int c;
3533 char_u *var;
3534 int copy_char;
3535 int mustfree; /* var was allocated, need to free it later */
3536 int at_start = TRUE; /* at start of a name */
3537 int startstr_len = 0;
3539 if (startstr != NULL)
3540 startstr_len = (int)STRLEN(startstr);
3542 src = skipwhite(srcp);
3543 --dstlen; /* leave one char space for "\," */
3544 while (*src && dstlen > 0)
3546 copy_char = TRUE;
3547 if ((*src == '$'
3548 #ifdef VMS
3549 && at_start
3550 #endif
3552 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3553 || *src == '%'
3554 #endif
3555 || (*src == '~' && at_start))
3557 mustfree = FALSE;
3560 * The variable name is copied into dst temporarily, because it may
3561 * be a string in read-only memory and a NUL needs to be appended.
3563 if (*src != '~') /* environment var */
3565 tail = src + 1;
3566 var = dst;
3567 c = dstlen - 1;
3569 #ifdef UNIX
3570 /* Unix has ${var-name} type environment vars */
3571 if (*tail == '{' && !vim_isIDc('{'))
3573 tail++; /* ignore '{' */
3574 while (c-- > 0 && *tail && *tail != '}')
3575 *var++ = *tail++;
3577 else
3578 #endif
3580 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3581 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3582 || (*src == '%' && *tail != '%')
3583 #endif
3586 #ifdef OS2 /* env vars only in uppercase */
3587 *var++ = TOUPPER_LOC(*tail);
3588 tail++; /* toupper() may be a macro! */
3589 #else
3590 *var++ = *tail++;
3591 #endif
3595 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3596 # ifdef UNIX
3597 if (src[1] == '{' && *tail != '}')
3598 # else
3599 if (*src == '%' && *tail != '%')
3600 # endif
3601 var = NULL;
3602 else
3604 # ifdef UNIX
3605 if (src[1] == '{')
3606 # else
3607 if (*src == '%')
3608 #endif
3609 ++tail;
3610 #endif
3611 *var = NUL;
3612 var = vim_getenv(dst, &mustfree);
3613 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3615 #endif
3617 /* home directory */
3618 else if ( src[1] == NUL
3619 || vim_ispathsep(src[1])
3620 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3622 var = homedir;
3623 tail = src + 1;
3625 else /* user directory */
3627 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3629 * Copy ~user to dst[], so we can put a NUL after it.
3631 tail = src;
3632 var = dst;
3633 c = dstlen - 1;
3634 while ( c-- > 0
3635 && *tail
3636 && vim_isfilec(*tail)
3637 && !vim_ispathsep(*tail))
3638 *var++ = *tail++;
3639 *var = NUL;
3640 # ifdef UNIX
3642 * If the system supports getpwnam(), use it.
3643 * Otherwise, or if getpwnam() fails, the shell is used to
3644 * expand ~user. This is slower and may fail if the shell
3645 * does not support ~user (old versions of /bin/sh).
3647 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3649 struct passwd *pw;
3651 /* Note: memory allocated by getpwnam() is never freed.
3652 * Calling endpwent() apparently doesn't help. */
3653 pw = getpwnam((char *)dst + 1);
3654 if (pw != NULL)
3655 var = (char_u *)pw->pw_dir;
3656 else
3657 var = NULL;
3659 if (var == NULL)
3660 # endif
3662 expand_T xpc;
3664 ExpandInit(&xpc);
3665 xpc.xp_context = EXPAND_FILES;
3666 var = ExpandOne(&xpc, dst, NULL,
3667 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
3668 mustfree = TRUE;
3671 # else /* !UNIX, thus VMS */
3673 * USER_HOME is a comma-separated list of
3674 * directories to search for the user account in.
3677 char_u test[MAXPATHL], paths[MAXPATHL];
3678 char_u *path, *next_path, *ptr;
3679 struct stat st;
3681 STRCPY(paths, USER_HOME);
3682 next_path = paths;
3683 while (*next_path)
3685 for (path = next_path; *next_path && *next_path != ',';
3686 next_path++);
3687 if (*next_path)
3688 *next_path++ = NUL;
3689 STRCPY(test, path);
3690 STRCAT(test, "/");
3691 STRCAT(test, dst + 1);
3692 if (mch_stat(test, &st) == 0)
3694 var = alloc(STRLEN(test) + 1);
3695 STRCPY(var, test);
3696 mustfree = TRUE;
3697 break;
3701 # endif /* UNIX */
3702 #else
3703 /* cannot expand user's home directory, so don't try */
3704 var = NULL;
3705 tail = (char_u *)""; /* for gcc */
3706 #endif /* UNIX || VMS */
3709 #ifdef BACKSLASH_IN_FILENAME
3710 /* If 'shellslash' is set change backslashes to forward slashes.
3711 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3712 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3714 char_u *p = vim_strsave(var);
3716 if (p != NULL)
3718 if (mustfree)
3719 vim_free(var);
3720 var = p;
3721 mustfree = TRUE;
3722 forward_slash(var);
3725 #endif
3727 /* If "var" contains white space, escape it with a backslash.
3728 * Required for ":e ~/tt" when $HOME includes a space. */
3729 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3731 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3733 if (p != NULL)
3735 if (mustfree)
3736 vim_free(var);
3737 var = p;
3738 mustfree = TRUE;
3742 if (var != NULL && *var != NUL
3743 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3745 STRCPY(dst, var);
3746 dstlen -= (int)STRLEN(var);
3747 c = (int)STRLEN(var);
3748 /* if var[] ends in a path separator and tail[] starts
3749 * with it, skip a character */
3750 if (*var != NUL && after_pathsep(dst, dst + c)
3751 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3752 && dst[-1] != ':'
3753 #endif
3754 && vim_ispathsep(*tail))
3755 ++tail;
3756 dst += c;
3757 src = tail;
3758 copy_char = FALSE;
3760 if (mustfree)
3761 vim_free(var);
3764 if (copy_char) /* copy at least one char */
3767 * Recognize the start of a new name, for '~'.
3769 at_start = FALSE;
3770 if (src[0] == '\\' && src[1] != NUL)
3772 *dst++ = *src++;
3773 --dstlen;
3775 else if (src[0] == ' ' || src[0] == ',')
3776 at_start = TRUE;
3777 *dst++ = *src++;
3778 --dstlen;
3780 if (startstr != NULL && src - startstr_len >= srcp
3781 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3782 at_start = TRUE;
3785 *dst = NUL;
3789 * Vim's version of getenv().
3790 * Special handling of $HOME, $VIM and $VIMRUNTIME.
3791 * Also does ACP to 'enc' conversion for Win32.
3793 char_u *
3794 vim_getenv(name, mustfree)
3795 char_u *name;
3796 int *mustfree; /* set to TRUE when returned is allocated */
3798 char_u *p;
3799 char_u *pend;
3800 int vimruntime;
3802 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3803 /* use "C:/" when $HOME is not set */
3804 if (STRCMP(name, "HOME") == 0)
3805 return homedir;
3806 #endif
3808 p = mch_getenv(name);
3809 if (p != NULL && *p == NUL) /* empty is the same as not set */
3810 p = NULL;
3812 if (p != NULL)
3814 #if defined(FEAT_MBYTE) && defined(WIN3264)
3815 if (enc_utf8)
3817 int len;
3818 char_u *pp;
3820 /* Convert from active codepage to UTF-8. Other conversions are
3821 * not done, because they would fail for non-ASCII characters. */
3822 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
3823 if (pp != NULL)
3825 p = pp;
3826 *mustfree = TRUE;
3829 #endif
3830 return p;
3833 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3834 if (!vimruntime && STRCMP(name, "VIM") != 0)
3835 return NULL;
3838 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3839 * Don't do this when default_vimruntime_dir is non-empty.
3841 if (vimruntime
3842 #ifdef HAVE_PATHDEF
3843 && *default_vimruntime_dir == NUL
3844 #endif
3847 p = mch_getenv((char_u *)"VIM");
3848 if (p != NULL && *p == NUL) /* empty is the same as not set */
3849 p = NULL;
3850 if (p != NULL)
3852 p = vim_version_dir(p);
3853 if (p != NULL)
3854 *mustfree = TRUE;
3855 else
3856 p = mch_getenv((char_u *)"VIM");
3858 #if defined(FEAT_MBYTE) && defined(WIN3264)
3859 if (enc_utf8)
3861 int len;
3862 char_u *pp;
3864 /* Convert from active codepage to UTF-8. Other conversions
3865 * are not done, because they would fail for non-ASCII
3866 * characters. */
3867 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
3868 if (pp != NULL)
3870 if (mustfree)
3871 vim_free(p);
3872 p = pp;
3873 *mustfree = TRUE;
3876 #endif
3881 * When expanding $VIM or $VIMRUNTIME fails, try using:
3882 * - the directory name from 'helpfile' (unless it contains '$')
3883 * - the executable name from argv[0]
3885 if (p == NULL)
3887 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3888 p = p_hf;
3889 #ifdef USE_EXE_NAME
3891 * Use the name of the executable, obtained from argv[0].
3893 else
3894 p = exe_name;
3895 #endif
3896 if (p != NULL)
3898 /* remove the file name */
3899 pend = gettail(p);
3901 /* remove "doc/" from 'helpfile', if present */
3902 if (p == p_hf)
3903 pend = remove_tail(p, pend, (char_u *)"doc");
3905 #ifdef USE_EXE_NAME
3906 # ifdef MACOS_X
3907 /* remove "MacOS" from exe_name and add "Resources/vim" */
3908 if (p == exe_name)
3910 char_u *pend1;
3911 char_u *pnew;
3913 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
3914 if (pend1 != pend)
3916 pnew = alloc((unsigned)(pend1 - p) + 15);
3917 if (pnew != NULL)
3919 STRNCPY(pnew, p, (pend1 - p));
3920 STRCPY(pnew + (pend1 - p), "Resources/vim");
3921 p = pnew;
3922 pend = p + STRLEN(p);
3926 # endif
3927 /* remove "src/" from exe_name, if present */
3928 if (p == exe_name)
3929 pend = remove_tail(p, pend, (char_u *)"src");
3930 #endif
3932 /* for $VIM, remove "runtime/" or "vim54/", if present */
3933 if (!vimruntime)
3935 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
3936 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
3939 /* remove trailing path separator */
3940 #ifndef MACOS_CLASSIC
3941 /* With MacOS path (with colons) the final colon is required */
3942 /* to avoid confusion between absoulute and relative path */
3943 if (pend > p && after_pathsep(p, pend))
3944 --pend;
3945 #endif
3947 #ifdef MACOS_X
3948 if (p == exe_name || p == p_hf)
3949 #endif
3950 /* check that the result is a directory name */
3951 p = vim_strnsave(p, (int)(pend - p));
3953 if (p != NULL && !mch_isdir(p))
3955 vim_free(p);
3956 p = NULL;
3958 else
3960 #ifdef USE_EXE_NAME
3961 /* may add "/vim54" or "/runtime" if it exists */
3962 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
3964 vim_free(p);
3965 p = pend;
3967 #endif
3968 *mustfree = TRUE;
3973 #ifdef HAVE_PATHDEF
3974 /* When there is a pathdef.c file we can use default_vim_dir and
3975 * default_vimruntime_dir */
3976 if (p == NULL)
3978 /* Only use default_vimruntime_dir when it is not empty */
3979 if (vimruntime && *default_vimruntime_dir != NUL)
3981 p = default_vimruntime_dir;
3982 *mustfree = FALSE;
3984 else if (*default_vim_dir != NUL)
3986 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
3987 *mustfree = TRUE;
3988 else
3990 p = default_vim_dir;
3991 *mustfree = FALSE;
3995 #endif
3998 * Set the environment variable, so that the new value can be found fast
3999 * next time, and others can also use it (e.g. Perl).
4001 if (p != NULL)
4003 if (vimruntime)
4005 vim_setenv((char_u *)"VIMRUNTIME", p);
4006 didset_vimruntime = TRUE;
4007 #ifdef FEAT_GETTEXT
4009 char_u *buf = concat_str(p, (char_u *)"/lang");
4011 if (buf != NULL)
4013 bindtextdomain(VIMPACKAGE, (char *)buf);
4014 vim_free(buf);
4017 #endif
4019 else
4021 vim_setenv((char_u *)"VIM", p);
4022 didset_vim = TRUE;
4025 return p;
4029 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4030 * Return NULL if not, return its name in allocated memory otherwise.
4032 static char_u *
4033 vim_version_dir(vimdir)
4034 char_u *vimdir;
4036 char_u *p;
4038 if (vimdir == NULL || *vimdir == NUL)
4039 return NULL;
4040 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4041 if (p != NULL && mch_isdir(p))
4042 return p;
4043 vim_free(p);
4044 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4045 if (p != NULL && mch_isdir(p))
4046 return p;
4047 vim_free(p);
4048 return NULL;
4052 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4053 * the length of "name/". Otherwise return "pend".
4055 static char_u *
4056 remove_tail(p, pend, name)
4057 char_u *p;
4058 char_u *pend;
4059 char_u *name;
4061 int len = (int)STRLEN(name) + 1;
4062 char_u *newend = pend - len;
4064 if (newend >= p
4065 && fnamencmp(newend, name, len - 1) == 0
4066 && (newend == p || after_pathsep(p, newend)))
4067 return newend;
4068 return pend;
4072 * Call expand_env() and store the result in an allocated string.
4073 * This is not very memory efficient, this expects the result to be freed
4074 * again soon.
4076 char_u *
4077 expand_env_save(src)
4078 char_u *src;
4080 char_u *p;
4082 p = alloc(MAXPATHL);
4083 if (p != NULL)
4084 expand_env(src, p, MAXPATHL);
4085 return p;
4089 * Our portable version of setenv.
4091 void
4092 vim_setenv(name, val)
4093 char_u *name;
4094 char_u *val;
4096 #ifdef HAVE_SETENV
4097 mch_setenv((char *)name, (char *)val, 1);
4098 #else
4099 char_u *envbuf;
4102 * Putenv does not copy the string, it has to remain
4103 * valid. The allocated memory will never be freed.
4105 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4106 if (envbuf != NULL)
4108 sprintf((char *)envbuf, "%s=%s", name, val);
4109 putenv((char *)envbuf);
4111 #endif
4114 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4116 * Function given to ExpandGeneric() to obtain an environment variable name.
4118 /*ARGSUSED*/
4119 char_u *
4120 get_env_name(xp, idx)
4121 expand_T *xp;
4122 int idx;
4124 # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4126 * No environ[] on the Amiga and on the Mac (using MPW).
4128 return NULL;
4129 # else
4130 # ifndef __WIN32__
4131 /* Borland C++ 5.2 has this in a header file. */
4132 extern char **environ;
4133 # endif
4134 # define ENVNAMELEN 100
4135 static char_u name[ENVNAMELEN];
4136 char_u *str;
4137 int n;
4139 str = (char_u *)environ[idx];
4140 if (str == NULL)
4141 return NULL;
4143 for (n = 0; n < ENVNAMELEN - 1; ++n)
4145 if (str[n] == '=' || str[n] == NUL)
4146 break;
4147 name[n] = str[n];
4149 name[n] = NUL;
4150 return name;
4151 # endif
4153 #endif
4156 * Replace home directory by "~" in each space or comma separated file name in
4157 * 'src'.
4158 * If anything fails (except when out of space) dst equals src.
4160 void
4161 home_replace(buf, src, dst, dstlen, one)
4162 buf_T *buf; /* when not NULL, check for help files */
4163 char_u *src; /* input file name */
4164 char_u *dst; /* where to put the result */
4165 int dstlen; /* maximum length of the result */
4166 int one; /* if TRUE, only replace one file name, include
4167 spaces and commas in the file name. */
4169 size_t dirlen = 0, envlen = 0;
4170 size_t len;
4171 char_u *homedir_env;
4172 char_u *p;
4174 if (src == NULL)
4176 *dst = NUL;
4177 return;
4181 * If the file is a help file, remove the path completely.
4183 if (buf != NULL && buf->b_help)
4185 STRCPY(dst, gettail(src));
4186 return;
4190 * We check both the value of the $HOME environment variable and the
4191 * "real" home directory.
4193 if (homedir != NULL)
4194 dirlen = STRLEN(homedir);
4196 #ifdef VMS
4197 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4198 #else
4199 homedir_env = mch_getenv((char_u *)"HOME");
4200 #endif
4202 if (homedir_env != NULL && *homedir_env == NUL)
4203 homedir_env = NULL;
4204 if (homedir_env != NULL)
4205 envlen = STRLEN(homedir_env);
4207 if (!one)
4208 src = skipwhite(src);
4209 while (*src && dstlen > 0)
4212 * Here we are at the beginning of a file name.
4213 * First, check to see if the beginning of the file name matches
4214 * $HOME or the "real" home directory. Check that there is a '/'
4215 * after the match (so that if e.g. the file is "/home/pieter/bla",
4216 * and the home directory is "/home/piet", the file does not end up
4217 * as "~er/bla" (which would seem to indicate the file "bla" in user
4218 * er's home directory)).
4220 p = homedir;
4221 len = dirlen;
4222 for (;;)
4224 if ( len
4225 && fnamencmp(src, p, len) == 0
4226 && (vim_ispathsep(src[len])
4227 || (!one && (src[len] == ',' || src[len] == ' '))
4228 || src[len] == NUL))
4230 src += len;
4231 if (--dstlen > 0)
4232 *dst++ = '~';
4235 * If it's just the home directory, add "/".
4237 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4238 *dst++ = '/';
4239 break;
4241 if (p == homedir_env)
4242 break;
4243 p = homedir_env;
4244 len = envlen;
4247 /* if (!one) skip to separator: space or comma */
4248 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4249 *dst++ = *src++;
4250 /* skip separator */
4251 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4252 *dst++ = *src++;
4254 /* if (dstlen == 0) out of space, what to do??? */
4256 *dst = NUL;
4260 * Like home_replace, store the replaced string in allocated memory.
4261 * When something fails, NULL is returned.
4263 char_u *
4264 home_replace_save(buf, src)
4265 buf_T *buf; /* when not NULL, check for help files */
4266 char_u *src; /* input file name */
4268 char_u *dst;
4269 unsigned len;
4271 len = 3; /* space for "~/" and trailing NUL */
4272 if (src != NULL) /* just in case */
4273 len += (unsigned)STRLEN(src);
4274 dst = alloc(len);
4275 if (dst != NULL)
4276 home_replace(buf, src, dst, len, TRUE);
4277 return dst;
4281 * Compare two file names and return:
4282 * FPC_SAME if they both exist and are the same file.
4283 * FPC_SAMEX if they both don't exist and have the same file name.
4284 * FPC_DIFF if they both exist and are different files.
4285 * FPC_NOTX if they both don't exist.
4286 * FPC_DIFFX if one of them doesn't exist.
4287 * For the first name environment variables are expanded
4290 fullpathcmp(s1, s2, checkname)
4291 char_u *s1, *s2;
4292 int checkname; /* when both don't exist, check file names */
4294 #ifdef UNIX
4295 char_u exp1[MAXPATHL];
4296 char_u full1[MAXPATHL];
4297 char_u full2[MAXPATHL];
4298 struct stat st1, st2;
4299 int r1, r2;
4301 expand_env(s1, exp1, MAXPATHL);
4302 r1 = mch_stat((char *)exp1, &st1);
4303 r2 = mch_stat((char *)s2, &st2);
4304 if (r1 != 0 && r2 != 0)
4306 /* if mch_stat() doesn't work, may compare the names */
4307 if (checkname)
4309 if (fnamecmp(exp1, s2) == 0)
4310 return FPC_SAMEX;
4311 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4312 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4313 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4314 return FPC_SAMEX;
4316 return FPC_NOTX;
4318 if (r1 != 0 || r2 != 0)
4319 return FPC_DIFFX;
4320 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4321 return FPC_SAME;
4322 return FPC_DIFF;
4323 #else
4324 char_u *exp1; /* expanded s1 */
4325 char_u *full1; /* full path of s1 */
4326 char_u *full2; /* full path of s2 */
4327 int retval = FPC_DIFF;
4328 int r1, r2;
4330 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4331 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4333 full1 = exp1 + MAXPATHL;
4334 full2 = full1 + MAXPATHL;
4336 expand_env(s1, exp1, MAXPATHL);
4337 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4338 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4340 /* If vim_FullName() fails, the file probably doesn't exist. */
4341 if (r1 != OK && r2 != OK)
4343 if (checkname && fnamecmp(exp1, s2) == 0)
4344 retval = FPC_SAMEX;
4345 else
4346 retval = FPC_NOTX;
4348 else if (r1 != OK || r2 != OK)
4349 retval = FPC_DIFFX;
4350 else if (fnamecmp(full1, full2))
4351 retval = FPC_DIFF;
4352 else
4353 retval = FPC_SAME;
4354 vim_free(exp1);
4356 return retval;
4357 #endif
4361 * Get the tail of a path: the file name.
4362 * Fail safe: never returns NULL.
4364 char_u *
4365 gettail(fname)
4366 char_u *fname;
4368 char_u *p1, *p2;
4370 if (fname == NULL)
4371 return (char_u *)"";
4372 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4374 if (vim_ispathsep(*p2))
4375 p1 = p2 + 1;
4376 mb_ptr_adv(p2);
4378 return p1;
4382 * Get pointer to tail of "fname", including path separators. Putting a NUL
4383 * here leaves the directory name. Takes care of "c:/" and "//".
4384 * Always returns a valid pointer.
4386 char_u *
4387 gettail_sep(fname)
4388 char_u *fname;
4390 char_u *p;
4391 char_u *t;
4393 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4394 t = gettail(fname);
4395 while (t > p && after_pathsep(fname, t))
4396 --t;
4397 #ifdef VMS
4398 /* path separator is part of the path */
4399 ++t;
4400 #endif
4401 return t;
4405 * get the next path component (just after the next path separator).
4407 char_u *
4408 getnextcomp(fname)
4409 char_u *fname;
4411 while (*fname && !vim_ispathsep(*fname))
4412 mb_ptr_adv(fname);
4413 if (*fname)
4414 ++fname;
4415 return fname;
4419 * Get a pointer to one character past the head of a path name.
4420 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4421 * If there is no head, path is returned.
4423 char_u *
4424 get_past_head(path)
4425 char_u *path;
4427 char_u *retval;
4429 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4430 /* may skip "c:" */
4431 if (isalpha(path[0]) && path[1] == ':')
4432 retval = path + 2;
4433 else
4434 retval = path;
4435 #else
4436 # if defined(AMIGA)
4437 /* may skip "label:" */
4438 retval = vim_strchr(path, ':');
4439 if (retval == NULL)
4440 retval = path;
4441 # else /* Unix */
4442 retval = path;
4443 # endif
4444 #endif
4446 while (vim_ispathsep(*retval))
4447 ++retval;
4449 return retval;
4453 * return TRUE if 'c' is a path separator.
4456 vim_ispathsep(c)
4457 int c;
4459 #ifdef RISCOS
4460 return (c == '.' || c == ':');
4461 #else
4462 # ifdef UNIX
4463 return (c == '/'); /* UNIX has ':' inside file names */
4464 # else
4465 # ifdef BACKSLASH_IN_FILENAME
4466 return (c == ':' || c == '/' || c == '\\');
4467 # else
4468 # ifdef VMS
4469 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4470 return (c == ':' || c == '[' || c == ']' || c == '/'
4471 || c == '<' || c == '>' || c == '"' );
4472 # else /* Amiga */
4473 return (c == ':' || c == '/');
4474 # endif /* VMS */
4475 # endif
4476 # endif
4477 #endif /* RISC OS */
4480 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
4482 * return TRUE if 'c' is a path list separator.
4485 vim_ispathlistsep(c)
4486 int c;
4488 #ifdef UNIX
4489 return (c == ':');
4490 #else
4491 return (c == ';'); /* might not be right for every system... */
4492 #endif
4494 #endif
4496 #if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4497 || defined(FEAT_EVAL) || defined(PROTO)
4499 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4500 * It's done in-place.
4502 void
4503 shorten_dir(str)
4504 char_u *str;
4506 char_u *tail, *s, *d;
4507 int skip = FALSE;
4509 tail = gettail(str);
4510 d = str;
4511 for (s = str; ; ++s)
4513 if (s >= tail) /* copy the whole tail */
4515 *d++ = *s;
4516 if (*s == NUL)
4517 break;
4519 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4521 *d++ = *s;
4522 skip = FALSE;
4524 else if (!skip)
4526 *d++ = *s; /* copy next char */
4527 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4528 skip = TRUE;
4529 # ifdef FEAT_MBYTE
4530 if (has_mbyte)
4532 int l = mb_ptr2len(s);
4534 while (--l > 0)
4535 *d++ = *++s;
4537 # endif
4541 #endif
4544 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4545 * Also returns TRUE if there is no directory name.
4546 * "fname" must be writable!.
4549 dir_of_file_exists(fname)
4550 char_u *fname;
4552 char_u *p;
4553 int c;
4554 int retval;
4556 p = gettail_sep(fname);
4557 if (p == fname)
4558 return TRUE;
4559 c = *p;
4560 *p = NUL;
4561 retval = mch_isdir(fname);
4562 *p = c;
4563 return retval;
4566 #if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4567 || defined(PROTO)
4569 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4572 vim_fnamecmp(x, y)
4573 char_u *x, *y;
4575 return vim_fnamencmp(x, y, MAXPATHL);
4579 vim_fnamencmp(x, y, len)
4580 char_u *x, *y;
4581 size_t len;
4583 while (len > 0 && *x && *y)
4585 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4586 && !(*x == '/' && *y == '\\')
4587 && !(*x == '\\' && *y == '/'))
4588 break;
4589 ++x;
4590 ++y;
4591 --len;
4593 if (len == 0)
4594 return 0;
4595 return (*x - *y);
4597 #endif
4600 * Concatenate file names fname1 and fname2 into allocated memory.
4601 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
4603 char_u *
4604 concat_fnames(fname1, fname2, sep)
4605 char_u *fname1;
4606 char_u *fname2;
4607 int sep;
4609 char_u *dest;
4611 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4612 if (dest != NULL)
4614 STRCPY(dest, fname1);
4615 if (sep)
4616 add_pathsep(dest);
4617 STRCAT(dest, fname2);
4619 return dest;
4622 #if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4624 * Concatenate two strings and return the result in allocated memory.
4625 * Returns NULL when out of memory.
4627 char_u *
4628 concat_str(str1, str2)
4629 char_u *str1;
4630 char_u *str2;
4632 char_u *dest;
4633 size_t l = STRLEN(str1);
4635 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4636 if (dest != NULL)
4638 STRCPY(dest, str1);
4639 STRCPY(dest + l, str2);
4641 return dest;
4643 #endif
4646 * Add a path separator to a file name, unless it already ends in a path
4647 * separator.
4649 void
4650 add_pathsep(p)
4651 char_u *p;
4653 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
4654 STRCAT(p, PATHSEPSTR);
4658 * FullName_save - Make an allocated copy of a full file name.
4659 * Returns NULL when out of memory.
4661 char_u *
4662 FullName_save(fname, force)
4663 char_u *fname;
4664 int force; /* force expansion, even when it already looks
4665 like a full path name */
4667 char_u *buf;
4668 char_u *new_fname = NULL;
4670 if (fname == NULL)
4671 return NULL;
4673 buf = alloc((unsigned)MAXPATHL);
4674 if (buf != NULL)
4676 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4677 new_fname = vim_strsave(buf);
4678 else
4679 new_fname = vim_strsave(fname);
4680 vim_free(buf);
4682 return new_fname;
4685 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4687 static char_u *skip_string __ARGS((char_u *p));
4690 * Find the start of a comment, not knowing if we are in a comment right now.
4691 * Search starts at w_cursor.lnum and goes backwards.
4693 pos_T *
4694 find_start_comment(ind_maxcomment) /* XXX */
4695 int ind_maxcomment;
4697 pos_T *pos;
4698 char_u *line;
4699 char_u *p;
4700 int cur_maxcomment = ind_maxcomment;
4702 for (;;)
4704 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4705 if (pos == NULL)
4706 break;
4709 * Check if the comment start we found is inside a string.
4710 * If it is then restrict the search to below this line and try again.
4712 line = ml_get(pos->lnum);
4713 for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
4714 p = skip_string(p);
4715 if ((unsigned)(p - line) <= pos->col)
4716 break;
4717 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4718 if (cur_maxcomment <= 0)
4720 pos = NULL;
4721 break;
4724 return pos;
4728 * Skip to the end of a "string" and a 'c' character.
4729 * If there is no string or character, return argument unmodified.
4731 static char_u *
4732 skip_string(p)
4733 char_u *p;
4735 int i;
4738 * We loop, because strings may be concatenated: "date""time".
4740 for ( ; ; ++p)
4742 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4744 if (!p[1]) /* ' at end of line */
4745 break;
4746 i = 2;
4747 if (p[1] == '\\') /* '\n' or '\000' */
4749 ++i;
4750 while (vim_isdigit(p[i - 1])) /* '\000' */
4751 ++i;
4753 if (p[i] == '\'') /* check for trailing ' */
4755 p += i;
4756 continue;
4759 else if (p[0] == '"') /* start of string */
4761 for (++p; p[0]; ++p)
4763 if (p[0] == '\\' && p[1] != NUL)
4764 ++p;
4765 else if (p[0] == '"') /* end of string */
4766 break;
4768 if (p[0] == '"')
4769 continue;
4771 break; /* no string found */
4773 if (!*p)
4774 --p; /* backup from NUL */
4775 return p;
4777 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
4779 #if defined(FEAT_CINDENT) || defined(PROTO)
4782 * Do C or expression indenting on the current line.
4784 void
4785 do_c_expr_indent()
4787 # ifdef FEAT_EVAL
4788 if (*curbuf->b_p_inde != NUL)
4789 fixthisline(get_expr_indent);
4790 else
4791 # endif
4792 fixthisline(get_c_indent);
4796 * Functions for C-indenting.
4797 * Most of this originally comes from Eric Fischer.
4800 * Below "XXX" means that this function may unlock the current line.
4803 static char_u *cin_skipcomment __ARGS((char_u *));
4804 static int cin_nocode __ARGS((char_u *));
4805 static pos_T *find_line_comment __ARGS((void));
4806 static int cin_islabel_skip __ARGS((char_u **));
4807 static int cin_isdefault __ARGS((char_u *));
4808 static char_u *after_label __ARGS((char_u *l));
4809 static int get_indent_nolabel __ARGS((linenr_T lnum));
4810 static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4811 static int cin_first_id_amount __ARGS((void));
4812 static int cin_get_equal_amount __ARGS((linenr_T lnum));
4813 static int cin_ispreproc __ARGS((char_u *));
4814 static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4815 static int cin_iscomment __ARGS((char_u *));
4816 static int cin_islinecomment __ARGS((char_u *));
4817 static int cin_isterminated __ARGS((char_u *, int, int));
4818 static int cin_isinit __ARGS((void));
4819 static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4820 static int cin_isif __ARGS((char_u *));
4821 static int cin_iselse __ARGS((char_u *));
4822 static int cin_isdo __ARGS((char_u *));
4823 static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
4824 static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
4825 static int cin_isbreak __ARGS((char_u *));
4826 static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
4827 static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
4828 static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4829 static int cin_skip2pos __ARGS((pos_T *trypos));
4830 static pos_T *find_start_brace __ARGS((int));
4831 static pos_T *find_match_paren __ARGS((int, int));
4832 static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4833 static int find_last_paren __ARGS((char_u *l, int start, int end));
4834 static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4836 static int ind_hash_comment = 0; /* # starts a comment */
4839 * Skip over white space and C comments within the line.
4840 * Also skip over Perl/shell comments if desired.
4842 static char_u *
4843 cin_skipcomment(s)
4844 char_u *s;
4846 while (*s)
4848 char_u *prev_s = s;
4850 s = skipwhite(s);
4852 /* Perl/shell # comment comment continues until eol. Require a space
4853 * before # to avoid recognizing $#array. */
4854 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
4856 s += STRLEN(s);
4857 break;
4859 if (*s != '/')
4860 break;
4861 ++s;
4862 if (*s == '/') /* slash-slash comment continues till eol */
4864 s += STRLEN(s);
4865 break;
4867 if (*s != '*')
4868 break;
4869 for (++s; *s; ++s) /* skip slash-star comment */
4870 if (s[0] == '*' && s[1] == '/')
4872 s += 2;
4873 break;
4876 return s;
4880 * Return TRUE if there there is no code at *s. White space and comments are
4881 * not considered code.
4883 static int
4884 cin_nocode(s)
4885 char_u *s;
4887 return *cin_skipcomment(s) == NUL;
4891 * Check previous lines for a "//" line comment, skipping over blank lines.
4893 static pos_T *
4894 find_line_comment() /* XXX */
4896 static pos_T pos;
4897 char_u *line;
4898 char_u *p;
4900 pos = curwin->w_cursor;
4901 while (--pos.lnum > 0)
4903 line = ml_get(pos.lnum);
4904 p = skipwhite(line);
4905 if (cin_islinecomment(p))
4907 pos.col = (int)(p - line);
4908 return &pos;
4910 if (*p != NUL)
4911 break;
4913 return NULL;
4917 * Check if string matches "label:"; move to character after ':' if true.
4919 static int
4920 cin_islabel_skip(s)
4921 char_u **s;
4923 if (!vim_isIDc(**s)) /* need at least one ID character */
4924 return FALSE;
4926 while (vim_isIDc(**s))
4927 (*s)++;
4929 *s = cin_skipcomment(*s);
4931 /* "::" is not a label, it's C++ */
4932 return (**s == ':' && *++*s != ':');
4936 * Recognize a label: "label:".
4937 * Note: curwin->w_cursor must be where we are looking for the label.
4940 cin_islabel(ind_maxcomment) /* XXX */
4941 int ind_maxcomment;
4943 char_u *s;
4945 s = cin_skipcomment(ml_get_curline());
4948 * Exclude "default" from labels, since it should be indented
4949 * like a switch label. Same for C++ scope declarations.
4951 if (cin_isdefault(s))
4952 return FALSE;
4953 if (cin_isscopedecl(s))
4954 return FALSE;
4956 if (cin_islabel_skip(&s))
4959 * Only accept a label if the previous line is terminated or is a case
4960 * label.
4962 pos_T cursor_save;
4963 pos_T *trypos;
4964 char_u *line;
4966 cursor_save = curwin->w_cursor;
4967 while (curwin->w_cursor.lnum > 1)
4969 --curwin->w_cursor.lnum;
4972 * If we're in a comment now, skip to the start of the comment.
4974 curwin->w_cursor.col = 0;
4975 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
4976 curwin->w_cursor = *trypos;
4978 line = ml_get_curline();
4979 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
4980 continue;
4981 if (*(line = cin_skipcomment(line)) == NUL)
4982 continue;
4984 curwin->w_cursor = cursor_save;
4985 if (cin_isterminated(line, TRUE, FALSE)
4986 || cin_isscopedecl(line)
4987 || cin_iscase(line)
4988 || (cin_islabel_skip(&line) && cin_nocode(line)))
4989 return TRUE;
4990 return FALSE;
4992 curwin->w_cursor = cursor_save;
4993 return TRUE; /* label at start of file??? */
4995 return FALSE;
4999 * Recognize structure initialization and enumerations.
5000 * Q&D-Implementation:
5001 * check for "=" at end or "[typedef] enum" at beginning of line.
5003 static int
5004 cin_isinit(void)
5006 char_u *s;
5008 s = cin_skipcomment(ml_get_curline());
5010 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5011 s = cin_skipcomment(s + 7);
5013 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5014 return TRUE;
5016 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5017 return TRUE;
5019 return FALSE;
5023 * Recognize a switch label: "case .*:" or "default:".
5026 cin_iscase(s)
5027 char_u *s;
5029 s = cin_skipcomment(s);
5030 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5032 for (s += 4; *s; ++s)
5034 s = cin_skipcomment(s);
5035 if (*s == ':')
5037 if (s[1] == ':') /* skip over "::" for C++ */
5038 ++s;
5039 else
5040 return TRUE;
5042 if (*s == '\'' && s[1] && s[2] == '\'')
5043 s += 2; /* skip over '.' */
5044 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5045 return FALSE; /* stop at comment */
5046 else if (*s == '"')
5047 return FALSE; /* stop at string */
5049 return FALSE;
5052 if (cin_isdefault(s))
5053 return TRUE;
5054 return FALSE;
5058 * Recognize a "default" switch label.
5060 static int
5061 cin_isdefault(s)
5062 char_u *s;
5064 return (STRNCMP(s, "default", 7) == 0
5065 && *(s = cin_skipcomment(s + 7)) == ':'
5066 && s[1] != ':');
5070 * Recognize a "public/private/proctected" scope declaration label.
5073 cin_isscopedecl(s)
5074 char_u *s;
5076 int i;
5078 s = cin_skipcomment(s);
5079 if (STRNCMP(s, "public", 6) == 0)
5080 i = 6;
5081 else if (STRNCMP(s, "protected", 9) == 0)
5082 i = 9;
5083 else if (STRNCMP(s, "private", 7) == 0)
5084 i = 7;
5085 else
5086 return FALSE;
5087 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5091 * Return a pointer to the first non-empty non-comment character after a ':'.
5092 * Return NULL if not found.
5093 * case 234: a = b;
5096 static char_u *
5097 after_label(l)
5098 char_u *l;
5100 for ( ; *l; ++l)
5102 if (*l == ':')
5104 if (l[1] == ':') /* skip over "::" for C++ */
5105 ++l;
5106 else if (!cin_iscase(l + 1))
5107 break;
5109 else if (*l == '\'' && l[1] && l[2] == '\'')
5110 l += 2; /* skip over 'x' */
5112 if (*l == NUL)
5113 return NULL;
5114 l = cin_skipcomment(l + 1);
5115 if (*l == NUL)
5116 return NULL;
5117 return l;
5121 * Get indent of line "lnum", skipping a label.
5122 * Return 0 if there is nothing after the label.
5124 static int
5125 get_indent_nolabel(lnum) /* XXX */
5126 linenr_T lnum;
5128 char_u *l;
5129 pos_T fp;
5130 colnr_T col;
5131 char_u *p;
5133 l = ml_get(lnum);
5134 p = after_label(l);
5135 if (p == NULL)
5136 return 0;
5138 fp.col = (colnr_T)(p - l);
5139 fp.lnum = lnum;
5140 getvcol(curwin, &fp, &col, NULL, NULL);
5141 return (int)col;
5145 * Find indent for line "lnum", ignoring any case or jump label.
5146 * Also return a pointer to the text (after the label) in "pp".
5147 * label: if (asdf && asdfasdf)
5150 static int
5151 skip_label(lnum, pp, ind_maxcomment)
5152 linenr_T lnum;
5153 char_u **pp;
5154 int ind_maxcomment;
5156 char_u *l;
5157 int amount;
5158 pos_T cursor_save;
5160 cursor_save = curwin->w_cursor;
5161 curwin->w_cursor.lnum = lnum;
5162 l = ml_get_curline();
5163 /* XXX */
5164 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5166 amount = get_indent_nolabel(lnum);
5167 l = after_label(ml_get_curline());
5168 if (l == NULL) /* just in case */
5169 l = ml_get_curline();
5171 else
5173 amount = get_indent();
5174 l = ml_get_curline();
5176 *pp = l;
5178 curwin->w_cursor = cursor_save;
5179 return amount;
5183 * Return the indent of the first variable name after a type in a declaration.
5184 * int a, indent of "a"
5185 * static struct foo b, indent of "b"
5186 * enum bla c, indent of "c"
5187 * Returns zero when it doesn't look like a declaration.
5189 static int
5190 cin_first_id_amount()
5192 char_u *line, *p, *s;
5193 int len;
5194 pos_T fp;
5195 colnr_T col;
5197 line = ml_get_curline();
5198 p = skipwhite(line);
5199 len = (int)(skiptowhite(p) - p);
5200 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5202 p = skipwhite(p + 6);
5203 len = (int)(skiptowhite(p) - p);
5205 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5206 p = skipwhite(p + 6);
5207 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5208 p = skipwhite(p + 4);
5209 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5210 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5212 s = skipwhite(p + len);
5213 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5214 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5215 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5216 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5217 p = s;
5219 for (len = 0; vim_isIDc(p[len]); ++len)
5221 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5222 return 0;
5224 p = skipwhite(p + len);
5225 fp.lnum = curwin->w_cursor.lnum;
5226 fp.col = (colnr_T)(p - line);
5227 getvcol(curwin, &fp, &col, NULL, NULL);
5228 return (int)col;
5232 * Return the indent of the first non-blank after an equal sign.
5233 * char *foo = "here";
5234 * Return zero if no (useful) equal sign found.
5235 * Return -1 if the line above "lnum" ends in a backslash.
5236 * foo = "asdf\
5237 * asdf\
5238 * here";
5240 static int
5241 cin_get_equal_amount(lnum)
5242 linenr_T lnum;
5244 char_u *line;
5245 char_u *s;
5246 colnr_T col;
5247 pos_T fp;
5249 if (lnum > 1)
5251 line = ml_get(lnum - 1);
5252 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5253 return -1;
5256 line = s = ml_get(lnum);
5257 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5259 if (cin_iscomment(s)) /* ignore comments */
5260 s = cin_skipcomment(s);
5261 else
5262 ++s;
5264 if (*s != '=')
5265 return 0;
5267 s = skipwhite(s + 1);
5268 if (cin_nocode(s))
5269 return 0;
5271 if (*s == '"') /* nice alignment for continued strings */
5272 ++s;
5274 fp.lnum = lnum;
5275 fp.col = (colnr_T)(s - line);
5276 getvcol(curwin, &fp, &col, NULL, NULL);
5277 return (int)col;
5281 * Recognize a preprocessor statement: Any line that starts with '#'.
5283 static int
5284 cin_ispreproc(s)
5285 char_u *s;
5287 s = skipwhite(s);
5288 if (*s == '#')
5289 return TRUE;
5290 return FALSE;
5294 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5295 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5296 * start and return the line in "*pp".
5298 static int
5299 cin_ispreproc_cont(pp, lnump)
5300 char_u **pp;
5301 linenr_T *lnump;
5303 char_u *line = *pp;
5304 linenr_T lnum = *lnump;
5305 int retval = FALSE;
5307 for (;;)
5309 if (cin_ispreproc(line))
5311 retval = TRUE;
5312 *lnump = lnum;
5313 break;
5315 if (lnum == 1)
5316 break;
5317 line = ml_get(--lnum);
5318 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5319 break;
5322 if (lnum != *lnump)
5323 *pp = ml_get(*lnump);
5324 return retval;
5328 * Recognize the start of a C or C++ comment.
5330 static int
5331 cin_iscomment(p)
5332 char_u *p;
5334 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5338 * Recognize the start of a "//" comment.
5340 static int
5341 cin_islinecomment(p)
5342 char_u *p;
5344 return (p[0] == '/' && p[1] == '/');
5348 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5349 * Don't consider "} else" a terminated line.
5350 * Return the character terminating the line (ending char's have precedence if
5351 * both apply in order to determine initializations).
5353 static int
5354 cin_isterminated(s, incl_open, incl_comma)
5355 char_u *s;
5356 int incl_open; /* include '{' at the end as terminator */
5357 int incl_comma; /* recognize a trailing comma */
5359 char_u found_start = 0;
5361 s = cin_skipcomment(s);
5363 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5364 found_start = *s;
5366 while (*s)
5368 /* skip over comments, "" strings and 'c'haracters */
5369 s = skip_string(cin_skipcomment(s));
5370 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5371 || (incl_comma && *s == ','))
5372 && cin_nocode(s + 1))
5373 return *s;
5375 if (*s)
5376 s++;
5378 return found_start;
5382 * Recognize the basic picture of a function declaration -- it needs to
5383 * have an open paren somewhere and a close paren at the end of the line and
5384 * no semicolons anywhere.
5385 * When a line ends in a comma we continue looking in the next line.
5386 * "sp" points to a string with the line. When looking at other lines it must
5387 * be restored to the line. When it's NULL fetch lines here.
5388 * "lnum" is where we start looking.
5390 static int
5391 cin_isfuncdecl(sp, first_lnum)
5392 char_u **sp;
5393 linenr_T first_lnum;
5395 char_u *s;
5396 linenr_T lnum = first_lnum;
5397 int retval = FALSE;
5399 if (sp == NULL)
5400 s = ml_get(lnum);
5401 else
5402 s = *sp;
5404 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5406 if (cin_iscomment(s)) /* ignore comments */
5407 s = cin_skipcomment(s);
5408 else
5409 ++s;
5411 if (*s != '(')
5412 return FALSE; /* ';', ' or " before any () or no '(' */
5414 while (*s && *s != ';' && *s != '\'' && *s != '"')
5416 if (*s == ')' && cin_nocode(s + 1))
5418 /* ')' at the end: may have found a match
5419 * Check for he previous line not to end in a backslash:
5420 * #if defined(x) && \
5421 * defined(y)
5423 lnum = first_lnum - 1;
5424 s = ml_get(lnum);
5425 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5426 retval = TRUE;
5427 goto done;
5429 if (*s == ',' && cin_nocode(s + 1))
5431 /* ',' at the end: continue looking in the next line */
5432 if (lnum >= curbuf->b_ml.ml_line_count)
5433 break;
5435 s = ml_get(++lnum);
5437 else if (cin_iscomment(s)) /* ignore comments */
5438 s = cin_skipcomment(s);
5439 else
5440 ++s;
5443 done:
5444 if (lnum != first_lnum && sp != NULL)
5445 *sp = ml_get(first_lnum);
5447 return retval;
5450 static int
5451 cin_isif(p)
5452 char_u *p;
5454 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5457 static int
5458 cin_iselse(p)
5459 char_u *p;
5461 if (*p == '}') /* accept "} else" */
5462 p = cin_skipcomment(p + 1);
5463 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5466 static int
5467 cin_isdo(p)
5468 char_u *p;
5470 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5474 * Check if this is a "while" that should have a matching "do".
5475 * We only accept a "while (condition) ;", with only white space between the
5476 * ')' and ';'. The condition may be spread over several lines.
5478 static int
5479 cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5480 char_u *p;
5481 linenr_T lnum;
5482 int ind_maxparen;
5484 pos_T cursor_save;
5485 pos_T *trypos;
5486 int retval = FALSE;
5488 p = cin_skipcomment(p);
5489 if (*p == '}') /* accept "} while (cond);" */
5490 p = cin_skipcomment(p + 1);
5491 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5493 cursor_save = curwin->w_cursor;
5494 curwin->w_cursor.lnum = lnum;
5495 curwin->w_cursor.col = 0;
5496 p = ml_get_curline();
5497 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5499 ++p;
5500 ++curwin->w_cursor.col;
5502 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5503 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5504 retval = TRUE;
5505 curwin->w_cursor = cursor_save;
5507 return retval;
5511 * Return TRUE if we are at the end of a do-while.
5512 * do
5513 * nothing;
5514 * while (foo
5515 * && bar); <-- here
5516 * Adjust the cursor to the line with "while".
5518 static int
5519 cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5520 int terminated;
5521 int ind_maxparen;
5522 int ind_maxcomment;
5524 char_u *line;
5525 char_u *p;
5526 char_u *s;
5527 pos_T *trypos;
5528 int i;
5530 if (terminated != ';') /* there must be a ';' at the end */
5531 return FALSE;
5533 p = line = ml_get_curline();
5534 while (*p != NUL)
5536 p = cin_skipcomment(p);
5537 if (*p == ')')
5539 s = skipwhite(p + 1);
5540 if (*s == ';' && cin_nocode(s + 1))
5542 /* Found ");" at end of the line, now check there is "while"
5543 * before the matching '('. XXX */
5544 i = (int)(p - line);
5545 curwin->w_cursor.col = i;
5546 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5547 if (trypos != NULL)
5549 s = cin_skipcomment(ml_get(trypos->lnum));
5550 if (*s == '}') /* accept "} while (cond);" */
5551 s = cin_skipcomment(s + 1);
5552 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5554 curwin->w_cursor.lnum = trypos->lnum;
5555 return TRUE;
5559 /* Searching may have made "line" invalid, get it again. */
5560 line = ml_get_curline();
5561 p = line + i;
5564 if (*p != NUL)
5565 ++p;
5567 return FALSE;
5570 static int
5571 cin_isbreak(p)
5572 char_u *p;
5574 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5578 * Find the position of a C++ base-class declaration or
5579 * constructor-initialization. eg:
5581 * class MyClass :
5582 * baseClass <-- here
5583 * class MyClass : public baseClass,
5584 * anotherBaseClass <-- here (should probably lineup ??)
5585 * MyClass::MyClass(...) :
5586 * baseClass(...) <-- here (constructor-initialization)
5588 * This is a lot of guessing. Watch out for "cond ? func() : foo".
5590 static int
5591 cin_is_cpp_baseclass(col)
5592 colnr_T *col; /* return: column to align with */
5594 char_u *s;
5595 int class_or_struct, lookfor_ctor_init, cpp_base_class;
5596 linenr_T lnum = curwin->w_cursor.lnum;
5597 char_u *line = ml_get_curline();
5599 *col = 0;
5601 s = skipwhite(line);
5602 if (*s == '#') /* skip #define FOO x ? (x) : x */
5603 return FALSE;
5604 s = cin_skipcomment(s);
5605 if (*s == NUL)
5606 return FALSE;
5608 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5610 /* Search for a line starting with '#', empty, ending in ';' or containing
5611 * '{' or '}' and start below it. This handles the following situations:
5612 * a = cond ?
5613 * func() :
5614 * asdf;
5615 * func::foo()
5616 * : something
5617 * {}
5618 * Foo::Foo (int one, int two)
5619 * : something(4),
5620 * somethingelse(3)
5621 * {}
5623 while (lnum > 1)
5625 line = ml_get(lnum - 1);
5626 s = skipwhite(line);
5627 if (*s == '#' || *s == NUL)
5628 break;
5629 while (*s != NUL)
5631 s = cin_skipcomment(s);
5632 if (*s == '{' || *s == '}'
5633 || (*s == ';' && cin_nocode(s + 1)))
5634 break;
5635 if (*s != NUL)
5636 ++s;
5638 if (*s != NUL)
5639 break;
5640 --lnum;
5643 line = ml_get(lnum);
5644 s = cin_skipcomment(line);
5645 for (;;)
5647 if (*s == NUL)
5649 if (lnum == curwin->w_cursor.lnum)
5650 break;
5651 /* Continue in the cursor line. */
5652 line = ml_get(++lnum);
5653 s = cin_skipcomment(line);
5654 if (*s == NUL)
5655 continue;
5658 if (s[0] == ':')
5660 if (s[1] == ':')
5662 /* skip double colon. It can't be a constructor
5663 * initialization any more */
5664 lookfor_ctor_init = FALSE;
5665 s = cin_skipcomment(s + 2);
5667 else if (lookfor_ctor_init || class_or_struct)
5669 /* we have something found, that looks like the start of
5670 * cpp-base-class-declaration or contructor-initialization */
5671 cpp_base_class = TRUE;
5672 lookfor_ctor_init = class_or_struct = FALSE;
5673 *col = 0;
5674 s = cin_skipcomment(s + 1);
5676 else
5677 s = cin_skipcomment(s + 1);
5679 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5680 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5682 class_or_struct = TRUE;
5683 lookfor_ctor_init = FALSE;
5685 if (*s == 'c')
5686 s = cin_skipcomment(s + 5);
5687 else
5688 s = cin_skipcomment(s + 6);
5690 else
5692 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5694 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5696 else if (s[0] == ')')
5698 /* Constructor-initialization is assumed if we come across
5699 * something like "):" */
5700 class_or_struct = FALSE;
5701 lookfor_ctor_init = TRUE;
5703 else if (s[0] == '?')
5705 /* Avoid seeing '() :' after '?' as constructor init. */
5706 return FALSE;
5708 else if (!vim_isIDc(s[0]))
5710 /* if it is not an identifier, we are wrong */
5711 class_or_struct = FALSE;
5712 lookfor_ctor_init = FALSE;
5714 else if (*col == 0)
5716 /* it can't be a constructor-initialization any more */
5717 lookfor_ctor_init = FALSE;
5719 /* the first statement starts here: lineup with this one... */
5720 if (cpp_base_class)
5721 *col = (colnr_T)(s - line);
5724 /* When the line ends in a comma don't align with it. */
5725 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5726 *col = 0;
5728 s = cin_skipcomment(s + 1);
5732 return cpp_base_class;
5735 static int
5736 get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5737 int col;
5738 int ind_maxparen;
5739 int ind_maxcomment;
5740 int ind_cpp_baseclass;
5742 int amount;
5743 colnr_T vcol;
5744 pos_T *trypos;
5746 if (col == 0)
5748 amount = get_indent();
5749 if (find_last_paren(ml_get_curline(), '(', ')')
5750 && (trypos = find_match_paren(ind_maxparen,
5751 ind_maxcomment)) != NULL)
5752 amount = get_indent_lnum(trypos->lnum); /* XXX */
5753 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5754 amount += ind_cpp_baseclass;
5756 else
5758 curwin->w_cursor.col = col;
5759 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5760 amount = (int)vcol;
5762 if (amount < ind_cpp_baseclass)
5763 amount = ind_cpp_baseclass;
5764 return amount;
5768 * Return TRUE if string "s" ends with the string "find", possibly followed by
5769 * white space and comments. Skip strings and comments.
5770 * Ignore "ignore" after "find" if it's not NULL.
5772 static int
5773 cin_ends_in(s, find, ignore)
5774 char_u *s;
5775 char_u *find;
5776 char_u *ignore;
5778 char_u *p = s;
5779 char_u *r;
5780 int len = (int)STRLEN(find);
5782 while (*p != NUL)
5784 p = cin_skipcomment(p);
5785 if (STRNCMP(p, find, len) == 0)
5787 r = skipwhite(p + len);
5788 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5789 r = skipwhite(r + STRLEN(ignore));
5790 if (cin_nocode(r))
5791 return TRUE;
5793 if (*p != NUL)
5794 ++p;
5796 return FALSE;
5800 * Skip strings, chars and comments until at or past "trypos".
5801 * Return the column found.
5803 static int
5804 cin_skip2pos(trypos)
5805 pos_T *trypos;
5807 char_u *line;
5808 char_u *p;
5810 p = line = ml_get(trypos->lnum);
5811 while (*p && (colnr_T)(p - line) < trypos->col)
5813 if (cin_iscomment(p))
5814 p = cin_skipcomment(p);
5815 else
5817 p = skip_string(p);
5818 ++p;
5821 return (int)(p - line);
5825 * Find the '{' at the start of the block we are in.
5826 * Return NULL if no match found.
5827 * Ignore a '{' that is in a comment, makes indenting the next three lines
5828 * work. */
5829 /* foo() */
5830 /* { */
5831 /* } */
5833 static pos_T *
5834 find_start_brace(ind_maxcomment) /* XXX */
5835 int ind_maxcomment;
5837 pos_T cursor_save;
5838 pos_T *trypos;
5839 pos_T *pos;
5840 static pos_T pos_copy;
5842 cursor_save = curwin->w_cursor;
5843 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5845 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5846 trypos = &pos_copy;
5847 curwin->w_cursor = *trypos;
5848 pos = NULL;
5849 /* ignore the { if it's in a // or / * * / comment */
5850 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5851 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5852 break;
5853 if (pos != NULL)
5854 curwin->w_cursor.lnum = pos->lnum;
5856 curwin->w_cursor = cursor_save;
5857 return trypos;
5861 * Find the matching '(', failing if it is in a comment.
5862 * Return NULL of no match found.
5864 static pos_T *
5865 find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5866 int ind_maxparen;
5867 int ind_maxcomment;
5869 pos_T cursor_save;
5870 pos_T *trypos;
5871 static pos_T pos_copy;
5873 cursor_save = curwin->w_cursor;
5874 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5876 /* check if the ( is in a // comment */
5877 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5878 trypos = NULL;
5879 else
5881 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5882 trypos = &pos_copy;
5883 curwin->w_cursor = *trypos;
5884 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5885 trypos = NULL;
5888 curwin->w_cursor = cursor_save;
5889 return trypos;
5893 * Return ind_maxparen corrected for the difference in line number between the
5894 * cursor position and "startpos". This makes sure that searching for a
5895 * matching paren above the cursor line doesn't find a match because of
5896 * looking a few lines further.
5898 static int
5899 corr_ind_maxparen(ind_maxparen, startpos)
5900 int ind_maxparen;
5901 pos_T *startpos;
5903 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5905 if (n > 0 && n < ind_maxparen / 2)
5906 return ind_maxparen - (int)n;
5907 return ind_maxparen;
5911 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5912 * line "l".
5914 static int
5915 find_last_paren(l, start, end)
5916 char_u *l;
5917 int start, end;
5919 int i;
5920 int retval = FALSE;
5921 int open_count = 0;
5923 curwin->w_cursor.col = 0; /* default is start of line */
5925 for (i = 0; l[i]; i++)
5927 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5928 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5929 if (l[i] == start)
5930 ++open_count;
5931 else if (l[i] == end)
5933 if (open_count > 0)
5934 --open_count;
5935 else
5937 curwin->w_cursor.col = i;
5938 retval = TRUE;
5942 return retval;
5946 get_c_indent()
5949 * spaces from a block's opening brace the prevailing indent for that
5950 * block should be
5952 int ind_level = curbuf->b_p_sw;
5955 * spaces from the edge of the line an open brace that's at the end of a
5956 * line is imagined to be.
5958 int ind_open_imag = 0;
5961 * spaces from the prevailing indent for a line that is not precededof by
5962 * an opening brace.
5964 int ind_no_brace = 0;
5967 * column where the first { of a function should be located }
5969 int ind_first_open = 0;
5972 * spaces from the prevailing indent a leftmost open brace should be
5973 * located
5975 int ind_open_extra = 0;
5978 * spaces from the matching open brace (real location for one at the left
5979 * edge; imaginary location from one that ends a line) the matching close
5980 * brace should be located
5982 int ind_close_extra = 0;
5985 * spaces from the edge of the line an open brace sitting in the leftmost
5986 * column is imagined to be
5988 int ind_open_left_imag = 0;
5991 * spaces from the switch() indent a "case xx" label should be located
5993 int ind_case = curbuf->b_p_sw;
5996 * spaces from the "case xx:" code after a switch() should be located
5998 int ind_case_code = curbuf->b_p_sw;
6001 * lineup break at end of case in switch() with case label
6003 int ind_case_break = 0;
6006 * spaces from the class declaration indent a scope declaration label
6007 * should be located
6009 int ind_scopedecl = curbuf->b_p_sw;
6012 * spaces from the scope declaration label code should be located
6014 int ind_scopedecl_code = curbuf->b_p_sw;
6017 * amount K&R-style parameters should be indented
6019 int ind_param = curbuf->b_p_sw;
6022 * amount a function type spec should be indented
6024 int ind_func_type = curbuf->b_p_sw;
6027 * amount a cpp base class declaration or constructor initialization
6028 * should be indented
6030 int ind_cpp_baseclass = curbuf->b_p_sw;
6033 * additional spaces beyond the prevailing indent a continuation line
6034 * should be located
6036 int ind_continuation = curbuf->b_p_sw;
6039 * spaces from the indent of the line with an unclosed parentheses
6041 int ind_unclosed = curbuf->b_p_sw * 2;
6044 * spaces from the indent of the line with an unclosed parentheses, which
6045 * itself is also unclosed
6047 int ind_unclosed2 = curbuf->b_p_sw;
6050 * suppress ignoring spaces from the indent of a line starting with an
6051 * unclosed parentheses.
6053 int ind_unclosed_noignore = 0;
6056 * If the opening paren is the last nonwhite character on the line, and
6057 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6058 * context (for very long lines).
6060 int ind_unclosed_wrapped = 0;
6063 * suppress ignoring white space when lining up with the character after
6064 * an unclosed parentheses.
6066 int ind_unclosed_whiteok = 0;
6069 * indent a closing parentheses under the line start of the matching
6070 * opening parentheses.
6072 int ind_matching_paren = 0;
6075 * indent a closing parentheses under the previous line.
6077 int ind_paren_prev = 0;
6080 * Extra indent for comments.
6082 int ind_comment = 0;
6085 * spaces from the comment opener when there is nothing after it.
6087 int ind_in_comment = 3;
6090 * boolean: if non-zero, use ind_in_comment even if there is something
6091 * after the comment opener.
6093 int ind_in_comment2 = 0;
6096 * max lines to search for an open paren
6098 int ind_maxparen = 20;
6101 * max lines to search for an open comment
6103 int ind_maxcomment = 70;
6106 * handle braces for java code
6108 int ind_java = 0;
6111 * handle blocked cases correctly
6113 int ind_keep_case_label = 0;
6115 pos_T cur_curpos;
6116 int amount;
6117 int scope_amount;
6118 int cur_amount = MAXCOL;
6119 colnr_T col;
6120 char_u *theline;
6121 char_u *linecopy;
6122 pos_T *trypos;
6123 pos_T *tryposBrace = NULL;
6124 pos_T our_paren_pos;
6125 char_u *start;
6126 int start_brace;
6127 #define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
6128 #define BRACE_AT_START 2 /* '{' is at start of line */
6129 #define BRACE_AT_END 3 /* '{' is at end of line */
6130 linenr_T ourscope;
6131 char_u *l;
6132 char_u *look;
6133 char_u terminated;
6134 int lookfor;
6135 #define LOOKFOR_INITIAL 0
6136 #define LOOKFOR_IF 1
6137 #define LOOKFOR_DO 2
6138 #define LOOKFOR_CASE 3
6139 #define LOOKFOR_ANY 4
6140 #define LOOKFOR_TERM 5
6141 #define LOOKFOR_UNTERM 6
6142 #define LOOKFOR_SCOPEDECL 7
6143 #define LOOKFOR_NOBREAK 8
6144 #define LOOKFOR_CPP_BASECLASS 9
6145 #define LOOKFOR_ENUM_OR_INIT 10
6147 int whilelevel;
6148 linenr_T lnum;
6149 char_u *options;
6150 int fraction = 0; /* init for GCC */
6151 int divider;
6152 int n;
6153 int iscase;
6154 int lookfor_break;
6155 int cont_amount = 0; /* amount for continuation line */
6157 for (options = curbuf->b_p_cino; *options; )
6159 l = options++;
6160 if (*options == '-')
6161 ++options;
6162 n = getdigits(&options);
6163 divider = 0;
6164 if (*options == '.') /* ".5s" means a fraction */
6166 fraction = atol((char *)++options);
6167 while (VIM_ISDIGIT(*options))
6169 ++options;
6170 if (divider)
6171 divider *= 10;
6172 else
6173 divider = 10;
6176 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6178 if (n == 0 && fraction == 0)
6179 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6180 else
6182 n *= curbuf->b_p_sw;
6183 if (divider)
6184 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6186 ++options;
6188 if (l[1] == '-')
6189 n = -n;
6190 /* When adding an entry here, also update the default 'cinoptions' in
6191 * doc/indent.txt, and add explanation for it! */
6192 switch (*l)
6194 case '>': ind_level = n; break;
6195 case 'e': ind_open_imag = n; break;
6196 case 'n': ind_no_brace = n; break;
6197 case 'f': ind_first_open = n; break;
6198 case '{': ind_open_extra = n; break;
6199 case '}': ind_close_extra = n; break;
6200 case '^': ind_open_left_imag = n; break;
6201 case ':': ind_case = n; break;
6202 case '=': ind_case_code = n; break;
6203 case 'b': ind_case_break = n; break;
6204 case 'p': ind_param = n; break;
6205 case 't': ind_func_type = n; break;
6206 case '/': ind_comment = n; break;
6207 case 'c': ind_in_comment = n; break;
6208 case 'C': ind_in_comment2 = n; break;
6209 case 'i': ind_cpp_baseclass = n; break;
6210 case '+': ind_continuation = n; break;
6211 case '(': ind_unclosed = n; break;
6212 case 'u': ind_unclosed2 = n; break;
6213 case 'U': ind_unclosed_noignore = n; break;
6214 case 'W': ind_unclosed_wrapped = n; break;
6215 case 'w': ind_unclosed_whiteok = n; break;
6216 case 'm': ind_matching_paren = n; break;
6217 case 'M': ind_paren_prev = n; break;
6218 case ')': ind_maxparen = n; break;
6219 case '*': ind_maxcomment = n; break;
6220 case 'g': ind_scopedecl = n; break;
6221 case 'h': ind_scopedecl_code = n; break;
6222 case 'j': ind_java = n; break;
6223 case 'l': ind_keep_case_label = n; break;
6224 case '#': ind_hash_comment = n; break;
6228 /* remember where the cursor was when we started */
6229 cur_curpos = curwin->w_cursor;
6231 /* Get a copy of the current contents of the line.
6232 * This is required, because only the most recent line obtained with
6233 * ml_get is valid! */
6234 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6235 if (linecopy == NULL)
6236 return 0;
6239 * In insert mode and the cursor is on a ')' truncate the line at the
6240 * cursor position. We don't want to line up with the matching '(' when
6241 * inserting new stuff.
6242 * For unknown reasons the cursor might be past the end of the line, thus
6243 * check for that.
6245 if ((State & INSERT)
6246 && curwin->w_cursor.col < STRLEN(linecopy)
6247 && linecopy[curwin->w_cursor.col] == ')')
6248 linecopy[curwin->w_cursor.col] = NUL;
6250 theline = skipwhite(linecopy);
6252 /* move the cursor to the start of the line */
6254 curwin->w_cursor.col = 0;
6257 * #defines and so on always go at the left when included in 'cinkeys'.
6259 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6261 amount = 0;
6265 * Is it a non-case label? Then that goes at the left margin too.
6267 else if (cin_islabel(ind_maxcomment)) /* XXX */
6269 amount = 0;
6273 * If we're inside a "//" comment and there is a "//" comment in a
6274 * previous line, lineup with that one.
6276 else if (cin_islinecomment(theline)
6277 && (trypos = find_line_comment()) != NULL) /* XXX */
6279 /* find how indented the line beginning the comment is */
6280 getvcol(curwin, trypos, &col, NULL, NULL);
6281 amount = col;
6285 * If we're inside a comment and not looking at the start of the
6286 * comment, try using the 'comments' option.
6288 else if (!cin_iscomment(theline)
6289 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6291 int lead_start_len = 2;
6292 int lead_middle_len = 1;
6293 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6294 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6295 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6296 char_u *p;
6297 int start_align = 0;
6298 int start_off = 0;
6299 int done = FALSE;
6301 /* find how indented the line beginning the comment is */
6302 getvcol(curwin, trypos, &col, NULL, NULL);
6303 amount = col;
6305 p = curbuf->b_p_com;
6306 while (*p != NUL)
6308 int align = 0;
6309 int off = 0;
6310 int what = 0;
6312 while (*p != NUL && *p != ':')
6314 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6315 what = *p++;
6316 else if (*p == COM_LEFT || *p == COM_RIGHT)
6317 align = *p++;
6318 else if (VIM_ISDIGIT(*p) || *p == '-')
6319 off = getdigits(&p);
6320 else
6321 ++p;
6324 if (*p == ':')
6325 ++p;
6326 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6327 if (what == COM_START)
6329 STRCPY(lead_start, lead_end);
6330 lead_start_len = (int)STRLEN(lead_start);
6331 start_off = off;
6332 start_align = align;
6334 else if (what == COM_MIDDLE)
6336 STRCPY(lead_middle, lead_end);
6337 lead_middle_len = (int)STRLEN(lead_middle);
6339 else if (what == COM_END)
6341 /* If our line starts with the middle comment string, line it
6342 * up with the comment opener per the 'comments' option. */
6343 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6344 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6346 done = TRUE;
6347 if (curwin->w_cursor.lnum > 1)
6349 /* If the start comment string matches in the previous
6350 * line, use the indent of that line pluss offset. If
6351 * the middle comment string matches in the previous
6352 * line, use the indent of that line. XXX */
6353 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6354 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6355 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6356 else if (STRNCMP(look, lead_middle,
6357 lead_middle_len) == 0)
6359 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6360 break;
6362 /* If the start comment string doesn't match with the
6363 * start of the comment, skip this entry. XXX */
6364 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6365 lead_start, lead_start_len) != 0)
6366 continue;
6368 if (start_off != 0)
6369 amount += start_off;
6370 else if (start_align == COM_RIGHT)
6371 amount += vim_strsize(lead_start)
6372 - vim_strsize(lead_middle);
6373 break;
6376 /* If our line starts with the end comment string, line it up
6377 * with the middle comment */
6378 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6379 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6381 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6382 /* XXX */
6383 if (off != 0)
6384 amount += off;
6385 else if (align == COM_RIGHT)
6386 amount += vim_strsize(lead_start)
6387 - vim_strsize(lead_middle);
6388 done = TRUE;
6389 break;
6394 /* If our line starts with an asterisk, line up with the
6395 * asterisk in the comment opener; otherwise, line up
6396 * with the first character of the comment text.
6398 if (done)
6400 else if (theline[0] == '*')
6401 amount += 1;
6402 else
6405 * If we are more than one line away from the comment opener, take
6406 * the indent of the previous non-empty line. If 'cino' has "CO"
6407 * and we are just below the comment opener and there are any
6408 * white characters after it line up with the text after it;
6409 * otherwise, add the amount specified by "c" in 'cino'
6411 amount = -1;
6412 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6414 if (linewhite(lnum)) /* skip blank lines */
6415 continue;
6416 amount = get_indent_lnum(lnum); /* XXX */
6417 break;
6419 if (amount == -1) /* use the comment opener */
6421 if (!ind_in_comment2)
6423 start = ml_get(trypos->lnum);
6424 look = start + trypos->col + 2; /* skip / and * */
6425 if (*look != NUL) /* if something after it */
6426 trypos->col = (colnr_T)(skipwhite(look) - start);
6428 getvcol(curwin, trypos, &col, NULL, NULL);
6429 amount = col;
6430 if (ind_in_comment2 || *look == NUL)
6431 amount += ind_in_comment;
6437 * Are we inside parentheses or braces?
6438 */ /* XXX */
6439 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6440 && ind_java == 0)
6441 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6442 || trypos != NULL)
6444 if (trypos != NULL && tryposBrace != NULL)
6446 /* Both an unmatched '(' and '{' is found. Use the one which is
6447 * closer to the current cursor position, set the other to NULL. */
6448 if (trypos->lnum != tryposBrace->lnum
6449 ? trypos->lnum < tryposBrace->lnum
6450 : trypos->col < tryposBrace->col)
6451 trypos = NULL;
6452 else
6453 tryposBrace = NULL;
6456 if (trypos != NULL)
6459 * If the matching paren is more than one line away, use the indent of
6460 * a previous non-empty line that matches the same paren.
6462 if (theline[0] == ')' && ind_paren_prev)
6464 /* Line up with the start of the matching paren line. */
6465 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6467 else
6469 amount = -1;
6470 our_paren_pos = *trypos;
6471 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
6473 l = skipwhite(ml_get(lnum));
6474 if (cin_nocode(l)) /* skip comment lines */
6475 continue;
6476 if (cin_ispreproc_cont(&l, &lnum))
6477 continue; /* ignore #define, #if, etc. */
6478 curwin->w_cursor.lnum = lnum;
6480 /* Skip a comment. XXX */
6481 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6483 lnum = trypos->lnum + 1;
6484 continue;
6487 /* XXX */
6488 if ((trypos = find_match_paren(
6489 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6490 ind_maxcomment)) != NULL
6491 && trypos->lnum == our_paren_pos.lnum
6492 && trypos->col == our_paren_pos.col)
6494 amount = get_indent_lnum(lnum); /* XXX */
6496 if (theline[0] == ')')
6498 if (our_paren_pos.lnum != lnum
6499 && cur_amount > amount)
6500 cur_amount = amount;
6501 amount = -1;
6503 break;
6509 * Line up with line where the matching paren is. XXX
6510 * If the line starts with a '(' or the indent for unclosed
6511 * parentheses is zero, line up with the unclosed parentheses.
6513 if (amount == -1)
6515 int ignore_paren_col = 0;
6517 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
6518 look = skipwhite(look);
6519 if (*look == '(')
6521 linenr_T save_lnum = curwin->w_cursor.lnum;
6522 char_u *line;
6523 int look_col;
6525 /* Ignore a '(' in front of the line that has a match before
6526 * our matching '('. */
6527 curwin->w_cursor.lnum = our_paren_pos.lnum;
6528 line = ml_get_curline();
6529 look_col = (int)(look - line);
6530 curwin->w_cursor.col = look_col + 1;
6531 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6532 != NULL
6533 && trypos->lnum == our_paren_pos.lnum
6534 && trypos->col < our_paren_pos.col)
6535 ignore_paren_col = trypos->col + 1;
6537 curwin->w_cursor.lnum = save_lnum;
6538 look = ml_get(our_paren_pos.lnum) + look_col;
6540 if (theline[0] == ')' || ind_unclosed == 0
6541 || (!ind_unclosed_noignore && *look == '('
6542 && ignore_paren_col == 0))
6545 * If we're looking at a close paren, line up right there;
6546 * otherwise, line up with the next (non-white) character.
6547 * When ind_unclosed_wrapped is set and the matching paren is
6548 * the last nonwhite character of the line, use either the
6549 * indent of the current line or the indentation of the next
6550 * outer paren and add ind_unclosed_wrapped (for very long
6551 * lines).
6553 if (theline[0] != ')')
6555 cur_amount = MAXCOL;
6556 l = ml_get(our_paren_pos.lnum);
6557 if (ind_unclosed_wrapped
6558 && cin_ends_in(l, (char_u *)"(", NULL))
6560 /* look for opening unmatched paren, indent one level
6561 * for each additional level */
6562 n = 1;
6563 for (col = 0; col < our_paren_pos.col; ++col)
6565 switch (l[col])
6567 case '(':
6568 case '{': ++n;
6569 break;
6571 case ')':
6572 case '}': if (n > 1)
6573 --n;
6574 break;
6578 our_paren_pos.col = 0;
6579 amount += n * ind_unclosed_wrapped;
6581 else if (ind_unclosed_whiteok)
6582 our_paren_pos.col++;
6583 else
6585 col = our_paren_pos.col + 1;
6586 while (vim_iswhite(l[col]))
6587 col++;
6588 if (l[col] != NUL) /* In case of trailing space */
6589 our_paren_pos.col = col;
6590 else
6591 our_paren_pos.col++;
6596 * Find how indented the paren is, or the character after it
6597 * if we did the above "if".
6599 if (our_paren_pos.col > 0)
6601 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6602 if (cur_amount > (int)col)
6603 cur_amount = col;
6607 if (theline[0] == ')' && ind_matching_paren)
6609 /* Line up with the start of the matching paren line. */
6611 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
6612 && *look == '(' && ignore_paren_col == 0))
6614 if (cur_amount != MAXCOL)
6615 amount = cur_amount;
6617 else
6619 /* Add ind_unclosed2 for each '(' before our matching one, but
6620 * ignore (void) before the line (ignore_paren_col). */
6621 col = our_paren_pos.col;
6622 while ((int)our_paren_pos.col > ignore_paren_col)
6624 --our_paren_pos.col;
6625 switch (*ml_get_pos(&our_paren_pos))
6627 case '(': amount += ind_unclosed2;
6628 col = our_paren_pos.col;
6629 break;
6630 case ')': amount -= ind_unclosed2;
6631 col = MAXCOL;
6632 break;
6636 /* Use ind_unclosed once, when the first '(' is not inside
6637 * braces */
6638 if (col == MAXCOL)
6639 amount += ind_unclosed;
6640 else
6642 curwin->w_cursor.lnum = our_paren_pos.lnum;
6643 curwin->w_cursor.col = col;
6644 if ((trypos = find_match_paren(ind_maxparen,
6645 ind_maxcomment)) != NULL)
6646 amount += ind_unclosed2;
6647 else
6648 amount += ind_unclosed;
6651 * For a line starting with ')' use the minimum of the two
6652 * positions, to avoid giving it more indent than the previous
6653 * lines:
6654 * func_long_name( if (x
6655 * arg && yy
6656 * ) ^ not here ) ^ not here
6658 if (cur_amount < amount)
6659 amount = cur_amount;
6663 /* add extra indent for a comment */
6664 if (cin_iscomment(theline))
6665 amount += ind_comment;
6669 * Are we at least inside braces, then?
6671 else
6673 trypos = tryposBrace;
6675 ourscope = trypos->lnum;
6676 start = ml_get(ourscope);
6679 * Now figure out how indented the line is in general.
6680 * If the brace was at the start of the line, we use that;
6681 * otherwise, check out the indentation of the line as
6682 * a whole and then add the "imaginary indent" to that.
6684 look = skipwhite(start);
6685 if (*look == '{')
6687 getvcol(curwin, trypos, &col, NULL, NULL);
6688 amount = col;
6689 if (*start == '{')
6690 start_brace = BRACE_IN_COL0;
6691 else
6692 start_brace = BRACE_AT_START;
6694 else
6697 * that opening brace might have been on a continuation
6698 * line. if so, find the start of the line.
6700 curwin->w_cursor.lnum = ourscope;
6703 * position the cursor over the rightmost paren, so that
6704 * matching it will take us back to the start of the line.
6706 lnum = ourscope;
6707 if (find_last_paren(start, '(', ')')
6708 && (trypos = find_match_paren(ind_maxparen,
6709 ind_maxcomment)) != NULL)
6710 lnum = trypos->lnum;
6713 * It could have been something like
6714 * case 1: if (asdf &&
6715 * ldfd) {
6718 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6719 amount = get_indent();
6720 else
6721 amount = skip_label(lnum, &l, ind_maxcomment);
6723 start_brace = BRACE_AT_END;
6727 * if we're looking at a closing brace, that's where
6728 * we want to be. otherwise, add the amount of room
6729 * that an indent is supposed to be.
6731 if (theline[0] == '}')
6734 * they may want closing braces to line up with something
6735 * other than the open brace. indulge them, if so.
6737 amount += ind_close_extra;
6739 else
6742 * If we're looking at an "else", try to find an "if"
6743 * to match it with.
6744 * If we're looking at a "while", try to find a "do"
6745 * to match it with.
6747 lookfor = LOOKFOR_INITIAL;
6748 if (cin_iselse(theline))
6749 lookfor = LOOKFOR_IF;
6750 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6751 /* XXX */
6752 lookfor = LOOKFOR_DO;
6753 if (lookfor != LOOKFOR_INITIAL)
6755 curwin->w_cursor.lnum = cur_curpos.lnum;
6756 if (find_match(lookfor, ourscope, ind_maxparen,
6757 ind_maxcomment) == OK)
6759 amount = get_indent(); /* XXX */
6760 goto theend;
6765 * We get here if we are not on an "while-of-do" or "else" (or
6766 * failed to find a matching "if").
6767 * Search backwards for something to line up with.
6768 * First set amount for when we don't find anything.
6772 * if the '{' is _really_ at the left margin, use the imaginary
6773 * location of a left-margin brace. Otherwise, correct the
6774 * location for ind_open_extra.
6777 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6779 amount = ind_open_left_imag;
6781 else
6783 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6784 amount += ind_open_imag;
6785 else
6787 /* Compensate for adding ind_open_extra later. */
6788 amount -= ind_open_extra;
6789 if (amount < 0)
6790 amount = 0;
6794 lookfor_break = FALSE;
6796 if (cin_iscase(theline)) /* it's a switch() label */
6798 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6799 amount += ind_case;
6801 else if (cin_isscopedecl(theline)) /* private:, ... */
6803 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6804 amount += ind_scopedecl;
6806 else
6808 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6809 lookfor_break = TRUE;
6811 lookfor = LOOKFOR_INITIAL;
6812 amount += ind_level; /* ind_level from start of block */
6814 scope_amount = amount;
6815 whilelevel = 0;
6818 * Search backwards. If we find something we recognize, line up
6819 * with that.
6821 * if we're looking at an open brace, indent
6822 * the usual amount relative to the conditional
6823 * that opens the block.
6825 curwin->w_cursor = cur_curpos;
6826 for (;;)
6828 curwin->w_cursor.lnum--;
6829 curwin->w_cursor.col = 0;
6832 * If we went all the way back to the start of our scope, line
6833 * up with it.
6835 if (curwin->w_cursor.lnum <= ourscope)
6837 /* we reached end of scope:
6838 * if looking for a enum or structure initialization
6839 * go further back:
6840 * if it is an initializer (enum xxx or xxx =), then
6841 * don't add ind_continuation, otherwise it is a variable
6842 * declaration:
6843 * int x,
6844 * here; <-- add ind_continuation
6846 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6848 if (curwin->w_cursor.lnum == 0
6849 || curwin->w_cursor.lnum
6850 < ourscope - ind_maxparen)
6852 /* nothing found (abuse ind_maxparen as limit)
6853 * assume terminated line (i.e. a variable
6854 * initialization) */
6855 if (cont_amount > 0)
6856 amount = cont_amount;
6857 else
6858 amount += ind_continuation;
6859 break;
6862 l = ml_get_curline();
6865 * If we're in a comment now, skip to the start of the
6866 * comment.
6868 trypos = find_start_comment(ind_maxcomment);
6869 if (trypos != NULL)
6871 curwin->w_cursor.lnum = trypos->lnum + 1;
6872 continue;
6876 * Skip preprocessor directives and blank lines.
6878 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6879 continue;
6881 if (cin_nocode(l))
6882 continue;
6884 terminated = cin_isterminated(l, FALSE, TRUE);
6887 * If we are at top level and the line looks like a
6888 * function declaration, we are done
6889 * (it's a variable declaration).
6891 if (start_brace != BRACE_IN_COL0
6892 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6894 /* if the line is terminated with another ','
6895 * it is a continued variable initialization.
6896 * don't add extra indent.
6897 * TODO: does not work, if a function
6898 * declaration is split over multiple lines:
6899 * cin_isfuncdecl returns FALSE then.
6901 if (terminated == ',')
6902 break;
6904 /* if it es a enum declaration or an assignment,
6905 * we are done.
6907 if (terminated != ';' && cin_isinit())
6908 break;
6910 /* nothing useful found */
6911 if (terminated == 0 || terminated == '{')
6912 continue;
6915 if (terminated != ';')
6917 /* Skip parens and braces. Position the cursor
6918 * over the rightmost paren, so that matching it
6919 * will take us back to the start of the line.
6920 */ /* XXX */
6921 trypos = NULL;
6922 if (find_last_paren(l, '(', ')'))
6923 trypos = find_match_paren(ind_maxparen,
6924 ind_maxcomment);
6926 if (trypos == NULL && find_last_paren(l, '{', '}'))
6927 trypos = find_start_brace(ind_maxcomment);
6929 if (trypos != NULL)
6931 curwin->w_cursor.lnum = trypos->lnum + 1;
6932 continue;
6936 /* it's a variable declaration, add indentation
6937 * like in
6938 * int a,
6939 * b;
6941 if (cont_amount > 0)
6942 amount = cont_amount;
6943 else
6944 amount += ind_continuation;
6946 else if (lookfor == LOOKFOR_UNTERM)
6948 if (cont_amount > 0)
6949 amount = cont_amount;
6950 else
6951 amount += ind_continuation;
6953 else if (lookfor != LOOKFOR_TERM
6954 && lookfor != LOOKFOR_CPP_BASECLASS)
6956 amount = scope_amount;
6957 if (theline[0] == '{')
6958 amount += ind_open_extra;
6960 break;
6964 * If we're in a comment now, skip to the start of the comment.
6965 */ /* XXX */
6966 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6968 curwin->w_cursor.lnum = trypos->lnum + 1;
6969 continue;
6972 l = ml_get_curline();
6975 * If this is a switch() label, may line up relative to that.
6976 * If this is a C++ scope declaration, do the same.
6978 iscase = cin_iscase(l);
6979 if (iscase || cin_isscopedecl(l))
6981 /* we are only looking for cpp base class
6982 * declaration/initialization any longer */
6983 if (lookfor == LOOKFOR_CPP_BASECLASS)
6984 break;
6986 /* When looking for a "do" we are not interested in
6987 * labels. */
6988 if (whilelevel > 0)
6989 continue;
6992 * case xx:
6993 * c = 99 + <- this indent plus continuation
6994 *-> here;
6996 if (lookfor == LOOKFOR_UNTERM
6997 || lookfor == LOOKFOR_ENUM_OR_INIT)
6999 if (cont_amount > 0)
7000 amount = cont_amount;
7001 else
7002 amount += ind_continuation;
7003 break;
7007 * case xx: <- line up with this case
7008 * x = 333;
7009 * case yy:
7011 if ( (iscase && lookfor == LOOKFOR_CASE)
7012 || (iscase && lookfor_break)
7013 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7016 * Check that this case label is not for another
7017 * switch()
7018 */ /* XXX */
7019 if ((trypos = find_start_brace(ind_maxcomment)) ==
7020 NULL || trypos->lnum == ourscope)
7022 amount = get_indent(); /* XXX */
7023 break;
7025 continue;
7028 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7031 * case xx: if (cond) <- line up with this if
7032 * y = y + 1;
7033 * -> s = 99;
7035 * case xx:
7036 * if (cond) <- line up with this line
7037 * y = y + 1;
7038 * -> s = 99;
7040 if (lookfor == LOOKFOR_TERM)
7042 if (n)
7043 amount = n;
7045 if (!lookfor_break)
7046 break;
7050 * case xx: x = x + 1; <- line up with this x
7051 * -> y = y + 1;
7053 * case xx: if (cond) <- line up with this if
7054 * -> y = y + 1;
7056 if (n)
7058 amount = n;
7059 l = after_label(ml_get_curline());
7060 if (l != NULL && cin_is_cinword(l))
7062 if (theline[0] == '{')
7063 amount += ind_open_extra;
7064 else
7065 amount += ind_level + ind_no_brace;
7067 break;
7071 * Try to get the indent of a statement before the switch
7072 * label. If nothing is found, line up relative to the
7073 * switch label.
7074 * break; <- may line up with this line
7075 * case xx:
7076 * -> y = 1;
7078 scope_amount = get_indent() + (iscase /* XXX */
7079 ? ind_case_code : ind_scopedecl_code);
7080 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7081 continue;
7085 * Looking for a switch() label or C++ scope declaration,
7086 * ignore other lines, skip {}-blocks.
7088 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7090 if (find_last_paren(l, '{', '}') && (trypos =
7091 find_start_brace(ind_maxcomment)) != NULL)
7092 curwin->w_cursor.lnum = trypos->lnum + 1;
7093 continue;
7097 * Ignore jump labels with nothing after them.
7099 if (cin_islabel(ind_maxcomment))
7101 l = after_label(ml_get_curline());
7102 if (l == NULL || cin_nocode(l))
7103 continue;
7107 * Ignore #defines, #if, etc.
7108 * Ignore comment and empty lines.
7109 * (need to get the line again, cin_islabel() may have
7110 * unlocked it)
7112 l = ml_get_curline();
7113 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7114 || cin_nocode(l))
7115 continue;
7118 * Are we at the start of a cpp base class declaration or
7119 * constructor initialization?
7120 */ /* XXX */
7121 n = FALSE;
7122 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7124 n = cin_is_cpp_baseclass(&col);
7125 l = ml_get_curline();
7127 if (n)
7129 if (lookfor == LOOKFOR_UNTERM)
7131 if (cont_amount > 0)
7132 amount = cont_amount;
7133 else
7134 amount += ind_continuation;
7136 else if (theline[0] == '{')
7138 /* Need to find start of the declaration. */
7139 lookfor = LOOKFOR_UNTERM;
7140 ind_continuation = 0;
7141 continue;
7143 else
7144 /* XXX */
7145 amount = get_baseclass_amount(col, ind_maxparen,
7146 ind_maxcomment, ind_cpp_baseclass);
7147 break;
7149 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7151 /* only look, whether there is a cpp base class
7152 * declaration or initialization before the opening brace.
7154 if (cin_isterminated(l, TRUE, FALSE))
7155 break;
7156 else
7157 continue;
7161 * What happens next depends on the line being terminated.
7162 * If terminated with a ',' only consider it terminating if
7163 * there is another unterminated statement behind, eg:
7164 * 123,
7165 * sizeof
7166 * here
7167 * Otherwise check whether it is a enumeration or structure
7168 * initialisation (not indented) or a variable declaration
7169 * (indented).
7171 terminated = cin_isterminated(l, FALSE, TRUE);
7173 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7174 && terminated == ','))
7177 * if we're in the middle of a paren thing,
7178 * go back to the line that starts it so
7179 * we can get the right prevailing indent
7180 * if ( foo &&
7181 * bar )
7184 * position the cursor over the rightmost paren, so that
7185 * matching it will take us back to the start of the line.
7187 (void)find_last_paren(l, '(', ')');
7188 trypos = find_match_paren(
7189 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7190 ind_maxcomment);
7193 * If we are looking for ',', we also look for matching
7194 * braces.
7196 if (trypos == NULL && terminated == ','
7197 && find_last_paren(l, '{', '}'))
7198 trypos = find_start_brace(ind_maxcomment);
7200 if (trypos != NULL)
7203 * Check if we are on a case label now. This is
7204 * handled above.
7205 * case xx: if ( asdf &&
7206 * asdf)
7208 curwin->w_cursor.lnum = trypos->lnum;
7209 l = ml_get_curline();
7210 if (cin_iscase(l) || cin_isscopedecl(l))
7212 ++curwin->w_cursor.lnum;
7213 continue;
7218 * Skip over continuation lines to find the one to get the
7219 * indent from
7220 * char *usethis = "bla\
7221 * bla",
7222 * here;
7224 if (terminated == ',')
7226 while (curwin->w_cursor.lnum > 1)
7228 l = ml_get(curwin->w_cursor.lnum - 1);
7229 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7230 break;
7231 --curwin->w_cursor.lnum;
7236 * Get indent and pointer to text for current line,
7237 * ignoring any jump label. XXX
7239 cur_amount = skip_label(curwin->w_cursor.lnum,
7240 &l, ind_maxcomment);
7243 * If this is just above the line we are indenting, and it
7244 * starts with a '{', line it up with this line.
7245 * while (not)
7246 * -> {
7249 if (terminated != ',' && lookfor != LOOKFOR_TERM
7250 && theline[0] == '{')
7252 amount = cur_amount;
7254 * Only add ind_open_extra when the current line
7255 * doesn't start with a '{', which must have a match
7256 * in the same line (scope is the same). Probably:
7257 * { 1, 2 },
7258 * -> { 3, 4 }
7260 if (*skipwhite(l) != '{')
7261 amount += ind_open_extra;
7263 if (ind_cpp_baseclass)
7265 /* have to look back, whether it is a cpp base
7266 * class declaration or initialization */
7267 lookfor = LOOKFOR_CPP_BASECLASS;
7268 continue;
7270 break;
7274 * Check if we are after an "if", "while", etc.
7275 * Also allow " } else".
7277 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7280 * Found an unterminated line after an if (), line up
7281 * with the last one.
7282 * if (cond)
7283 * 100 +
7284 * -> here;
7286 if (lookfor == LOOKFOR_UNTERM
7287 || lookfor == LOOKFOR_ENUM_OR_INIT)
7289 if (cont_amount > 0)
7290 amount = cont_amount;
7291 else
7292 amount += ind_continuation;
7293 break;
7297 * If this is just above the line we are indenting, we
7298 * are finished.
7299 * while (not)
7300 * -> here;
7301 * Otherwise this indent can be used when the line
7302 * before this is terminated.
7303 * yyy;
7304 * if (stat)
7305 * while (not)
7306 * xxx;
7307 * -> here;
7309 amount = cur_amount;
7310 if (theline[0] == '{')
7311 amount += ind_open_extra;
7312 if (lookfor != LOOKFOR_TERM)
7314 amount += ind_level + ind_no_brace;
7315 break;
7319 * Special trick: when expecting the while () after a
7320 * do, line up with the while()
7321 * do
7322 * x = 1;
7323 * -> here
7325 l = skipwhite(ml_get_curline());
7326 if (cin_isdo(l))
7328 if (whilelevel == 0)
7329 break;
7330 --whilelevel;
7334 * When searching for a terminated line, don't use the
7335 * one between the "if" and the "else".
7336 * Need to use the scope of this "else". XXX
7337 * If whilelevel != 0 continue looking for a "do {".
7339 if (cin_iselse(l)
7340 && whilelevel == 0
7341 && ((trypos = find_start_brace(ind_maxcomment))
7342 == NULL
7343 || find_match(LOOKFOR_IF, trypos->lnum,
7344 ind_maxparen, ind_maxcomment) == FAIL))
7345 break;
7349 * If we're below an unterminated line that is not an
7350 * "if" or something, we may line up with this line or
7351 * add something for a continuation line, depending on
7352 * the line before this one.
7354 else
7357 * Found two unterminated lines on a row, line up with
7358 * the last one.
7359 * c = 99 +
7360 * 100 +
7361 * -> here;
7363 if (lookfor == LOOKFOR_UNTERM)
7365 /* When line ends in a comma add extra indent */
7366 if (terminated == ',')
7367 amount += ind_continuation;
7368 break;
7371 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7373 /* Found two lines ending in ',', lineup with the
7374 * lowest one, but check for cpp base class
7375 * declaration/initialization, if it is an
7376 * opening brace or we are looking just for
7377 * enumerations/initializations. */
7378 if (terminated == ',')
7380 if (ind_cpp_baseclass == 0)
7381 break;
7383 lookfor = LOOKFOR_CPP_BASECLASS;
7384 continue;
7387 /* Ignore unterminated lines in between, but
7388 * reduce indent. */
7389 if (amount > cur_amount)
7390 amount = cur_amount;
7392 else
7395 * Found first unterminated line on a row, may
7396 * line up with this line, remember its indent
7397 * 100 +
7398 * -> here;
7400 amount = cur_amount;
7403 * If previous line ends in ',', check whether we
7404 * are in an initialization or enum
7405 * struct xxx =
7407 * sizeof a,
7408 * 124 };
7409 * or a normal possible continuation line.
7410 * but only, of no other statement has been found
7411 * yet.
7413 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7415 lookfor = LOOKFOR_ENUM_OR_INIT;
7416 cont_amount = cin_first_id_amount();
7418 else
7420 if (lookfor == LOOKFOR_INITIAL
7421 && *l != NUL
7422 && l[STRLEN(l) - 1] == '\\')
7423 /* XXX */
7424 cont_amount = cin_get_equal_amount(
7425 curwin->w_cursor.lnum);
7426 if (lookfor != LOOKFOR_TERM)
7427 lookfor = LOOKFOR_UNTERM;
7434 * Check if we are after a while (cond);
7435 * If so: Ignore until the matching "do".
7437 /* XXX */
7438 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7439 ind_maxcomment))
7442 * Found an unterminated line after a while ();, line up
7443 * with the last one.
7444 * while (cond);
7445 * 100 + <- line up with this one
7446 * -> here;
7448 if (lookfor == LOOKFOR_UNTERM
7449 || lookfor == LOOKFOR_ENUM_OR_INIT)
7451 if (cont_amount > 0)
7452 amount = cont_amount;
7453 else
7454 amount += ind_continuation;
7455 break;
7458 if (whilelevel == 0)
7460 lookfor = LOOKFOR_TERM;
7461 amount = get_indent(); /* XXX */
7462 if (theline[0] == '{')
7463 amount += ind_open_extra;
7465 ++whilelevel;
7469 * We are after a "normal" statement.
7470 * If we had another statement we can stop now and use the
7471 * indent of that other statement.
7472 * Otherwise the indent of the current statement may be used,
7473 * search backwards for the next "normal" statement.
7475 else
7478 * Skip single break line, if before a switch label. It
7479 * may be lined up with the case label.
7481 if (lookfor == LOOKFOR_NOBREAK
7482 && cin_isbreak(skipwhite(ml_get_curline())))
7484 lookfor = LOOKFOR_ANY;
7485 continue;
7489 * Handle "do {" line.
7491 if (whilelevel > 0)
7493 l = cin_skipcomment(ml_get_curline());
7494 if (cin_isdo(l))
7496 amount = get_indent(); /* XXX */
7497 --whilelevel;
7498 continue;
7503 * Found a terminated line above an unterminated line. Add
7504 * the amount for a continuation line.
7505 * x = 1;
7506 * y = foo +
7507 * -> here;
7508 * or
7509 * int x = 1;
7510 * int foo,
7511 * -> here;
7513 if (lookfor == LOOKFOR_UNTERM
7514 || lookfor == LOOKFOR_ENUM_OR_INIT)
7516 if (cont_amount > 0)
7517 amount = cont_amount;
7518 else
7519 amount += ind_continuation;
7520 break;
7524 * Found a terminated line above a terminated line or "if"
7525 * etc. line. Use the amount of the line below us.
7526 * x = 1; x = 1;
7527 * if (asdf) y = 2;
7528 * while (asdf) ->here;
7529 * here;
7530 * ->foo;
7532 if (lookfor == LOOKFOR_TERM)
7534 if (!lookfor_break && whilelevel == 0)
7535 break;
7539 * First line above the one we're indenting is terminated.
7540 * To know what needs to be done look further backward for
7541 * a terminated line.
7543 else
7546 * position the cursor over the rightmost paren, so
7547 * that matching it will take us back to the start of
7548 * the line. Helps for:
7549 * func(asdr,
7550 * asdfasdf);
7551 * here;
7553 term_again:
7554 l = ml_get_curline();
7555 if (find_last_paren(l, '(', ')')
7556 && (trypos = find_match_paren(ind_maxparen,
7557 ind_maxcomment)) != NULL)
7560 * Check if we are on a case label now. This is
7561 * handled above.
7562 * case xx: if ( asdf &&
7563 * asdf)
7565 curwin->w_cursor.lnum = trypos->lnum;
7566 l = ml_get_curline();
7567 if (cin_iscase(l) || cin_isscopedecl(l))
7569 ++curwin->w_cursor.lnum;
7570 continue;
7574 /* When aligning with the case statement, don't align
7575 * with a statement after it.
7576 * case 1: { <-- don't use this { position
7577 * stat;
7579 * case 2:
7580 * stat;
7583 iscase = (ind_keep_case_label && cin_iscase(l));
7586 * Get indent and pointer to text for current line,
7587 * ignoring any jump label.
7589 amount = skip_label(curwin->w_cursor.lnum,
7590 &l, ind_maxcomment);
7592 if (theline[0] == '{')
7593 amount += ind_open_extra;
7594 /* See remark above: "Only add ind_open_extra.." */
7595 l = skipwhite(l);
7596 if (*l == '{')
7597 amount -= ind_open_extra;
7598 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7601 * When a terminated line starts with "else" skip to
7602 * the matching "if":
7603 * else 3;
7604 * indent this;
7605 * Need to use the scope of this "else". XXX
7606 * If whilelevel != 0 continue looking for a "do {".
7608 if (lookfor == LOOKFOR_TERM
7609 && *l != '}'
7610 && cin_iselse(l)
7611 && whilelevel == 0)
7613 if ((trypos = find_start_brace(ind_maxcomment))
7614 == NULL
7615 || find_match(LOOKFOR_IF, trypos->lnum,
7616 ind_maxparen, ind_maxcomment) == FAIL)
7617 break;
7618 continue;
7622 * If we're at the end of a block, skip to the start of
7623 * that block.
7625 curwin->w_cursor.col = 0;
7626 if (*cin_skipcomment(l) == '}'
7627 && (trypos = find_start_brace(ind_maxcomment))
7628 != NULL) /* XXX */
7630 curwin->w_cursor.lnum = trypos->lnum;
7631 /* if not "else {" check for terminated again */
7632 /* but skip block for "} else {" */
7633 l = cin_skipcomment(ml_get_curline());
7634 if (*l == '}' || !cin_iselse(l))
7635 goto term_again;
7636 ++curwin->w_cursor.lnum;
7644 /* add extra indent for a comment */
7645 if (cin_iscomment(theline))
7646 amount += ind_comment;
7650 * ok -- we're not inside any sort of structure at all!
7652 * this means we're at the top level, and everything should
7653 * basically just match where the previous line is, except
7654 * for the lines immediately following a function declaration,
7655 * which are K&R-style parameters and need to be indented.
7657 else
7660 * if our line starts with an open brace, forget about any
7661 * prevailing indent and make sure it looks like the start
7662 * of a function
7665 if (theline[0] == '{')
7667 amount = ind_first_open;
7671 * If the NEXT line is a function declaration, the current
7672 * line needs to be indented as a function type spec.
7673 * Don't do this if the current line looks like a comment
7674 * or if the current line is terminated, ie. ends in ';'.
7676 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7677 && !cin_nocode(theline)
7678 && !cin_ends_in(theline, (char_u *)":", NULL)
7679 && !cin_ends_in(theline, (char_u *)",", NULL)
7680 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7681 && !cin_isterminated(theline, FALSE, TRUE))
7683 amount = ind_func_type;
7685 else
7687 amount = 0;
7688 curwin->w_cursor = cur_curpos;
7690 /* search backwards until we find something we recognize */
7692 while (curwin->w_cursor.lnum > 1)
7694 curwin->w_cursor.lnum--;
7695 curwin->w_cursor.col = 0;
7697 l = ml_get_curline();
7700 * If we're in a comment now, skip to the start of the comment.
7701 */ /* XXX */
7702 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7704 curwin->w_cursor.lnum = trypos->lnum + 1;
7705 continue;
7709 * Are we at the start of a cpp base class declaration or
7710 * constructor initialization?
7711 */ /* XXX */
7712 n = FALSE;
7713 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7715 n = cin_is_cpp_baseclass(&col);
7716 l = ml_get_curline();
7718 if (n)
7720 /* XXX */
7721 amount = get_baseclass_amount(col, ind_maxparen,
7722 ind_maxcomment, ind_cpp_baseclass);
7723 break;
7727 * Skip preprocessor directives and blank lines.
7729 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7730 continue;
7732 if (cin_nocode(l))
7733 continue;
7736 * If the previous line ends in ',', use one level of
7737 * indentation:
7738 * int foo,
7739 * bar;
7740 * do this before checking for '}' in case of eg.
7741 * enum foobar
7743 * ...
7744 * } foo,
7745 * bar;
7747 n = 0;
7748 if (cin_ends_in(l, (char_u *)",", NULL)
7749 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7751 /* take us back to opening paren */
7752 if (find_last_paren(l, '(', ')')
7753 && (trypos = find_match_paren(ind_maxparen,
7754 ind_maxcomment)) != NULL)
7755 curwin->w_cursor.lnum = trypos->lnum;
7757 /* For a line ending in ',' that is a continuation line go
7758 * back to the first line with a backslash:
7759 * char *foo = "bla\
7760 * bla",
7761 * here;
7763 while (n == 0 && curwin->w_cursor.lnum > 1)
7765 l = ml_get(curwin->w_cursor.lnum - 1);
7766 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7767 break;
7768 --curwin->w_cursor.lnum;
7771 amount = get_indent(); /* XXX */
7773 if (amount == 0)
7774 amount = cin_first_id_amount();
7775 if (amount == 0)
7776 amount = ind_continuation;
7777 break;
7781 * If the line looks like a function declaration, and we're
7782 * not in a comment, put it the left margin.
7784 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7785 break;
7786 l = ml_get_curline();
7789 * Finding the closing '}' of a previous function. Put
7790 * current line at the left margin. For when 'cino' has "fs".
7792 if (*skipwhite(l) == '}')
7793 break;
7795 /* (matching {)
7796 * If the previous line ends on '};' (maybe followed by
7797 * comments) align at column 0. For example:
7798 * char *string_array[] = { "foo",
7799 * / * x * / "b};ar" }; / * foobar * /
7801 if (cin_ends_in(l, (char_u *)"};", NULL))
7802 break;
7805 * If the PREVIOUS line is a function declaration, the current
7806 * line (and the ones that follow) needs to be indented as
7807 * parameters.
7809 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7811 amount = ind_param;
7812 break;
7816 * If the previous line ends in ';' and the line before the
7817 * previous line ends in ',' or '\', ident to column zero:
7818 * int foo,
7819 * bar;
7820 * indent_to_0 here;
7822 if (cin_ends_in(l, (char_u *)";", NULL))
7824 l = ml_get(curwin->w_cursor.lnum - 1);
7825 if (cin_ends_in(l, (char_u *)",", NULL)
7826 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7827 break;
7828 l = ml_get_curline();
7832 * Doesn't look like anything interesting -- so just
7833 * use the indent of this line.
7835 * Position the cursor over the rightmost paren, so that
7836 * matching it will take us back to the start of the line.
7838 find_last_paren(l, '(', ')');
7840 if ((trypos = find_match_paren(ind_maxparen,
7841 ind_maxcomment)) != NULL)
7842 curwin->w_cursor.lnum = trypos->lnum;
7843 amount = get_indent(); /* XXX */
7844 break;
7847 /* add extra indent for a comment */
7848 if (cin_iscomment(theline))
7849 amount += ind_comment;
7851 /* add extra indent if the previous line ended in a backslash:
7852 * "asdfasdf\
7853 * here";
7854 * char *foo = "asdf\
7855 * here";
7857 if (cur_curpos.lnum > 1)
7859 l = ml_get(cur_curpos.lnum - 1);
7860 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7862 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7863 if (cur_amount > 0)
7864 amount = cur_amount;
7865 else if (cur_amount == 0)
7866 amount += ind_continuation;
7872 theend:
7873 /* put the cursor back where it belongs */
7874 curwin->w_cursor = cur_curpos;
7876 vim_free(linecopy);
7878 if (amount < 0)
7879 return 0;
7880 return amount;
7883 static int
7884 find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7885 int lookfor;
7886 linenr_T ourscope;
7887 int ind_maxparen;
7888 int ind_maxcomment;
7890 char_u *look;
7891 pos_T *theirscope;
7892 char_u *mightbeif;
7893 int elselevel;
7894 int whilelevel;
7896 if (lookfor == LOOKFOR_IF)
7898 elselevel = 1;
7899 whilelevel = 0;
7901 else
7903 elselevel = 0;
7904 whilelevel = 1;
7907 curwin->w_cursor.col = 0;
7909 while (curwin->w_cursor.lnum > ourscope + 1)
7911 curwin->w_cursor.lnum--;
7912 curwin->w_cursor.col = 0;
7914 look = cin_skipcomment(ml_get_curline());
7915 if (cin_iselse(look)
7916 || cin_isif(look)
7917 || cin_isdo(look) /* XXX */
7918 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7921 * if we've gone outside the braces entirely,
7922 * we must be out of scope...
7924 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7925 if (theirscope == NULL)
7926 break;
7929 * and if the brace enclosing this is further
7930 * back than the one enclosing the else, we're
7931 * out of luck too.
7933 if (theirscope->lnum < ourscope)
7934 break;
7937 * and if they're enclosed in a *deeper* brace,
7938 * then we can ignore it because it's in a
7939 * different scope...
7941 if (theirscope->lnum > ourscope)
7942 continue;
7945 * if it was an "else" (that's not an "else if")
7946 * then we need to go back to another if, so
7947 * increment elselevel
7949 look = cin_skipcomment(ml_get_curline());
7950 if (cin_iselse(look))
7952 mightbeif = cin_skipcomment(look + 4);
7953 if (!cin_isif(mightbeif))
7954 ++elselevel;
7955 continue;
7959 * if it was a "while" then we need to go back to
7960 * another "do", so increment whilelevel. XXX
7962 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7964 ++whilelevel;
7965 continue;
7968 /* If it's an "if" decrement elselevel */
7969 look = cin_skipcomment(ml_get_curline());
7970 if (cin_isif(look))
7972 elselevel--;
7974 * When looking for an "if" ignore "while"s that
7975 * get in the way.
7977 if (elselevel == 0 && lookfor == LOOKFOR_IF)
7978 whilelevel = 0;
7981 /* If it's a "do" decrement whilelevel */
7982 if (cin_isdo(look))
7983 whilelevel--;
7986 * if we've used up all the elses, then
7987 * this must be the if that we want!
7988 * match the indent level of that if.
7990 if (elselevel <= 0 && whilelevel <= 0)
7992 return OK;
7996 return FAIL;
7999 # if defined(FEAT_EVAL) || defined(PROTO)
8001 * Get indent level from 'indentexpr'.
8004 get_expr_indent()
8006 int indent;
8007 pos_T pos;
8008 int save_State;
8009 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8010 OPT_LOCAL);
8012 pos = curwin->w_cursor;
8013 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
8014 if (use_sandbox)
8015 ++sandbox;
8016 ++textlock;
8017 indent = eval_to_number(curbuf->b_p_inde);
8018 if (use_sandbox)
8019 --sandbox;
8020 --textlock;
8022 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8023 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8024 * command. */
8025 save_State = State;
8026 State = INSERT;
8027 curwin->w_cursor = pos;
8028 check_cursor();
8029 State = save_State;
8031 /* If there is an error, just keep the current indent. */
8032 if (indent < 0)
8033 indent = get_indent();
8035 return indent;
8037 # endif
8039 #endif /* FEAT_CINDENT */
8041 #if defined(FEAT_LISP) || defined(PROTO)
8043 static int lisp_match __ARGS((char_u *p));
8045 static int
8046 lisp_match(p)
8047 char_u *p;
8049 char_u buf[LSIZE];
8050 int len;
8051 char_u *word = p_lispwords;
8053 while (*word != NUL)
8055 (void)copy_option_part(&word, buf, LSIZE, ",");
8056 len = (int)STRLEN(buf);
8057 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8058 return TRUE;
8060 return FALSE;
8064 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8065 * The incompatible newer method is quite a bit better at indenting
8066 * code in lisp-like languages than the traditional one; it's still
8067 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8069 * TODO:
8070 * Findmatch() should be adapted for lisp, also to make showmatch
8071 * work correctly: now (v5.3) it seems all C/C++ oriented:
8072 * - it does not recognize the #\( and #\) notations as character literals
8073 * - it doesn't know about comments starting with a semicolon
8074 * - it incorrectly interprets '(' as a character literal
8075 * All this messes up get_lisp_indent in some rare cases.
8076 * Update from Sergey Khorev:
8077 * I tried to fix the first two issues.
8080 get_lisp_indent()
8082 pos_T *pos, realpos, paren;
8083 int amount;
8084 char_u *that;
8085 colnr_T col;
8086 colnr_T firsttry;
8087 int parencount, quotecount;
8088 int vi_lisp;
8090 /* Set vi_lisp to use the vi-compatible method */
8091 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8093 realpos = curwin->w_cursor;
8094 curwin->w_cursor.col = 0;
8096 if ((pos = findmatch(NULL, '(')) == NULL)
8097 pos = findmatch(NULL, '[');
8098 else
8100 paren = *pos;
8101 pos = findmatch(NULL, '[');
8102 if (pos == NULL || ltp(pos, &paren))
8103 pos = &paren;
8105 if (pos != NULL)
8107 /* Extra trick: Take the indent of the first previous non-white
8108 * line that is at the same () level. */
8109 amount = -1;
8110 parencount = 0;
8112 while (--curwin->w_cursor.lnum >= pos->lnum)
8114 if (linewhite(curwin->w_cursor.lnum))
8115 continue;
8116 for (that = ml_get_curline(); *that != NUL; ++that)
8118 if (*that == ';')
8120 while (*(that + 1) != NUL)
8121 ++that;
8122 continue;
8124 if (*that == '\\')
8126 if (*(that + 1) != NUL)
8127 ++that;
8128 continue;
8130 if (*that == '"' && *(that + 1) != NUL)
8132 while (*++that && *that != '"')
8134 /* skipping escaped characters in the string */
8135 if (*that == '\\')
8137 if (*++that == NUL)
8138 break;
8139 if (that[1] == NUL)
8141 ++that;
8142 break;
8147 if (*that == '(' || *that == '[')
8148 ++parencount;
8149 else if (*that == ')' || *that == ']')
8150 --parencount;
8152 if (parencount == 0)
8154 amount = get_indent();
8155 break;
8159 if (amount == -1)
8161 curwin->w_cursor.lnum = pos->lnum;
8162 curwin->w_cursor.col = pos->col;
8163 col = pos->col;
8165 that = ml_get_curline();
8167 if (vi_lisp && get_indent() == 0)
8168 amount = 2;
8169 else
8171 amount = 0;
8172 while (*that && col)
8174 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8175 col--;
8179 * Some keywords require "body" indenting rules (the
8180 * non-standard-lisp ones are Scheme special forms):
8182 * (let ((a 1)) instead (let ((a 1))
8183 * (...)) of (...))
8186 if (!vi_lisp && (*that == '(' || *that == '[')
8187 && lisp_match(that + 1))
8188 amount += 2;
8189 else
8191 that++;
8192 amount++;
8193 firsttry = amount;
8195 while (vim_iswhite(*that))
8197 amount += lbr_chartabsize(that, (colnr_T)amount);
8198 ++that;
8201 if (*that && *that != ';') /* not a comment line */
8203 /* test *that != '(' to accomodate first let/do
8204 * argument if it is more than one line */
8205 if (!vi_lisp && *that != '(' && *that != '[')
8206 firsttry++;
8208 parencount = 0;
8209 quotecount = 0;
8211 if (vi_lisp
8212 || (*that != '"'
8213 && *that != '\''
8214 && *that != '#'
8215 && (*that < '0' || *that > '9')))
8217 while (*that
8218 && (!vim_iswhite(*that)
8219 || quotecount
8220 || parencount)
8221 && (!((*that == '(' || *that == '[')
8222 && !quotecount
8223 && !parencount
8224 && vi_lisp)))
8226 if (*that == '"')
8227 quotecount = !quotecount;
8228 if ((*that == '(' || *that == '[')
8229 && !quotecount)
8230 ++parencount;
8231 if ((*that == ')' || *that == ']')
8232 && !quotecount)
8233 --parencount;
8234 if (*that == '\\' && *(that+1) != NUL)
8235 amount += lbr_chartabsize_adv(&that,
8236 (colnr_T)amount);
8237 amount += lbr_chartabsize_adv(&that,
8238 (colnr_T)amount);
8241 while (vim_iswhite(*that))
8243 amount += lbr_chartabsize(that, (colnr_T)amount);
8244 that++;
8246 if (!*that || *that == ';')
8247 amount = firsttry;
8253 else
8254 amount = 0; /* no matching '(' or '[' found, use zero indent */
8256 curwin->w_cursor = realpos;
8258 return amount;
8260 #endif /* FEAT_LISP */
8262 void
8263 prepare_to_exit()
8265 #if defined(SIGHUP) && defined(SIG_IGN)
8266 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8267 * makes Vim exit and then handling SIGHUP causes various reentrance
8268 * problems. */
8269 signal(SIGHUP, SIG_IGN);
8270 #endif
8272 #ifdef FEAT_GUI
8273 if (gui.in_use)
8275 gui.dying = TRUE;
8276 out_trash(); /* trash any pending output */
8278 else
8279 #endif
8281 windgoto((int)Rows - 1, 0);
8284 * Switch terminal mode back now, so messages end up on the "normal"
8285 * screen (if there are two screens).
8287 settmode(TMODE_COOK);
8288 #ifdef WIN3264
8289 if (can_end_termcap_mode(FALSE) == TRUE)
8290 #endif
8291 stoptermcap();
8292 out_flush();
8297 * Preserve files and exit.
8298 * When called IObuff must contain a message.
8300 void
8301 preserve_exit()
8303 buf_T *buf;
8305 prepare_to_exit();
8307 /* Setting this will prevent free() calls. That avoids calling free()
8308 * recursively when free() was invoked with a bad pointer. */
8309 really_exiting = TRUE;
8311 out_str(IObuff);
8312 screen_start(); /* don't know where cursor is now */
8313 out_flush();
8315 ml_close_notmod(); /* close all not-modified buffers */
8317 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8319 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8321 OUT_STR(_("Vim: preserving files...\n"));
8322 screen_start(); /* don't know where cursor is now */
8323 out_flush();
8324 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8325 break;
8329 ml_close_all(FALSE); /* close all memfiles, without deleting */
8331 OUT_STR(_("Vim: Finished.\n"));
8333 getout(1);
8337 * return TRUE if "fname" exists.
8340 vim_fexists(fname)
8341 char_u *fname;
8343 struct stat st;
8345 if (mch_stat((char *)fname, &st))
8346 return FALSE;
8347 return TRUE;
8351 * Check for CTRL-C pressed, but only once in a while.
8352 * Should be used instead of ui_breakcheck() for functions that check for
8353 * each line in the file. Calling ui_breakcheck() each time takes too much
8354 * time, because it can be a system call.
8357 #ifndef BREAKCHECK_SKIP
8358 # ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8359 # define BREAKCHECK_SKIP 200
8360 # else
8361 # define BREAKCHECK_SKIP 32
8362 # endif
8363 #endif
8365 static int breakcheck_count = 0;
8367 void
8368 line_breakcheck()
8370 if (++breakcheck_count >= BREAKCHECK_SKIP)
8372 breakcheck_count = 0;
8373 ui_breakcheck();
8378 * Like line_breakcheck() but check 10 times less often.
8380 void
8381 fast_breakcheck()
8383 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8385 breakcheck_count = 0;
8386 ui_breakcheck();
8391 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8392 * 'wildignore'.
8393 * Returns OK or FAIL.
8396 expand_wildcards(num_pat, pat, num_file, file, flags)
8397 int num_pat; /* number of input patterns */
8398 char_u **pat; /* array of input patterns */
8399 int *num_file; /* resulting number of files */
8400 char_u ***file; /* array of resulting files */
8401 int flags; /* EW_DIR, etc. */
8403 int retval;
8404 int i, j;
8405 char_u *p;
8406 int non_suf_match; /* number without matching suffix */
8408 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8410 /* When keeping all matches, return here */
8411 if (flags & EW_KEEPALL)
8412 return retval;
8414 #ifdef FEAT_WILDIGN
8416 * Remove names that match 'wildignore'.
8418 if (*p_wig)
8420 char_u *ffname;
8422 /* check all files in (*file)[] */
8423 for (i = 0; i < *num_file; ++i)
8425 ffname = FullName_save((*file)[i], FALSE);
8426 if (ffname == NULL) /* out of memory */
8427 break;
8428 # ifdef VMS
8429 vms_remove_version(ffname);
8430 # endif
8431 if (match_file_list(p_wig, (*file)[i], ffname))
8433 /* remove this matching file from the list */
8434 vim_free((*file)[i]);
8435 for (j = i; j + 1 < *num_file; ++j)
8436 (*file)[j] = (*file)[j + 1];
8437 --*num_file;
8438 --i;
8440 vim_free(ffname);
8443 #endif
8446 * Move the names where 'suffixes' match to the end.
8448 if (*num_file > 1)
8450 non_suf_match = 0;
8451 for (i = 0; i < *num_file; ++i)
8453 if (!match_suffix((*file)[i]))
8456 * Move the name without matching suffix to the front
8457 * of the list.
8459 p = (*file)[i];
8460 for (j = i; j > non_suf_match; --j)
8461 (*file)[j] = (*file)[j - 1];
8462 (*file)[non_suf_match++] = p;
8467 return retval;
8471 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8474 match_suffix(fname)
8475 char_u *fname;
8477 int fnamelen, setsuflen;
8478 char_u *setsuf;
8479 #define MAXSUFLEN 30 /* maximum length of a file suffix */
8480 char_u suf_buf[MAXSUFLEN];
8482 fnamelen = (int)STRLEN(fname);
8483 setsuflen = 0;
8484 for (setsuf = p_su; *setsuf; )
8486 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
8487 if (fnamelen >= setsuflen
8488 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8489 (size_t)setsuflen) == 0)
8490 break;
8491 setsuflen = 0;
8493 return (setsuflen != 0);
8496 #if !defined(NO_EXPANDPATH) || defined(PROTO)
8498 # ifdef VIM_BACKTICK
8499 static int vim_backtick __ARGS((char_u *p));
8500 static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8501 # endif
8503 # if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8505 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8506 * it's shared between these systems.
8508 # if defined(DJGPP) || defined(PROTO)
8509 # define _cdecl /* DJGPP doesn't have this */
8510 # else
8511 # ifdef __BORLANDC__
8512 # define _cdecl _RTLENTRYF
8513 # endif
8514 # endif
8517 * comparison function for qsort in dos_expandpath()
8519 static int _cdecl
8520 pstrcmp(const void *a, const void *b)
8522 return (pathcmp(*(char **)a, *(char **)b, -1));
8525 # ifndef WIN3264
8526 static void
8527 namelowcpy(
8528 char_u *d,
8529 char_u *s)
8531 # ifdef DJGPP
8532 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8533 while (*s)
8534 *d++ = *s++;
8535 else
8536 # endif
8537 while (*s)
8538 *d++ = TOLOWER_LOC(*s++);
8539 *d = NUL;
8541 # endif
8544 * Recursively expand one path component into all matching files and/or
8545 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8546 * Return the number of matches found.
8547 * "path" has backslashes before chars that are not to be expanded, starting
8548 * at "path[wildoff]".
8549 * Return the number of matches found.
8550 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
8552 static int
8553 dos_expandpath(
8554 garray_T *gap,
8555 char_u *path,
8556 int wildoff,
8557 int flags, /* EW_* flags */
8558 int didstar) /* expanded "**" once already */
8560 char_u *buf;
8561 char_u *path_end;
8562 char_u *p, *s, *e;
8563 int start_len = gap->ga_len;
8564 char_u *pat;
8565 regmatch_T regmatch;
8566 int starts_with_dot;
8567 int matches;
8568 int len;
8569 int starstar = FALSE;
8570 static int stardepth = 0; /* depth for "**" expansion */
8571 #ifdef WIN3264
8572 WIN32_FIND_DATA fb;
8573 HANDLE hFind = (HANDLE)0;
8574 # ifdef FEAT_MBYTE
8575 WIN32_FIND_DATAW wfb;
8576 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8577 # endif
8578 #else
8579 struct ffblk fb;
8580 #endif
8581 char_u *matchname;
8582 int ok;
8584 /* Expanding "**" may take a long time, check for CTRL-C. */
8585 if (stardepth > 0)
8587 ui_breakcheck();
8588 if (got_int)
8589 return 0;
8592 /* make room for file name */
8593 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8594 if (buf == NULL)
8595 return 0;
8598 * Find the first part in the path name that contains a wildcard or a ~1.
8599 * Copy it into buf, including the preceding characters.
8601 p = buf;
8602 s = buf;
8603 e = NULL;
8604 path_end = path;
8605 while (*path_end != NUL)
8607 /* May ignore a wildcard that has a backslash before it; it will
8608 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8609 if (path_end >= path + wildoff && rem_backslash(path_end))
8610 *p++ = *path_end++;
8611 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8613 if (e != NULL)
8614 break;
8615 s = p + 1;
8617 else if (path_end >= path + wildoff
8618 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8619 e = p;
8620 #ifdef FEAT_MBYTE
8621 if (has_mbyte)
8623 len = (*mb_ptr2len)(path_end);
8624 STRNCPY(p, path_end, len);
8625 p += len;
8626 path_end += len;
8628 else
8629 #endif
8630 *p++ = *path_end++;
8632 e = p;
8633 *e = NUL;
8635 /* now we have one wildcard component between s and e */
8636 /* Remove backslashes between "wildoff" and the start of the wildcard
8637 * component. */
8638 for (p = buf + wildoff; p < s; ++p)
8639 if (rem_backslash(p))
8641 mch_memmove(p, p + 1, STRLEN(p));
8642 --e;
8643 --s;
8646 /* Check for "**" between "s" and "e". */
8647 for (p = s; p < e; ++p)
8648 if (p[0] == '*' && p[1] == '*')
8649 starstar = TRUE;
8651 starts_with_dot = (*s == '.');
8652 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8653 if (pat == NULL)
8655 vim_free(buf);
8656 return 0;
8659 /* compile the regexp into a program */
8660 regmatch.rm_ic = TRUE; /* Always ignore case */
8661 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8662 vim_free(pat);
8664 if (regmatch.regprog == NULL)
8666 vim_free(buf);
8667 return 0;
8670 /* remember the pattern or file name being looked for */
8671 matchname = vim_strsave(s);
8673 /* If "**" is by itself, this is the first time we encounter it and more
8674 * is following then find matches without any directory. */
8675 if (!didstar && stardepth < 100 && starstar && e - s == 2
8676 && *path_end == '/')
8678 STRCPY(s, path_end + 1);
8679 ++stardepth;
8680 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8681 --stardepth;
8684 /* Scan all files in the directory with "dir/ *.*" */
8685 STRCPY(s, "*.*");
8686 #ifdef WIN3264
8687 # ifdef FEAT_MBYTE
8688 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8690 /* The active codepage differs from 'encoding'. Attempt using the
8691 * wide function. If it fails because it is not implemented fall back
8692 * to the non-wide version (for Windows 98) */
8693 wn = enc_to_ucs2(buf, NULL);
8694 if (wn != NULL)
8696 hFind = FindFirstFileW(wn, &wfb);
8697 if (hFind == INVALID_HANDLE_VALUE
8698 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8700 vim_free(wn);
8701 wn = NULL;
8706 if (wn == NULL)
8707 # endif
8708 hFind = FindFirstFile(buf, &fb);
8709 ok = (hFind != INVALID_HANDLE_VALUE);
8710 #else
8711 /* If we are expanding wildcards we try both files and directories */
8712 ok = (findfirst((char *)buf, &fb,
8713 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8714 #endif
8716 while (ok)
8718 #ifdef WIN3264
8719 # ifdef FEAT_MBYTE
8720 if (wn != NULL)
8721 p = ucs2_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8722 else
8723 # endif
8724 p = (char_u *)fb.cFileName;
8725 #else
8726 p = (char_u *)fb.ff_name;
8727 #endif
8728 /* Ignore entries starting with a dot, unless when asked for. Accept
8729 * all entries found with "matchname". */
8730 if ((p[0] != '.' || starts_with_dot)
8731 && (matchname == NULL
8732 || vim_regexec(&regmatch, p, (colnr_T)0)))
8734 #ifdef WIN3264
8735 STRCPY(s, p);
8736 #else
8737 namelowcpy(s, p);
8738 #endif
8739 len = (int)STRLEN(buf);
8741 if (starstar && stardepth < 100)
8743 /* For "**" in the pattern first go deeper in the tree to
8744 * find matches. */
8745 STRCPY(buf + len, "/**");
8746 STRCPY(buf + len + 3, path_end);
8747 ++stardepth;
8748 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8749 --stardepth;
8752 STRCPY(buf + len, path_end);
8753 if (mch_has_exp_wildcard(path_end))
8755 /* need to expand another component of the path */
8756 /* remove backslashes for the remaining components only */
8757 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
8759 else
8761 /* no more wildcards, check if there is a match */
8762 /* remove backslashes for the remaining components only */
8763 if (*path_end != 0)
8764 backslash_halve(buf + len + 1);
8765 if (mch_getperm(buf) >= 0) /* add existing file */
8766 addfile(gap, buf, flags);
8770 #ifdef WIN3264
8771 # ifdef FEAT_MBYTE
8772 if (wn != NULL)
8774 vim_free(p);
8775 ok = FindNextFileW(hFind, &wfb);
8777 else
8778 # endif
8779 ok = FindNextFile(hFind, &fb);
8780 #else
8781 ok = (findnext(&fb) == 0);
8782 #endif
8784 /* If no more matches and no match was used, try expanding the name
8785 * itself. Finds the long name of a short filename. */
8786 if (!ok && matchname != NULL && gap->ga_len == start_len)
8788 STRCPY(s, matchname);
8789 #ifdef WIN3264
8790 FindClose(hFind);
8791 # ifdef FEAT_MBYTE
8792 if (wn != NULL)
8794 vim_free(wn);
8795 wn = enc_to_ucs2(buf, NULL);
8796 if (wn != NULL)
8797 hFind = FindFirstFileW(wn, &wfb);
8799 if (wn == NULL)
8800 # endif
8801 hFind = FindFirstFile(buf, &fb);
8802 ok = (hFind != INVALID_HANDLE_VALUE);
8803 #else
8804 ok = (findfirst((char *)buf, &fb,
8805 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8806 #endif
8807 vim_free(matchname);
8808 matchname = NULL;
8812 #ifdef WIN3264
8813 FindClose(hFind);
8814 # ifdef FEAT_MBYTE
8815 vim_free(wn);
8816 # endif
8817 #endif
8818 vim_free(buf);
8819 vim_free(regmatch.regprog);
8820 vim_free(matchname);
8822 matches = gap->ga_len - start_len;
8823 if (matches > 0)
8824 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8825 sizeof(char_u *), pstrcmp);
8826 return matches;
8830 mch_expandpath(
8831 garray_T *gap,
8832 char_u *path,
8833 int flags) /* EW_* flags */
8835 return dos_expandpath(gap, path, 0, flags, FALSE);
8837 # endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8839 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8840 || defined(PROTO)
8842 * Unix style wildcard expansion code.
8843 * It's here because it's used both for Unix and Mac.
8845 static int pstrcmp __ARGS((const void *, const void *));
8847 static int
8848 pstrcmp(a, b)
8849 const void *a, *b;
8851 return (pathcmp(*(char **)a, *(char **)b, -1));
8855 * Recursively expand one path component into all matching files and/or
8856 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8857 * "path" has backslashes before chars that are not to be expanded, starting
8858 * at "path + wildoff".
8859 * Return the number of matches found.
8860 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8863 unix_expandpath(gap, path, wildoff, flags, didstar)
8864 garray_T *gap;
8865 char_u *path;
8866 int wildoff;
8867 int flags; /* EW_* flags */
8868 int didstar; /* expanded "**" once already */
8870 char_u *buf;
8871 char_u *path_end;
8872 char_u *p, *s, *e;
8873 int start_len = gap->ga_len;
8874 char_u *pat;
8875 regmatch_T regmatch;
8876 int starts_with_dot;
8877 int matches;
8878 int len;
8879 int starstar = FALSE;
8880 static int stardepth = 0; /* depth for "**" expansion */
8882 DIR *dirp;
8883 struct dirent *dp;
8885 /* Expanding "**" may take a long time, check for CTRL-C. */
8886 if (stardepth > 0)
8888 ui_breakcheck();
8889 if (got_int)
8890 return 0;
8893 /* make room for file name */
8894 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8895 if (buf == NULL)
8896 return 0;
8899 * Find the first part in the path name that contains a wildcard.
8900 * Copy it into "buf", including the preceding characters.
8902 p = buf;
8903 s = buf;
8904 e = NULL;
8905 path_end = path;
8906 while (*path_end != NUL)
8908 /* May ignore a wildcard that has a backslash before it; it will
8909 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8910 if (path_end >= path + wildoff && rem_backslash(path_end))
8911 *p++ = *path_end++;
8912 else if (*path_end == '/')
8914 if (e != NULL)
8915 break;
8916 s = p + 1;
8918 else if (path_end >= path + wildoff
8919 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
8920 e = p;
8921 #ifdef FEAT_MBYTE
8922 if (has_mbyte)
8924 len = (*mb_ptr2len)(path_end);
8925 STRNCPY(p, path_end, len);
8926 p += len;
8927 path_end += len;
8929 else
8930 #endif
8931 *p++ = *path_end++;
8933 e = p;
8934 *e = NUL;
8936 /* now we have one wildcard component between "s" and "e" */
8937 /* Remove backslashes between "wildoff" and the start of the wildcard
8938 * component. */
8939 for (p = buf + wildoff; p < s; ++p)
8940 if (rem_backslash(p))
8942 mch_memmove(p, p + 1, STRLEN(p));
8943 --e;
8944 --s;
8947 /* Check for "**" between "s" and "e". */
8948 for (p = s; p < e; ++p)
8949 if (p[0] == '*' && p[1] == '*')
8950 starstar = TRUE;
8952 /* convert the file pattern to a regexp pattern */
8953 starts_with_dot = (*s == '.');
8954 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8955 if (pat == NULL)
8957 vim_free(buf);
8958 return 0;
8961 /* compile the regexp into a program */
8962 #ifdef CASE_INSENSITIVE_FILENAME
8963 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
8964 #else
8965 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
8966 #endif
8967 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8968 vim_free(pat);
8970 if (regmatch.regprog == NULL)
8972 vim_free(buf);
8973 return 0;
8976 /* If "**" is by itself, this is the first time we encounter it and more
8977 * is following then find matches without any directory. */
8978 if (!didstar && stardepth < 100 && starstar && e - s == 2
8979 && *path_end == '/')
8981 STRCPY(s, path_end + 1);
8982 ++stardepth;
8983 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8984 --stardepth;
8987 /* open the directory for scanning */
8988 *s = NUL;
8989 dirp = opendir(*buf == NUL ? "." : (char *)buf);
8991 /* Find all matching entries */
8992 if (dirp != NULL)
8994 for (;;)
8996 dp = readdir(dirp);
8997 if (dp == NULL)
8998 break;
8999 if ((dp->d_name[0] != '.' || starts_with_dot)
9000 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
9002 STRCPY(s, dp->d_name);
9003 len = STRLEN(buf);
9005 if (starstar && stardepth < 100)
9007 /* For "**" in the pattern first go deeper in the tree to
9008 * find matches. */
9009 STRCPY(buf + len, "/**");
9010 STRCPY(buf + len + 3, path_end);
9011 ++stardepth;
9012 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9013 --stardepth;
9016 STRCPY(buf + len, path_end);
9017 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9019 /* need to expand another component of the path */
9020 /* remove backslashes for the remaining components only */
9021 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9023 else
9025 /* no more wildcards, check if there is a match */
9026 /* remove backslashes for the remaining components only */
9027 if (*path_end != NUL)
9028 backslash_halve(buf + len + 1);
9029 if (mch_getperm(buf) >= 0) /* add existing file */
9031 #ifdef MACOS_CONVERT
9032 size_t precomp_len = STRLEN(buf)+1;
9033 char_u *precomp_buf =
9034 mac_precompose_path(buf, precomp_len, &precomp_len);
9036 if (precomp_buf)
9038 mch_memmove(buf, precomp_buf, precomp_len);
9039 vim_free(precomp_buf);
9041 #endif
9042 addfile(gap, buf, flags);
9048 closedir(dirp);
9051 vim_free(buf);
9052 vim_free(regmatch.regprog);
9054 matches = gap->ga_len - start_len;
9055 if (matches > 0)
9056 qsort(((char_u **)gap->ga_data) + start_len, matches,
9057 sizeof(char_u *), pstrcmp);
9058 return matches;
9060 #endif
9063 * Generic wildcard expansion code.
9065 * Characters in "pat" that should not be expanded must be preceded with a
9066 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9068 * Return FAIL when no single file was found. In this case "num_file" is not
9069 * set, and "file" may contain an error message.
9070 * Return OK when some files found. "num_file" is set to the number of
9071 * matches, "file" to the array of matches. Call FreeWild() later.
9074 gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9075 int num_pat; /* number of input patterns */
9076 char_u **pat; /* array of input patterns */
9077 int *num_file; /* resulting number of files */
9078 char_u ***file; /* array of resulting files */
9079 int flags; /* EW_* flags */
9081 int i;
9082 garray_T ga;
9083 char_u *p;
9084 static int recursive = FALSE;
9085 int add_pat;
9088 * expand_env() is called to expand things like "~user". If this fails,
9089 * it calls ExpandOne(), which brings us back here. In this case, always
9090 * call the machine specific expansion function, if possible. Otherwise,
9091 * return FAIL.
9093 if (recursive)
9094 #ifdef SPECIAL_WILDCHAR
9095 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9096 #else
9097 return FAIL;
9098 #endif
9100 #ifdef SPECIAL_WILDCHAR
9102 * If there are any special wildcard characters which we cannot handle
9103 * here, call machine specific function for all the expansion. This
9104 * avoids starting the shell for each argument separately.
9105 * For `=expr` do use the internal function.
9107 for (i = 0; i < num_pat; i++)
9109 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9110 # ifdef VIM_BACKTICK
9111 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9112 # endif
9114 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9116 #endif
9118 recursive = TRUE;
9121 * The matching file names are stored in a growarray. Init it empty.
9123 ga_init2(&ga, (int)sizeof(char_u *), 30);
9125 for (i = 0; i < num_pat; ++i)
9127 add_pat = -1;
9128 p = pat[i];
9130 #ifdef VIM_BACKTICK
9131 if (vim_backtick(p))
9132 add_pat = expand_backtick(&ga, p, flags);
9133 else
9134 #endif
9137 * First expand environment variables, "~/" and "~user/".
9139 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9141 p = expand_env_save(p);
9142 if (p == NULL)
9143 p = pat[i];
9144 #ifdef UNIX
9146 * On Unix, if expand_env() can't expand an environment
9147 * variable, use the shell to do that. Discard previously
9148 * found file names and start all over again.
9150 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9152 vim_free(p);
9153 ga_clear(&ga);
9154 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9155 flags);
9156 recursive = FALSE;
9157 return i;
9159 #endif
9163 * If there are wildcards: Expand file names and add each match to
9164 * the list. If there is no match, and EW_NOTFOUND is given, add
9165 * the pattern.
9166 * If there are no wildcards: Add the file name if it exists or
9167 * when EW_NOTFOUND is given.
9169 if (mch_has_exp_wildcard(p))
9170 add_pat = mch_expandpath(&ga, p, flags);
9173 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9175 char_u *t = backslash_halve_save(p);
9177 #if defined(MACOS_CLASSIC)
9178 slash_to_colon(t);
9179 #endif
9180 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9181 * "vim c:/" work. */
9182 if (flags & EW_NOTFOUND)
9183 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9184 else if (mch_getperm(t) >= 0)
9185 addfile(&ga, t, flags);
9186 vim_free(t);
9189 if (p != pat[i])
9190 vim_free(p);
9193 *num_file = ga.ga_len;
9194 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9196 recursive = FALSE;
9198 return (ga.ga_data != NULL) ? OK : FAIL;
9201 # ifdef VIM_BACKTICK
9204 * Return TRUE if we can expand this backtick thing here.
9206 static int
9207 vim_backtick(p)
9208 char_u *p;
9210 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9214 * Expand an item in `backticks` by executing it as a command.
9215 * Currently only works when pat[] starts and ends with a `.
9216 * Returns number of file names found.
9218 static int
9219 expand_backtick(gap, pat, flags)
9220 garray_T *gap;
9221 char_u *pat;
9222 int flags; /* EW_* flags */
9224 char_u *p;
9225 char_u *cmd;
9226 char_u *buffer;
9227 int cnt = 0;
9228 int i;
9230 /* Create the command: lop off the backticks. */
9231 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9232 if (cmd == NULL)
9233 return 0;
9235 #ifdef FEAT_EVAL
9236 if (*cmd == '=') /* `={expr}`: Expand expression */
9237 buffer = eval_to_string(cmd + 1, &p, TRUE);
9238 else
9239 #endif
9240 buffer = get_cmd_output(cmd, NULL,
9241 (flags & EW_SILENT) ? SHELL_SILENT : 0);
9242 vim_free(cmd);
9243 if (buffer == NULL)
9244 return 0;
9246 cmd = buffer;
9247 while (*cmd != NUL)
9249 cmd = skipwhite(cmd); /* skip over white space */
9250 p = cmd;
9251 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9252 ++p;
9253 /* add an entry if it is not empty */
9254 if (p > cmd)
9256 i = *p;
9257 *p = NUL;
9258 addfile(gap, cmd, flags);
9259 *p = i;
9260 ++cnt;
9262 cmd = p;
9263 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9264 ++cmd;
9267 vim_free(buffer);
9268 return cnt;
9270 # endif /* VIM_BACKTICK */
9273 * Add a file to a file list. Accepted flags:
9274 * EW_DIR add directories
9275 * EW_FILE add files
9276 * EW_EXEC add executable files
9277 * EW_NOTFOUND add even when it doesn't exist
9278 * EW_ADDSLASH add slash after directory name
9280 void
9281 addfile(gap, f, flags)
9282 garray_T *gap;
9283 char_u *f; /* filename */
9284 int flags;
9286 char_u *p;
9287 int isdir;
9289 /* if the file/dir doesn't exist, may not add it */
9290 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9291 return;
9293 #ifdef FNAME_ILLEGAL
9294 /* if the file/dir contains illegal characters, don't add it */
9295 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9296 return;
9297 #endif
9299 isdir = mch_isdir(f);
9300 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9301 return;
9303 /* If the file isn't executable, may not add it. Do accept directories. */
9304 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9305 return;
9307 /* Make room for another item in the file list. */
9308 if (ga_grow(gap, 1) == FAIL)
9309 return;
9311 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9312 if (p == NULL)
9313 return;
9315 STRCPY(p, f);
9316 #ifdef BACKSLASH_IN_FILENAME
9317 slash_adjust(p);
9318 #endif
9320 * Append a slash or backslash after directory names if none is present.
9322 #ifndef DONT_ADD_PATHSEP_TO_DIR
9323 if (isdir && (flags & EW_ADDSLASH))
9324 add_pathsep(p);
9325 #endif
9326 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
9328 #endif /* !NO_EXPANDPATH */
9330 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9332 #ifndef SEEK_SET
9333 # define SEEK_SET 0
9334 #endif
9335 #ifndef SEEK_END
9336 # define SEEK_END 2
9337 #endif
9340 * Get the stdout of an external command.
9341 * Returns an allocated string, or NULL for error.
9343 char_u *
9344 get_cmd_output(cmd, infile, flags)
9345 char_u *cmd;
9346 char_u *infile; /* optional input file name */
9347 int flags; /* can be SHELL_SILENT */
9349 char_u *tempname;
9350 char_u *command;
9351 char_u *buffer = NULL;
9352 int len;
9353 int i = 0;
9354 FILE *fd;
9356 if (check_restricted() || check_secure())
9357 return NULL;
9359 /* get a name for the temp file */
9360 if ((tempname = vim_tempname('o')) == NULL)
9362 EMSG(_(e_notmp));
9363 return NULL;
9366 /* Add the redirection stuff */
9367 command = make_filter_cmd(cmd, infile, tempname);
9368 if (command == NULL)
9369 goto done;
9372 * Call the shell to execute the command (errors are ignored).
9373 * Don't check timestamps here.
9375 ++no_check_timestamps;
9376 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9377 --no_check_timestamps;
9379 vim_free(command);
9382 * read the names from the file into memory
9384 # ifdef VMS
9385 /* created temporary file is not always readable as binary */
9386 fd = mch_fopen((char *)tempname, "r");
9387 # else
9388 fd = mch_fopen((char *)tempname, READBIN);
9389 # endif
9391 if (fd == NULL)
9393 EMSG2(_(e_notopen), tempname);
9394 goto done;
9397 fseek(fd, 0L, SEEK_END);
9398 len = ftell(fd); /* get size of temp file */
9399 fseek(fd, 0L, SEEK_SET);
9401 buffer = alloc(len + 1);
9402 if (buffer != NULL)
9403 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9404 fclose(fd);
9405 mch_remove(tempname);
9406 if (buffer == NULL)
9407 goto done;
9408 #ifdef VMS
9409 len = i; /* VMS doesn't give us what we asked for... */
9410 #endif
9411 if (i != len)
9413 EMSG2(_(e_notread), tempname);
9414 vim_free(buffer);
9415 buffer = NULL;
9417 else
9418 buffer[len] = '\0'; /* make sure the buffer is terminated */
9420 done:
9421 vim_free(tempname);
9422 return buffer;
9424 #endif
9427 * Free the list of files returned by expand_wildcards() or other expansion
9428 * functions.
9430 void
9431 FreeWild(count, files)
9432 int count;
9433 char_u **files;
9435 if (count <= 0 || files == NULL)
9436 return;
9437 #if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9439 * Is this still OK for when other functions than expand_wildcards() have
9440 * been used???
9442 _fnexplodefree((char **)files);
9443 #else
9444 while (count--)
9445 vim_free(files[count]);
9446 vim_free(files);
9447 #endif
9451 * return TRUE when need to go to Insert mode because of 'insertmode'.
9452 * Don't do this when still processing a command or a mapping.
9453 * Don't do this when inside a ":normal" command.
9456 goto_im()
9458 return (p_im && stuff_empty() && typebuf_typed());