Merge branch 'vim' into feat/var-tabstops
[vim_extended.git] / src / misc1.c
blobbe525996ba77698f9959b67daa5ad5a14a745bd1
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * misc1.c: functions that didn't seem to fit elsewhere
14 #include "vim.h"
15 #include "version.h"
17 static char_u *vim_version_dir __ARGS((char_u *vimdir));
18 static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
19 static int copy_indent __ARGS((int size, char_u *src));
22 * Count the size (in window cells) of the indent in the current line.
24 int
25 get_indent()
27 #ifdef FEAT_VARTABS
28 return get_indent_str_vtab(ml_get_curline(), curbuf->b_p_ts, curbuf->b_p_vts_ary);
29 #else
30 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
31 #endif
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 #ifdef FEAT_VARTABS
42 return get_indent_str_vtab(ml_get(lnum), curbuf->b_p_ts, curbuf->b_p_vts_ary);
43 #else
44 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
45 #endif
48 #if defined(FEAT_FOLDING) || defined(PROTO)
50 * Count the size (in window cells) of the indent in line "lnum" of buffer
51 * "buf".
53 int
54 get_indent_buf(buf, lnum)
55 buf_T *buf;
56 linenr_T lnum;
58 #ifdef FEAT_VARTABS
59 return get_indent_str_vtab(ml_get_buf(buf, lnum, FALSE), curbuf->b_p_ts, buf->b_p_vts_ary);
60 #else
61 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
62 #endif
64 #endif
67 * count the size (in window cells) of the indent in line "ptr", with
68 * 'tabstop' at "ts"
70 int
71 get_indent_str(ptr, ts)
72 char_u *ptr;
73 int ts;
75 int count = 0;
77 for ( ; *ptr; ++ptr)
79 if (*ptr == TAB) /* count a tab for what it is worth */
80 count += ts - (count % ts);
81 else if (*ptr == ' ')
82 ++count; /* count a space for one */
83 else
84 break;
86 return count;
89 #ifdef FEAT_VARTABS
91 * count the size (in window cells) of the indent in line "ptr", using
92 * variable tabstops
94 int
95 get_indent_str_vtab(ptr, ts, vts)
96 char_u *ptr;
97 int ts;
98 int *vts;
100 int count = 0;
102 for ( ; *ptr; ++ptr)
104 if (*ptr == TAB) /* count a tab for what it is worth */
105 count += tabstop_padding(count, ts, vts);
106 else if (*ptr == ' ')
107 ++count; /* count a space for one */
108 else
109 break;
111 return count;
113 #endif
116 * Set the indent of the current line.
117 * Leaves the cursor on the first non-blank in the line.
118 * Caller must take care of undo.
119 * "flags":
120 * SIN_CHANGED: call changed_bytes() if the line was changed.
121 * SIN_INSERT: insert the indent in front of the line.
122 * SIN_UNDO: save line for undo before changing it.
123 * Returns TRUE if the line was changed.
126 set_indent(size, flags)
127 int size; /* measured in spaces */
128 int flags;
130 char_u *p;
131 char_u *newline;
132 char_u *oldline;
133 char_u *s;
134 int todo;
135 int ind_len; /* measured in characters */
136 int line_len;
137 int doit = FALSE;
138 int ind_done = 0; /* measured in spaces */
139 #ifdef FEAT_VARTABS
140 int ind_col = 0;
141 #endif
142 int tab_pad;
143 int retval = FALSE;
144 int orig_char_len = -1; /* number of initial whitespace chars when
145 'et' and 'pi' are both set */
148 * First check if there is anything to do and compute the number of
149 * characters needed for the indent.
151 todo = size;
152 ind_len = 0;
153 p = oldline = ml_get_curline();
155 /* Calculate the buffer size for the new indent, and check to see if it
156 * isn't already set */
158 /* if 'expandtab' isn't set: use TABs; if both 'expandtab' and
159 * 'preserveindent' are set count the number of characters at the
160 * beginning of the line to be copied */
161 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
163 /* If 'preserveindent' is set then reuse as much as possible of
164 * the existing indent structure for the new indent */
165 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
167 ind_done = 0;
169 /* count as many characters as we can use */
170 while (todo > 0 && vim_iswhite(*p))
172 if (*p == TAB)
174 #ifdef FEAT_VARTABS
175 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
176 curbuf->b_p_vts_ary);
177 #else
178 tab_pad = (int)curbuf->b_p_ts
179 - (ind_done % (int)curbuf->b_p_ts);
180 #endif
181 /* stop if this tab will overshoot the target */
182 if (todo < tab_pad)
183 break;
184 todo -= tab_pad;
185 ++ind_len;
186 ind_done += tab_pad;
188 else
190 --todo;
191 ++ind_len;
192 ++ind_done;
194 ++p;
197 #ifdef FEAT_VARTABS
198 /* These diverge from this point. */
199 ind_col = ind_done;
200 #endif
201 /* Set initial number of whitespace chars to copy if we are
202 * preserving indent but expandtab is set */
203 if (curbuf->b_p_et)
204 orig_char_len = ind_len;
206 /* Fill to next tabstop with a tab, if possible */
207 #ifdef FEAT_VARTABS
208 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
209 curbuf->b_p_vts_ary);
210 #else
211 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
212 #endif
213 if (todo >= tab_pad && orig_char_len == -1)
215 doit = TRUE;
216 todo -= tab_pad;
217 ++ind_len;
218 /* ind_done += tab_pad; */
219 #ifdef FEAT_VARTABS
220 ind_col += tab_pad;
221 #endif
225 /* count tabs required for indent */
226 #ifdef FEAT_VARTABS
227 for (;;)
229 tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts, curbuf->b_p_vts_ary);
230 if (todo < tab_pad)
231 break;
232 if (*p != TAB)
233 doit = TRUE;
234 else
235 ++p;
236 todo -= tab_pad;
237 ++ind_len;
238 ind_col += tab_pad;
240 #else
241 while (todo >= (int)curbuf->b_p_ts)
243 if (*p != TAB)
244 doit = TRUE;
245 else
246 ++p;
247 todo -= (int)curbuf->b_p_ts;
248 ++ind_len;
249 /* ind_done += (int)curbuf->b_p_ts; */
251 #endif
253 /* count spaces required for indent */
254 while (todo > 0)
256 if (*p != ' ')
257 doit = TRUE;
258 else
259 ++p;
260 --todo;
261 ++ind_len;
262 /* ++ind_done; */
265 /* Return if the indent is OK already. */
266 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
267 return FALSE;
269 /* Allocate memory for the new line. */
270 if (flags & SIN_INSERT)
271 p = oldline;
272 else
273 p = skipwhite(p);
274 line_len = (int)STRLEN(p) + 1;
276 /* If 'preserveindent' and 'expandtab' are both set keep the original
277 * characters and allocate accordingly. We will fill the rest with spaces
278 * after the if (!curbuf->b_p_et) below. */
279 if (orig_char_len != -1)
281 newline = alloc(orig_char_len + size - ind_done + line_len);
282 if (newline == NULL)
283 return FALSE;
284 todo = size - ind_done;
285 ind_len = orig_char_len + todo; /* Set total length of indent in
286 * characters, which may have been
287 * undercounted until now */
288 p = oldline;
289 s = newline;
290 while (orig_char_len > 0)
292 *s++ = *p++;
293 orig_char_len--;
296 /* Skip over any additional white space (useful when newindent is less
297 * than old) */
298 while (vim_iswhite(*p))
299 ++p;
302 else
304 todo = size;
305 newline = alloc(ind_len + line_len);
306 if (newline == NULL)
307 return FALSE;
308 s = newline;
311 /* Put the characters in the new line. */
312 /* if 'expandtab' isn't set: use TABs */
313 if (!curbuf->b_p_et)
315 /* If 'preserveindent' is set then reuse as much as possible of
316 * the existing indent structure for the new indent */
317 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
319 p = oldline;
320 ind_done = 0;
322 while (todo > 0 && vim_iswhite(*p))
324 if (*p == TAB)
326 #ifdef FEAT_VARTABS
327 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
328 curbuf->b_p_vts_ary);
329 #else
330 tab_pad = (int)curbuf->b_p_ts
331 - (ind_done % (int)curbuf->b_p_ts);
332 #endif
333 /* stop if this tab will overshoot the target */
334 if (todo < tab_pad)
335 break;
336 todo -= tab_pad;
337 ind_done += tab_pad;
339 else
341 --todo;
342 ++ind_done;
344 *s++ = *p++;
347 /* Fill to next tabstop with a tab, if possible */
348 #ifdef FEAT_VARTABS
349 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
350 curbuf->b_p_vts_ary);
351 #else
352 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
353 #endif
354 if (todo >= tab_pad)
356 *s++ = TAB;
357 todo -= tab_pad;
358 #ifdef FEAT_VARTABS
359 ind_done += tab_pad;
360 #endif
363 p = skipwhite(p);
366 #ifdef FEAT_VARTABS
367 for (;;)
369 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts, curbuf->b_p_vts_ary);
370 if (todo < tab_pad)
371 break;
372 *s++ = TAB;
373 todo -= tab_pad;
374 ind_done += tab_pad;
376 #else
377 while (todo >= (int)curbuf->b_p_ts)
379 *s++ = TAB;
380 todo -= (int)curbuf->b_p_ts;
382 #endif
384 while (todo > 0)
386 *s++ = ' ';
387 --todo;
389 mch_memmove(s, p, (size_t)line_len);
391 /* Replace the line (unless undo fails). */
392 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
394 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
395 if (flags & SIN_CHANGED)
396 changed_bytes(curwin->w_cursor.lnum, 0);
397 /* Correct saved cursor position if it's after the indent. */
398 if (saved_cursor.lnum == curwin->w_cursor.lnum
399 && saved_cursor.col >= (colnr_T)(p - oldline))
400 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
401 retval = TRUE;
403 else
404 vim_free(newline);
406 curwin->w_cursor.col = ind_len;
407 return retval;
411 * Copy the indent from ptr to the current line (and fill to size)
412 * Leaves the cursor on the first non-blank in the line.
413 * Returns TRUE if the line was changed.
415 static int
416 copy_indent(size, src)
417 int size;
418 char_u *src;
420 char_u *p = NULL;
421 char_u *line = NULL;
422 char_u *s;
423 int todo;
424 int ind_len;
425 int line_len = 0;
426 int tab_pad;
427 int ind_done;
428 int round;
429 #ifdef FEAT_VARTABS
430 int ind_col;
431 #endif
433 /* Round 1: compute the number of characters needed for the indent
434 * Round 2: copy the characters. */
435 for (round = 1; round <= 2; ++round)
437 todo = size;
438 ind_len = 0;
439 ind_done = 0;
440 #ifdef FEAT_VARTABS
441 ind_col = 0;
442 #endif
443 s = src;
445 /* Count/copy the usable portion of the source line */
446 while (todo > 0 && vim_iswhite(*s))
448 if (*s == TAB)
450 #ifdef FEAT_VARTABS
451 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts, curbuf->b_p_vts_ary);
452 #else
453 tab_pad = (int)curbuf->b_p_ts
454 - (ind_done % (int)curbuf->b_p_ts);
455 #endif
456 /* Stop if this tab will overshoot the target */
457 if (todo < tab_pad)
458 break;
459 todo -= tab_pad;
460 ind_done += tab_pad;
461 #ifdef FEAT_VARTABS
462 ind_col += tab_pad;
463 #endif
465 else
467 --todo;
468 ++ind_done;
469 #ifdef FEAT_VARTABS
470 ++ind_col;
471 #endif
473 ++ind_len;
474 if (p != NULL)
475 *p++ = *s;
476 ++s;
479 /* Fill to next tabstop with a tab, if possible */
480 #ifdef FEAT_VARTABS
481 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts, curbuf->b_p_vts_ary);
482 #else
483 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
484 #endif
485 if (todo >= tab_pad)
487 todo -= tab_pad;
488 ++ind_len;
489 #ifdef FEAT_VARTABS
490 ind_col += tab_pad;
491 #endif
492 if (p != NULL)
493 *p++ = TAB;
496 /* Add tabs required for indent */
497 #ifdef FEAT_VARTABS
498 for (;;)
500 tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts, curbuf->b_p_vts_ary);
501 if (todo < tab_pad)
502 break;
503 todo -= tab_pad;
504 ++ind_len;
505 ind_col += tab_pad;
506 if (p != NULL)
507 *p++ = TAB;
509 #else
510 while (todo >= (int)curbuf->b_p_ts)
512 todo -= (int)curbuf->b_p_ts;
513 ++ind_len;
514 if (p != NULL)
515 *p++ = TAB;
517 #endif
519 /* Count/add spaces required for indent */
520 while (todo > 0)
522 --todo;
523 ++ind_len;
524 if (p != NULL)
525 *p++ = ' ';
528 if (p == NULL)
530 /* Allocate memory for the result: the copied indent, new indent
531 * and the rest of the line. */
532 line_len = (int)STRLEN(ml_get_curline()) + 1;
533 line = alloc(ind_len + line_len);
534 if (line == NULL)
535 return FALSE;
536 p = line;
540 /* Append the original line */
541 mch_memmove(p, ml_get_curline(), (size_t)line_len);
543 /* Replace the line */
544 ml_replace(curwin->w_cursor.lnum, line, FALSE);
546 /* Put the cursor after the indent. */
547 curwin->w_cursor.col = ind_len;
548 return TRUE;
552 * Return the indent of the current line after a number. Return -1 if no
553 * number was found. Used for 'n' in 'formatoptions': numbered list.
554 * Since a pattern is used it can actually handle more than numbers.
557 get_number_indent(lnum)
558 linenr_T lnum;
560 colnr_T col;
561 pos_T pos;
562 regmmatch_T regmatch;
564 if (lnum > curbuf->b_ml.ml_line_count)
565 return -1;
566 pos.lnum = 0;
567 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
568 if (regmatch.regprog != NULL)
570 regmatch.rmm_ic = FALSE;
571 regmatch.rmm_maxcol = 0;
572 if (vim_regexec_multi(&regmatch, curwin, curbuf, lnum,
573 (colnr_T)0, NULL))
575 pos.lnum = regmatch.endpos[0].lnum + lnum;
576 pos.col = regmatch.endpos[0].col;
577 #ifdef FEAT_VIRTUALEDIT
578 pos.coladd = 0;
579 #endif
581 vim_free(regmatch.regprog);
584 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
585 return -1;
586 getvcol(curwin, &pos, &col, NULL, NULL);
587 return (int)col;
590 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
592 static int cin_is_cinword __ARGS((char_u *line));
595 * Return TRUE if the string "line" starts with a word from 'cinwords'.
597 static int
598 cin_is_cinword(line)
599 char_u *line;
601 char_u *cinw;
602 char_u *cinw_buf;
603 int cinw_len;
604 int retval = FALSE;
605 int len;
607 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
608 cinw_buf = alloc((unsigned)cinw_len);
609 if (cinw_buf != NULL)
611 line = skipwhite(line);
612 for (cinw = curbuf->b_p_cinw; *cinw; )
614 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
615 if (STRNCMP(line, cinw_buf, len) == 0
616 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
618 retval = TRUE;
619 break;
622 vim_free(cinw_buf);
624 return retval;
626 #endif
629 * open_line: Add a new line below or above the current line.
631 * For VREPLACE mode, we only add a new line when we get to the end of the
632 * file, otherwise we just start replacing the next line.
634 * Caller must take care of undo. Since VREPLACE may affect any number of
635 * lines however, it may call u_save_cursor() again when starting to change a
636 * new line.
637 * "flags": OPENLINE_DELSPACES delete spaces after cursor
638 * OPENLINE_DO_COM format comments
639 * OPENLINE_KEEPTRAIL keep trailing spaces
640 * OPENLINE_MARKFIX adjust mark positions after the line break
642 * Return TRUE for success, FALSE for failure
645 open_line(dir, flags, old_indent)
646 int dir; /* FORWARD or BACKWARD */
647 int flags;
648 int old_indent; /* indent for after ^^D in Insert mode */
650 char_u *saved_line; /* copy of the original line */
651 char_u *next_line = NULL; /* copy of the next line */
652 char_u *p_extra = NULL; /* what goes to next line */
653 int less_cols = 0; /* less columns for mark in new line */
654 int less_cols_off = 0; /* columns to skip for mark adjust */
655 pos_T old_cursor; /* old cursor position */
656 int newcol = 0; /* new cursor column */
657 int newindent = 0; /* auto-indent of the new line */
658 int n;
659 int trunc_line = FALSE; /* truncate current line afterwards */
660 int retval = FALSE; /* return value, default is FAIL */
661 #ifdef FEAT_COMMENTS
662 int extra_len = 0; /* length of p_extra string */
663 int lead_len; /* length of comment leader */
664 char_u *lead_flags; /* position in 'comments' for comment leader */
665 char_u *leader = NULL; /* copy of comment leader */
666 #endif
667 char_u *allocated = NULL; /* allocated memory */
668 #if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
669 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
670 char_u *p;
671 #endif
672 int saved_char = NUL; /* init for GCC */
673 #if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
674 pos_T *pos;
675 #endif
676 #ifdef FEAT_SMARTINDENT
677 int do_si = (!p_paste && curbuf->b_p_si
678 # ifdef FEAT_CINDENT
679 && !curbuf->b_p_cin
680 # endif
682 int no_si = FALSE; /* reset did_si afterwards */
683 int first_char = NUL; /* init for GCC */
684 #endif
685 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
686 int vreplace_mode;
687 #endif
688 int did_append; /* appended a new line */
689 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
692 * make a copy of the current line so we can mess with it
694 saved_line = vim_strsave(ml_get_curline());
695 if (saved_line == NULL) /* out of memory! */
696 return FALSE;
698 #ifdef FEAT_VREPLACE
699 if (State & VREPLACE_FLAG)
702 * With VREPLACE we make a copy of the next line, which we will be
703 * starting to replace. First make the new line empty and let vim play
704 * with the indenting and comment leader to its heart's content. Then
705 * we grab what it ended up putting on the new line, put back the
706 * original line, and call ins_char() to put each new character onto
707 * the line, replacing what was there before and pushing the right
708 * stuff onto the replace stack. -- webb.
710 if (curwin->w_cursor.lnum < orig_line_count)
711 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
712 else
713 next_line = vim_strsave((char_u *)"");
714 if (next_line == NULL) /* out of memory! */
715 goto theend;
718 * In VREPLACE mode, a NL replaces the rest of the line, and starts
719 * replacing the next line, so push all of the characters left on the
720 * line onto the replace stack. We'll push any other characters that
721 * might be replaced at the start of the next line (due to autoindent
722 * etc) a bit later.
724 replace_push(NUL); /* Call twice because BS over NL expects it */
725 replace_push(NUL);
726 p = saved_line + curwin->w_cursor.col;
727 while (*p != NUL)
729 #ifdef FEAT_MBYTE
730 if (has_mbyte)
731 p += replace_push_mb(p);
732 else
733 #endif
734 replace_push(*p++);
736 saved_line[curwin->w_cursor.col] = NUL;
738 #endif
740 if ((State & INSERT)
741 #ifdef FEAT_VREPLACE
742 && !(State & VREPLACE_FLAG)
743 #endif
746 p_extra = saved_line + curwin->w_cursor.col;
747 #ifdef FEAT_SMARTINDENT
748 if (do_si) /* need first char after new line break */
750 p = skipwhite(p_extra);
751 first_char = *p;
753 #endif
754 #ifdef FEAT_COMMENTS
755 extra_len = (int)STRLEN(p_extra);
756 #endif
757 saved_char = *p_extra;
758 *p_extra = NUL;
761 u_clearline(); /* cannot do "U" command when adding lines */
762 #ifdef FEAT_SMARTINDENT
763 did_si = FALSE;
764 #endif
765 ai_col = 0;
768 * If we just did an auto-indent, then we didn't type anything on
769 * the prior line, and it should be truncated. Do this even if 'ai' is not
770 * set because automatically inserting a comment leader also sets did_ai.
772 if (dir == FORWARD && did_ai)
773 trunc_line = TRUE;
776 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
777 * indent to use for the new line.
779 if (curbuf->b_p_ai
780 #ifdef FEAT_SMARTINDENT
781 || do_si
782 #endif
786 * count white space on current line
788 #ifdef FEAT_VARTABS
789 newindent = get_indent_str_vtab(saved_line, curbuf->b_p_ts,
790 curbuf->b_p_vts_ary);
791 #else
792 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
793 #endif
794 if (newindent == 0)
795 newindent = old_indent; /* for ^^D command in insert mode */
797 #ifdef FEAT_SMARTINDENT
799 * Do smart indenting.
800 * In insert/replace mode (only when dir == FORWARD)
801 * we may move some text to the next line. If it starts with '{'
802 * don't add an indent. Fixes inserting a NL before '{' in line
803 * "if (condition) {"
805 if (!trunc_line && do_si && *saved_line != NUL
806 && (p_extra == NULL || first_char != '{'))
808 char_u *ptr;
809 char_u last_char;
811 old_cursor = curwin->w_cursor;
812 ptr = saved_line;
813 # ifdef FEAT_COMMENTS
814 if (flags & OPENLINE_DO_COM)
815 lead_len = get_leader_len(ptr, NULL, FALSE);
816 else
817 lead_len = 0;
818 # endif
819 if (dir == FORWARD)
822 * Skip preprocessor directives, unless they are
823 * recognised as comments.
825 if (
826 # ifdef FEAT_COMMENTS
827 lead_len == 0 &&
828 # endif
829 ptr[0] == '#')
831 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
832 ptr = ml_get(--curwin->w_cursor.lnum);
833 newindent = get_indent();
835 # ifdef FEAT_COMMENTS
836 if (flags & OPENLINE_DO_COM)
837 lead_len = get_leader_len(ptr, NULL, FALSE);
838 else
839 lead_len = 0;
840 if (lead_len > 0)
843 * This case gets the following right:
844 * \*
845 * * A comment (read '\' as '/').
846 * *\
847 * #define IN_THE_WAY
848 * This should line up here;
850 p = skipwhite(ptr);
851 if (p[0] == '/' && p[1] == '*')
852 p++;
853 if (p[0] == '*')
855 for (p++; *p; p++)
857 if (p[0] == '/' && p[-1] == '*')
860 * End of C comment, indent should line up
861 * with the line containing the start of
862 * the comment
864 curwin->w_cursor.col = (colnr_T)(p - ptr);
865 if ((pos = findmatch(NULL, NUL)) != NULL)
867 curwin->w_cursor.lnum = pos->lnum;
868 newindent = get_indent();
874 else /* Not a comment line */
875 # endif
877 /* Find last non-blank in line */
878 p = ptr + STRLEN(ptr) - 1;
879 while (p > ptr && vim_iswhite(*p))
880 --p;
881 last_char = *p;
884 * find the character just before the '{' or ';'
886 if (last_char == '{' || last_char == ';')
888 if (p > ptr)
889 --p;
890 while (p > ptr && vim_iswhite(*p))
891 --p;
894 * Try to catch lines that are split over multiple
895 * lines. eg:
896 * if (condition &&
897 * condition) {
898 * Should line up here!
901 if (*p == ')')
903 curwin->w_cursor.col = (colnr_T)(p - ptr);
904 if ((pos = findmatch(NULL, '(')) != NULL)
906 curwin->w_cursor.lnum = pos->lnum;
907 newindent = get_indent();
908 ptr = ml_get_curline();
912 * If last character is '{' do indent, without
913 * checking for "if" and the like.
915 if (last_char == '{')
917 did_si = TRUE; /* do indent */
918 no_si = TRUE; /* don't delete it when '{' typed */
921 * Look for "if" and the like, use 'cinwords'.
922 * Don't do this if the previous line ended in ';' or
923 * '}'.
925 else if (last_char != ';' && last_char != '}'
926 && cin_is_cinword(ptr))
927 did_si = TRUE;
930 else /* dir == BACKWARD */
933 * Skip preprocessor directives, unless they are
934 * recognised as comments.
936 if (
937 # ifdef FEAT_COMMENTS
938 lead_len == 0 &&
939 # endif
940 ptr[0] == '#')
942 int was_backslashed = FALSE;
944 while ((ptr[0] == '#' || was_backslashed) &&
945 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
947 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
948 was_backslashed = TRUE;
949 else
950 was_backslashed = FALSE;
951 ptr = ml_get(++curwin->w_cursor.lnum);
953 if (was_backslashed)
954 newindent = 0; /* Got to end of file */
955 else
956 newindent = get_indent();
958 p = skipwhite(ptr);
959 if (*p == '}') /* if line starts with '}': do indent */
960 did_si = TRUE;
961 else /* can delete indent when '{' typed */
962 can_si_back = TRUE;
964 curwin->w_cursor = old_cursor;
966 if (do_si)
967 can_si = TRUE;
968 #endif /* FEAT_SMARTINDENT */
970 did_ai = TRUE;
973 #ifdef FEAT_COMMENTS
975 * Find out if the current line starts with a comment leader.
976 * This may then be inserted in front of the new line.
978 end_comment_pending = NUL;
979 if (flags & OPENLINE_DO_COM)
980 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD);
981 else
982 lead_len = 0;
983 if (lead_len > 0)
985 char_u *lead_repl = NULL; /* replaces comment leader */
986 int lead_repl_len = 0; /* length of *lead_repl */
987 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
988 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
989 char_u *comment_end = NULL; /* where lead_end has been found */
990 int extra_space = FALSE; /* append extra space */
991 int current_flag;
992 int require_blank = FALSE; /* requires blank after middle */
993 char_u *p2;
996 * If the comment leader has the start, middle or end flag, it may not
997 * be used or may be replaced with the middle leader.
999 for (p = lead_flags; *p && *p != ':'; ++p)
1001 if (*p == COM_BLANK)
1003 require_blank = TRUE;
1004 continue;
1006 if (*p == COM_START || *p == COM_MIDDLE)
1008 current_flag = *p;
1009 if (*p == COM_START)
1012 * Doing "O" on a start of comment does not insert leader.
1014 if (dir == BACKWARD)
1016 lead_len = 0;
1017 break;
1020 /* find start of middle part */
1021 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
1022 require_blank = FALSE;
1026 * Isolate the strings of the middle and end leader.
1028 while (*p && p[-1] != ':') /* find end of middle flags */
1030 if (*p == COM_BLANK)
1031 require_blank = TRUE;
1032 ++p;
1034 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
1036 while (*p && p[-1] != ':') /* find end of end flags */
1038 /* Check whether we allow automatic ending of comments */
1039 if (*p == COM_AUTO_END)
1040 end_comment_pending = -1; /* means we want to set it */
1041 ++p;
1043 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
1045 if (end_comment_pending == -1) /* we can set it now */
1046 end_comment_pending = lead_end[n - 1];
1049 * If the end of the comment is in the same line, don't use
1050 * the comment leader.
1052 if (dir == FORWARD)
1054 for (p = saved_line + lead_len; *p; ++p)
1055 if (STRNCMP(p, lead_end, n) == 0)
1057 comment_end = p;
1058 lead_len = 0;
1059 break;
1064 * Doing "o" on a start of comment inserts the middle leader.
1066 if (lead_len > 0)
1068 if (current_flag == COM_START)
1070 lead_repl = lead_middle;
1071 lead_repl_len = (int)STRLEN(lead_middle);
1075 * If we have hit RETURN immediately after the start
1076 * comment leader, then put a space after the middle
1077 * comment leader on the next line.
1079 if (!vim_iswhite(saved_line[lead_len - 1])
1080 && ((p_extra != NULL
1081 && (int)curwin->w_cursor.col == lead_len)
1082 || (p_extra == NULL
1083 && saved_line[lead_len] == NUL)
1084 || require_blank))
1085 extra_space = TRUE;
1087 break;
1089 if (*p == COM_END)
1092 * Doing "o" on the end of a comment does not insert leader.
1093 * Remember where the end is, might want to use it to find the
1094 * start (for C-comments).
1096 if (dir == FORWARD)
1098 comment_end = skipwhite(saved_line);
1099 lead_len = 0;
1100 break;
1104 * Doing "O" on the end of a comment inserts the middle leader.
1105 * Find the string for the middle leader, searching backwards.
1107 while (p > curbuf->b_p_com && *p != ',')
1108 --p;
1109 for (lead_repl = p; lead_repl > curbuf->b_p_com
1110 && lead_repl[-1] != ':'; --lead_repl)
1112 lead_repl_len = (int)(p - lead_repl);
1114 /* We can probably always add an extra space when doing "O" on
1115 * the comment-end */
1116 extra_space = TRUE;
1118 /* Check whether we allow automatic ending of comments */
1119 for (p2 = p; *p2 && *p2 != ':'; p2++)
1121 if (*p2 == COM_AUTO_END)
1122 end_comment_pending = -1; /* means we want to set it */
1124 if (end_comment_pending == -1)
1126 /* Find last character in end-comment string */
1127 while (*p2 && *p2 != ',')
1128 p2++;
1129 end_comment_pending = p2[-1];
1131 break;
1133 if (*p == COM_FIRST)
1136 * Comment leader for first line only: Don't repeat leader
1137 * when using "O", blank out leader when using "o".
1139 if (dir == BACKWARD)
1140 lead_len = 0;
1141 else
1143 lead_repl = (char_u *)"";
1144 lead_repl_len = 0;
1146 break;
1149 if (lead_len)
1151 /* allocate buffer (may concatenate p_exta later) */
1152 leader = alloc(lead_len + lead_repl_len + extra_space +
1153 extra_len + 1);
1154 allocated = leader; /* remember to free it later */
1156 if (leader == NULL)
1157 lead_len = 0;
1158 else
1160 vim_strncpy(leader, saved_line, lead_len);
1163 * Replace leader with lead_repl, right or left adjusted
1165 if (lead_repl != NULL)
1167 int c = 0;
1168 int off = 0;
1170 for (p = lead_flags; *p != NUL && *p != ':'; )
1172 if (*p == COM_RIGHT || *p == COM_LEFT)
1173 c = *p++;
1174 else if (VIM_ISDIGIT(*p) || *p == '-')
1175 off = getdigits(&p);
1176 else
1177 ++p;
1179 if (c == COM_RIGHT) /* right adjusted leader */
1181 /* find last non-white in the leader to line up with */
1182 for (p = leader + lead_len - 1; p > leader
1183 && vim_iswhite(*p); --p)
1185 ++p;
1187 #ifdef FEAT_MBYTE
1188 /* Compute the length of the replaced characters in
1189 * screen characters, not bytes. */
1191 int repl_size = vim_strnsize(lead_repl,
1192 lead_repl_len);
1193 int old_size = 0;
1194 char_u *endp = p;
1195 int l;
1197 while (old_size < repl_size && p > leader)
1199 mb_ptr_back(leader, p);
1200 old_size += ptr2cells(p);
1202 l = lead_repl_len - (int)(endp - p);
1203 if (l != 0)
1204 mch_memmove(endp + l, endp,
1205 (size_t)((leader + lead_len) - endp));
1206 lead_len += l;
1208 #else
1209 if (p < leader + lead_repl_len)
1210 p = leader;
1211 else
1212 p -= lead_repl_len;
1213 #endif
1214 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1215 if (p + lead_repl_len > leader + lead_len)
1216 p[lead_repl_len] = NUL;
1218 /* blank-out any other chars from the old leader. */
1219 while (--p >= leader)
1221 #ifdef FEAT_MBYTE
1222 int l = mb_head_off(leader, p);
1224 if (l > 1)
1226 p -= l;
1227 if (ptr2cells(p) > 1)
1229 p[1] = ' ';
1230 --l;
1232 mch_memmove(p + 1, p + l + 1,
1233 (size_t)((leader + lead_len) - (p + l + 1)));
1234 lead_len -= l;
1235 *p = ' ';
1237 else
1238 #endif
1239 if (!vim_iswhite(*p))
1240 *p = ' ';
1243 else /* left adjusted leader */
1245 p = skipwhite(leader);
1246 #ifdef FEAT_MBYTE
1247 /* Compute the length of the replaced characters in
1248 * screen characters, not bytes. Move the part that is
1249 * not to be overwritten. */
1251 int repl_size = vim_strnsize(lead_repl,
1252 lead_repl_len);
1253 int i;
1254 int l;
1256 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1258 l = (*mb_ptr2len)(p + i);
1259 if (vim_strnsize(p, i + l) > repl_size)
1260 break;
1262 if (i != lead_repl_len)
1264 mch_memmove(p + lead_repl_len, p + i,
1265 (size_t)(lead_len - i - (p - leader)));
1266 lead_len += lead_repl_len - i;
1269 #endif
1270 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1272 /* Replace any remaining non-white chars in the old
1273 * leader by spaces. Keep Tabs, the indent must
1274 * remain the same. */
1275 for (p += lead_repl_len; p < leader + lead_len; ++p)
1276 if (!vim_iswhite(*p))
1278 /* Don't put a space before a TAB. */
1279 if (p + 1 < leader + lead_len && p[1] == TAB)
1281 --lead_len;
1282 mch_memmove(p, p + 1,
1283 (leader + lead_len) - p);
1285 else
1287 #ifdef FEAT_MBYTE
1288 int l = (*mb_ptr2len)(p);
1290 if (l > 1)
1292 if (ptr2cells(p) > 1)
1294 /* Replace a double-wide char with
1295 * two spaces */
1296 --l;
1297 *p++ = ' ';
1299 mch_memmove(p + 1, p + l,
1300 (leader + lead_len) - p);
1301 lead_len -= l - 1;
1303 #endif
1304 *p = ' ';
1307 *p = NUL;
1310 /* Recompute the indent, it may have changed. */
1311 if (curbuf->b_p_ai
1312 #ifdef FEAT_SMARTINDENT
1313 || do_si
1314 #endif
1316 #ifdef FEAT_VARTABS
1317 newindent = get_indent_str_vtab(leader, curbuf->b_p_ts,
1318 curbuf->b_p_vts_ary);
1319 #else
1320 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1321 #endif
1323 /* Add the indent offset */
1324 if (newindent + off < 0)
1326 off = -newindent;
1327 newindent = 0;
1329 else
1330 newindent += off;
1332 /* Correct trailing spaces for the shift, so that
1333 * alignment remains equal. */
1334 while (off > 0 && lead_len > 0
1335 && leader[lead_len - 1] == ' ')
1337 /* Don't do it when there is a tab before the space */
1338 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1339 break;
1340 --lead_len;
1341 --off;
1344 /* If the leader ends in white space, don't add an
1345 * extra space */
1346 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1347 extra_space = FALSE;
1348 leader[lead_len] = NUL;
1351 if (extra_space)
1353 leader[lead_len++] = ' ';
1354 leader[lead_len] = NUL;
1357 newcol = lead_len;
1360 * if a new indent will be set below, remove the indent that
1361 * is in the comment leader
1363 if (newindent
1364 #ifdef FEAT_SMARTINDENT
1365 || did_si
1366 #endif
1369 while (lead_len && vim_iswhite(*leader))
1371 --lead_len;
1372 --newcol;
1373 ++leader;
1378 #ifdef FEAT_SMARTINDENT
1379 did_si = can_si = FALSE;
1380 #endif
1382 else if (comment_end != NULL)
1385 * We have finished a comment, so we don't use the leader.
1386 * If this was a C-comment and 'ai' or 'si' is set do a normal
1387 * indent to align with the line containing the start of the
1388 * comment.
1390 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1391 (curbuf->b_p_ai
1392 #ifdef FEAT_SMARTINDENT
1393 || do_si
1394 #endif
1397 old_cursor = curwin->w_cursor;
1398 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1399 if ((pos = findmatch(NULL, NUL)) != NULL)
1401 curwin->w_cursor.lnum = pos->lnum;
1402 newindent = get_indent();
1404 curwin->w_cursor = old_cursor;
1408 #endif
1410 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1411 if (p_extra != NULL)
1413 *p_extra = saved_char; /* restore char that NUL replaced */
1416 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1417 * non-blank.
1419 * When in REPLACE mode, put the deleted blanks on the replace stack,
1420 * preceded by a NUL, so they can be put back when a BS is entered.
1422 if (REPLACE_NORMAL(State))
1423 replace_push(NUL); /* end of extra blanks */
1424 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1426 while ((*p_extra == ' ' || *p_extra == '\t')
1427 #ifdef FEAT_MBYTE
1428 && (!enc_utf8
1429 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1430 #endif
1433 if (REPLACE_NORMAL(State))
1434 replace_push(*p_extra);
1435 ++p_extra;
1436 ++less_cols_off;
1439 if (*p_extra != NUL)
1440 did_ai = FALSE; /* append some text, don't truncate now */
1442 /* columns for marks adjusted for removed columns */
1443 less_cols = (int)(p_extra - saved_line);
1446 if (p_extra == NULL)
1447 p_extra = (char_u *)""; /* append empty line */
1449 #ifdef FEAT_COMMENTS
1450 /* concatenate leader and p_extra, if there is a leader */
1451 if (lead_len)
1453 STRCAT(leader, p_extra);
1454 p_extra = leader;
1455 did_ai = TRUE; /* So truncating blanks works with comments */
1456 less_cols -= lead_len;
1458 else
1459 end_comment_pending = NUL; /* turns out there was no leader */
1460 #endif
1462 old_cursor = curwin->w_cursor;
1463 if (dir == BACKWARD)
1464 --curwin->w_cursor.lnum;
1465 #ifdef FEAT_VREPLACE
1466 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1467 #endif
1469 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1470 == FAIL)
1471 goto theend;
1472 /* Postpone calling changed_lines(), because it would mess up folding
1473 * with markers. */
1474 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1475 did_append = TRUE;
1477 #ifdef FEAT_VREPLACE
1478 else
1481 * In VREPLACE mode we are starting to replace the next line.
1483 curwin->w_cursor.lnum++;
1484 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1486 /* In case we NL to a new line, BS to the previous one, and NL
1487 * again, we don't want to save the new line for undo twice.
1489 (void)u_save_cursor(); /* errors are ignored! */
1490 vr_lines_changed++;
1492 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1493 changed_bytes(curwin->w_cursor.lnum, 0);
1494 curwin->w_cursor.lnum--;
1495 did_append = FALSE;
1497 #endif
1499 if (newindent
1500 #ifdef FEAT_SMARTINDENT
1501 || did_si
1502 #endif
1505 ++curwin->w_cursor.lnum;
1506 #ifdef FEAT_SMARTINDENT
1507 if (did_si)
1509 if (p_sr)
1510 newindent -= newindent % (int)curbuf->b_p_sw;
1511 newindent += (int)curbuf->b_p_sw;
1513 #endif
1514 /* Copy the indent */
1515 if (curbuf->b_p_ci)
1517 (void)copy_indent(newindent, saved_line);
1520 * Set the 'preserveindent' option so that any further screwing
1521 * with the line doesn't entirely destroy our efforts to preserve
1522 * it. It gets restored at the function end.
1524 curbuf->b_p_pi = TRUE;
1526 else
1527 (void)set_indent(newindent, SIN_INSERT);
1528 less_cols -= curwin->w_cursor.col;
1530 ai_col = curwin->w_cursor.col;
1533 * In REPLACE mode, for each character in the new indent, there must
1534 * be a NUL on the replace stack, for when it is deleted with BS
1536 if (REPLACE_NORMAL(State))
1537 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1538 replace_push(NUL);
1539 newcol += curwin->w_cursor.col;
1540 #ifdef FEAT_SMARTINDENT
1541 if (no_si)
1542 did_si = FALSE;
1543 #endif
1546 #ifdef FEAT_COMMENTS
1548 * In REPLACE mode, for each character in the extra leader, there must be
1549 * a NUL on the replace stack, for when it is deleted with BS.
1551 if (REPLACE_NORMAL(State))
1552 while (lead_len-- > 0)
1553 replace_push(NUL);
1554 #endif
1556 curwin->w_cursor = old_cursor;
1558 if (dir == FORWARD)
1560 if (trunc_line || (State & INSERT))
1562 /* truncate current line at cursor */
1563 saved_line[curwin->w_cursor.col] = NUL;
1564 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1565 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1566 truncate_spaces(saved_line);
1567 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1568 saved_line = NULL;
1569 if (did_append)
1571 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1572 curwin->w_cursor.lnum + 1, 1L);
1573 did_append = FALSE;
1575 /* Move marks after the line break to the new line. */
1576 if (flags & OPENLINE_MARKFIX)
1577 mark_col_adjust(curwin->w_cursor.lnum,
1578 curwin->w_cursor.col + less_cols_off,
1579 1L, (long)-less_cols);
1581 else
1582 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1586 * Put the cursor on the new line. Careful: the scrollup() above may
1587 * have moved w_cursor, we must use old_cursor.
1589 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1591 if (did_append)
1592 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1594 curwin->w_cursor.col = newcol;
1595 #ifdef FEAT_VIRTUALEDIT
1596 curwin->w_cursor.coladd = 0;
1597 #endif
1599 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1601 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1602 * fixthisline() from doing it (via change_indent()) by telling it we're in
1603 * normal INSERT mode.
1605 if (State & VREPLACE_FLAG)
1607 vreplace_mode = State; /* So we know to put things right later */
1608 State = INSERT;
1610 else
1611 vreplace_mode = 0;
1612 #endif
1613 #ifdef FEAT_LISP
1615 * May do lisp indenting.
1617 if (!p_paste
1618 # ifdef FEAT_COMMENTS
1619 && leader == NULL
1620 # endif
1621 && curbuf->b_p_lisp
1622 && curbuf->b_p_ai)
1624 fixthisline(get_lisp_indent);
1625 p = ml_get_curline();
1626 ai_col = (colnr_T)(skipwhite(p) - p);
1628 #endif
1629 #ifdef FEAT_CINDENT
1631 * May do indenting after opening a new line.
1633 if (!p_paste
1634 && (curbuf->b_p_cin
1635 # ifdef FEAT_EVAL
1636 || *curbuf->b_p_inde != NUL
1637 # endif
1639 && in_cinkeys(dir == FORWARD
1640 ? KEY_OPEN_FORW
1641 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1643 do_c_expr_indent();
1644 p = ml_get_curline();
1645 ai_col = (colnr_T)(skipwhite(p) - p);
1647 #endif
1648 #if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1649 if (vreplace_mode != 0)
1650 State = vreplace_mode;
1651 #endif
1653 #ifdef FEAT_VREPLACE
1655 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1656 * original line, and inserts the new stuff char by char, pushing old stuff
1657 * onto the replace stack (via ins_char()).
1659 if (State & VREPLACE_FLAG)
1661 /* Put new line in p_extra */
1662 p_extra = vim_strsave(ml_get_curline());
1663 if (p_extra == NULL)
1664 goto theend;
1666 /* Put back original line */
1667 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1669 /* Insert new stuff into line again */
1670 curwin->w_cursor.col = 0;
1671 #ifdef FEAT_VIRTUALEDIT
1672 curwin->w_cursor.coladd = 0;
1673 #endif
1674 ins_bytes(p_extra); /* will call changed_bytes() */
1675 vim_free(p_extra);
1676 next_line = NULL;
1678 #endif
1680 retval = TRUE; /* success! */
1681 theend:
1682 curbuf->b_p_pi = saved_pi;
1683 vim_free(saved_line);
1684 vim_free(next_line);
1685 vim_free(allocated);
1686 return retval;
1689 #if defined(FEAT_COMMENTS) || defined(PROTO)
1691 * get_leader_len() returns the length of the prefix of the given string
1692 * which introduces a comment. If this string is not a comment then 0 is
1693 * returned.
1694 * When "flags" is not NULL, it is set to point to the flags of the recognized
1695 * comment leader.
1696 * "backward" must be true for the "O" command.
1699 get_leader_len(line, flags, backward)
1700 char_u *line;
1701 char_u **flags;
1702 int backward;
1704 int i, j;
1705 int got_com = FALSE;
1706 int found_one;
1707 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1708 char_u *string; /* pointer to comment string */
1709 char_u *list;
1711 i = 0;
1712 while (vim_iswhite(line[i])) /* leading white space is ignored */
1713 ++i;
1716 * Repeat to match several nested comment strings.
1718 while (line[i])
1721 * scan through the 'comments' option for a match
1723 found_one = FALSE;
1724 for (list = curbuf->b_p_com; *list; )
1727 * Get one option part into part_buf[]. Advance list to next one.
1728 * put string at start of string.
1730 if (!got_com && flags != NULL) /* remember where flags started */
1731 *flags = list;
1732 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1733 string = vim_strchr(part_buf, ':');
1734 if (string == NULL) /* missing ':', ignore this part */
1735 continue;
1736 *string++ = NUL; /* isolate flags from string */
1739 * When already found a nested comment, only accept further
1740 * nested comments.
1742 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1743 continue;
1745 /* When 'O' flag used don't use for "O" command */
1746 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1747 continue;
1750 * Line contents and string must match.
1751 * When string starts with white space, must have some white space
1752 * (but the amount does not need to match, there might be a mix of
1753 * TABs and spaces).
1755 if (vim_iswhite(string[0]))
1757 if (i == 0 || !vim_iswhite(line[i - 1]))
1758 continue;
1759 while (vim_iswhite(string[0]))
1760 ++string;
1762 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1764 if (string[j] != NUL)
1765 continue;
1768 * When 'b' flag used, there must be white space or an
1769 * end-of-line after the string in the line.
1771 if (vim_strchr(part_buf, COM_BLANK) != NULL
1772 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1773 continue;
1776 * We have found a match, stop searching.
1778 i += j;
1779 got_com = TRUE;
1780 found_one = TRUE;
1781 break;
1785 * No match found, stop scanning.
1787 if (!found_one)
1788 break;
1791 * Include any trailing white space.
1793 while (vim_iswhite(line[i]))
1794 ++i;
1797 * If this comment doesn't nest, stop here.
1799 if (vim_strchr(part_buf, COM_NEST) == NULL)
1800 break;
1802 return (got_com ? i : 0);
1804 #endif
1807 * Return the number of window lines occupied by buffer line "lnum".
1810 plines(lnum)
1811 linenr_T lnum;
1813 return plines_win(curwin, lnum, TRUE);
1817 plines_win(wp, lnum, winheight)
1818 win_T *wp;
1819 linenr_T lnum;
1820 int winheight; /* when TRUE limit to window height */
1822 #if defined(FEAT_DIFF) || defined(PROTO)
1823 /* Check for filler lines above this buffer line. When folded the result
1824 * is one line anyway. */
1825 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1829 plines_nofill(lnum)
1830 linenr_T lnum;
1832 return plines_win_nofill(curwin, lnum, TRUE);
1836 plines_win_nofill(wp, lnum, winheight)
1837 win_T *wp;
1838 linenr_T lnum;
1839 int winheight; /* when TRUE limit to window height */
1841 #endif
1842 int lines;
1844 if (!wp->w_p_wrap)
1845 return 1;
1847 #ifdef FEAT_VERTSPLIT
1848 if (wp->w_width == 0)
1849 return 1;
1850 #endif
1852 #ifdef FEAT_FOLDING
1853 /* A folded lines is handled just like an empty line. */
1854 /* NOTE: Caller must handle lines that are MAYBE folded. */
1855 if (lineFolded(wp, lnum) == TRUE)
1856 return 1;
1857 #endif
1859 lines = plines_win_nofold(wp, lnum);
1860 if (winheight > 0 && lines > wp->w_height)
1861 return (int)wp->w_height;
1862 return lines;
1866 * Return number of window lines physical line "lnum" will occupy in window
1867 * "wp". Does not care about folding, 'wrap' or 'diff'.
1870 plines_win_nofold(wp, lnum)
1871 win_T *wp;
1872 linenr_T lnum;
1874 char_u *s;
1875 long col;
1876 int width;
1878 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1879 if (*s == NUL) /* empty line */
1880 return 1;
1881 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1884 * If list mode is on, then the '$' at the end of the line may take up one
1885 * extra column.
1887 if (wp->w_p_list && lcs_eol != NUL)
1888 col += 1;
1891 * Add column offset for 'number' and 'foldcolumn'.
1893 width = W_WIDTH(wp) - win_col_off(wp);
1894 if (width <= 0)
1895 return 32000;
1896 if (col <= width)
1897 return 1;
1898 col -= width;
1899 width += win_col_off2(wp);
1900 return (col + (width - 1)) / width + 1;
1904 * Like plines_win(), but only reports the number of physical screen lines
1905 * used from the start of the line to the given column number.
1908 plines_win_col(wp, lnum, column)
1909 win_T *wp;
1910 linenr_T lnum;
1911 long column;
1913 long col;
1914 char_u *s;
1915 int lines = 0;
1916 int width;
1918 #ifdef FEAT_DIFF
1919 /* Check for filler lines above this buffer line. When folded the result
1920 * is one line anyway. */
1921 lines = diff_check_fill(wp, lnum);
1922 #endif
1924 if (!wp->w_p_wrap)
1925 return lines + 1;
1927 #ifdef FEAT_VERTSPLIT
1928 if (wp->w_width == 0)
1929 return lines + 1;
1930 #endif
1932 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1934 col = 0;
1935 while (*s != NUL && --column >= 0)
1937 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
1938 mb_ptr_adv(s);
1942 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1943 * INSERT mode, then col must be adjusted so that it represents the last
1944 * screen position of the TAB. This only fixes an error when the TAB wraps
1945 * from one screen line to the next (when 'columns' is not a multiple of
1946 * 'ts') -- webb.
1948 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1949 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1952 * Add column offset for 'number', 'foldcolumn', etc.
1954 width = W_WIDTH(wp) - win_col_off(wp);
1955 if (width <= 0)
1956 return 9999;
1958 lines += 1;
1959 if (col > width)
1960 lines += (col - width) / (width + win_col_off2(wp)) + 1;
1961 return lines;
1965 plines_m_win(wp, first, last)
1966 win_T *wp;
1967 linenr_T first, last;
1969 int count = 0;
1971 while (first <= last)
1973 #ifdef FEAT_FOLDING
1974 int x;
1976 /* Check if there are any really folded lines, but also included lines
1977 * that are maybe folded. */
1978 x = foldedCount(wp, first, NULL);
1979 if (x > 0)
1981 ++count; /* count 1 for "+-- folded" line */
1982 first += x;
1984 else
1985 #endif
1987 #ifdef FEAT_DIFF
1988 if (first == wp->w_topline)
1989 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1990 else
1991 #endif
1992 count += plines_win(wp, first, TRUE);
1993 ++first;
1996 return (count);
1999 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
2001 * Insert string "p" at the cursor position. Stops at a NUL byte.
2002 * Handles Replace mode and multi-byte characters.
2004 void
2005 ins_bytes(p)
2006 char_u *p;
2008 ins_bytes_len(p, (int)STRLEN(p));
2010 #endif
2012 #if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
2013 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
2015 * Insert string "p" with length "len" at the cursor position.
2016 * Handles Replace mode and multi-byte characters.
2018 void
2019 ins_bytes_len(p, len)
2020 char_u *p;
2021 int len;
2023 int i;
2024 # ifdef FEAT_MBYTE
2025 int n;
2027 if (has_mbyte)
2028 for (i = 0; i < len; i += n)
2030 if (enc_utf8)
2031 /* avoid reading past p[len] */
2032 n = utfc_ptr2len_len(p + i, len - i);
2033 else
2034 n = (*mb_ptr2len)(p + i);
2035 ins_char_bytes(p + i, n);
2037 else
2038 # endif
2039 for (i = 0; i < len; ++i)
2040 ins_char(p[i]);
2042 #endif
2045 * Insert or replace a single character at the cursor position.
2046 * When in REPLACE or VREPLACE mode, replace any existing character.
2047 * Caller must have prepared for undo.
2048 * For multi-byte characters we get the whole character, the caller must
2049 * convert bytes to a character.
2051 void
2052 ins_char(c)
2053 int c;
2055 #if defined(FEAT_MBYTE) || defined(PROTO)
2056 char_u buf[MB_MAXBYTES];
2057 int n;
2059 n = (*mb_char2bytes)(c, buf);
2061 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
2062 * Happens for CTRL-Vu9900. */
2063 if (buf[0] == 0)
2064 buf[0] = '\n';
2066 ins_char_bytes(buf, n);
2069 void
2070 ins_char_bytes(buf, charlen)
2071 char_u *buf;
2072 int charlen;
2074 int c = buf[0];
2075 #endif
2076 int newlen; /* nr of bytes inserted */
2077 int oldlen; /* nr of bytes deleted (0 when not replacing) */
2078 char_u *p;
2079 char_u *newp;
2080 char_u *oldp;
2081 int linelen; /* length of old line including NUL */
2082 colnr_T col;
2083 linenr_T lnum = curwin->w_cursor.lnum;
2084 int i;
2086 #ifdef FEAT_VIRTUALEDIT
2087 /* Break tabs if needed. */
2088 if (virtual_active() && curwin->w_cursor.coladd > 0)
2089 coladvance_force(getviscol());
2090 #endif
2092 col = curwin->w_cursor.col;
2093 oldp = ml_get(lnum);
2094 linelen = (int)STRLEN(oldp) + 1;
2096 /* The lengths default to the values for when not replacing. */
2097 oldlen = 0;
2098 #ifdef FEAT_MBYTE
2099 newlen = charlen;
2100 #else
2101 newlen = 1;
2102 #endif
2104 if (State & REPLACE_FLAG)
2106 #ifdef FEAT_VREPLACE
2107 if (State & VREPLACE_FLAG)
2109 colnr_T new_vcol = 0; /* init for GCC */
2110 colnr_T vcol;
2111 int old_list;
2112 #ifndef FEAT_MBYTE
2113 char_u buf[2];
2114 #endif
2117 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
2118 * Returns the old value of list, so when finished,
2119 * curwin->w_p_list should be set back to this.
2121 old_list = curwin->w_p_list;
2122 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
2123 curwin->w_p_list = FALSE;
2126 * In virtual replace mode each character may replace one or more
2127 * characters (zero if it's a TAB). Count the number of bytes to
2128 * be deleted to make room for the new character, counting screen
2129 * cells. May result in adding spaces to fill a gap.
2131 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
2132 #ifndef FEAT_MBYTE
2133 buf[0] = c;
2134 buf[1] = NUL;
2135 #endif
2136 new_vcol = vcol + chartabsize(buf, vcol);
2137 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
2139 vcol += chartabsize(oldp + col + oldlen, vcol);
2140 /* Don't need to remove a TAB that takes us to the right
2141 * position. */
2142 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
2143 break;
2144 #ifdef FEAT_MBYTE
2145 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
2146 #else
2147 ++oldlen;
2148 #endif
2149 /* Deleted a bit too much, insert spaces. */
2150 if (vcol > new_vcol)
2151 newlen += vcol - new_vcol;
2153 curwin->w_p_list = old_list;
2155 else
2156 #endif
2157 if (oldp[col] != NUL)
2159 /* normal replace */
2160 #ifdef FEAT_MBYTE
2161 oldlen = (*mb_ptr2len)(oldp + col);
2162 #else
2163 oldlen = 1;
2164 #endif
2168 /* Push the replaced bytes onto the replace stack, so that they can be
2169 * put back when BS is used. The bytes of a multi-byte character are
2170 * done the other way around, so that the first byte is popped off
2171 * first (it tells the byte length of the character). */
2172 replace_push(NUL);
2173 for (i = 0; i < oldlen; ++i)
2175 #ifdef FEAT_MBYTE
2176 if (has_mbyte)
2177 i += replace_push_mb(oldp + col + i) - 1;
2178 else
2179 #endif
2180 replace_push(oldp[col + i]);
2184 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
2185 if (newp == NULL)
2186 return;
2188 /* Copy bytes before the cursor. */
2189 if (col > 0)
2190 mch_memmove(newp, oldp, (size_t)col);
2192 /* Copy bytes after the changed character(s). */
2193 p = newp + col;
2194 mch_memmove(p + newlen, oldp + col + oldlen,
2195 (size_t)(linelen - col - oldlen));
2197 /* Insert or overwrite the new character. */
2198 #ifdef FEAT_MBYTE
2199 mch_memmove(p, buf, charlen);
2200 i = charlen;
2201 #else
2202 *p = c;
2203 i = 1;
2204 #endif
2206 /* Fill with spaces when necessary. */
2207 while (i < newlen)
2208 p[i++] = ' ';
2210 /* Replace the line in the buffer. */
2211 ml_replace(lnum, newp, FALSE);
2213 /* mark the buffer as changed and prepare for displaying */
2214 changed_bytes(lnum, col);
2217 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2218 * show the match for right parens and braces.
2220 if (p_sm && (State & INSERT)
2221 && msg_silent == 0
2222 #ifdef FEAT_MBYTE
2223 && charlen == 1
2224 #endif
2225 #ifdef FEAT_INS_EXPAND
2226 && !ins_compl_active()
2227 #endif
2229 showmatch(c);
2231 #ifdef FEAT_RIGHTLEFT
2232 if (!p_ri || (State & REPLACE_FLAG))
2233 #endif
2235 /* Normal insert: move cursor right */
2236 #ifdef FEAT_MBYTE
2237 curwin->w_cursor.col += charlen;
2238 #else
2239 ++curwin->w_cursor.col;
2240 #endif
2243 * TODO: should try to update w_row here, to avoid recomputing it later.
2248 * Insert a string at the cursor position.
2249 * Note: Does NOT handle Replace mode.
2250 * Caller must have prepared for undo.
2252 void
2253 ins_str(s)
2254 char_u *s;
2256 char_u *oldp, *newp;
2257 int newlen = (int)STRLEN(s);
2258 int oldlen;
2259 colnr_T col;
2260 linenr_T lnum = curwin->w_cursor.lnum;
2262 #ifdef FEAT_VIRTUALEDIT
2263 if (virtual_active() && curwin->w_cursor.coladd > 0)
2264 coladvance_force(getviscol());
2265 #endif
2267 col = curwin->w_cursor.col;
2268 oldp = ml_get(lnum);
2269 oldlen = (int)STRLEN(oldp);
2271 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2272 if (newp == NULL)
2273 return;
2274 if (col > 0)
2275 mch_memmove(newp, oldp, (size_t)col);
2276 mch_memmove(newp + col, s, (size_t)newlen);
2277 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2278 ml_replace(lnum, newp, FALSE);
2279 changed_bytes(lnum, col);
2280 curwin->w_cursor.col += newlen;
2284 * Delete one character under the cursor.
2285 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2286 * Caller must have prepared for undo.
2288 * return FAIL for failure, OK otherwise
2291 del_char(fixpos)
2292 int fixpos;
2294 #ifdef FEAT_MBYTE
2295 if (has_mbyte)
2297 /* Make sure the cursor is at the start of a character. */
2298 mb_adjust_cursor();
2299 if (*ml_get_cursor() == NUL)
2300 return FAIL;
2301 return del_chars(1L, fixpos);
2303 #endif
2304 return del_bytes(1L, fixpos, TRUE);
2307 #if defined(FEAT_MBYTE) || defined(PROTO)
2309 * Like del_bytes(), but delete characters instead of bytes.
2312 del_chars(count, fixpos)
2313 long count;
2314 int fixpos;
2316 long bytes = 0;
2317 long i;
2318 char_u *p;
2319 int l;
2321 p = ml_get_cursor();
2322 for (i = 0; i < count && *p != NUL; ++i)
2324 l = (*mb_ptr2len)(p);
2325 bytes += l;
2326 p += l;
2328 return del_bytes(bytes, fixpos, TRUE);
2330 #endif
2333 * Delete "count" bytes under the cursor.
2334 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2335 * Caller must have prepared for undo.
2337 * return FAIL for failure, OK otherwise
2340 del_bytes(count, fixpos_arg, use_delcombine)
2341 long count;
2342 int fixpos_arg;
2343 int use_delcombine UNUSED; /* 'delcombine' option applies */
2345 char_u *oldp, *newp;
2346 colnr_T oldlen;
2347 linenr_T lnum = curwin->w_cursor.lnum;
2348 colnr_T col = curwin->w_cursor.col;
2349 int was_alloced;
2350 long movelen;
2351 int fixpos = fixpos_arg;
2353 oldp = ml_get(lnum);
2354 oldlen = (int)STRLEN(oldp);
2357 * Can't do anything when the cursor is on the NUL after the line.
2359 if (col >= oldlen)
2360 return FAIL;
2362 #ifdef FEAT_MBYTE
2363 /* If 'delcombine' is set and deleting (less than) one character, only
2364 * delete the last combining character. */
2365 if (p_deco && use_delcombine && enc_utf8
2366 && utfc_ptr2len(oldp + col) >= count)
2368 int cc[MAX_MCO];
2369 int n;
2371 (void)utfc_ptr2char(oldp + col, cc);
2372 if (cc[0] != NUL)
2374 /* Find the last composing char, there can be several. */
2375 n = col;
2378 col = n;
2379 count = utf_ptr2len(oldp + n);
2380 n += count;
2381 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2382 fixpos = 0;
2385 #endif
2388 * When count is too big, reduce it.
2390 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2391 if (movelen <= 1)
2394 * If we just took off the last character of a non-blank line, and
2395 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2396 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
2398 if (col > 0 && fixpos && restart_edit == 0
2399 #ifdef FEAT_VIRTUALEDIT
2400 && (ve_flags & VE_ONEMORE) == 0
2401 #endif
2404 --curwin->w_cursor.col;
2405 #ifdef FEAT_VIRTUALEDIT
2406 curwin->w_cursor.coladd = 0;
2407 #endif
2408 #ifdef FEAT_MBYTE
2409 if (has_mbyte)
2410 curwin->w_cursor.col -=
2411 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2412 #endif
2414 count = oldlen - col;
2415 movelen = 1;
2419 * If the old line has been allocated the deletion can be done in the
2420 * existing line. Otherwise a new line has to be allocated
2421 * Can't do this when using Netbeans, because we would need to invoke
2422 * netbeans_removed(), which deallocates the line. Let ml_replace() take
2423 * care of notifiying Netbeans.
2425 #ifdef FEAT_NETBEANS_INTG
2426 if (usingNetbeans)
2427 was_alloced = FALSE;
2428 else
2429 #endif
2430 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
2431 if (was_alloced)
2432 newp = oldp; /* use same allocated memory */
2433 else
2434 { /* need to allocate a new line */
2435 newp = alloc((unsigned)(oldlen + 1 - count));
2436 if (newp == NULL)
2437 return FAIL;
2438 mch_memmove(newp, oldp, (size_t)col);
2440 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2441 if (!was_alloced)
2442 ml_replace(lnum, newp, FALSE);
2444 /* mark the buffer as changed and prepare for displaying */
2445 changed_bytes(lnum, curwin->w_cursor.col);
2447 return OK;
2451 * Delete from cursor to end of line.
2452 * Caller must have prepared for undo.
2454 * return FAIL for failure, OK otherwise
2457 truncate_line(fixpos)
2458 int fixpos; /* if TRUE fix the cursor position when done */
2460 char_u *newp;
2461 linenr_T lnum = curwin->w_cursor.lnum;
2462 colnr_T col = curwin->w_cursor.col;
2464 if (col == 0)
2465 newp = vim_strsave((char_u *)"");
2466 else
2467 newp = vim_strnsave(ml_get(lnum), col);
2469 if (newp == NULL)
2470 return FAIL;
2472 ml_replace(lnum, newp, FALSE);
2474 /* mark the buffer as changed and prepare for displaying */
2475 changed_bytes(lnum, curwin->w_cursor.col);
2478 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2480 if (fixpos && curwin->w_cursor.col > 0)
2481 --curwin->w_cursor.col;
2483 return OK;
2487 * Delete "nlines" lines at the cursor.
2488 * Saves the lines for undo first if "undo" is TRUE.
2490 void
2491 del_lines(nlines, undo)
2492 long nlines; /* number of lines to delete */
2493 int undo; /* if TRUE, prepare for undo */
2495 long n;
2496 linenr_T first = curwin->w_cursor.lnum;
2498 if (nlines <= 0)
2499 return;
2501 /* save the deleted lines for undo */
2502 if (undo && u_savedel(first, nlines) == FAIL)
2503 return;
2505 for (n = 0; n < nlines; )
2507 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2508 break;
2510 ml_delete(first, TRUE);
2511 ++n;
2513 /* If we delete the last line in the file, stop */
2514 if (first > curbuf->b_ml.ml_line_count)
2515 break;
2518 /* Correct the cursor position before calling deleted_lines_mark(), it may
2519 * trigger a callback to display the cursor. */
2520 curwin->w_cursor.col = 0;
2521 check_cursor_lnum();
2523 /* adjust marks, mark the buffer as changed and prepare for displaying */
2524 deleted_lines_mark(first, n);
2528 gchar_pos(pos)
2529 pos_T *pos;
2531 char_u *ptr = ml_get_pos(pos);
2533 #ifdef FEAT_MBYTE
2534 if (has_mbyte)
2535 return (*mb_ptr2char)(ptr);
2536 #endif
2537 return (int)*ptr;
2541 gchar_cursor()
2543 #ifdef FEAT_MBYTE
2544 if (has_mbyte)
2545 return (*mb_ptr2char)(ml_get_cursor());
2546 #endif
2547 return (int)*ml_get_cursor();
2551 * Write a character at the current cursor position.
2552 * It is directly written into the block.
2554 void
2555 pchar_cursor(c)
2556 int c;
2558 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2559 + curwin->w_cursor.col) = c;
2562 #if 0 /* not used */
2564 * Put *pos at end of current buffer
2566 void
2567 goto_endofbuf(pos)
2568 pos_T *pos;
2570 char_u *p;
2572 pos->lnum = curbuf->b_ml.ml_line_count;
2573 pos->col = 0;
2574 p = ml_get(pos->lnum);
2575 while (*p++)
2576 ++pos->col;
2578 #endif
2581 * When extra == 0: Return TRUE if the cursor is before or on the first
2582 * non-blank in the line.
2583 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2584 * the line.
2587 inindent(extra)
2588 int extra;
2590 char_u *ptr;
2591 colnr_T col;
2593 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2594 ++ptr;
2595 if (col >= curwin->w_cursor.col + extra)
2596 return TRUE;
2597 else
2598 return FALSE;
2602 * Skip to next part of an option argument: Skip space and comma.
2604 char_u *
2605 skip_to_option_part(p)
2606 char_u *p;
2608 if (*p == ',')
2609 ++p;
2610 while (*p == ' ')
2611 ++p;
2612 return p;
2616 * changed() is called when something in the current buffer is changed.
2618 * Most often called through changed_bytes() and changed_lines(), which also
2619 * mark the area of the display to be redrawn.
2621 void
2622 changed()
2624 #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2625 /* The text of the preediting area is inserted, but this doesn't
2626 * mean a change of the buffer yet. That is delayed until the
2627 * text is committed. (this means preedit becomes empty) */
2628 if (im_is_preediting() && !xim_changed_while_preediting)
2629 return;
2630 xim_changed_while_preediting = FALSE;
2631 #endif
2633 if (!curbuf->b_changed)
2635 int save_msg_scroll = msg_scroll;
2637 /* Give a warning about changing a read-only file. This may also
2638 * check-out the file, thus change "curbuf"! */
2639 change_warning(0);
2641 /* Create a swap file if that is wanted.
2642 * Don't do this for "nofile" and "nowrite" buffer types. */
2643 if (curbuf->b_may_swap
2644 #ifdef FEAT_QUICKFIX
2645 && !bt_dontwrite(curbuf)
2646 #endif
2649 ml_open_file(curbuf);
2651 /* The ml_open_file() can cause an ATTENTION message.
2652 * Wait two seconds, to make sure the user reads this unexpected
2653 * message. Since we could be anywhere, call wait_return() now,
2654 * and don't let the emsg() set msg_scroll. */
2655 if (need_wait_return && emsg_silent == 0)
2657 out_flush();
2658 ui_delay(2000L, TRUE);
2659 wait_return(TRUE);
2660 msg_scroll = save_msg_scroll;
2663 curbuf->b_changed = TRUE;
2664 ml_setflags(curbuf);
2665 #ifdef FEAT_WINDOWS
2666 check_status(curbuf);
2667 redraw_tabline = TRUE;
2668 #endif
2669 #ifdef FEAT_TITLE
2670 need_maketitle = TRUE; /* set window title later */
2671 #endif
2673 ++curbuf->b_changedtick;
2676 static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2677 static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
2678 static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2681 * Changed bytes within a single line for the current buffer.
2682 * - marks the windows on this buffer to be redisplayed
2683 * - marks the buffer changed by calling changed()
2684 * - invalidates cached values
2686 void
2687 changed_bytes(lnum, col)
2688 linenr_T lnum;
2689 colnr_T col;
2691 changedOneline(curbuf, lnum);
2692 changed_common(lnum, col, lnum + 1, 0L);
2694 #ifdef FEAT_DIFF
2695 /* Diff highlighting in other diff windows may need to be updated too. */
2696 if (curwin->w_p_diff)
2698 win_T *wp;
2699 linenr_T wlnum;
2701 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2702 if (wp->w_p_diff && wp != curwin)
2704 redraw_win_later(wp, VALID);
2705 wlnum = diff_lnum_win(lnum, wp);
2706 if (wlnum > 0)
2707 changedOneline(wp->w_buffer, wlnum);
2710 #endif
2713 static void
2714 changedOneline(buf, lnum)
2715 buf_T *buf;
2716 linenr_T lnum;
2718 if (buf->b_mod_set)
2720 /* find the maximum area that must be redisplayed */
2721 if (lnum < buf->b_mod_top)
2722 buf->b_mod_top = lnum;
2723 else if (lnum >= buf->b_mod_bot)
2724 buf->b_mod_bot = lnum + 1;
2726 else
2728 /* set the area that must be redisplayed to one line */
2729 buf->b_mod_set = TRUE;
2730 buf->b_mod_top = lnum;
2731 buf->b_mod_bot = lnum + 1;
2732 buf->b_mod_xlines = 0;
2737 * Appended "count" lines below line "lnum" in the current buffer.
2738 * Must be called AFTER the change and after mark_adjust().
2739 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2741 void
2742 appended_lines(lnum, count)
2743 linenr_T lnum;
2744 long count;
2746 changed_lines(lnum + 1, 0, lnum + 1, count);
2750 * Like appended_lines(), but adjust marks first.
2752 void
2753 appended_lines_mark(lnum, count)
2754 linenr_T lnum;
2755 long count;
2757 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2758 changed_lines(lnum + 1, 0, lnum + 1, count);
2762 * Deleted "count" lines at line "lnum" in the current buffer.
2763 * Must be called AFTER the change and after mark_adjust().
2764 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2766 void
2767 deleted_lines(lnum, count)
2768 linenr_T lnum;
2769 long count;
2771 changed_lines(lnum, 0, lnum + count, -count);
2775 * Like deleted_lines(), but adjust marks first.
2776 * Make sure the cursor is on a valid line before calling, a GUI callback may
2777 * be triggered to display the cursor.
2779 void
2780 deleted_lines_mark(lnum, count)
2781 linenr_T lnum;
2782 long count;
2784 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2785 changed_lines(lnum, 0, lnum + count, -count);
2789 * Changed lines for the current buffer.
2790 * Must be called AFTER the change and after mark_adjust().
2791 * - mark the buffer changed by calling changed()
2792 * - mark the windows on this buffer to be redisplayed
2793 * - invalidate cached values
2794 * "lnum" is the first line that needs displaying, "lnume" the first line
2795 * below the changed lines (BEFORE the change).
2796 * When only inserting lines, "lnum" and "lnume" are equal.
2797 * Takes care of calling changed() and updating b_mod_*.
2799 void
2800 changed_lines(lnum, col, lnume, xtra)
2801 linenr_T lnum; /* first line with change */
2802 colnr_T col; /* column in first line with change */
2803 linenr_T lnume; /* line below last changed line */
2804 long xtra; /* number of extra lines (negative when deleting) */
2806 changed_lines_buf(curbuf, lnum, lnume, xtra);
2808 #ifdef FEAT_DIFF
2809 if (xtra == 0 && curwin->w_p_diff)
2811 /* When the number of lines doesn't change then mark_adjust() isn't
2812 * called and other diff buffers still need to be marked for
2813 * displaying. */
2814 win_T *wp;
2815 linenr_T wlnum;
2817 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2818 if (wp->w_p_diff && wp != curwin)
2820 redraw_win_later(wp, VALID);
2821 wlnum = diff_lnum_win(lnum, wp);
2822 if (wlnum > 0)
2823 changed_lines_buf(wp->w_buffer, wlnum,
2824 lnume - lnum + wlnum, 0L);
2827 #endif
2829 changed_common(lnum, col, lnume, xtra);
2832 static void
2833 changed_lines_buf(buf, lnum, lnume, xtra)
2834 buf_T *buf;
2835 linenr_T lnum; /* first line with change */
2836 linenr_T lnume; /* line below last changed line */
2837 long xtra; /* number of extra lines (negative when deleting) */
2839 if (buf->b_mod_set)
2841 /* find the maximum area that must be redisplayed */
2842 if (lnum < buf->b_mod_top)
2843 buf->b_mod_top = lnum;
2844 if (lnum < buf->b_mod_bot)
2846 /* adjust old bot position for xtra lines */
2847 buf->b_mod_bot += xtra;
2848 if (buf->b_mod_bot < lnum)
2849 buf->b_mod_bot = lnum;
2851 if (lnume + xtra > buf->b_mod_bot)
2852 buf->b_mod_bot = lnume + xtra;
2853 buf->b_mod_xlines += xtra;
2855 else
2857 /* set the area that must be redisplayed */
2858 buf->b_mod_set = TRUE;
2859 buf->b_mod_top = lnum;
2860 buf->b_mod_bot = lnume + xtra;
2861 buf->b_mod_xlines = xtra;
2865 static void
2866 changed_common(lnum, col, lnume, xtra)
2867 linenr_T lnum;
2868 colnr_T col;
2869 linenr_T lnume;
2870 long xtra;
2872 win_T *wp;
2873 #ifdef FEAT_WINDOWS
2874 tabpage_T *tp;
2875 #endif
2876 int i;
2877 #ifdef FEAT_JUMPLIST
2878 int cols;
2879 pos_T *p;
2880 int add;
2881 #endif
2883 /* mark the buffer as modified */
2884 changed();
2886 /* set the '. mark */
2887 if (!cmdmod.keepjumps)
2889 curbuf->b_last_change.lnum = lnum;
2890 curbuf->b_last_change.col = col;
2892 #ifdef FEAT_JUMPLIST
2893 /* Create a new entry if a new undo-able change was started or we
2894 * don't have an entry yet. */
2895 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2897 if (curbuf->b_changelistlen == 0)
2898 add = TRUE;
2899 else
2901 /* Don't create a new entry when the line number is the same
2902 * as the last one and the column is not too far away. Avoids
2903 * creating many entries for typing "xxxxx". */
2904 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2905 if (p->lnum != lnum)
2906 add = TRUE;
2907 else
2909 cols = comp_textwidth(FALSE);
2910 if (cols == 0)
2911 cols = 79;
2912 add = (p->col + cols < col || col + cols < p->col);
2915 if (add)
2917 /* This is the first of a new sequence of undo-able changes
2918 * and it's at some distance of the last change. Use a new
2919 * position in the changelist. */
2920 curbuf->b_new_change = FALSE;
2922 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2924 /* changelist is full: remove oldest entry */
2925 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2926 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2927 sizeof(pos_T) * (JUMPLISTSIZE - 1));
2928 FOR_ALL_TAB_WINDOWS(tp, wp)
2930 /* Correct position in changelist for other windows on
2931 * this buffer. */
2932 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2933 --wp->w_changelistidx;
2936 FOR_ALL_TAB_WINDOWS(tp, wp)
2938 /* For other windows, if the position in the changelist is
2939 * at the end it stays at the end. */
2940 if (wp->w_buffer == curbuf
2941 && wp->w_changelistidx == curbuf->b_changelistlen)
2942 ++wp->w_changelistidx;
2944 ++curbuf->b_changelistlen;
2947 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2948 curbuf->b_last_change;
2949 /* The current window is always after the last change, so that "g,"
2950 * takes you back to it. */
2951 curwin->w_changelistidx = curbuf->b_changelistlen;
2952 #endif
2955 FOR_ALL_TAB_WINDOWS(tp, wp)
2957 if (wp->w_buffer == curbuf)
2959 /* Mark this window to be redrawn later. */
2960 if (wp->w_redr_type < VALID)
2961 wp->w_redr_type = VALID;
2963 /* Check if a change in the buffer has invalidated the cached
2964 * values for the cursor. */
2965 #ifdef FEAT_FOLDING
2967 * Update the folds for this window. Can't postpone this, because
2968 * a following operator might work on the whole fold: ">>dd".
2970 foldUpdate(wp, lnum, lnume + xtra - 1);
2972 /* The change may cause lines above or below the change to become
2973 * included in a fold. Set lnum/lnume to the first/last line that
2974 * might be displayed differently.
2975 * Set w_cline_folded here as an efficient way to update it when
2976 * inserting lines just above a closed fold. */
2977 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2978 if (wp->w_cursor.lnum == lnum)
2979 wp->w_cline_folded = i;
2980 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2981 if (wp->w_cursor.lnum == lnume)
2982 wp->w_cline_folded = i;
2984 /* If the changed line is in a range of previously folded lines,
2985 * compare with the first line in that range. */
2986 if (wp->w_cursor.lnum <= lnum)
2988 i = find_wl_entry(wp, lnum);
2989 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2990 changed_line_abv_curs_win(wp);
2992 #endif
2994 if (wp->w_cursor.lnum > lnum)
2995 changed_line_abv_curs_win(wp);
2996 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2997 changed_cline_bef_curs_win(wp);
2998 if (wp->w_botline >= lnum)
3000 /* Assume that botline doesn't change (inserted lines make
3001 * other lines scroll down below botline). */
3002 approximate_botline_win(wp);
3005 /* Check if any w_lines[] entries have become invalid.
3006 * For entries below the change: Correct the lnums for
3007 * inserted/deleted lines. Makes it possible to stop displaying
3008 * after the change. */
3009 for (i = 0; i < wp->w_lines_valid; ++i)
3010 if (wp->w_lines[i].wl_valid)
3012 if (wp->w_lines[i].wl_lnum >= lnum)
3014 if (wp->w_lines[i].wl_lnum < lnume)
3016 /* line included in change */
3017 wp->w_lines[i].wl_valid = FALSE;
3019 else if (xtra != 0)
3021 /* line below change */
3022 wp->w_lines[i].wl_lnum += xtra;
3023 #ifdef FEAT_FOLDING
3024 wp->w_lines[i].wl_lastlnum += xtra;
3025 #endif
3028 #ifdef FEAT_FOLDING
3029 else if (wp->w_lines[i].wl_lastlnum >= lnum)
3031 /* change somewhere inside this range of folded lines,
3032 * may need to be redrawn */
3033 wp->w_lines[i].wl_valid = FALSE;
3035 #endif
3038 #ifdef FEAT_FOLDING
3039 /* Take care of side effects for setting w_topline when folds have
3040 * changed. Esp. when the buffer was changed in another window. */
3041 if (hasAnyFolding(wp))
3042 set_topline(wp, wp->w_topline);
3043 #endif
3047 /* Call update_screen() later, which checks out what needs to be redrawn,
3048 * since it notices b_mod_set and then uses b_mod_*. */
3049 if (must_redraw < VALID)
3050 must_redraw = VALID;
3052 #ifdef FEAT_AUTOCMD
3053 /* when the cursor line is changed always trigger CursorMoved */
3054 if (lnum <= curwin->w_cursor.lnum
3055 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
3056 last_cursormoved.lnum = 0;
3057 #endif
3061 * unchanged() is called when the changed flag must be reset for buffer 'buf'
3063 void
3064 unchanged(buf, ff)
3065 buf_T *buf;
3066 int ff; /* also reset 'fileformat' */
3068 if (buf->b_changed || (ff && file_ff_differs(buf)))
3070 buf->b_changed = 0;
3071 ml_setflags(buf);
3072 if (ff)
3073 save_file_ff(buf);
3074 #ifdef FEAT_WINDOWS
3075 check_status(buf);
3076 redraw_tabline = TRUE;
3077 #endif
3078 #ifdef FEAT_TITLE
3079 need_maketitle = TRUE; /* set window title later */
3080 #endif
3082 ++buf->b_changedtick;
3083 #ifdef FEAT_NETBEANS_INTG
3084 netbeans_unmodified(buf);
3085 #endif
3088 #if defined(FEAT_WINDOWS) || defined(PROTO)
3090 * check_status: called when the status bars for the buffer 'buf'
3091 * need to be updated
3093 void
3094 check_status(buf)
3095 buf_T *buf;
3097 win_T *wp;
3099 for (wp = firstwin; wp != NULL; wp = wp->w_next)
3100 if (wp->w_buffer == buf && wp->w_status_height)
3102 wp->w_redr_status = TRUE;
3103 if (must_redraw < VALID)
3104 must_redraw = VALID;
3107 #endif
3110 * If the file is readonly, give a warning message with the first change.
3111 * Don't do this for autocommands.
3112 * Don't use emsg(), because it flushes the macro buffer.
3113 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
3114 * will be TRUE.
3116 void
3117 change_warning(col)
3118 int col; /* column for message; non-zero when in insert
3119 mode and 'showmode' is on */
3121 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
3123 if (curbuf->b_did_warn == FALSE
3124 && curbufIsChanged() == 0
3125 #ifdef FEAT_AUTOCMD
3126 && !autocmd_busy
3127 #endif
3128 && curbuf->b_p_ro)
3130 #ifdef FEAT_AUTOCMD
3131 ++curbuf_lock;
3132 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
3133 --curbuf_lock;
3134 if (!curbuf->b_p_ro)
3135 return;
3136 #endif
3138 * Do what msg() does, but with a column offset if the warning should
3139 * be after the mode message.
3141 msg_start();
3142 if (msg_row == Rows - 1)
3143 msg_col = col;
3144 msg_source(hl_attr(HLF_W));
3145 MSG_PUTS_ATTR(_(w_readonly), hl_attr(HLF_W) | MSG_HIST);
3146 #ifdef FEAT_EVAL
3147 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
3148 #endif
3149 msg_clr_eos();
3150 (void)msg_end();
3151 if (msg_silent == 0 && !silent_mode)
3153 out_flush();
3154 ui_delay(1000L, TRUE); /* give the user time to think about it */
3156 curbuf->b_did_warn = TRUE;
3157 redraw_cmdline = FALSE; /* don't redraw and erase the message */
3158 if (msg_row < Rows - 1)
3159 showmode();
3164 * Ask for a reply from the user, a 'y' or a 'n'.
3165 * No other characters are accepted, the message is repeated until a valid
3166 * reply is entered or CTRL-C is hit.
3167 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
3168 * from any buffers but directly from the user.
3170 * return the 'y' or 'n'
3173 ask_yesno(str, direct)
3174 char_u *str;
3175 int direct;
3177 int r = ' ';
3178 int save_State = State;
3180 if (exiting) /* put terminal in raw mode for this question */
3181 settmode(TMODE_RAW);
3182 ++no_wait_return;
3183 #ifdef USE_ON_FLY_SCROLL
3184 dont_scroll = TRUE; /* disallow scrolling here */
3185 #endif
3186 State = CONFIRM; /* mouse behaves like with :confirm */
3187 #ifdef FEAT_MOUSE
3188 setmouse(); /* disables mouse for xterm */
3189 #endif
3190 ++no_mapping;
3191 ++allow_keys; /* no mapping here, but recognize keys */
3193 while (r != 'y' && r != 'n')
3195 /* same highlighting as for wait_return */
3196 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
3197 if (direct)
3198 r = get_keystroke();
3199 else
3200 r = plain_vgetc();
3201 if (r == Ctrl_C || r == ESC)
3202 r = 'n';
3203 msg_putchar(r); /* show what you typed */
3204 out_flush();
3206 --no_wait_return;
3207 State = save_State;
3208 #ifdef FEAT_MOUSE
3209 setmouse();
3210 #endif
3211 --no_mapping;
3212 --allow_keys;
3214 return r;
3218 * Get a key stroke directly from the user.
3219 * Ignores mouse clicks and scrollbar events, except a click for the left
3220 * button (used at the more prompt).
3221 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3222 * Disadvantage: typeahead is ignored.
3223 * Translates the interrupt character for unix to ESC.
3226 get_keystroke()
3228 #define CBUFLEN 151
3229 char_u buf[CBUFLEN];
3230 int len = 0;
3231 int n;
3232 int save_mapped_ctrl_c = mapped_ctrl_c;
3233 int waited = 0;
3235 mapped_ctrl_c = FALSE; /* mappings are not used here */
3236 for (;;)
3238 cursor_on();
3239 out_flush();
3241 /* First time: blocking wait. Second time: wait up to 100ms for a
3242 * terminal code to complete. Leave some room for check_termcode() to
3243 * insert a key code into (max 5 chars plus NUL). And
3244 * fix_input_buffer() can triple the number of bytes. */
3245 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3246 len == 0 ? -1L : 100L, 0);
3247 if (n > 0)
3249 /* Replace zero and CSI by a special key code. */
3250 n = fix_input_buffer(buf + len, n, FALSE);
3251 len += n;
3252 waited = 0;
3254 else if (len > 0)
3255 ++waited; /* keep track of the waiting time */
3257 /* Incomplete termcode and not timed out yet: get more characters */
3258 if ((n = check_termcode(1, buf, len)) < 0
3259 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
3260 continue;
3262 /* found a termcode: adjust length */
3263 if (n > 0)
3264 len = n;
3265 if (len == 0) /* nothing typed yet */
3266 continue;
3268 /* Handle modifier and/or special key code. */
3269 n = buf[0];
3270 if (n == K_SPECIAL)
3272 n = TO_SPECIAL(buf[1], buf[2]);
3273 if (buf[1] == KS_MODIFIER
3274 || n == K_IGNORE
3275 #ifdef FEAT_MOUSE
3276 || n == K_LEFTMOUSE_NM
3277 || n == K_LEFTDRAG
3278 || n == K_LEFTRELEASE
3279 || n == K_LEFTRELEASE_NM
3280 || n == K_MIDDLEMOUSE
3281 || n == K_MIDDLEDRAG
3282 || n == K_MIDDLERELEASE
3283 || n == K_RIGHTMOUSE
3284 || n == K_RIGHTDRAG
3285 || n == K_RIGHTRELEASE
3286 || n == K_MOUSEDOWN
3287 || n == K_MOUSEUP
3288 || n == K_X1MOUSE
3289 || n == K_X1DRAG
3290 || n == K_X1RELEASE
3291 || n == K_X2MOUSE
3292 || n == K_X2DRAG
3293 || n == K_X2RELEASE
3294 # ifdef FEAT_GUI
3295 || n == K_VER_SCROLLBAR
3296 || n == K_HOR_SCROLLBAR
3297 # endif
3298 #endif
3301 if (buf[1] == KS_MODIFIER)
3302 mod_mask = buf[2];
3303 len -= 3;
3304 if (len > 0)
3305 mch_memmove(buf, buf + 3, (size_t)len);
3306 continue;
3308 break;
3310 #ifdef FEAT_MBYTE
3311 if (has_mbyte)
3313 if (MB_BYTE2LEN(n) > len)
3314 continue; /* more bytes to get */
3315 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3316 n = (*mb_ptr2char)(buf);
3318 #endif
3319 #ifdef UNIX
3320 if (n == intr_char)
3321 n = ESC;
3322 #endif
3323 break;
3326 mapped_ctrl_c = save_mapped_ctrl_c;
3327 return n;
3331 * Get a number from the user.
3332 * When "mouse_used" is not NULL allow using the mouse.
3335 get_number(colon, mouse_used)
3336 int colon; /* allow colon to abort */
3337 int *mouse_used;
3339 int n = 0;
3340 int c;
3341 int typed = 0;
3343 if (mouse_used != NULL)
3344 *mouse_used = FALSE;
3346 /* When not printing messages, the user won't know what to type, return a
3347 * zero (as if CR was hit). */
3348 if (msg_silent != 0)
3349 return 0;
3351 #ifdef USE_ON_FLY_SCROLL
3352 dont_scroll = TRUE; /* disallow scrolling here */
3353 #endif
3354 ++no_mapping;
3355 ++allow_keys; /* no mapping here, but recognize keys */
3356 for (;;)
3358 windgoto(msg_row, msg_col);
3359 c = safe_vgetc();
3360 if (VIM_ISDIGIT(c))
3362 n = n * 10 + c - '0';
3363 msg_putchar(c);
3364 ++typed;
3366 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3368 if (typed > 0)
3370 MSG_PUTS("\b \b");
3371 --typed;
3373 n /= 10;
3375 #ifdef FEAT_MOUSE
3376 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3378 *mouse_used = TRUE;
3379 n = mouse_row + 1;
3380 break;
3382 #endif
3383 else if (n == 0 && c == ':' && colon)
3385 stuffcharReadbuff(':');
3386 if (!exmode_active)
3387 cmdline_row = msg_row;
3388 skip_redraw = TRUE; /* skip redraw once */
3389 do_redraw = FALSE;
3390 break;
3392 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3393 break;
3395 --no_mapping;
3396 --allow_keys;
3397 return n;
3401 * Ask the user to enter a number.
3402 * When "mouse_used" is not NULL allow using the mouse and in that case return
3403 * the line number.
3406 prompt_for_number(mouse_used)
3407 int *mouse_used;
3409 int i;
3410 int save_cmdline_row;
3411 int save_State;
3413 /* When using ":silent" assume that <CR> was entered. */
3414 if (mouse_used != NULL)
3415 MSG_PUTS(_("Type number and <Enter> or click with mouse (empty cancels): "));
3416 else
3417 MSG_PUTS(_("Type number and <Enter> (empty cancels): "));
3419 /* Set the state such that text can be selected/copied/pasted and we still
3420 * get mouse events. */
3421 save_cmdline_row = cmdline_row;
3422 cmdline_row = 0;
3423 save_State = State;
3424 State = CMDLINE;
3426 i = get_number(TRUE, mouse_used);
3427 if (KeyTyped)
3429 /* don't call wait_return() now */
3430 /* msg_putchar('\n'); */
3431 cmdline_row = msg_row - 1;
3432 need_wait_return = FALSE;
3433 msg_didany = FALSE;
3434 msg_didout = FALSE;
3436 else
3437 cmdline_row = save_cmdline_row;
3438 State = save_State;
3440 return i;
3443 void
3444 msgmore(n)
3445 long n;
3447 long pn;
3449 if (global_busy /* no messages now, wait until global is finished */
3450 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3451 return;
3453 /* We don't want to overwrite another important message, but do overwrite
3454 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3455 * then "put" reports the last action. */
3456 if (keep_msg != NULL && !keep_msg_more)
3457 return;
3459 if (n > 0)
3460 pn = n;
3461 else
3462 pn = -n;
3464 if (pn > p_report)
3466 if (pn == 1)
3468 if (n > 0)
3469 STRCPY(msg_buf, _("1 more line"));
3470 else
3471 STRCPY(msg_buf, _("1 line less"));
3473 else
3475 if (n > 0)
3476 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3477 else
3478 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3480 if (got_int)
3481 STRCAT(msg_buf, _(" (Interrupted)"));
3482 if (msg(msg_buf))
3484 set_keep_msg(msg_buf, 0);
3485 keep_msg_more = TRUE;
3491 * flush map and typeahead buffers and give a warning for an error
3493 void
3494 beep_flush()
3496 if (emsg_silent == 0)
3498 flush_buffers(FALSE);
3499 vim_beep();
3504 * give a warning for an error
3506 void
3507 vim_beep()
3509 if (emsg_silent == 0)
3511 if (p_vb
3512 #ifdef FEAT_GUI
3513 /* While the GUI is starting up the termcap is set for the GUI
3514 * but the output still goes to a terminal. */
3515 && !(gui.in_use && gui.starting)
3516 #endif
3519 out_str(T_VB);
3521 else
3523 #ifdef MSDOS
3525 * The number of beeps outputted is reduced to avoid having to wait
3526 * for all the beeps to finish. This is only a problem on systems
3527 * where the beeps don't overlap.
3529 if (beep_count == 0 || beep_count == 10)
3531 out_char(BELL);
3532 beep_count = 1;
3534 else
3535 ++beep_count;
3536 #else
3537 out_char(BELL);
3538 #endif
3541 /* When 'verbose' is set and we are sourcing a script or executing a
3542 * function give the user a hint where the beep comes from. */
3543 if (vim_strchr(p_debug, 'e') != NULL)
3545 msg_source(hl_attr(HLF_W));
3546 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3552 * To get the "real" home directory:
3553 * - get value of $HOME
3554 * For Unix:
3555 * - go to that directory
3556 * - do mch_dirname() to get the real name of that directory.
3557 * This also works with mounts and links.
3558 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3560 static char_u *homedir = NULL;
3562 void
3563 init_homedir()
3565 char_u *var;
3567 /* In case we are called a second time (when 'encoding' changes). */
3568 vim_free(homedir);
3569 homedir = NULL;
3571 #ifdef VMS
3572 var = mch_getenv((char_u *)"SYS$LOGIN");
3573 #else
3574 var = mch_getenv((char_u *)"HOME");
3575 #endif
3577 if (var != NULL && *var == NUL) /* empty is same as not set */
3578 var = NULL;
3580 #ifdef WIN3264
3582 * Weird but true: $HOME may contain an indirect reference to another
3583 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3584 * when $HOME is being set.
3586 if (var != NULL && *var == '%')
3588 char_u *p;
3589 char_u *exp;
3591 p = vim_strchr(var + 1, '%');
3592 if (p != NULL)
3594 vim_strncpy(NameBuff, var + 1, p - (var + 1));
3595 exp = mch_getenv(NameBuff);
3596 if (exp != NULL && *exp != NUL
3597 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3599 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
3600 var = NameBuff;
3601 /* Also set $HOME, it's needed for _viminfo. */
3602 vim_setenv((char_u *)"HOME", NameBuff);
3608 * Typically, $HOME is not defined on Windows, unless the user has
3609 * specifically defined it for Vim's sake. However, on Windows NT
3610 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3611 * each user. Try constructing $HOME from these.
3613 if (var == NULL)
3615 char_u *homedrive, *homepath;
3617 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3618 homepath = mch_getenv((char_u *)"HOMEPATH");
3619 if (homepath == NULL || *homepath == NUL)
3620 homepath = "\\";
3621 if (homedrive != NULL
3622 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3624 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3625 if (NameBuff[0] != NUL)
3627 var = NameBuff;
3628 /* Also set $HOME, it's needed for _viminfo. */
3629 vim_setenv((char_u *)"HOME", NameBuff);
3634 # if defined(FEAT_MBYTE)
3635 if (enc_utf8 && var != NULL)
3637 int len;
3638 char_u *pp;
3640 /* Convert from active codepage to UTF-8. Other conversions are
3641 * not done, because they would fail for non-ASCII characters. */
3642 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
3643 if (pp != NULL)
3645 homedir = pp;
3646 return;
3649 # endif
3650 #endif
3652 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3654 * Default home dir is C:/
3655 * Best assumption we can make in such a situation.
3657 if (var == NULL)
3658 var = "C:/";
3659 #endif
3660 if (var != NULL)
3662 #ifdef UNIX
3664 * Change to the directory and get the actual path. This resolves
3665 * links. Don't do it when we can't return.
3667 if (mch_dirname(NameBuff, MAXPATHL) == OK
3668 && mch_chdir((char *)NameBuff) == 0)
3670 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3671 var = IObuff;
3672 if (mch_chdir((char *)NameBuff) != 0)
3673 EMSG(_(e_prev_dir));
3675 #endif
3676 homedir = vim_strsave(var);
3680 #if defined(EXITFREE) || defined(PROTO)
3681 void
3682 free_homedir()
3684 vim_free(homedir);
3686 #endif
3689 * Call expand_env() and store the result in an allocated string.
3690 * This is not very memory efficient, this expects the result to be freed
3691 * again soon.
3693 char_u *
3694 expand_env_save(src)
3695 char_u *src;
3697 return expand_env_save_opt(src, FALSE);
3701 * Idem, but when "one" is TRUE handle the string as one file name, only
3702 * expand "~" at the start.
3704 char_u *
3705 expand_env_save_opt(src, one)
3706 char_u *src;
3707 int one;
3709 char_u *p;
3711 p = alloc(MAXPATHL);
3712 if (p != NULL)
3713 expand_env_esc(src, p, MAXPATHL, FALSE, one, NULL);
3714 return p;
3718 * Expand environment variable with path name.
3719 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3720 * Skips over "\ ", "\~" and "\$" (not for Win32 though).
3721 * If anything fails no expansion is done and dst equals src.
3723 void
3724 expand_env(src, dst, dstlen)
3725 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3726 char_u *dst; /* where to put the result */
3727 int dstlen; /* maximum length of the result */
3729 expand_env_esc(src, dst, dstlen, FALSE, FALSE, NULL);
3732 void
3733 expand_env_esc(srcp, dst, dstlen, esc, one, startstr)
3734 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
3735 char_u *dst; /* where to put the result */
3736 int dstlen; /* maximum length of the result */
3737 int esc; /* escape spaces in expanded variables */
3738 int one; /* "srcp" is one file name */
3739 char_u *startstr; /* start again after this (can be NULL) */
3741 char_u *src;
3742 char_u *tail;
3743 int c;
3744 char_u *var;
3745 int copy_char;
3746 int mustfree; /* var was allocated, need to free it later */
3747 int at_start = TRUE; /* at start of a name */
3748 int startstr_len = 0;
3750 if (startstr != NULL)
3751 startstr_len = (int)STRLEN(startstr);
3753 src = skipwhite(srcp);
3754 --dstlen; /* leave one char space for "\," */
3755 while (*src && dstlen > 0)
3757 copy_char = TRUE;
3758 if ((*src == '$'
3759 #ifdef VMS
3760 && at_start
3761 #endif
3763 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3764 || *src == '%'
3765 #endif
3766 || (*src == '~' && at_start))
3768 mustfree = FALSE;
3771 * The variable name is copied into dst temporarily, because it may
3772 * be a string in read-only memory and a NUL needs to be appended.
3774 if (*src != '~') /* environment var */
3776 tail = src + 1;
3777 var = dst;
3778 c = dstlen - 1;
3780 #ifdef UNIX
3781 /* Unix has ${var-name} type environment vars */
3782 if (*tail == '{' && !vim_isIDc('{'))
3784 tail++; /* ignore '{' */
3785 while (c-- > 0 && *tail && *tail != '}')
3786 *var++ = *tail++;
3788 else
3789 #endif
3791 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3792 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3793 || (*src == '%' && *tail != '%')
3794 #endif
3797 #ifdef OS2 /* env vars only in uppercase */
3798 *var++ = TOUPPER_LOC(*tail);
3799 tail++; /* toupper() may be a macro! */
3800 #else
3801 *var++ = *tail++;
3802 #endif
3806 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3807 # ifdef UNIX
3808 if (src[1] == '{' && *tail != '}')
3809 # else
3810 if (*src == '%' && *tail != '%')
3811 # endif
3812 var = NULL;
3813 else
3815 # ifdef UNIX
3816 if (src[1] == '{')
3817 # else
3818 if (*src == '%')
3819 #endif
3820 ++tail;
3821 #endif
3822 *var = NUL;
3823 var = vim_getenv(dst, &mustfree);
3824 #if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3826 #endif
3828 /* home directory */
3829 else if ( src[1] == NUL
3830 || vim_ispathsep(src[1])
3831 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3833 var = homedir;
3834 tail = src + 1;
3836 else /* user directory */
3838 #if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3840 * Copy ~user to dst[], so we can put a NUL after it.
3842 tail = src;
3843 var = dst;
3844 c = dstlen - 1;
3845 while ( c-- > 0
3846 && *tail
3847 && vim_isfilec(*tail)
3848 && !vim_ispathsep(*tail))
3849 *var++ = *tail++;
3850 *var = NUL;
3851 # ifdef UNIX
3853 * If the system supports getpwnam(), use it.
3854 * Otherwise, or if getpwnam() fails, the shell is used to
3855 * expand ~user. This is slower and may fail if the shell
3856 * does not support ~user (old versions of /bin/sh).
3858 # if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3860 struct passwd *pw;
3862 /* Note: memory allocated by getpwnam() is never freed.
3863 * Calling endpwent() apparently doesn't help. */
3864 pw = getpwnam((char *)dst + 1);
3865 if (pw != NULL)
3866 var = (char_u *)pw->pw_dir;
3867 else
3868 var = NULL;
3870 if (var == NULL)
3871 # endif
3873 expand_T xpc;
3875 ExpandInit(&xpc);
3876 xpc.xp_context = EXPAND_FILES;
3877 var = ExpandOne(&xpc, dst, NULL,
3878 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
3879 mustfree = TRUE;
3882 # else /* !UNIX, thus VMS */
3884 * USER_HOME is a comma-separated list of
3885 * directories to search for the user account in.
3888 char_u test[MAXPATHL], paths[MAXPATHL];
3889 char_u *path, *next_path, *ptr;
3890 struct stat st;
3892 STRCPY(paths, USER_HOME);
3893 next_path = paths;
3894 while (*next_path)
3896 for (path = next_path; *next_path && *next_path != ',';
3897 next_path++);
3898 if (*next_path)
3899 *next_path++ = NUL;
3900 STRCPY(test, path);
3901 STRCAT(test, "/");
3902 STRCAT(test, dst + 1);
3903 if (mch_stat(test, &st) == 0)
3905 var = alloc(STRLEN(test) + 1);
3906 STRCPY(var, test);
3907 mustfree = TRUE;
3908 break;
3912 # endif /* UNIX */
3913 #else
3914 /* cannot expand user's home directory, so don't try */
3915 var = NULL;
3916 tail = (char_u *)""; /* for gcc */
3917 #endif /* UNIX || VMS */
3920 #ifdef BACKSLASH_IN_FILENAME
3921 /* If 'shellslash' is set change backslashes to forward slashes.
3922 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3923 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3925 char_u *p = vim_strsave(var);
3927 if (p != NULL)
3929 if (mustfree)
3930 vim_free(var);
3931 var = p;
3932 mustfree = TRUE;
3933 forward_slash(var);
3936 #endif
3938 /* If "var" contains white space, escape it with a backslash.
3939 * Required for ":e ~/tt" when $HOME includes a space. */
3940 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3942 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3944 if (p != NULL)
3946 if (mustfree)
3947 vim_free(var);
3948 var = p;
3949 mustfree = TRUE;
3953 if (var != NULL && *var != NUL
3954 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3956 STRCPY(dst, var);
3957 dstlen -= (int)STRLEN(var);
3958 c = (int)STRLEN(var);
3959 /* if var[] ends in a path separator and tail[] starts
3960 * with it, skip a character */
3961 if (*var != NUL && after_pathsep(dst, dst + c)
3962 #if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3963 && dst[-1] != ':'
3964 #endif
3965 && vim_ispathsep(*tail))
3966 ++tail;
3967 dst += c;
3968 src = tail;
3969 copy_char = FALSE;
3971 if (mustfree)
3972 vim_free(var);
3975 if (copy_char) /* copy at least one char */
3978 * Recognize the start of a new name, for '~'.
3979 * Don't do this when "one" is TRUE, to avoid expanding "~" in
3980 * ":edit foo ~ foo".
3982 at_start = FALSE;
3983 if (src[0] == '\\' && src[1] != NUL)
3985 *dst++ = *src++;
3986 --dstlen;
3988 else if ((src[0] == ' ' || src[0] == ',') && !one)
3989 at_start = TRUE;
3990 *dst++ = *src++;
3991 --dstlen;
3993 if (startstr != NULL && src - startstr_len >= srcp
3994 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3995 at_start = TRUE;
3998 *dst = NUL;
4002 * Vim's version of getenv().
4003 * Special handling of $HOME, $VIM and $VIMRUNTIME.
4004 * Also does ACP to 'enc' conversion for Win32.
4006 char_u *
4007 vim_getenv(name, mustfree)
4008 char_u *name;
4009 int *mustfree; /* set to TRUE when returned is allocated */
4011 char_u *p;
4012 char_u *pend;
4013 int vimruntime;
4015 #if defined(OS2) || defined(MSDOS) || defined(MSWIN)
4016 /* use "C:/" when $HOME is not set */
4017 if (STRCMP(name, "HOME") == 0)
4018 return homedir;
4019 #endif
4021 p = mch_getenv(name);
4022 if (p != NULL && *p == NUL) /* empty is the same as not set */
4023 p = NULL;
4025 if (p != NULL)
4027 #if defined(FEAT_MBYTE) && defined(WIN3264)
4028 if (enc_utf8)
4030 int len;
4031 char_u *pp;
4033 /* Convert from active codepage to UTF-8. Other conversions are
4034 * not done, because they would fail for non-ASCII characters. */
4035 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4036 if (pp != NULL)
4038 p = pp;
4039 *mustfree = TRUE;
4042 #endif
4043 return p;
4046 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
4047 if (!vimruntime && STRCMP(name, "VIM") != 0)
4048 return NULL;
4051 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
4052 * Don't do this when default_vimruntime_dir is non-empty.
4054 if (vimruntime
4055 #ifdef HAVE_PATHDEF
4056 && *default_vimruntime_dir == NUL
4057 #endif
4060 p = mch_getenv((char_u *)"VIM");
4061 if (p != NULL && *p == NUL) /* empty is the same as not set */
4062 p = NULL;
4063 if (p != NULL)
4065 p = vim_version_dir(p);
4066 if (p != NULL)
4067 *mustfree = TRUE;
4068 else
4069 p = mch_getenv((char_u *)"VIM");
4071 #if defined(FEAT_MBYTE) && defined(WIN3264)
4072 if (enc_utf8)
4074 int len;
4075 char_u *pp;
4077 /* Convert from active codepage to UTF-8. Other conversions
4078 * are not done, because they would fail for non-ASCII
4079 * characters. */
4080 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
4081 if (pp != NULL)
4083 if (mustfree)
4084 vim_free(p);
4085 p = pp;
4086 *mustfree = TRUE;
4089 #endif
4094 * When expanding $VIM or $VIMRUNTIME fails, try using:
4095 * - the directory name from 'helpfile' (unless it contains '$')
4096 * - the executable name from argv[0]
4098 if (p == NULL)
4100 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
4101 p = p_hf;
4102 #ifdef USE_EXE_NAME
4104 * Use the name of the executable, obtained from argv[0].
4106 else
4107 p = exe_name;
4108 #endif
4109 if (p != NULL)
4111 /* remove the file name */
4112 pend = gettail(p);
4114 /* remove "doc/" from 'helpfile', if present */
4115 if (p == p_hf)
4116 pend = remove_tail(p, pend, (char_u *)"doc");
4118 #ifdef USE_EXE_NAME
4119 # ifdef MACOS_X
4120 /* remove "MacOS" from exe_name and add "Resources/vim" */
4121 if (p == exe_name)
4123 char_u *pend1;
4124 char_u *pnew;
4126 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
4127 if (pend1 != pend)
4129 pnew = alloc((unsigned)(pend1 - p) + 15);
4130 if (pnew != NULL)
4132 STRNCPY(pnew, p, (pend1 - p));
4133 STRCPY(pnew + (pend1 - p), "Resources/vim");
4134 p = pnew;
4135 pend = p + STRLEN(p);
4139 # endif
4140 /* remove "src/" from exe_name, if present */
4141 if (p == exe_name)
4142 pend = remove_tail(p, pend, (char_u *)"src");
4143 #endif
4145 /* for $VIM, remove "runtime/" or "vim54/", if present */
4146 if (!vimruntime)
4148 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
4149 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
4152 /* remove trailing path separator */
4153 #ifndef MACOS_CLASSIC
4154 /* With MacOS path (with colons) the final colon is required */
4155 /* to avoid confusion between absolute and relative path */
4156 if (pend > p && after_pathsep(p, pend))
4157 --pend;
4158 #endif
4160 #ifdef MACOS_X
4161 if (p == exe_name || p == p_hf)
4162 #endif
4163 /* check that the result is a directory name */
4164 p = vim_strnsave(p, (int)(pend - p));
4166 if (p != NULL && !mch_isdir(p))
4168 vim_free(p);
4169 p = NULL;
4171 else
4173 #ifdef USE_EXE_NAME
4174 /* may add "/vim54" or "/runtime" if it exists */
4175 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
4177 vim_free(p);
4178 p = pend;
4180 #endif
4181 *mustfree = TRUE;
4186 #ifdef HAVE_PATHDEF
4187 /* When there is a pathdef.c file we can use default_vim_dir and
4188 * default_vimruntime_dir */
4189 if (p == NULL)
4191 /* Only use default_vimruntime_dir when it is not empty */
4192 if (vimruntime && *default_vimruntime_dir != NUL)
4194 p = default_vimruntime_dir;
4195 *mustfree = FALSE;
4197 else if (*default_vim_dir != NUL)
4199 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
4200 *mustfree = TRUE;
4201 else
4203 p = default_vim_dir;
4204 *mustfree = FALSE;
4208 #endif
4211 * Set the environment variable, so that the new value can be found fast
4212 * next time, and others can also use it (e.g. Perl).
4214 if (p != NULL)
4216 if (vimruntime)
4218 vim_setenv((char_u *)"VIMRUNTIME", p);
4219 didset_vimruntime = TRUE;
4220 #ifdef FEAT_GETTEXT
4222 char_u *buf = concat_str(p, (char_u *)"/lang");
4224 if (buf != NULL)
4226 bindtextdomain(VIMPACKAGE, (char *)buf);
4227 vim_free(buf);
4230 #endif
4232 else
4234 vim_setenv((char_u *)"VIM", p);
4235 didset_vim = TRUE;
4238 return p;
4242 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
4243 * Return NULL if not, return its name in allocated memory otherwise.
4245 static char_u *
4246 vim_version_dir(vimdir)
4247 char_u *vimdir;
4249 char_u *p;
4251 if (vimdir == NULL || *vimdir == NUL)
4252 return NULL;
4253 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4254 if (p != NULL && mch_isdir(p))
4255 return p;
4256 vim_free(p);
4257 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4258 if (p != NULL && mch_isdir(p))
4259 return p;
4260 vim_free(p);
4261 return NULL;
4265 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4266 * the length of "name/". Otherwise return "pend".
4268 static char_u *
4269 remove_tail(p, pend, name)
4270 char_u *p;
4271 char_u *pend;
4272 char_u *name;
4274 int len = (int)STRLEN(name) + 1;
4275 char_u *newend = pend - len;
4277 if (newend >= p
4278 && fnamencmp(newend, name, len - 1) == 0
4279 && (newend == p || after_pathsep(p, newend)))
4280 return newend;
4281 return pend;
4285 * Our portable version of setenv.
4287 void
4288 vim_setenv(name, val)
4289 char_u *name;
4290 char_u *val;
4292 #ifdef HAVE_SETENV
4293 mch_setenv((char *)name, (char *)val, 1);
4294 #else
4295 char_u *envbuf;
4298 * Putenv does not copy the string, it has to remain
4299 * valid. The allocated memory will never be freed.
4301 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4302 if (envbuf != NULL)
4304 sprintf((char *)envbuf, "%s=%s", name, val);
4305 putenv((char *)envbuf);
4307 #endif
4310 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4312 * Function given to ExpandGeneric() to obtain an environment variable name.
4314 char_u *
4315 get_env_name(xp, idx)
4316 expand_T *xp UNUSED;
4317 int idx;
4319 # if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4321 * No environ[] on the Amiga and on the Mac (using MPW).
4323 return NULL;
4324 # else
4325 # ifndef __WIN32__
4326 /* Borland C++ 5.2 has this in a header file. */
4327 extern char **environ;
4328 # endif
4329 # define ENVNAMELEN 100
4330 static char_u name[ENVNAMELEN];
4331 char_u *str;
4332 int n;
4334 str = (char_u *)environ[idx];
4335 if (str == NULL)
4336 return NULL;
4338 for (n = 0; n < ENVNAMELEN - 1; ++n)
4340 if (str[n] == '=' || str[n] == NUL)
4341 break;
4342 name[n] = str[n];
4344 name[n] = NUL;
4345 return name;
4346 # endif
4348 #endif
4351 * Replace home directory by "~" in each space or comma separated file name in
4352 * 'src'.
4353 * If anything fails (except when out of space) dst equals src.
4355 void
4356 home_replace(buf, src, dst, dstlen, one)
4357 buf_T *buf; /* when not NULL, check for help files */
4358 char_u *src; /* input file name */
4359 char_u *dst; /* where to put the result */
4360 int dstlen; /* maximum length of the result */
4361 int one; /* if TRUE, only replace one file name, include
4362 spaces and commas in the file name. */
4364 size_t dirlen = 0, envlen = 0;
4365 size_t len;
4366 char_u *homedir_env;
4367 char_u *p;
4369 if (src == NULL)
4371 *dst = NUL;
4372 return;
4376 * If the file is a help file, remove the path completely.
4378 if (buf != NULL && buf->b_help)
4380 STRCPY(dst, gettail(src));
4381 return;
4385 * We check both the value of the $HOME environment variable and the
4386 * "real" home directory.
4388 if (homedir != NULL)
4389 dirlen = STRLEN(homedir);
4391 #ifdef VMS
4392 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4393 #else
4394 homedir_env = mch_getenv((char_u *)"HOME");
4395 #endif
4397 if (homedir_env != NULL && *homedir_env == NUL)
4398 homedir_env = NULL;
4399 if (homedir_env != NULL)
4400 envlen = STRLEN(homedir_env);
4402 if (!one)
4403 src = skipwhite(src);
4404 while (*src && dstlen > 0)
4407 * Here we are at the beginning of a file name.
4408 * First, check to see if the beginning of the file name matches
4409 * $HOME or the "real" home directory. Check that there is a '/'
4410 * after the match (so that if e.g. the file is "/home/pieter/bla",
4411 * and the home directory is "/home/piet", the file does not end up
4412 * as "~er/bla" (which would seem to indicate the file "bla" in user
4413 * er's home directory)).
4415 p = homedir;
4416 len = dirlen;
4417 for (;;)
4419 if ( len
4420 && fnamencmp(src, p, len) == 0
4421 && (vim_ispathsep(src[len])
4422 || (!one && (src[len] == ',' || src[len] == ' '))
4423 || src[len] == NUL))
4425 src += len;
4426 if (--dstlen > 0)
4427 *dst++ = '~';
4430 * If it's just the home directory, add "/".
4432 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4433 *dst++ = '/';
4434 break;
4436 if (p == homedir_env)
4437 break;
4438 p = homedir_env;
4439 len = envlen;
4442 /* if (!one) skip to separator: space or comma */
4443 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4444 *dst++ = *src++;
4445 /* skip separator */
4446 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4447 *dst++ = *src++;
4449 /* if (dstlen == 0) out of space, what to do??? */
4451 *dst = NUL;
4455 * Like home_replace, store the replaced string in allocated memory.
4456 * When something fails, NULL is returned.
4458 char_u *
4459 home_replace_save(buf, src)
4460 buf_T *buf; /* when not NULL, check for help files */
4461 char_u *src; /* input file name */
4463 char_u *dst;
4464 unsigned len;
4466 len = 3; /* space for "~/" and trailing NUL */
4467 if (src != NULL) /* just in case */
4468 len += (unsigned)STRLEN(src);
4469 dst = alloc(len);
4470 if (dst != NULL)
4471 home_replace(buf, src, dst, len, TRUE);
4472 return dst;
4476 * Compare two file names and return:
4477 * FPC_SAME if they both exist and are the same file.
4478 * FPC_SAMEX if they both don't exist and have the same file name.
4479 * FPC_DIFF if they both exist and are different files.
4480 * FPC_NOTX if they both don't exist.
4481 * FPC_DIFFX if one of them doesn't exist.
4482 * For the first name environment variables are expanded
4485 fullpathcmp(s1, s2, checkname)
4486 char_u *s1, *s2;
4487 int checkname; /* when both don't exist, check file names */
4489 #ifdef UNIX
4490 char_u exp1[MAXPATHL];
4491 char_u full1[MAXPATHL];
4492 char_u full2[MAXPATHL];
4493 struct stat st1, st2;
4494 int r1, r2;
4496 expand_env(s1, exp1, MAXPATHL);
4497 r1 = mch_stat((char *)exp1, &st1);
4498 r2 = mch_stat((char *)s2, &st2);
4499 if (r1 != 0 && r2 != 0)
4501 /* if mch_stat() doesn't work, may compare the names */
4502 if (checkname)
4504 if (fnamecmp(exp1, s2) == 0)
4505 return FPC_SAMEX;
4506 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4507 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4508 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4509 return FPC_SAMEX;
4511 return FPC_NOTX;
4513 if (r1 != 0 || r2 != 0)
4514 return FPC_DIFFX;
4515 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4516 return FPC_SAME;
4517 return FPC_DIFF;
4518 #else
4519 char_u *exp1; /* expanded s1 */
4520 char_u *full1; /* full path of s1 */
4521 char_u *full2; /* full path of s2 */
4522 int retval = FPC_DIFF;
4523 int r1, r2;
4525 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4526 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4528 full1 = exp1 + MAXPATHL;
4529 full2 = full1 + MAXPATHL;
4531 expand_env(s1, exp1, MAXPATHL);
4532 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4533 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4535 /* If vim_FullName() fails, the file probably doesn't exist. */
4536 if (r1 != OK && r2 != OK)
4538 if (checkname && fnamecmp(exp1, s2) == 0)
4539 retval = FPC_SAMEX;
4540 else
4541 retval = FPC_NOTX;
4543 else if (r1 != OK || r2 != OK)
4544 retval = FPC_DIFFX;
4545 else if (fnamecmp(full1, full2))
4546 retval = FPC_DIFF;
4547 else
4548 retval = FPC_SAME;
4549 vim_free(exp1);
4551 return retval;
4552 #endif
4556 * Get the tail of a path: the file name.
4557 * Fail safe: never returns NULL.
4559 char_u *
4560 gettail(fname)
4561 char_u *fname;
4563 char_u *p1, *p2;
4565 if (fname == NULL)
4566 return (char_u *)"";
4567 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4569 if (vim_ispathsep(*p2))
4570 p1 = p2 + 1;
4571 mb_ptr_adv(p2);
4573 return p1;
4577 * Get pointer to tail of "fname", including path separators. Putting a NUL
4578 * here leaves the directory name. Takes care of "c:/" and "//".
4579 * Always returns a valid pointer.
4581 char_u *
4582 gettail_sep(fname)
4583 char_u *fname;
4585 char_u *p;
4586 char_u *t;
4588 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4589 t = gettail(fname);
4590 while (t > p && after_pathsep(fname, t))
4591 --t;
4592 #ifdef VMS
4593 /* path separator is part of the path */
4594 ++t;
4595 #endif
4596 return t;
4600 * get the next path component (just after the next path separator).
4602 char_u *
4603 getnextcomp(fname)
4604 char_u *fname;
4606 while (*fname && !vim_ispathsep(*fname))
4607 mb_ptr_adv(fname);
4608 if (*fname)
4609 ++fname;
4610 return fname;
4614 * Get a pointer to one character past the head of a path name.
4615 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4616 * If there is no head, path is returned.
4618 char_u *
4619 get_past_head(path)
4620 char_u *path;
4622 char_u *retval;
4624 #if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4625 /* may skip "c:" */
4626 if (isalpha(path[0]) && path[1] == ':')
4627 retval = path + 2;
4628 else
4629 retval = path;
4630 #else
4631 # if defined(AMIGA)
4632 /* may skip "label:" */
4633 retval = vim_strchr(path, ':');
4634 if (retval == NULL)
4635 retval = path;
4636 # else /* Unix */
4637 retval = path;
4638 # endif
4639 #endif
4641 while (vim_ispathsep(*retval))
4642 ++retval;
4644 return retval;
4648 * return TRUE if 'c' is a path separator.
4651 vim_ispathsep(c)
4652 int c;
4654 #ifdef RISCOS
4655 return (c == '.' || c == ':');
4656 #else
4657 # ifdef UNIX
4658 return (c == '/'); /* UNIX has ':' inside file names */
4659 # else
4660 # ifdef BACKSLASH_IN_FILENAME
4661 return (c == ':' || c == '/' || c == '\\');
4662 # else
4663 # ifdef VMS
4664 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4665 return (c == ':' || c == '[' || c == ']' || c == '/'
4666 || c == '<' || c == '>' || c == '"' );
4667 # else /* Amiga */
4668 return (c == ':' || c == '/');
4669 # endif /* VMS */
4670 # endif
4671 # endif
4672 #endif /* RISC OS */
4675 #if defined(FEAT_SEARCHPATH) || defined(PROTO)
4677 * return TRUE if 'c' is a path list separator.
4680 vim_ispathlistsep(c)
4681 int c;
4683 #ifdef UNIX
4684 return (c == ':');
4685 #else
4686 return (c == ';'); /* might not be right for every system... */
4687 #endif
4689 #endif
4691 #if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4692 || defined(FEAT_EVAL) || defined(PROTO)
4694 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4695 * It's done in-place.
4697 void
4698 shorten_dir(str)
4699 char_u *str;
4701 char_u *tail, *s, *d;
4702 int skip = FALSE;
4704 tail = gettail(str);
4705 d = str;
4706 for (s = str; ; ++s)
4708 if (s >= tail) /* copy the whole tail */
4710 *d++ = *s;
4711 if (*s == NUL)
4712 break;
4714 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4716 *d++ = *s;
4717 skip = FALSE;
4719 else if (!skip)
4721 *d++ = *s; /* copy next char */
4722 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4723 skip = TRUE;
4724 # ifdef FEAT_MBYTE
4725 if (has_mbyte)
4727 int l = mb_ptr2len(s);
4729 while (--l > 0)
4730 *d++ = *++s;
4732 # endif
4736 #endif
4739 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4740 * Also returns TRUE if there is no directory name.
4741 * "fname" must be writable!.
4744 dir_of_file_exists(fname)
4745 char_u *fname;
4747 char_u *p;
4748 int c;
4749 int retval;
4751 p = gettail_sep(fname);
4752 if (p == fname)
4753 return TRUE;
4754 c = *p;
4755 *p = NUL;
4756 retval = mch_isdir(fname);
4757 *p = c;
4758 return retval;
4761 #if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4762 || defined(PROTO)
4764 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4767 vim_fnamecmp(x, y)
4768 char_u *x, *y;
4770 return vim_fnamencmp(x, y, MAXPATHL);
4774 vim_fnamencmp(x, y, len)
4775 char_u *x, *y;
4776 size_t len;
4778 while (len > 0 && *x && *y)
4780 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4781 && !(*x == '/' && *y == '\\')
4782 && !(*x == '\\' && *y == '/'))
4783 break;
4784 ++x;
4785 ++y;
4786 --len;
4788 if (len == 0)
4789 return 0;
4790 return (*x - *y);
4792 #endif
4795 * Concatenate file names fname1 and fname2 into allocated memory.
4796 * Only add a '/' or '\\' when 'sep' is TRUE and it is necessary.
4798 char_u *
4799 concat_fnames(fname1, fname2, sep)
4800 char_u *fname1;
4801 char_u *fname2;
4802 int sep;
4804 char_u *dest;
4806 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4807 if (dest != NULL)
4809 STRCPY(dest, fname1);
4810 if (sep)
4811 add_pathsep(dest);
4812 STRCAT(dest, fname2);
4814 return dest;
4818 * Concatenate two strings and return the result in allocated memory.
4819 * Returns NULL when out of memory.
4821 char_u *
4822 concat_str(str1, str2)
4823 char_u *str1;
4824 char_u *str2;
4826 char_u *dest;
4827 size_t l = STRLEN(str1);
4829 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4830 if (dest != NULL)
4832 STRCPY(dest, str1);
4833 STRCPY(dest + l, str2);
4835 return dest;
4839 * Add a path separator to a file name, unless it already ends in a path
4840 * separator.
4842 void
4843 add_pathsep(p)
4844 char_u *p;
4846 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
4847 STRCAT(p, PATHSEPSTR);
4851 * FullName_save - Make an allocated copy of a full file name.
4852 * Returns NULL when out of memory.
4854 char_u *
4855 FullName_save(fname, force)
4856 char_u *fname;
4857 int force; /* force expansion, even when it already looks
4858 like a full path name */
4860 char_u *buf;
4861 char_u *new_fname = NULL;
4863 if (fname == NULL)
4864 return NULL;
4866 buf = alloc((unsigned)MAXPATHL);
4867 if (buf != NULL)
4869 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4870 new_fname = vim_strsave(buf);
4871 else
4872 new_fname = vim_strsave(fname);
4873 vim_free(buf);
4875 return new_fname;
4878 #if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4880 static char_u *skip_string __ARGS((char_u *p));
4883 * Find the start of a comment, not knowing if we are in a comment right now.
4884 * Search starts at w_cursor.lnum and goes backwards.
4886 pos_T *
4887 find_start_comment(ind_maxcomment) /* XXX */
4888 int ind_maxcomment;
4890 pos_T *pos;
4891 char_u *line;
4892 char_u *p;
4893 int cur_maxcomment = ind_maxcomment;
4895 for (;;)
4897 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4898 if (pos == NULL)
4899 break;
4902 * Check if the comment start we found is inside a string.
4903 * If it is then restrict the search to below this line and try again.
4905 line = ml_get(pos->lnum);
4906 for (p = line; *p && (colnr_T)(p - line) < pos->col; ++p)
4907 p = skip_string(p);
4908 if ((colnr_T)(p - line) <= pos->col)
4909 break;
4910 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4911 if (cur_maxcomment <= 0)
4913 pos = NULL;
4914 break;
4917 return pos;
4921 * Skip to the end of a "string" and a 'c' character.
4922 * If there is no string or character, return argument unmodified.
4924 static char_u *
4925 skip_string(p)
4926 char_u *p;
4928 int i;
4931 * We loop, because strings may be concatenated: "date""time".
4933 for ( ; ; ++p)
4935 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4937 if (!p[1]) /* ' at end of line */
4938 break;
4939 i = 2;
4940 if (p[1] == '\\') /* '\n' or '\000' */
4942 ++i;
4943 while (vim_isdigit(p[i - 1])) /* '\000' */
4944 ++i;
4946 if (p[i] == '\'') /* check for trailing ' */
4948 p += i;
4949 continue;
4952 else if (p[0] == '"') /* start of string */
4954 for (++p; p[0]; ++p)
4956 if (p[0] == '\\' && p[1] != NUL)
4957 ++p;
4958 else if (p[0] == '"') /* end of string */
4959 break;
4961 if (p[0] == '"')
4962 continue;
4964 break; /* no string found */
4966 if (!*p)
4967 --p; /* backup from NUL */
4968 return p;
4970 #endif /* FEAT_CINDENT || FEAT_SYN_HL */
4972 #if defined(FEAT_CINDENT) || defined(PROTO)
4975 * Do C or expression indenting on the current line.
4977 void
4978 do_c_expr_indent()
4980 # ifdef FEAT_EVAL
4981 if (*curbuf->b_p_inde != NUL)
4982 fixthisline(get_expr_indent);
4983 else
4984 # endif
4985 fixthisline(get_c_indent);
4989 * Functions for C-indenting.
4990 * Most of this originally comes from Eric Fischer.
4993 * Below "XXX" means that this function may unlock the current line.
4996 static char_u *cin_skipcomment __ARGS((char_u *));
4997 static int cin_nocode __ARGS((char_u *));
4998 static pos_T *find_line_comment __ARGS((void));
4999 static int cin_islabel_skip __ARGS((char_u **));
5000 static int cin_isdefault __ARGS((char_u *));
5001 static char_u *after_label __ARGS((char_u *l));
5002 static int get_indent_nolabel __ARGS((linenr_T lnum));
5003 static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
5004 static int cin_first_id_amount __ARGS((void));
5005 static int cin_get_equal_amount __ARGS((linenr_T lnum));
5006 static int cin_ispreproc __ARGS((char_u *));
5007 static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
5008 static int cin_iscomment __ARGS((char_u *));
5009 static int cin_islinecomment __ARGS((char_u *));
5010 static int cin_isterminated __ARGS((char_u *, int, int));
5011 static int cin_isinit __ARGS((void));
5012 static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
5013 static int cin_isif __ARGS((char_u *));
5014 static int cin_iselse __ARGS((char_u *));
5015 static int cin_isdo __ARGS((char_u *));
5016 static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
5017 static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
5018 static int cin_isbreak __ARGS((char_u *));
5019 static int cin_is_cpp_baseclass __ARGS((colnr_T *col));
5020 static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
5021 static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
5022 static int cin_skip2pos __ARGS((pos_T *trypos));
5023 static pos_T *find_start_brace __ARGS((int));
5024 static pos_T *find_match_paren __ARGS((int, int));
5025 static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
5026 static int find_last_paren __ARGS((char_u *l, int start, int end));
5027 static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
5029 static int ind_hash_comment = 0; /* # starts a comment */
5032 * Skip over white space and C comments within the line.
5033 * Also skip over Perl/shell comments if desired.
5035 static char_u *
5036 cin_skipcomment(s)
5037 char_u *s;
5039 while (*s)
5041 char_u *prev_s = s;
5043 s = skipwhite(s);
5045 /* Perl/shell # comment comment continues until eol. Require a space
5046 * before # to avoid recognizing $#array. */
5047 if (ind_hash_comment != 0 && s != prev_s && *s == '#')
5049 s += STRLEN(s);
5050 break;
5052 if (*s != '/')
5053 break;
5054 ++s;
5055 if (*s == '/') /* slash-slash comment continues till eol */
5057 s += STRLEN(s);
5058 break;
5060 if (*s != '*')
5061 break;
5062 for (++s; *s; ++s) /* skip slash-star comment */
5063 if (s[0] == '*' && s[1] == '/')
5065 s += 2;
5066 break;
5069 return s;
5073 * Return TRUE if there there is no code at *s. White space and comments are
5074 * not considered code.
5076 static int
5077 cin_nocode(s)
5078 char_u *s;
5080 return *cin_skipcomment(s) == NUL;
5084 * Check previous lines for a "//" line comment, skipping over blank lines.
5086 static pos_T *
5087 find_line_comment() /* XXX */
5089 static pos_T pos;
5090 char_u *line;
5091 char_u *p;
5093 pos = curwin->w_cursor;
5094 while (--pos.lnum > 0)
5096 line = ml_get(pos.lnum);
5097 p = skipwhite(line);
5098 if (cin_islinecomment(p))
5100 pos.col = (int)(p - line);
5101 return &pos;
5103 if (*p != NUL)
5104 break;
5106 return NULL;
5110 * Check if string matches "label:"; move to character after ':' if true.
5112 static int
5113 cin_islabel_skip(s)
5114 char_u **s;
5116 if (!vim_isIDc(**s)) /* need at least one ID character */
5117 return FALSE;
5119 while (vim_isIDc(**s))
5120 (*s)++;
5122 *s = cin_skipcomment(*s);
5124 /* "::" is not a label, it's C++ */
5125 return (**s == ':' && *++*s != ':');
5129 * Recognize a label: "label:".
5130 * Note: curwin->w_cursor must be where we are looking for the label.
5133 cin_islabel(ind_maxcomment) /* XXX */
5134 int ind_maxcomment;
5136 char_u *s;
5138 s = cin_skipcomment(ml_get_curline());
5141 * Exclude "default" from labels, since it should be indented
5142 * like a switch label. Same for C++ scope declarations.
5144 if (cin_isdefault(s))
5145 return FALSE;
5146 if (cin_isscopedecl(s))
5147 return FALSE;
5149 if (cin_islabel_skip(&s))
5152 * Only accept a label if the previous line is terminated or is a case
5153 * label.
5155 pos_T cursor_save;
5156 pos_T *trypos;
5157 char_u *line;
5159 cursor_save = curwin->w_cursor;
5160 while (curwin->w_cursor.lnum > 1)
5162 --curwin->w_cursor.lnum;
5165 * If we're in a comment now, skip to the start of the comment.
5167 curwin->w_cursor.col = 0;
5168 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5169 curwin->w_cursor = *trypos;
5171 line = ml_get_curline();
5172 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
5173 continue;
5174 if (*(line = cin_skipcomment(line)) == NUL)
5175 continue;
5177 curwin->w_cursor = cursor_save;
5178 if (cin_isterminated(line, TRUE, FALSE)
5179 || cin_isscopedecl(line)
5180 || cin_iscase(line)
5181 || (cin_islabel_skip(&line) && cin_nocode(line)))
5182 return TRUE;
5183 return FALSE;
5185 curwin->w_cursor = cursor_save;
5186 return TRUE; /* label at start of file??? */
5188 return FALSE;
5192 * Recognize structure initialization and enumerations.
5193 * Q&D-Implementation:
5194 * check for "=" at end or "[typedef] enum" at beginning of line.
5196 static int
5197 cin_isinit(void)
5199 char_u *s;
5201 s = cin_skipcomment(ml_get_curline());
5203 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
5204 s = cin_skipcomment(s + 7);
5206 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
5207 return TRUE;
5209 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
5210 return TRUE;
5212 return FALSE;
5216 * Recognize a switch label: "case .*:" or "default:".
5219 cin_iscase(s)
5220 char_u *s;
5222 s = cin_skipcomment(s);
5223 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
5225 for (s += 4; *s; ++s)
5227 s = cin_skipcomment(s);
5228 if (*s == ':')
5230 if (s[1] == ':') /* skip over "::" for C++ */
5231 ++s;
5232 else
5233 return TRUE;
5235 if (*s == '\'' && s[1] && s[2] == '\'')
5236 s += 2; /* skip over '.' */
5237 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
5238 return FALSE; /* stop at comment */
5239 else if (*s == '"')
5240 return FALSE; /* stop at string */
5242 return FALSE;
5245 if (cin_isdefault(s))
5246 return TRUE;
5247 return FALSE;
5251 * Recognize a "default" switch label.
5253 static int
5254 cin_isdefault(s)
5255 char_u *s;
5257 return (STRNCMP(s, "default", 7) == 0
5258 && *(s = cin_skipcomment(s + 7)) == ':'
5259 && s[1] != ':');
5263 * Recognize a "public/private/proctected" scope declaration label.
5266 cin_isscopedecl(s)
5267 char_u *s;
5269 int i;
5271 s = cin_skipcomment(s);
5272 if (STRNCMP(s, "public", 6) == 0)
5273 i = 6;
5274 else if (STRNCMP(s, "protected", 9) == 0)
5275 i = 9;
5276 else if (STRNCMP(s, "private", 7) == 0)
5277 i = 7;
5278 else
5279 return FALSE;
5280 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5284 * Return a pointer to the first non-empty non-comment character after a ':'.
5285 * Return NULL if not found.
5286 * case 234: a = b;
5289 static char_u *
5290 after_label(l)
5291 char_u *l;
5293 for ( ; *l; ++l)
5295 if (*l == ':')
5297 if (l[1] == ':') /* skip over "::" for C++ */
5298 ++l;
5299 else if (!cin_iscase(l + 1))
5300 break;
5302 else if (*l == '\'' && l[1] && l[2] == '\'')
5303 l += 2; /* skip over 'x' */
5305 if (*l == NUL)
5306 return NULL;
5307 l = cin_skipcomment(l + 1);
5308 if (*l == NUL)
5309 return NULL;
5310 return l;
5314 * Get indent of line "lnum", skipping a label.
5315 * Return 0 if there is nothing after the label.
5317 static int
5318 get_indent_nolabel(lnum) /* XXX */
5319 linenr_T lnum;
5321 char_u *l;
5322 pos_T fp;
5323 colnr_T col;
5324 char_u *p;
5326 l = ml_get(lnum);
5327 p = after_label(l);
5328 if (p == NULL)
5329 return 0;
5331 fp.col = (colnr_T)(p - l);
5332 fp.lnum = lnum;
5333 getvcol(curwin, &fp, &col, NULL, NULL);
5334 return (int)col;
5338 * Find indent for line "lnum", ignoring any case or jump label.
5339 * Also return a pointer to the text (after the label) in "pp".
5340 * label: if (asdf && asdfasdf)
5343 static int
5344 skip_label(lnum, pp, ind_maxcomment)
5345 linenr_T lnum;
5346 char_u **pp;
5347 int ind_maxcomment;
5349 char_u *l;
5350 int amount;
5351 pos_T cursor_save;
5353 cursor_save = curwin->w_cursor;
5354 curwin->w_cursor.lnum = lnum;
5355 l = ml_get_curline();
5356 /* XXX */
5357 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5359 amount = get_indent_nolabel(lnum);
5360 l = after_label(ml_get_curline());
5361 if (l == NULL) /* just in case */
5362 l = ml_get_curline();
5364 else
5366 amount = get_indent();
5367 l = ml_get_curline();
5369 *pp = l;
5371 curwin->w_cursor = cursor_save;
5372 return amount;
5376 * Return the indent of the first variable name after a type in a declaration.
5377 * int a, indent of "a"
5378 * static struct foo b, indent of "b"
5379 * enum bla c, indent of "c"
5380 * Returns zero when it doesn't look like a declaration.
5382 static int
5383 cin_first_id_amount()
5385 char_u *line, *p, *s;
5386 int len;
5387 pos_T fp;
5388 colnr_T col;
5390 line = ml_get_curline();
5391 p = skipwhite(line);
5392 len = (int)(skiptowhite(p) - p);
5393 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5395 p = skipwhite(p + 6);
5396 len = (int)(skiptowhite(p) - p);
5398 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5399 p = skipwhite(p + 6);
5400 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5401 p = skipwhite(p + 4);
5402 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5403 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5405 s = skipwhite(p + len);
5406 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5407 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5408 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5409 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5410 p = s;
5412 for (len = 0; vim_isIDc(p[len]); ++len)
5414 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5415 return 0;
5417 p = skipwhite(p + len);
5418 fp.lnum = curwin->w_cursor.lnum;
5419 fp.col = (colnr_T)(p - line);
5420 getvcol(curwin, &fp, &col, NULL, NULL);
5421 return (int)col;
5425 * Return the indent of the first non-blank after an equal sign.
5426 * char *foo = "here";
5427 * Return zero if no (useful) equal sign found.
5428 * Return -1 if the line above "lnum" ends in a backslash.
5429 * foo = "asdf\
5430 * asdf\
5431 * here";
5433 static int
5434 cin_get_equal_amount(lnum)
5435 linenr_T lnum;
5437 char_u *line;
5438 char_u *s;
5439 colnr_T col;
5440 pos_T fp;
5442 if (lnum > 1)
5444 line = ml_get(lnum - 1);
5445 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5446 return -1;
5449 line = s = ml_get(lnum);
5450 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5452 if (cin_iscomment(s)) /* ignore comments */
5453 s = cin_skipcomment(s);
5454 else
5455 ++s;
5457 if (*s != '=')
5458 return 0;
5460 s = skipwhite(s + 1);
5461 if (cin_nocode(s))
5462 return 0;
5464 if (*s == '"') /* nice alignment for continued strings */
5465 ++s;
5467 fp.lnum = lnum;
5468 fp.col = (colnr_T)(s - line);
5469 getvcol(curwin, &fp, &col, NULL, NULL);
5470 return (int)col;
5474 * Recognize a preprocessor statement: Any line that starts with '#'.
5476 static int
5477 cin_ispreproc(s)
5478 char_u *s;
5480 s = skipwhite(s);
5481 if (*s == '#')
5482 return TRUE;
5483 return FALSE;
5487 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5488 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5489 * start and return the line in "*pp".
5491 static int
5492 cin_ispreproc_cont(pp, lnump)
5493 char_u **pp;
5494 linenr_T *lnump;
5496 char_u *line = *pp;
5497 linenr_T lnum = *lnump;
5498 int retval = FALSE;
5500 for (;;)
5502 if (cin_ispreproc(line))
5504 retval = TRUE;
5505 *lnump = lnum;
5506 break;
5508 if (lnum == 1)
5509 break;
5510 line = ml_get(--lnum);
5511 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5512 break;
5515 if (lnum != *lnump)
5516 *pp = ml_get(*lnump);
5517 return retval;
5521 * Recognize the start of a C or C++ comment.
5523 static int
5524 cin_iscomment(p)
5525 char_u *p;
5527 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5531 * Recognize the start of a "//" comment.
5533 static int
5534 cin_islinecomment(p)
5535 char_u *p;
5537 return (p[0] == '/' && p[1] == '/');
5541 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5542 * Don't consider "} else" a terminated line.
5543 * Return the character terminating the line (ending char's have precedence if
5544 * both apply in order to determine initializations).
5546 static int
5547 cin_isterminated(s, incl_open, incl_comma)
5548 char_u *s;
5549 int incl_open; /* include '{' at the end as terminator */
5550 int incl_comma; /* recognize a trailing comma */
5552 char_u found_start = 0;
5554 s = cin_skipcomment(s);
5556 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5557 found_start = *s;
5559 while (*s)
5561 /* skip over comments, "" strings and 'c'haracters */
5562 s = skip_string(cin_skipcomment(s));
5563 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5564 || (incl_comma && *s == ','))
5565 && cin_nocode(s + 1))
5566 return *s;
5568 if (*s)
5569 s++;
5571 return found_start;
5575 * Recognize the basic picture of a function declaration -- it needs to
5576 * have an open paren somewhere and a close paren at the end of the line and
5577 * no semicolons anywhere.
5578 * When a line ends in a comma we continue looking in the next line.
5579 * "sp" points to a string with the line. When looking at other lines it must
5580 * be restored to the line. When it's NULL fetch lines here.
5581 * "lnum" is where we start looking.
5583 static int
5584 cin_isfuncdecl(sp, first_lnum)
5585 char_u **sp;
5586 linenr_T first_lnum;
5588 char_u *s;
5589 linenr_T lnum = first_lnum;
5590 int retval = FALSE;
5592 if (sp == NULL)
5593 s = ml_get(lnum);
5594 else
5595 s = *sp;
5597 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5599 if (cin_iscomment(s)) /* ignore comments */
5600 s = cin_skipcomment(s);
5601 else
5602 ++s;
5604 if (*s != '(')
5605 return FALSE; /* ';', ' or " before any () or no '(' */
5607 while (*s && *s != ';' && *s != '\'' && *s != '"')
5609 if (*s == ')' && cin_nocode(s + 1))
5611 /* ')' at the end: may have found a match
5612 * Check for he previous line not to end in a backslash:
5613 * #if defined(x) && \
5614 * defined(y)
5616 lnum = first_lnum - 1;
5617 s = ml_get(lnum);
5618 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5619 retval = TRUE;
5620 goto done;
5622 if (*s == ',' && cin_nocode(s + 1))
5624 /* ',' at the end: continue looking in the next line */
5625 if (lnum >= curbuf->b_ml.ml_line_count)
5626 break;
5628 s = ml_get(++lnum);
5630 else if (cin_iscomment(s)) /* ignore comments */
5631 s = cin_skipcomment(s);
5632 else
5633 ++s;
5636 done:
5637 if (lnum != first_lnum && sp != NULL)
5638 *sp = ml_get(first_lnum);
5640 return retval;
5643 static int
5644 cin_isif(p)
5645 char_u *p;
5647 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5650 static int
5651 cin_iselse(p)
5652 char_u *p;
5654 if (*p == '}') /* accept "} else" */
5655 p = cin_skipcomment(p + 1);
5656 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5659 static int
5660 cin_isdo(p)
5661 char_u *p;
5663 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5667 * Check if this is a "while" that should have a matching "do".
5668 * We only accept a "while (condition) ;", with only white space between the
5669 * ')' and ';'. The condition may be spread over several lines.
5671 static int
5672 cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5673 char_u *p;
5674 linenr_T lnum;
5675 int ind_maxparen;
5677 pos_T cursor_save;
5678 pos_T *trypos;
5679 int retval = FALSE;
5681 p = cin_skipcomment(p);
5682 if (*p == '}') /* accept "} while (cond);" */
5683 p = cin_skipcomment(p + 1);
5684 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5686 cursor_save = curwin->w_cursor;
5687 curwin->w_cursor.lnum = lnum;
5688 curwin->w_cursor.col = 0;
5689 p = ml_get_curline();
5690 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5692 ++p;
5693 ++curwin->w_cursor.col;
5695 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5696 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5697 retval = TRUE;
5698 curwin->w_cursor = cursor_save;
5700 return retval;
5704 * Return TRUE if we are at the end of a do-while.
5705 * do
5706 * nothing;
5707 * while (foo
5708 * && bar); <-- here
5709 * Adjust the cursor to the line with "while".
5711 static int
5712 cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5713 int terminated;
5714 int ind_maxparen;
5715 int ind_maxcomment;
5717 char_u *line;
5718 char_u *p;
5719 char_u *s;
5720 pos_T *trypos;
5721 int i;
5723 if (terminated != ';') /* there must be a ';' at the end */
5724 return FALSE;
5726 p = line = ml_get_curline();
5727 while (*p != NUL)
5729 p = cin_skipcomment(p);
5730 if (*p == ')')
5732 s = skipwhite(p + 1);
5733 if (*s == ';' && cin_nocode(s + 1))
5735 /* Found ");" at end of the line, now check there is "while"
5736 * before the matching '('. XXX */
5737 i = (int)(p - line);
5738 curwin->w_cursor.col = i;
5739 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5740 if (trypos != NULL)
5742 s = cin_skipcomment(ml_get(trypos->lnum));
5743 if (*s == '}') /* accept "} while (cond);" */
5744 s = cin_skipcomment(s + 1);
5745 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5747 curwin->w_cursor.lnum = trypos->lnum;
5748 return TRUE;
5752 /* Searching may have made "line" invalid, get it again. */
5753 line = ml_get_curline();
5754 p = line + i;
5757 if (*p != NUL)
5758 ++p;
5760 return FALSE;
5763 static int
5764 cin_isbreak(p)
5765 char_u *p;
5767 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5771 * Find the position of a C++ base-class declaration or
5772 * constructor-initialization. eg:
5774 * class MyClass :
5775 * baseClass <-- here
5776 * class MyClass : public baseClass,
5777 * anotherBaseClass <-- here (should probably lineup ??)
5778 * MyClass::MyClass(...) :
5779 * baseClass(...) <-- here (constructor-initialization)
5781 * This is a lot of guessing. Watch out for "cond ? func() : foo".
5783 static int
5784 cin_is_cpp_baseclass(col)
5785 colnr_T *col; /* return: column to align with */
5787 char_u *s;
5788 int class_or_struct, lookfor_ctor_init, cpp_base_class;
5789 linenr_T lnum = curwin->w_cursor.lnum;
5790 char_u *line = ml_get_curline();
5792 *col = 0;
5794 s = skipwhite(line);
5795 if (*s == '#') /* skip #define FOO x ? (x) : x */
5796 return FALSE;
5797 s = cin_skipcomment(s);
5798 if (*s == NUL)
5799 return FALSE;
5801 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5803 /* Search for a line starting with '#', empty, ending in ';' or containing
5804 * '{' or '}' and start below it. This handles the following situations:
5805 * a = cond ?
5806 * func() :
5807 * asdf;
5808 * func::foo()
5809 * : something
5810 * {}
5811 * Foo::Foo (int one, int two)
5812 * : something(4),
5813 * somethingelse(3)
5814 * {}
5816 while (lnum > 1)
5818 line = ml_get(lnum - 1);
5819 s = skipwhite(line);
5820 if (*s == '#' || *s == NUL)
5821 break;
5822 while (*s != NUL)
5824 s = cin_skipcomment(s);
5825 if (*s == '{' || *s == '}'
5826 || (*s == ';' && cin_nocode(s + 1)))
5827 break;
5828 if (*s != NUL)
5829 ++s;
5831 if (*s != NUL)
5832 break;
5833 --lnum;
5836 line = ml_get(lnum);
5837 s = cin_skipcomment(line);
5838 for (;;)
5840 if (*s == NUL)
5842 if (lnum == curwin->w_cursor.lnum)
5843 break;
5844 /* Continue in the cursor line. */
5845 line = ml_get(++lnum);
5846 s = cin_skipcomment(line);
5847 if (*s == NUL)
5848 continue;
5851 if (s[0] == ':')
5853 if (s[1] == ':')
5855 /* skip double colon. It can't be a constructor
5856 * initialization any more */
5857 lookfor_ctor_init = FALSE;
5858 s = cin_skipcomment(s + 2);
5860 else if (lookfor_ctor_init || class_or_struct)
5862 /* we have something found, that looks like the start of
5863 * cpp-base-class-declaration or constructor-initialization */
5864 cpp_base_class = TRUE;
5865 lookfor_ctor_init = class_or_struct = FALSE;
5866 *col = 0;
5867 s = cin_skipcomment(s + 1);
5869 else
5870 s = cin_skipcomment(s + 1);
5872 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5873 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5875 class_or_struct = TRUE;
5876 lookfor_ctor_init = FALSE;
5878 if (*s == 'c')
5879 s = cin_skipcomment(s + 5);
5880 else
5881 s = cin_skipcomment(s + 6);
5883 else
5885 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5887 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5889 else if (s[0] == ')')
5891 /* Constructor-initialization is assumed if we come across
5892 * something like "):" */
5893 class_or_struct = FALSE;
5894 lookfor_ctor_init = TRUE;
5896 else if (s[0] == '?')
5898 /* Avoid seeing '() :' after '?' as constructor init. */
5899 return FALSE;
5901 else if (!vim_isIDc(s[0]))
5903 /* if it is not an identifier, we are wrong */
5904 class_or_struct = FALSE;
5905 lookfor_ctor_init = FALSE;
5907 else if (*col == 0)
5909 /* it can't be a constructor-initialization any more */
5910 lookfor_ctor_init = FALSE;
5912 /* the first statement starts here: lineup with this one... */
5913 if (cpp_base_class)
5914 *col = (colnr_T)(s - line);
5917 /* When the line ends in a comma don't align with it. */
5918 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5919 *col = 0;
5921 s = cin_skipcomment(s + 1);
5925 return cpp_base_class;
5928 static int
5929 get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5930 int col;
5931 int ind_maxparen;
5932 int ind_maxcomment;
5933 int ind_cpp_baseclass;
5935 int amount;
5936 colnr_T vcol;
5937 pos_T *trypos;
5939 if (col == 0)
5941 amount = get_indent();
5942 if (find_last_paren(ml_get_curline(), '(', ')')
5943 && (trypos = find_match_paren(ind_maxparen,
5944 ind_maxcomment)) != NULL)
5945 amount = get_indent_lnum(trypos->lnum); /* XXX */
5946 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5947 amount += ind_cpp_baseclass;
5949 else
5951 curwin->w_cursor.col = col;
5952 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5953 amount = (int)vcol;
5955 if (amount < ind_cpp_baseclass)
5956 amount = ind_cpp_baseclass;
5957 return amount;
5961 * Return TRUE if string "s" ends with the string "find", possibly followed by
5962 * white space and comments. Skip strings and comments.
5963 * Ignore "ignore" after "find" if it's not NULL.
5965 static int
5966 cin_ends_in(s, find, ignore)
5967 char_u *s;
5968 char_u *find;
5969 char_u *ignore;
5971 char_u *p = s;
5972 char_u *r;
5973 int len = (int)STRLEN(find);
5975 while (*p != NUL)
5977 p = cin_skipcomment(p);
5978 if (STRNCMP(p, find, len) == 0)
5980 r = skipwhite(p + len);
5981 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5982 r = skipwhite(r + STRLEN(ignore));
5983 if (cin_nocode(r))
5984 return TRUE;
5986 if (*p != NUL)
5987 ++p;
5989 return FALSE;
5993 * Skip strings, chars and comments until at or past "trypos".
5994 * Return the column found.
5996 static int
5997 cin_skip2pos(trypos)
5998 pos_T *trypos;
6000 char_u *line;
6001 char_u *p;
6003 p = line = ml_get(trypos->lnum);
6004 while (*p && (colnr_T)(p - line) < trypos->col)
6006 if (cin_iscomment(p))
6007 p = cin_skipcomment(p);
6008 else
6010 p = skip_string(p);
6011 ++p;
6014 return (int)(p - line);
6018 * Find the '{' at the start of the block we are in.
6019 * Return NULL if no match found.
6020 * Ignore a '{' that is in a comment, makes indenting the next three lines
6021 * work. */
6022 /* foo() */
6023 /* { */
6024 /* } */
6026 static pos_T *
6027 find_start_brace(ind_maxcomment) /* XXX */
6028 int ind_maxcomment;
6030 pos_T cursor_save;
6031 pos_T *trypos;
6032 pos_T *pos;
6033 static pos_T pos_copy;
6035 cursor_save = curwin->w_cursor;
6036 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
6038 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
6039 trypos = &pos_copy;
6040 curwin->w_cursor = *trypos;
6041 pos = NULL;
6042 /* ignore the { if it's in a // or / * * / comment */
6043 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
6044 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
6045 break;
6046 if (pos != NULL)
6047 curwin->w_cursor.lnum = pos->lnum;
6049 curwin->w_cursor = cursor_save;
6050 return trypos;
6054 * Find the matching '(', failing if it is in a comment.
6055 * Return NULL of no match found.
6057 static pos_T *
6058 find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
6059 int ind_maxparen;
6060 int ind_maxcomment;
6062 pos_T cursor_save;
6063 pos_T *trypos;
6064 static pos_T pos_copy;
6066 cursor_save = curwin->w_cursor;
6067 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
6069 /* check if the ( is in a // comment */
6070 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
6071 trypos = NULL;
6072 else
6074 pos_copy = *trypos; /* copy trypos, findmatch will change it */
6075 trypos = &pos_copy;
6076 curwin->w_cursor = *trypos;
6077 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
6078 trypos = NULL;
6081 curwin->w_cursor = cursor_save;
6082 return trypos;
6086 * Return ind_maxparen corrected for the difference in line number between the
6087 * cursor position and "startpos". This makes sure that searching for a
6088 * matching paren above the cursor line doesn't find a match because of
6089 * looking a few lines further.
6091 static int
6092 corr_ind_maxparen(ind_maxparen, startpos)
6093 int ind_maxparen;
6094 pos_T *startpos;
6096 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
6098 if (n > 0 && n < ind_maxparen / 2)
6099 return ind_maxparen - (int)n;
6100 return ind_maxparen;
6104 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
6105 * line "l".
6107 static int
6108 find_last_paren(l, start, end)
6109 char_u *l;
6110 int start, end;
6112 int i;
6113 int retval = FALSE;
6114 int open_count = 0;
6116 curwin->w_cursor.col = 0; /* default is start of line */
6118 for (i = 0; l[i]; i++)
6120 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
6121 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
6122 if (l[i] == start)
6123 ++open_count;
6124 else if (l[i] == end)
6126 if (open_count > 0)
6127 --open_count;
6128 else
6130 curwin->w_cursor.col = i;
6131 retval = TRUE;
6135 return retval;
6139 get_c_indent()
6142 * spaces from a block's opening brace the prevailing indent for that
6143 * block should be
6145 int ind_level = curbuf->b_p_sw;
6148 * spaces from the edge of the line an open brace that's at the end of a
6149 * line is imagined to be.
6151 int ind_open_imag = 0;
6154 * spaces from the prevailing indent for a line that is not precededof by
6155 * an opening brace.
6157 int ind_no_brace = 0;
6160 * column where the first { of a function should be located }
6162 int ind_first_open = 0;
6165 * spaces from the prevailing indent a leftmost open brace should be
6166 * located
6168 int ind_open_extra = 0;
6171 * spaces from the matching open brace (real location for one at the left
6172 * edge; imaginary location from one that ends a line) the matching close
6173 * brace should be located
6175 int ind_close_extra = 0;
6178 * spaces from the edge of the line an open brace sitting in the leftmost
6179 * column is imagined to be
6181 int ind_open_left_imag = 0;
6184 * spaces from the switch() indent a "case xx" label should be located
6186 int ind_case = curbuf->b_p_sw;
6189 * spaces from the "case xx:" code after a switch() should be located
6191 int ind_case_code = curbuf->b_p_sw;
6194 * lineup break at end of case in switch() with case label
6196 int ind_case_break = 0;
6199 * spaces from the class declaration indent a scope declaration label
6200 * should be located
6202 int ind_scopedecl = curbuf->b_p_sw;
6205 * spaces from the scope declaration label code should be located
6207 int ind_scopedecl_code = curbuf->b_p_sw;
6210 * amount K&R-style parameters should be indented
6212 int ind_param = curbuf->b_p_sw;
6215 * amount a function type spec should be indented
6217 int ind_func_type = curbuf->b_p_sw;
6220 * amount a cpp base class declaration or constructor initialization
6221 * should be indented
6223 int ind_cpp_baseclass = curbuf->b_p_sw;
6226 * additional spaces beyond the prevailing indent a continuation line
6227 * should be located
6229 int ind_continuation = curbuf->b_p_sw;
6232 * spaces from the indent of the line with an unclosed parentheses
6234 int ind_unclosed = curbuf->b_p_sw * 2;
6237 * spaces from the indent of the line with an unclosed parentheses, which
6238 * itself is also unclosed
6240 int ind_unclosed2 = curbuf->b_p_sw;
6243 * suppress ignoring spaces from the indent of a line starting with an
6244 * unclosed parentheses.
6246 int ind_unclosed_noignore = 0;
6249 * If the opening paren is the last nonwhite character on the line, and
6250 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6251 * context (for very long lines).
6253 int ind_unclosed_wrapped = 0;
6256 * suppress ignoring white space when lining up with the character after
6257 * an unclosed parentheses.
6259 int ind_unclosed_whiteok = 0;
6262 * indent a closing parentheses under the line start of the matching
6263 * opening parentheses.
6265 int ind_matching_paren = 0;
6268 * indent a closing parentheses under the previous line.
6270 int ind_paren_prev = 0;
6273 * Extra indent for comments.
6275 int ind_comment = 0;
6278 * spaces from the comment opener when there is nothing after it.
6280 int ind_in_comment = 3;
6283 * boolean: if non-zero, use ind_in_comment even if there is something
6284 * after the comment opener.
6286 int ind_in_comment2 = 0;
6289 * max lines to search for an open paren
6291 int ind_maxparen = 20;
6294 * max lines to search for an open comment
6296 int ind_maxcomment = 70;
6299 * handle braces for java code
6301 int ind_java = 0;
6304 * handle blocked cases correctly
6306 int ind_keep_case_label = 0;
6308 pos_T cur_curpos;
6309 int amount;
6310 int scope_amount;
6311 int cur_amount = MAXCOL;
6312 colnr_T col;
6313 char_u *theline;
6314 char_u *linecopy;
6315 pos_T *trypos;
6316 pos_T *tryposBrace = NULL;
6317 pos_T our_paren_pos;
6318 char_u *start;
6319 int start_brace;
6320 #define BRACE_IN_COL0 1 /* '{' is in column 0 */
6321 #define BRACE_AT_START 2 /* '{' is at start of line */
6322 #define BRACE_AT_END 3 /* '{' is at end of line */
6323 linenr_T ourscope;
6324 char_u *l;
6325 char_u *look;
6326 char_u terminated;
6327 int lookfor;
6328 #define LOOKFOR_INITIAL 0
6329 #define LOOKFOR_IF 1
6330 #define LOOKFOR_DO 2
6331 #define LOOKFOR_CASE 3
6332 #define LOOKFOR_ANY 4
6333 #define LOOKFOR_TERM 5
6334 #define LOOKFOR_UNTERM 6
6335 #define LOOKFOR_SCOPEDECL 7
6336 #define LOOKFOR_NOBREAK 8
6337 #define LOOKFOR_CPP_BASECLASS 9
6338 #define LOOKFOR_ENUM_OR_INIT 10
6340 int whilelevel;
6341 linenr_T lnum;
6342 char_u *options;
6343 int fraction = 0; /* init for GCC */
6344 int divider;
6345 int n;
6346 int iscase;
6347 int lookfor_break;
6348 int cont_amount = 0; /* amount for continuation line */
6350 for (options = curbuf->b_p_cino; *options; )
6352 l = options++;
6353 if (*options == '-')
6354 ++options;
6355 n = getdigits(&options);
6356 divider = 0;
6357 if (*options == '.') /* ".5s" means a fraction */
6359 fraction = atol((char *)++options);
6360 while (VIM_ISDIGIT(*options))
6362 ++options;
6363 if (divider)
6364 divider *= 10;
6365 else
6366 divider = 10;
6369 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6371 if (n == 0 && fraction == 0)
6372 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6373 else
6375 n *= curbuf->b_p_sw;
6376 if (divider)
6377 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6379 ++options;
6381 if (l[1] == '-')
6382 n = -n;
6383 /* When adding an entry here, also update the default 'cinoptions' in
6384 * doc/indent.txt, and add explanation for it! */
6385 switch (*l)
6387 case '>': ind_level = n; break;
6388 case 'e': ind_open_imag = n; break;
6389 case 'n': ind_no_brace = n; break;
6390 case 'f': ind_first_open = n; break;
6391 case '{': ind_open_extra = n; break;
6392 case '}': ind_close_extra = n; break;
6393 case '^': ind_open_left_imag = n; break;
6394 case ':': ind_case = n; break;
6395 case '=': ind_case_code = n; break;
6396 case 'b': ind_case_break = n; break;
6397 case 'p': ind_param = n; break;
6398 case 't': ind_func_type = n; break;
6399 case '/': ind_comment = n; break;
6400 case 'c': ind_in_comment = n; break;
6401 case 'C': ind_in_comment2 = n; break;
6402 case 'i': ind_cpp_baseclass = n; break;
6403 case '+': ind_continuation = n; break;
6404 case '(': ind_unclosed = n; break;
6405 case 'u': ind_unclosed2 = n; break;
6406 case 'U': ind_unclosed_noignore = n; break;
6407 case 'W': ind_unclosed_wrapped = n; break;
6408 case 'w': ind_unclosed_whiteok = n; break;
6409 case 'm': ind_matching_paren = n; break;
6410 case 'M': ind_paren_prev = n; break;
6411 case ')': ind_maxparen = n; break;
6412 case '*': ind_maxcomment = n; break;
6413 case 'g': ind_scopedecl = n; break;
6414 case 'h': ind_scopedecl_code = n; break;
6415 case 'j': ind_java = n; break;
6416 case 'l': ind_keep_case_label = n; break;
6417 case '#': ind_hash_comment = n; break;
6421 /* remember where the cursor was when we started */
6422 cur_curpos = curwin->w_cursor;
6424 /* Get a copy of the current contents of the line.
6425 * This is required, because only the most recent line obtained with
6426 * ml_get is valid! */
6427 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6428 if (linecopy == NULL)
6429 return 0;
6432 * In insert mode and the cursor is on a ')' truncate the line at the
6433 * cursor position. We don't want to line up with the matching '(' when
6434 * inserting new stuff.
6435 * For unknown reasons the cursor might be past the end of the line, thus
6436 * check for that.
6438 if ((State & INSERT)
6439 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
6440 && linecopy[curwin->w_cursor.col] == ')')
6441 linecopy[curwin->w_cursor.col] = NUL;
6443 theline = skipwhite(linecopy);
6445 /* move the cursor to the start of the line */
6447 curwin->w_cursor.col = 0;
6450 * #defines and so on always go at the left when included in 'cinkeys'.
6452 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6454 amount = 0;
6458 * Is it a non-case label? Then that goes at the left margin too.
6460 else if (cin_islabel(ind_maxcomment)) /* XXX */
6462 amount = 0;
6466 * If we're inside a "//" comment and there is a "//" comment in a
6467 * previous line, lineup with that one.
6469 else if (cin_islinecomment(theline)
6470 && (trypos = find_line_comment()) != NULL) /* XXX */
6472 /* find how indented the line beginning the comment is */
6473 getvcol(curwin, trypos, &col, NULL, NULL);
6474 amount = col;
6478 * If we're inside a comment and not looking at the start of the
6479 * comment, try using the 'comments' option.
6481 else if (!cin_iscomment(theline)
6482 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6484 int lead_start_len = 2;
6485 int lead_middle_len = 1;
6486 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6487 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6488 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6489 char_u *p;
6490 int start_align = 0;
6491 int start_off = 0;
6492 int done = FALSE;
6494 /* find how indented the line beginning the comment is */
6495 getvcol(curwin, trypos, &col, NULL, NULL);
6496 amount = col;
6498 p = curbuf->b_p_com;
6499 while (*p != NUL)
6501 int align = 0;
6502 int off = 0;
6503 int what = 0;
6505 while (*p != NUL && *p != ':')
6507 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6508 what = *p++;
6509 else if (*p == COM_LEFT || *p == COM_RIGHT)
6510 align = *p++;
6511 else if (VIM_ISDIGIT(*p) || *p == '-')
6512 off = getdigits(&p);
6513 else
6514 ++p;
6517 if (*p == ':')
6518 ++p;
6519 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6520 if (what == COM_START)
6522 STRCPY(lead_start, lead_end);
6523 lead_start_len = (int)STRLEN(lead_start);
6524 start_off = off;
6525 start_align = align;
6527 else if (what == COM_MIDDLE)
6529 STRCPY(lead_middle, lead_end);
6530 lead_middle_len = (int)STRLEN(lead_middle);
6532 else if (what == COM_END)
6534 /* If our line starts with the middle comment string, line it
6535 * up with the comment opener per the 'comments' option. */
6536 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6537 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6539 done = TRUE;
6540 if (curwin->w_cursor.lnum > 1)
6542 /* If the start comment string matches in the previous
6543 * line, use the indent of that line plus offset. If
6544 * the middle comment string matches in the previous
6545 * line, use the indent of that line. XXX */
6546 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6547 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6548 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6549 else if (STRNCMP(look, lead_middle,
6550 lead_middle_len) == 0)
6552 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6553 break;
6555 /* If the start comment string doesn't match with the
6556 * start of the comment, skip this entry. XXX */
6557 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6558 lead_start, lead_start_len) != 0)
6559 continue;
6561 if (start_off != 0)
6562 amount += start_off;
6563 else if (start_align == COM_RIGHT)
6564 amount += vim_strsize(lead_start)
6565 - vim_strsize(lead_middle);
6566 break;
6569 /* If our line starts with the end comment string, line it up
6570 * with the middle comment */
6571 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6572 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6574 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6575 /* XXX */
6576 if (off != 0)
6577 amount += off;
6578 else if (align == COM_RIGHT)
6579 amount += vim_strsize(lead_start)
6580 - vim_strsize(lead_middle);
6581 done = TRUE;
6582 break;
6587 /* If our line starts with an asterisk, line up with the
6588 * asterisk in the comment opener; otherwise, line up
6589 * with the first character of the comment text.
6591 if (done)
6593 else if (theline[0] == '*')
6594 amount += 1;
6595 else
6598 * If we are more than one line away from the comment opener, take
6599 * the indent of the previous non-empty line. If 'cino' has "CO"
6600 * and we are just below the comment opener and there are any
6601 * white characters after it line up with the text after it;
6602 * otherwise, add the amount specified by "c" in 'cino'
6604 amount = -1;
6605 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6607 if (linewhite(lnum)) /* skip blank lines */
6608 continue;
6609 amount = get_indent_lnum(lnum); /* XXX */
6610 break;
6612 if (amount == -1) /* use the comment opener */
6614 if (!ind_in_comment2)
6616 start = ml_get(trypos->lnum);
6617 look = start + trypos->col + 2; /* skip / and * */
6618 if (*look != NUL) /* if something after it */
6619 trypos->col = (colnr_T)(skipwhite(look) - start);
6621 getvcol(curwin, trypos, &col, NULL, NULL);
6622 amount = col;
6623 if (ind_in_comment2 || *look == NUL)
6624 amount += ind_in_comment;
6630 * Are we inside parentheses or braces?
6631 */ /* XXX */
6632 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6633 && ind_java == 0)
6634 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6635 || trypos != NULL)
6637 if (trypos != NULL && tryposBrace != NULL)
6639 /* Both an unmatched '(' and '{' is found. Use the one which is
6640 * closer to the current cursor position, set the other to NULL. */
6641 if (trypos->lnum != tryposBrace->lnum
6642 ? trypos->lnum < tryposBrace->lnum
6643 : trypos->col < tryposBrace->col)
6644 trypos = NULL;
6645 else
6646 tryposBrace = NULL;
6649 if (trypos != NULL)
6652 * If the matching paren is more than one line away, use the indent of
6653 * a previous non-empty line that matches the same paren.
6655 if (theline[0] == ')' && ind_paren_prev)
6657 /* Line up with the start of the matching paren line. */
6658 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6660 else
6662 amount = -1;
6663 our_paren_pos = *trypos;
6664 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
6666 l = skipwhite(ml_get(lnum));
6667 if (cin_nocode(l)) /* skip comment lines */
6668 continue;
6669 if (cin_ispreproc_cont(&l, &lnum))
6670 continue; /* ignore #define, #if, etc. */
6671 curwin->w_cursor.lnum = lnum;
6673 /* Skip a comment. XXX */
6674 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6676 lnum = trypos->lnum + 1;
6677 continue;
6680 /* XXX */
6681 if ((trypos = find_match_paren(
6682 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6683 ind_maxcomment)) != NULL
6684 && trypos->lnum == our_paren_pos.lnum
6685 && trypos->col == our_paren_pos.col)
6687 amount = get_indent_lnum(lnum); /* XXX */
6689 if (theline[0] == ')')
6691 if (our_paren_pos.lnum != lnum
6692 && cur_amount > amount)
6693 cur_amount = amount;
6694 amount = -1;
6696 break;
6702 * Line up with line where the matching paren is. XXX
6703 * If the line starts with a '(' or the indent for unclosed
6704 * parentheses is zero, line up with the unclosed parentheses.
6706 if (amount == -1)
6708 int ignore_paren_col = 0;
6710 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
6711 look = skipwhite(look);
6712 if (*look == '(')
6714 linenr_T save_lnum = curwin->w_cursor.lnum;
6715 char_u *line;
6716 int look_col;
6718 /* Ignore a '(' in front of the line that has a match before
6719 * our matching '('. */
6720 curwin->w_cursor.lnum = our_paren_pos.lnum;
6721 line = ml_get_curline();
6722 look_col = (int)(look - line);
6723 curwin->w_cursor.col = look_col + 1;
6724 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6725 != NULL
6726 && trypos->lnum == our_paren_pos.lnum
6727 && trypos->col < our_paren_pos.col)
6728 ignore_paren_col = trypos->col + 1;
6730 curwin->w_cursor.lnum = save_lnum;
6731 look = ml_get(our_paren_pos.lnum) + look_col;
6733 if (theline[0] == ')' || ind_unclosed == 0
6734 || (!ind_unclosed_noignore && *look == '('
6735 && ignore_paren_col == 0))
6738 * If we're looking at a close paren, line up right there;
6739 * otherwise, line up with the next (non-white) character.
6740 * When ind_unclosed_wrapped is set and the matching paren is
6741 * the last nonwhite character of the line, use either the
6742 * indent of the current line or the indentation of the next
6743 * outer paren and add ind_unclosed_wrapped (for very long
6744 * lines).
6746 if (theline[0] != ')')
6748 cur_amount = MAXCOL;
6749 l = ml_get(our_paren_pos.lnum);
6750 if (ind_unclosed_wrapped
6751 && cin_ends_in(l, (char_u *)"(", NULL))
6753 /* look for opening unmatched paren, indent one level
6754 * for each additional level */
6755 n = 1;
6756 for (col = 0; col < our_paren_pos.col; ++col)
6758 switch (l[col])
6760 case '(':
6761 case '{': ++n;
6762 break;
6764 case ')':
6765 case '}': if (n > 1)
6766 --n;
6767 break;
6771 our_paren_pos.col = 0;
6772 amount += n * ind_unclosed_wrapped;
6774 else if (ind_unclosed_whiteok)
6775 our_paren_pos.col++;
6776 else
6778 col = our_paren_pos.col + 1;
6779 while (vim_iswhite(l[col]))
6780 col++;
6781 if (l[col] != NUL) /* In case of trailing space */
6782 our_paren_pos.col = col;
6783 else
6784 our_paren_pos.col++;
6789 * Find how indented the paren is, or the character after it
6790 * if we did the above "if".
6792 if (our_paren_pos.col > 0)
6794 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6795 if (cur_amount > (int)col)
6796 cur_amount = col;
6800 if (theline[0] == ')' && ind_matching_paren)
6802 /* Line up with the start of the matching paren line. */
6804 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
6805 && *look == '(' && ignore_paren_col == 0))
6807 if (cur_amount != MAXCOL)
6808 amount = cur_amount;
6810 else
6812 /* Add ind_unclosed2 for each '(' before our matching one, but
6813 * ignore (void) before the line (ignore_paren_col). */
6814 col = our_paren_pos.col;
6815 while ((int)our_paren_pos.col > ignore_paren_col)
6817 --our_paren_pos.col;
6818 switch (*ml_get_pos(&our_paren_pos))
6820 case '(': amount += ind_unclosed2;
6821 col = our_paren_pos.col;
6822 break;
6823 case ')': amount -= ind_unclosed2;
6824 col = MAXCOL;
6825 break;
6829 /* Use ind_unclosed once, when the first '(' is not inside
6830 * braces */
6831 if (col == MAXCOL)
6832 amount += ind_unclosed;
6833 else
6835 curwin->w_cursor.lnum = our_paren_pos.lnum;
6836 curwin->w_cursor.col = col;
6837 if ((trypos = find_match_paren(ind_maxparen,
6838 ind_maxcomment)) != NULL)
6839 amount += ind_unclosed2;
6840 else
6841 amount += ind_unclosed;
6844 * For a line starting with ')' use the minimum of the two
6845 * positions, to avoid giving it more indent than the previous
6846 * lines:
6847 * func_long_name( if (x
6848 * arg && yy
6849 * ) ^ not here ) ^ not here
6851 if (cur_amount < amount)
6852 amount = cur_amount;
6856 /* add extra indent for a comment */
6857 if (cin_iscomment(theline))
6858 amount += ind_comment;
6862 * Are we at least inside braces, then?
6864 else
6866 trypos = tryposBrace;
6868 ourscope = trypos->lnum;
6869 start = ml_get(ourscope);
6872 * Now figure out how indented the line is in general.
6873 * If the brace was at the start of the line, we use that;
6874 * otherwise, check out the indentation of the line as
6875 * a whole and then add the "imaginary indent" to that.
6877 look = skipwhite(start);
6878 if (*look == '{')
6880 getvcol(curwin, trypos, &col, NULL, NULL);
6881 amount = col;
6882 if (*start == '{')
6883 start_brace = BRACE_IN_COL0;
6884 else
6885 start_brace = BRACE_AT_START;
6887 else
6890 * that opening brace might have been on a continuation
6891 * line. if so, find the start of the line.
6893 curwin->w_cursor.lnum = ourscope;
6896 * position the cursor over the rightmost paren, so that
6897 * matching it will take us back to the start of the line.
6899 lnum = ourscope;
6900 if (find_last_paren(start, '(', ')')
6901 && (trypos = find_match_paren(ind_maxparen,
6902 ind_maxcomment)) != NULL)
6903 lnum = trypos->lnum;
6906 * It could have been something like
6907 * case 1: if (asdf &&
6908 * ldfd) {
6911 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6912 amount = get_indent();
6913 else
6914 amount = skip_label(lnum, &l, ind_maxcomment);
6916 start_brace = BRACE_AT_END;
6920 * if we're looking at a closing brace, that's where
6921 * we want to be. otherwise, add the amount of room
6922 * that an indent is supposed to be.
6924 if (theline[0] == '}')
6927 * they may want closing braces to line up with something
6928 * other than the open brace. indulge them, if so.
6930 amount += ind_close_extra;
6932 else
6935 * If we're looking at an "else", try to find an "if"
6936 * to match it with.
6937 * If we're looking at a "while", try to find a "do"
6938 * to match it with.
6940 lookfor = LOOKFOR_INITIAL;
6941 if (cin_iselse(theline))
6942 lookfor = LOOKFOR_IF;
6943 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6944 /* XXX */
6945 lookfor = LOOKFOR_DO;
6946 if (lookfor != LOOKFOR_INITIAL)
6948 curwin->w_cursor.lnum = cur_curpos.lnum;
6949 if (find_match(lookfor, ourscope, ind_maxparen,
6950 ind_maxcomment) == OK)
6952 amount = get_indent(); /* XXX */
6953 goto theend;
6958 * We get here if we are not on an "while-of-do" or "else" (or
6959 * failed to find a matching "if").
6960 * Search backwards for something to line up with.
6961 * First set amount for when we don't find anything.
6965 * if the '{' is _really_ at the left margin, use the imaginary
6966 * location of a left-margin brace. Otherwise, correct the
6967 * location for ind_open_extra.
6970 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6972 amount = ind_open_left_imag;
6974 else
6976 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6977 amount += ind_open_imag;
6978 else
6980 /* Compensate for adding ind_open_extra later. */
6981 amount -= ind_open_extra;
6982 if (amount < 0)
6983 amount = 0;
6987 lookfor_break = FALSE;
6989 if (cin_iscase(theline)) /* it's a switch() label */
6991 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6992 amount += ind_case;
6994 else if (cin_isscopedecl(theline)) /* private:, ... */
6996 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6997 amount += ind_scopedecl;
6999 else
7001 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7002 lookfor_break = TRUE;
7004 lookfor = LOOKFOR_INITIAL;
7005 amount += ind_level; /* ind_level from start of block */
7007 scope_amount = amount;
7008 whilelevel = 0;
7011 * Search backwards. If we find something we recognize, line up
7012 * with that.
7014 * if we're looking at an open brace, indent
7015 * the usual amount relative to the conditional
7016 * that opens the block.
7018 curwin->w_cursor = cur_curpos;
7019 for (;;)
7021 curwin->w_cursor.lnum--;
7022 curwin->w_cursor.col = 0;
7025 * If we went all the way back to the start of our scope, line
7026 * up with it.
7028 if (curwin->w_cursor.lnum <= ourscope)
7030 /* we reached end of scope:
7031 * if looking for a enum or structure initialization
7032 * go further back:
7033 * if it is an initializer (enum xxx or xxx =), then
7034 * don't add ind_continuation, otherwise it is a variable
7035 * declaration:
7036 * int x,
7037 * here; <-- add ind_continuation
7039 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7041 if (curwin->w_cursor.lnum == 0
7042 || curwin->w_cursor.lnum
7043 < ourscope - ind_maxparen)
7045 /* nothing found (abuse ind_maxparen as limit)
7046 * assume terminated line (i.e. a variable
7047 * initialization) */
7048 if (cont_amount > 0)
7049 amount = cont_amount;
7050 else
7051 amount += ind_continuation;
7052 break;
7055 l = ml_get_curline();
7058 * If we're in a comment now, skip to the start of the
7059 * comment.
7061 trypos = find_start_comment(ind_maxcomment);
7062 if (trypos != NULL)
7064 curwin->w_cursor.lnum = trypos->lnum + 1;
7065 curwin->w_cursor.col = 0;
7066 continue;
7070 * Skip preprocessor directives and blank lines.
7072 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7073 continue;
7075 if (cin_nocode(l))
7076 continue;
7078 terminated = cin_isterminated(l, FALSE, TRUE);
7081 * If we are at top level and the line looks like a
7082 * function declaration, we are done
7083 * (it's a variable declaration).
7085 if (start_brace != BRACE_IN_COL0
7086 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7088 /* if the line is terminated with another ','
7089 * it is a continued variable initialization.
7090 * don't add extra indent.
7091 * TODO: does not work, if a function
7092 * declaration is split over multiple lines:
7093 * cin_isfuncdecl returns FALSE then.
7095 if (terminated == ',')
7096 break;
7098 /* if it es a enum declaration or an assignment,
7099 * we are done.
7101 if (terminated != ';' && cin_isinit())
7102 break;
7104 /* nothing useful found */
7105 if (terminated == 0 || terminated == '{')
7106 continue;
7109 if (terminated != ';')
7111 /* Skip parens and braces. Position the cursor
7112 * over the rightmost paren, so that matching it
7113 * will take us back to the start of the line.
7114 */ /* XXX */
7115 trypos = NULL;
7116 if (find_last_paren(l, '(', ')'))
7117 trypos = find_match_paren(ind_maxparen,
7118 ind_maxcomment);
7120 if (trypos == NULL && find_last_paren(l, '{', '}'))
7121 trypos = find_start_brace(ind_maxcomment);
7123 if (trypos != NULL)
7125 curwin->w_cursor.lnum = trypos->lnum + 1;
7126 curwin->w_cursor.col = 0;
7127 continue;
7131 /* it's a variable declaration, add indentation
7132 * like in
7133 * int a,
7134 * b;
7136 if (cont_amount > 0)
7137 amount = cont_amount;
7138 else
7139 amount += ind_continuation;
7141 else if (lookfor == LOOKFOR_UNTERM)
7143 if (cont_amount > 0)
7144 amount = cont_amount;
7145 else
7146 amount += ind_continuation;
7148 else if (lookfor != LOOKFOR_TERM
7149 && lookfor != LOOKFOR_CPP_BASECLASS)
7151 amount = scope_amount;
7152 if (theline[0] == '{')
7153 amount += ind_open_extra;
7155 break;
7159 * If we're in a comment now, skip to the start of the comment.
7160 */ /* XXX */
7161 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7163 curwin->w_cursor.lnum = trypos->lnum + 1;
7164 curwin->w_cursor.col = 0;
7165 continue;
7168 l = ml_get_curline();
7171 * If this is a switch() label, may line up relative to that.
7172 * If this is a C++ scope declaration, do the same.
7174 iscase = cin_iscase(l);
7175 if (iscase || cin_isscopedecl(l))
7177 /* we are only looking for cpp base class
7178 * declaration/initialization any longer */
7179 if (lookfor == LOOKFOR_CPP_BASECLASS)
7180 break;
7182 /* When looking for a "do" we are not interested in
7183 * labels. */
7184 if (whilelevel > 0)
7185 continue;
7188 * case xx:
7189 * c = 99 + <- this indent plus continuation
7190 *-> here;
7192 if (lookfor == LOOKFOR_UNTERM
7193 || lookfor == LOOKFOR_ENUM_OR_INIT)
7195 if (cont_amount > 0)
7196 amount = cont_amount;
7197 else
7198 amount += ind_continuation;
7199 break;
7203 * case xx: <- line up with this case
7204 * x = 333;
7205 * case yy:
7207 if ( (iscase && lookfor == LOOKFOR_CASE)
7208 || (iscase && lookfor_break)
7209 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7212 * Check that this case label is not for another
7213 * switch()
7214 */ /* XXX */
7215 if ((trypos = find_start_brace(ind_maxcomment)) ==
7216 NULL || trypos->lnum == ourscope)
7218 amount = get_indent(); /* XXX */
7219 break;
7221 continue;
7224 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7227 * case xx: if (cond) <- line up with this if
7228 * y = y + 1;
7229 * -> s = 99;
7231 * case xx:
7232 * if (cond) <- line up with this line
7233 * y = y + 1;
7234 * -> s = 99;
7236 if (lookfor == LOOKFOR_TERM)
7238 if (n)
7239 amount = n;
7241 if (!lookfor_break)
7242 break;
7246 * case xx: x = x + 1; <- line up with this x
7247 * -> y = y + 1;
7249 * case xx: if (cond) <- line up with this if
7250 * -> y = y + 1;
7252 if (n)
7254 amount = n;
7255 l = after_label(ml_get_curline());
7256 if (l != NULL && cin_is_cinword(l))
7258 if (theline[0] == '{')
7259 amount += ind_open_extra;
7260 else
7261 amount += ind_level + ind_no_brace;
7263 break;
7267 * Try to get the indent of a statement before the switch
7268 * label. If nothing is found, line up relative to the
7269 * switch label.
7270 * break; <- may line up with this line
7271 * case xx:
7272 * -> y = 1;
7274 scope_amount = get_indent() + (iscase /* XXX */
7275 ? ind_case_code : ind_scopedecl_code);
7276 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7277 continue;
7281 * Looking for a switch() label or C++ scope declaration,
7282 * ignore other lines, skip {}-blocks.
7284 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7286 if (find_last_paren(l, '{', '}') && (trypos =
7287 find_start_brace(ind_maxcomment)) != NULL)
7289 curwin->w_cursor.lnum = trypos->lnum + 1;
7290 curwin->w_cursor.col = 0;
7292 continue;
7296 * Ignore jump labels with nothing after them.
7298 if (cin_islabel(ind_maxcomment))
7300 l = after_label(ml_get_curline());
7301 if (l == NULL || cin_nocode(l))
7302 continue;
7306 * Ignore #defines, #if, etc.
7307 * Ignore comment and empty lines.
7308 * (need to get the line again, cin_islabel() may have
7309 * unlocked it)
7311 l = ml_get_curline();
7312 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7313 || cin_nocode(l))
7314 continue;
7317 * Are we at the start of a cpp base class declaration or
7318 * constructor initialization?
7319 */ /* XXX */
7320 n = FALSE;
7321 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7323 n = cin_is_cpp_baseclass(&col);
7324 l = ml_get_curline();
7326 if (n)
7328 if (lookfor == LOOKFOR_UNTERM)
7330 if (cont_amount > 0)
7331 amount = cont_amount;
7332 else
7333 amount += ind_continuation;
7335 else if (theline[0] == '{')
7337 /* Need to find start of the declaration. */
7338 lookfor = LOOKFOR_UNTERM;
7339 ind_continuation = 0;
7340 continue;
7342 else
7343 /* XXX */
7344 amount = get_baseclass_amount(col, ind_maxparen,
7345 ind_maxcomment, ind_cpp_baseclass);
7346 break;
7348 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7350 /* only look, whether there is a cpp base class
7351 * declaration or initialization before the opening brace.
7353 if (cin_isterminated(l, TRUE, FALSE))
7354 break;
7355 else
7356 continue;
7360 * What happens next depends on the line being terminated.
7361 * If terminated with a ',' only consider it terminating if
7362 * there is another unterminated statement behind, eg:
7363 * 123,
7364 * sizeof
7365 * here
7366 * Otherwise check whether it is a enumeration or structure
7367 * initialisation (not indented) or a variable declaration
7368 * (indented).
7370 terminated = cin_isterminated(l, FALSE, TRUE);
7372 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7373 && terminated == ','))
7376 * if we're in the middle of a paren thing,
7377 * go back to the line that starts it so
7378 * we can get the right prevailing indent
7379 * if ( foo &&
7380 * bar )
7383 * position the cursor over the rightmost paren, so that
7384 * matching it will take us back to the start of the line.
7386 (void)find_last_paren(l, '(', ')');
7387 trypos = find_match_paren(
7388 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7389 ind_maxcomment);
7392 * If we are looking for ',', we also look for matching
7393 * braces.
7395 if (trypos == NULL && terminated == ','
7396 && find_last_paren(l, '{', '}'))
7397 trypos = find_start_brace(ind_maxcomment);
7399 if (trypos != NULL)
7402 * Check if we are on a case label now. This is
7403 * handled above.
7404 * case xx: if ( asdf &&
7405 * asdf)
7407 curwin->w_cursor = *trypos;
7408 l = ml_get_curline();
7409 if (cin_iscase(l) || cin_isscopedecl(l))
7411 ++curwin->w_cursor.lnum;
7412 curwin->w_cursor.col = 0;
7413 continue;
7418 * Skip over continuation lines to find the one to get the
7419 * indent from
7420 * char *usethis = "bla\
7421 * bla",
7422 * here;
7424 if (terminated == ',')
7426 while (curwin->w_cursor.lnum > 1)
7428 l = ml_get(curwin->w_cursor.lnum - 1);
7429 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7430 break;
7431 --curwin->w_cursor.lnum;
7432 curwin->w_cursor.col = 0;
7437 * Get indent and pointer to text for current line,
7438 * ignoring any jump label. XXX
7440 cur_amount = skip_label(curwin->w_cursor.lnum,
7441 &l, ind_maxcomment);
7444 * If this is just above the line we are indenting, and it
7445 * starts with a '{', line it up with this line.
7446 * while (not)
7447 * -> {
7450 if (terminated != ',' && lookfor != LOOKFOR_TERM
7451 && theline[0] == '{')
7453 amount = cur_amount;
7455 * Only add ind_open_extra when the current line
7456 * doesn't start with a '{', which must have a match
7457 * in the same line (scope is the same). Probably:
7458 * { 1, 2 },
7459 * -> { 3, 4 }
7461 if (*skipwhite(l) != '{')
7462 amount += ind_open_extra;
7464 if (ind_cpp_baseclass)
7466 /* have to look back, whether it is a cpp base
7467 * class declaration or initialization */
7468 lookfor = LOOKFOR_CPP_BASECLASS;
7469 continue;
7471 break;
7475 * Check if we are after an "if", "while", etc.
7476 * Also allow " } else".
7478 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7481 * Found an unterminated line after an if (), line up
7482 * with the last one.
7483 * if (cond)
7484 * 100 +
7485 * -> here;
7487 if (lookfor == LOOKFOR_UNTERM
7488 || lookfor == LOOKFOR_ENUM_OR_INIT)
7490 if (cont_amount > 0)
7491 amount = cont_amount;
7492 else
7493 amount += ind_continuation;
7494 break;
7498 * If this is just above the line we are indenting, we
7499 * are finished.
7500 * while (not)
7501 * -> here;
7502 * Otherwise this indent can be used when the line
7503 * before this is terminated.
7504 * yyy;
7505 * if (stat)
7506 * while (not)
7507 * xxx;
7508 * -> here;
7510 amount = cur_amount;
7511 if (theline[0] == '{')
7512 amount += ind_open_extra;
7513 if (lookfor != LOOKFOR_TERM)
7515 amount += ind_level + ind_no_brace;
7516 break;
7520 * Special trick: when expecting the while () after a
7521 * do, line up with the while()
7522 * do
7523 * x = 1;
7524 * -> here
7526 l = skipwhite(ml_get_curline());
7527 if (cin_isdo(l))
7529 if (whilelevel == 0)
7530 break;
7531 --whilelevel;
7535 * When searching for a terminated line, don't use the
7536 * one between the "if" and the "else".
7537 * Need to use the scope of this "else". XXX
7538 * If whilelevel != 0 continue looking for a "do {".
7540 if (cin_iselse(l)
7541 && whilelevel == 0
7542 && ((trypos = find_start_brace(ind_maxcomment))
7543 == NULL
7544 || find_match(LOOKFOR_IF, trypos->lnum,
7545 ind_maxparen, ind_maxcomment) == FAIL))
7546 break;
7550 * If we're below an unterminated line that is not an
7551 * "if" or something, we may line up with this line or
7552 * add something for a continuation line, depending on
7553 * the line before this one.
7555 else
7558 * Found two unterminated lines on a row, line up with
7559 * the last one.
7560 * c = 99 +
7561 * 100 +
7562 * -> here;
7564 if (lookfor == LOOKFOR_UNTERM)
7566 /* When line ends in a comma add extra indent */
7567 if (terminated == ',')
7568 amount += ind_continuation;
7569 break;
7572 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7574 /* Found two lines ending in ',', lineup with the
7575 * lowest one, but check for cpp base class
7576 * declaration/initialization, if it is an
7577 * opening brace or we are looking just for
7578 * enumerations/initializations. */
7579 if (terminated == ',')
7581 if (ind_cpp_baseclass == 0)
7582 break;
7584 lookfor = LOOKFOR_CPP_BASECLASS;
7585 continue;
7588 /* Ignore unterminated lines in between, but
7589 * reduce indent. */
7590 if (amount > cur_amount)
7591 amount = cur_amount;
7593 else
7596 * Found first unterminated line on a row, may
7597 * line up with this line, remember its indent
7598 * 100 +
7599 * -> here;
7601 amount = cur_amount;
7604 * If previous line ends in ',', check whether we
7605 * are in an initialization or enum
7606 * struct xxx =
7608 * sizeof a,
7609 * 124 };
7610 * or a normal possible continuation line.
7611 * but only, of no other statement has been found
7612 * yet.
7614 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7616 lookfor = LOOKFOR_ENUM_OR_INIT;
7617 cont_amount = cin_first_id_amount();
7619 else
7621 if (lookfor == LOOKFOR_INITIAL
7622 && *l != NUL
7623 && l[STRLEN(l) - 1] == '\\')
7624 /* XXX */
7625 cont_amount = cin_get_equal_amount(
7626 curwin->w_cursor.lnum);
7627 if (lookfor != LOOKFOR_TERM)
7628 lookfor = LOOKFOR_UNTERM;
7635 * Check if we are after a while (cond);
7636 * If so: Ignore until the matching "do".
7638 /* XXX */
7639 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7640 ind_maxcomment))
7643 * Found an unterminated line after a while ();, line up
7644 * with the last one.
7645 * while (cond);
7646 * 100 + <- line up with this one
7647 * -> here;
7649 if (lookfor == LOOKFOR_UNTERM
7650 || lookfor == LOOKFOR_ENUM_OR_INIT)
7652 if (cont_amount > 0)
7653 amount = cont_amount;
7654 else
7655 amount += ind_continuation;
7656 break;
7659 if (whilelevel == 0)
7661 lookfor = LOOKFOR_TERM;
7662 amount = get_indent(); /* XXX */
7663 if (theline[0] == '{')
7664 amount += ind_open_extra;
7666 ++whilelevel;
7670 * We are after a "normal" statement.
7671 * If we had another statement we can stop now and use the
7672 * indent of that other statement.
7673 * Otherwise the indent of the current statement may be used,
7674 * search backwards for the next "normal" statement.
7676 else
7679 * Skip single break line, if before a switch label. It
7680 * may be lined up with the case label.
7682 if (lookfor == LOOKFOR_NOBREAK
7683 && cin_isbreak(skipwhite(ml_get_curline())))
7685 lookfor = LOOKFOR_ANY;
7686 continue;
7690 * Handle "do {" line.
7692 if (whilelevel > 0)
7694 l = cin_skipcomment(ml_get_curline());
7695 if (cin_isdo(l))
7697 amount = get_indent(); /* XXX */
7698 --whilelevel;
7699 continue;
7704 * Found a terminated line above an unterminated line. Add
7705 * the amount for a continuation line.
7706 * x = 1;
7707 * y = foo +
7708 * -> here;
7709 * or
7710 * int x = 1;
7711 * int foo,
7712 * -> here;
7714 if (lookfor == LOOKFOR_UNTERM
7715 || lookfor == LOOKFOR_ENUM_OR_INIT)
7717 if (cont_amount > 0)
7718 amount = cont_amount;
7719 else
7720 amount += ind_continuation;
7721 break;
7725 * Found a terminated line above a terminated line or "if"
7726 * etc. line. Use the amount of the line below us.
7727 * x = 1; x = 1;
7728 * if (asdf) y = 2;
7729 * while (asdf) ->here;
7730 * here;
7731 * ->foo;
7733 if (lookfor == LOOKFOR_TERM)
7735 if (!lookfor_break && whilelevel == 0)
7736 break;
7740 * First line above the one we're indenting is terminated.
7741 * To know what needs to be done look further backward for
7742 * a terminated line.
7744 else
7747 * position the cursor over the rightmost paren, so
7748 * that matching it will take us back to the start of
7749 * the line. Helps for:
7750 * func(asdr,
7751 * asdfasdf);
7752 * here;
7754 term_again:
7755 l = ml_get_curline();
7756 if (find_last_paren(l, '(', ')')
7757 && (trypos = find_match_paren(ind_maxparen,
7758 ind_maxcomment)) != NULL)
7761 * Check if we are on a case label now. This is
7762 * handled above.
7763 * case xx: if ( asdf &&
7764 * asdf)
7766 curwin->w_cursor = *trypos;
7767 l = ml_get_curline();
7768 if (cin_iscase(l) || cin_isscopedecl(l))
7770 ++curwin->w_cursor.lnum;
7771 curwin->w_cursor.col = 0;
7772 continue;
7776 /* When aligning with the case statement, don't align
7777 * with a statement after it.
7778 * case 1: { <-- don't use this { position
7779 * stat;
7781 * case 2:
7782 * stat;
7785 iscase = (ind_keep_case_label && cin_iscase(l));
7788 * Get indent and pointer to text for current line,
7789 * ignoring any jump label.
7791 amount = skip_label(curwin->w_cursor.lnum,
7792 &l, ind_maxcomment);
7794 if (theline[0] == '{')
7795 amount += ind_open_extra;
7796 /* See remark above: "Only add ind_open_extra.." */
7797 l = skipwhite(l);
7798 if (*l == '{')
7799 amount -= ind_open_extra;
7800 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7803 * When a terminated line starts with "else" skip to
7804 * the matching "if":
7805 * else 3;
7806 * indent this;
7807 * Need to use the scope of this "else". XXX
7808 * If whilelevel != 0 continue looking for a "do {".
7810 if (lookfor == LOOKFOR_TERM
7811 && *l != '}'
7812 && cin_iselse(l)
7813 && whilelevel == 0)
7815 if ((trypos = find_start_brace(ind_maxcomment))
7816 == NULL
7817 || find_match(LOOKFOR_IF, trypos->lnum,
7818 ind_maxparen, ind_maxcomment) == FAIL)
7819 break;
7820 continue;
7824 * If we're at the end of a block, skip to the start of
7825 * that block.
7827 curwin->w_cursor.col = 0;
7828 if (*cin_skipcomment(l) == '}'
7829 && (trypos = find_start_brace(ind_maxcomment))
7830 != NULL) /* XXX */
7832 curwin->w_cursor = *trypos;
7833 /* if not "else {" check for terminated again */
7834 /* but skip block for "} else {" */
7835 l = cin_skipcomment(ml_get_curline());
7836 if (*l == '}' || !cin_iselse(l))
7837 goto term_again;
7838 ++curwin->w_cursor.lnum;
7839 curwin->w_cursor.col = 0;
7847 /* add extra indent for a comment */
7848 if (cin_iscomment(theline))
7849 amount += ind_comment;
7853 * ok -- we're not inside any sort of structure at all!
7855 * this means we're at the top level, and everything should
7856 * basically just match where the previous line is, except
7857 * for the lines immediately following a function declaration,
7858 * which are K&R-style parameters and need to be indented.
7860 else
7863 * if our line starts with an open brace, forget about any
7864 * prevailing indent and make sure it looks like the start
7865 * of a function
7868 if (theline[0] == '{')
7870 amount = ind_first_open;
7874 * If the NEXT line is a function declaration, the current
7875 * line needs to be indented as a function type spec.
7876 * Don't do this if the current line looks like a comment or if the
7877 * current line is terminated, ie. ends in ';', or if the current line
7878 * contains { or }: "void f() {\n if (1)"
7880 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7881 && !cin_nocode(theline)
7882 && vim_strchr(theline, '{') == NULL
7883 && vim_strchr(theline, '}') == NULL
7884 && !cin_ends_in(theline, (char_u *)":", NULL)
7885 && !cin_ends_in(theline, (char_u *)",", NULL)
7886 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7887 && !cin_isterminated(theline, FALSE, TRUE))
7889 amount = ind_func_type;
7891 else
7893 amount = 0;
7894 curwin->w_cursor = cur_curpos;
7896 /* search backwards until we find something we recognize */
7898 while (curwin->w_cursor.lnum > 1)
7900 curwin->w_cursor.lnum--;
7901 curwin->w_cursor.col = 0;
7903 l = ml_get_curline();
7906 * If we're in a comment now, skip to the start of the comment.
7907 */ /* XXX */
7908 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7910 curwin->w_cursor.lnum = trypos->lnum + 1;
7911 curwin->w_cursor.col = 0;
7912 continue;
7916 * Are we at the start of a cpp base class declaration or
7917 * constructor initialization?
7918 */ /* XXX */
7919 n = FALSE;
7920 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7922 n = cin_is_cpp_baseclass(&col);
7923 l = ml_get_curline();
7925 if (n)
7927 /* XXX */
7928 amount = get_baseclass_amount(col, ind_maxparen,
7929 ind_maxcomment, ind_cpp_baseclass);
7930 break;
7934 * Skip preprocessor directives and blank lines.
7936 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7937 continue;
7939 if (cin_nocode(l))
7940 continue;
7943 * If the previous line ends in ',', use one level of
7944 * indentation:
7945 * int foo,
7946 * bar;
7947 * do this before checking for '}' in case of eg.
7948 * enum foobar
7950 * ...
7951 * } foo,
7952 * bar;
7954 n = 0;
7955 if (cin_ends_in(l, (char_u *)",", NULL)
7956 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7958 /* take us back to opening paren */
7959 if (find_last_paren(l, '(', ')')
7960 && (trypos = find_match_paren(ind_maxparen,
7961 ind_maxcomment)) != NULL)
7962 curwin->w_cursor = *trypos;
7964 /* For a line ending in ',' that is a continuation line go
7965 * back to the first line with a backslash:
7966 * char *foo = "bla\
7967 * bla",
7968 * here;
7970 while (n == 0 && curwin->w_cursor.lnum > 1)
7972 l = ml_get(curwin->w_cursor.lnum - 1);
7973 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7974 break;
7975 --curwin->w_cursor.lnum;
7976 curwin->w_cursor.col = 0;
7979 amount = get_indent(); /* XXX */
7981 if (amount == 0)
7982 amount = cin_first_id_amount();
7983 if (amount == 0)
7984 amount = ind_continuation;
7985 break;
7989 * If the line looks like a function declaration, and we're
7990 * not in a comment, put it the left margin.
7992 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7993 break;
7994 l = ml_get_curline();
7997 * Finding the closing '}' of a previous function. Put
7998 * current line at the left margin. For when 'cino' has "fs".
8000 if (*skipwhite(l) == '}')
8001 break;
8003 /* (matching {)
8004 * If the previous line ends on '};' (maybe followed by
8005 * comments) align at column 0. For example:
8006 * char *string_array[] = { "foo",
8007 * / * x * / "b};ar" }; / * foobar * /
8009 if (cin_ends_in(l, (char_u *)"};", NULL))
8010 break;
8013 * If the PREVIOUS line is a function declaration, the current
8014 * line (and the ones that follow) needs to be indented as
8015 * parameters.
8017 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
8019 amount = ind_param;
8020 break;
8024 * If the previous line ends in ';' and the line before the
8025 * previous line ends in ',' or '\', ident to column zero:
8026 * int foo,
8027 * bar;
8028 * indent_to_0 here;
8030 if (cin_ends_in(l, (char_u *)";", NULL))
8032 l = ml_get(curwin->w_cursor.lnum - 1);
8033 if (cin_ends_in(l, (char_u *)",", NULL)
8034 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8035 break;
8036 l = ml_get_curline();
8040 * Doesn't look like anything interesting -- so just
8041 * use the indent of this line.
8043 * Position the cursor over the rightmost paren, so that
8044 * matching it will take us back to the start of the line.
8046 find_last_paren(l, '(', ')');
8048 if ((trypos = find_match_paren(ind_maxparen,
8049 ind_maxcomment)) != NULL)
8050 curwin->w_cursor = *trypos;
8051 amount = get_indent(); /* XXX */
8052 break;
8055 /* add extra indent for a comment */
8056 if (cin_iscomment(theline))
8057 amount += ind_comment;
8059 /* add extra indent if the previous line ended in a backslash:
8060 * "asdfasdf\
8061 * here";
8062 * char *foo = "asdf\
8063 * here";
8065 if (cur_curpos.lnum > 1)
8067 l = ml_get(cur_curpos.lnum - 1);
8068 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8070 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8071 if (cur_amount > 0)
8072 amount = cur_amount;
8073 else if (cur_amount == 0)
8074 amount += ind_continuation;
8080 theend:
8081 /* put the cursor back where it belongs */
8082 curwin->w_cursor = cur_curpos;
8084 vim_free(linecopy);
8086 if (amount < 0)
8087 return 0;
8088 return amount;
8091 static int
8092 find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8093 int lookfor;
8094 linenr_T ourscope;
8095 int ind_maxparen;
8096 int ind_maxcomment;
8098 char_u *look;
8099 pos_T *theirscope;
8100 char_u *mightbeif;
8101 int elselevel;
8102 int whilelevel;
8104 if (lookfor == LOOKFOR_IF)
8106 elselevel = 1;
8107 whilelevel = 0;
8109 else
8111 elselevel = 0;
8112 whilelevel = 1;
8115 curwin->w_cursor.col = 0;
8117 while (curwin->w_cursor.lnum > ourscope + 1)
8119 curwin->w_cursor.lnum--;
8120 curwin->w_cursor.col = 0;
8122 look = cin_skipcomment(ml_get_curline());
8123 if (cin_iselse(look)
8124 || cin_isif(look)
8125 || cin_isdo(look) /* XXX */
8126 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8129 * if we've gone outside the braces entirely,
8130 * we must be out of scope...
8132 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8133 if (theirscope == NULL)
8134 break;
8137 * and if the brace enclosing this is further
8138 * back than the one enclosing the else, we're
8139 * out of luck too.
8141 if (theirscope->lnum < ourscope)
8142 break;
8145 * and if they're enclosed in a *deeper* brace,
8146 * then we can ignore it because it's in a
8147 * different scope...
8149 if (theirscope->lnum > ourscope)
8150 continue;
8153 * if it was an "else" (that's not an "else if")
8154 * then we need to go back to another if, so
8155 * increment elselevel
8157 look = cin_skipcomment(ml_get_curline());
8158 if (cin_iselse(look))
8160 mightbeif = cin_skipcomment(look + 4);
8161 if (!cin_isif(mightbeif))
8162 ++elselevel;
8163 continue;
8167 * if it was a "while" then we need to go back to
8168 * another "do", so increment whilelevel. XXX
8170 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8172 ++whilelevel;
8173 continue;
8176 /* If it's an "if" decrement elselevel */
8177 look = cin_skipcomment(ml_get_curline());
8178 if (cin_isif(look))
8180 elselevel--;
8182 * When looking for an "if" ignore "while"s that
8183 * get in the way.
8185 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8186 whilelevel = 0;
8189 /* If it's a "do" decrement whilelevel */
8190 if (cin_isdo(look))
8191 whilelevel--;
8194 * if we've used up all the elses, then
8195 * this must be the if that we want!
8196 * match the indent level of that if.
8198 if (elselevel <= 0 && whilelevel <= 0)
8200 return OK;
8204 return FAIL;
8207 # if defined(FEAT_EVAL) || defined(PROTO)
8209 * Get indent level from 'indentexpr'.
8212 get_expr_indent()
8214 int indent;
8215 pos_T pos;
8216 int save_State;
8217 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8218 OPT_LOCAL);
8220 pos = curwin->w_cursor;
8221 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
8222 if (use_sandbox)
8223 ++sandbox;
8224 ++textlock;
8225 indent = eval_to_number(curbuf->b_p_inde);
8226 if (use_sandbox)
8227 --sandbox;
8228 --textlock;
8230 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8231 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8232 * command. */
8233 save_State = State;
8234 State = INSERT;
8235 curwin->w_cursor = pos;
8236 check_cursor();
8237 State = save_State;
8239 /* If there is an error, just keep the current indent. */
8240 if (indent < 0)
8241 indent = get_indent();
8243 return indent;
8245 # endif
8247 #endif /* FEAT_CINDENT */
8249 #if defined(FEAT_LISP) || defined(PROTO)
8251 static int lisp_match __ARGS((char_u *p));
8253 static int
8254 lisp_match(p)
8255 char_u *p;
8257 char_u buf[LSIZE];
8258 int len;
8259 char_u *word = p_lispwords;
8261 while (*word != NUL)
8263 (void)copy_option_part(&word, buf, LSIZE, ",");
8264 len = (int)STRLEN(buf);
8265 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8266 return TRUE;
8268 return FALSE;
8272 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8273 * The incompatible newer method is quite a bit better at indenting
8274 * code in lisp-like languages than the traditional one; it's still
8275 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8277 * TODO:
8278 * Findmatch() should be adapted for lisp, also to make showmatch
8279 * work correctly: now (v5.3) it seems all C/C++ oriented:
8280 * - it does not recognize the #\( and #\) notations as character literals
8281 * - it doesn't know about comments starting with a semicolon
8282 * - it incorrectly interprets '(' as a character literal
8283 * All this messes up get_lisp_indent in some rare cases.
8284 * Update from Sergey Khorev:
8285 * I tried to fix the first two issues.
8288 get_lisp_indent()
8290 pos_T *pos, realpos, paren;
8291 int amount;
8292 char_u *that;
8293 colnr_T col;
8294 colnr_T firsttry;
8295 int parencount, quotecount;
8296 int vi_lisp;
8298 /* Set vi_lisp to use the vi-compatible method */
8299 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8301 realpos = curwin->w_cursor;
8302 curwin->w_cursor.col = 0;
8304 if ((pos = findmatch(NULL, '(')) == NULL)
8305 pos = findmatch(NULL, '[');
8306 else
8308 paren = *pos;
8309 pos = findmatch(NULL, '[');
8310 if (pos == NULL || ltp(pos, &paren))
8311 pos = &paren;
8313 if (pos != NULL)
8315 /* Extra trick: Take the indent of the first previous non-white
8316 * line that is at the same () level. */
8317 amount = -1;
8318 parencount = 0;
8320 while (--curwin->w_cursor.lnum >= pos->lnum)
8322 if (linewhite(curwin->w_cursor.lnum))
8323 continue;
8324 for (that = ml_get_curline(); *that != NUL; ++that)
8326 if (*that == ';')
8328 while (*(that + 1) != NUL)
8329 ++that;
8330 continue;
8332 if (*that == '\\')
8334 if (*(that + 1) != NUL)
8335 ++that;
8336 continue;
8338 if (*that == '"' && *(that + 1) != NUL)
8340 while (*++that && *that != '"')
8342 /* skipping escaped characters in the string */
8343 if (*that == '\\')
8345 if (*++that == NUL)
8346 break;
8347 if (that[1] == NUL)
8349 ++that;
8350 break;
8355 if (*that == '(' || *that == '[')
8356 ++parencount;
8357 else if (*that == ')' || *that == ']')
8358 --parencount;
8360 if (parencount == 0)
8362 amount = get_indent();
8363 break;
8367 if (amount == -1)
8369 curwin->w_cursor.lnum = pos->lnum;
8370 curwin->w_cursor.col = pos->col;
8371 col = pos->col;
8373 that = ml_get_curline();
8375 if (vi_lisp && get_indent() == 0)
8376 amount = 2;
8377 else
8379 amount = 0;
8380 while (*that && col)
8382 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8383 col--;
8387 * Some keywords require "body" indenting rules (the
8388 * non-standard-lisp ones are Scheme special forms):
8390 * (let ((a 1)) instead (let ((a 1))
8391 * (...)) of (...))
8394 if (!vi_lisp && (*that == '(' || *that == '[')
8395 && lisp_match(that + 1))
8396 amount += 2;
8397 else
8399 that++;
8400 amount++;
8401 firsttry = amount;
8403 while (vim_iswhite(*that))
8405 amount += lbr_chartabsize(that, (colnr_T)amount);
8406 ++that;
8409 if (*that && *that != ';') /* not a comment line */
8411 /* test *that != '(' to accommodate first let/do
8412 * argument if it is more than one line */
8413 if (!vi_lisp && *that != '(' && *that != '[')
8414 firsttry++;
8416 parencount = 0;
8417 quotecount = 0;
8419 if (vi_lisp
8420 || (*that != '"'
8421 && *that != '\''
8422 && *that != '#'
8423 && (*that < '0' || *that > '9')))
8425 while (*that
8426 && (!vim_iswhite(*that)
8427 || quotecount
8428 || parencount)
8429 && (!((*that == '(' || *that == '[')
8430 && !quotecount
8431 && !parencount
8432 && vi_lisp)))
8434 if (*that == '"')
8435 quotecount = !quotecount;
8436 if ((*that == '(' || *that == '[')
8437 && !quotecount)
8438 ++parencount;
8439 if ((*that == ')' || *that == ']')
8440 && !quotecount)
8441 --parencount;
8442 if (*that == '\\' && *(that+1) != NUL)
8443 amount += lbr_chartabsize_adv(&that,
8444 (colnr_T)amount);
8445 amount += lbr_chartabsize_adv(&that,
8446 (colnr_T)amount);
8449 while (vim_iswhite(*that))
8451 amount += lbr_chartabsize(that, (colnr_T)amount);
8452 that++;
8454 if (!*that || *that == ';')
8455 amount = firsttry;
8461 else
8462 amount = 0; /* no matching '(' or '[' found, use zero indent */
8464 curwin->w_cursor = realpos;
8466 return amount;
8468 #endif /* FEAT_LISP */
8470 void
8471 prepare_to_exit()
8473 #if defined(SIGHUP) && defined(SIG_IGN)
8474 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8475 * makes Vim exit and then handling SIGHUP causes various reentrance
8476 * problems. */
8477 signal(SIGHUP, SIG_IGN);
8478 #endif
8480 #ifdef FEAT_GUI
8481 if (gui.in_use)
8483 gui.dying = TRUE;
8484 out_trash(); /* trash any pending output */
8486 else
8487 #endif
8489 windgoto((int)Rows - 1, 0);
8492 * Switch terminal mode back now, so messages end up on the "normal"
8493 * screen (if there are two screens).
8495 settmode(TMODE_COOK);
8496 #ifdef WIN3264
8497 if (can_end_termcap_mode(FALSE) == TRUE)
8498 #endif
8499 stoptermcap();
8500 out_flush();
8505 * Preserve files and exit.
8506 * When called IObuff must contain a message.
8508 void
8509 preserve_exit()
8511 buf_T *buf;
8513 prepare_to_exit();
8515 /* Setting this will prevent free() calls. That avoids calling free()
8516 * recursively when free() was invoked with a bad pointer. */
8517 really_exiting = TRUE;
8519 out_str(IObuff);
8520 screen_start(); /* don't know where cursor is now */
8521 out_flush();
8523 ml_close_notmod(); /* close all not-modified buffers */
8525 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8527 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8529 OUT_STR(_("Vim: preserving files...\n"));
8530 screen_start(); /* don't know where cursor is now */
8531 out_flush();
8532 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8533 break;
8537 ml_close_all(FALSE); /* close all memfiles, without deleting */
8539 OUT_STR(_("Vim: Finished.\n"));
8541 getout(1);
8545 * return TRUE if "fname" exists.
8548 vim_fexists(fname)
8549 char_u *fname;
8551 struct stat st;
8553 if (mch_stat((char *)fname, &st))
8554 return FALSE;
8555 return TRUE;
8559 * Check for CTRL-C pressed, but only once in a while.
8560 * Should be used instead of ui_breakcheck() for functions that check for
8561 * each line in the file. Calling ui_breakcheck() each time takes too much
8562 * time, because it can be a system call.
8565 #ifndef BREAKCHECK_SKIP
8566 # ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8567 # define BREAKCHECK_SKIP 200
8568 # else
8569 # define BREAKCHECK_SKIP 32
8570 # endif
8571 #endif
8573 static int breakcheck_count = 0;
8575 void
8576 line_breakcheck()
8578 if (++breakcheck_count >= BREAKCHECK_SKIP)
8580 breakcheck_count = 0;
8581 ui_breakcheck();
8586 * Like line_breakcheck() but check 10 times less often.
8588 void
8589 fast_breakcheck()
8591 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8593 breakcheck_count = 0;
8594 ui_breakcheck();
8599 * Invoke expand_wildcards() for one pattern.
8600 * Expand items like "%:h" before the expansion.
8601 * Returns OK or FAIL.
8604 expand_wildcards_eval(pat, num_file, file, flags)
8605 char_u **pat; /* pointer to input pattern */
8606 int *num_file; /* resulting number of files */
8607 char_u ***file; /* array of resulting files */
8608 int flags; /* EW_DIR, etc. */
8610 int ret = FAIL;
8611 char_u *eval_pat = NULL;
8612 char_u *exp_pat = *pat;
8613 char_u *ignored_msg;
8614 int usedlen;
8616 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
8618 ++emsg_off;
8619 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
8620 NULL, &ignored_msg, NULL);
8621 --emsg_off;
8622 if (eval_pat != NULL)
8623 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
8626 if (exp_pat != NULL)
8627 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
8629 if (eval_pat != NULL)
8631 vim_free(exp_pat);
8632 vim_free(eval_pat);
8635 return ret;
8639 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8640 * 'wildignore'.
8641 * Returns OK or FAIL.
8644 expand_wildcards(num_pat, pat, num_file, file, flags)
8645 int num_pat; /* number of input patterns */
8646 char_u **pat; /* array of input patterns */
8647 int *num_file; /* resulting number of files */
8648 char_u ***file; /* array of resulting files */
8649 int flags; /* EW_DIR, etc. */
8651 int retval;
8652 int i, j;
8653 char_u *p;
8654 int non_suf_match; /* number without matching suffix */
8656 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8658 /* When keeping all matches, return here */
8659 if (flags & EW_KEEPALL)
8660 return retval;
8662 #ifdef FEAT_WILDIGN
8664 * Remove names that match 'wildignore'.
8666 if (*p_wig)
8668 char_u *ffname;
8670 /* check all files in (*file)[] */
8671 for (i = 0; i < *num_file; ++i)
8673 ffname = FullName_save((*file)[i], FALSE);
8674 if (ffname == NULL) /* out of memory */
8675 break;
8676 # ifdef VMS
8677 vms_remove_version(ffname);
8678 # endif
8679 if (match_file_list(p_wig, (*file)[i], ffname))
8681 /* remove this matching file from the list */
8682 vim_free((*file)[i]);
8683 for (j = i; j + 1 < *num_file; ++j)
8684 (*file)[j] = (*file)[j + 1];
8685 --*num_file;
8686 --i;
8688 vim_free(ffname);
8691 #endif
8694 * Move the names where 'suffixes' match to the end.
8696 if (*num_file > 1)
8698 non_suf_match = 0;
8699 for (i = 0; i < *num_file; ++i)
8701 if (!match_suffix((*file)[i]))
8704 * Move the name without matching suffix to the front
8705 * of the list.
8707 p = (*file)[i];
8708 for (j = i; j > non_suf_match; --j)
8709 (*file)[j] = (*file)[j - 1];
8710 (*file)[non_suf_match++] = p;
8715 return retval;
8719 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8722 match_suffix(fname)
8723 char_u *fname;
8725 int fnamelen, setsuflen;
8726 char_u *setsuf;
8727 #define MAXSUFLEN 30 /* maximum length of a file suffix */
8728 char_u suf_buf[MAXSUFLEN];
8730 fnamelen = (int)STRLEN(fname);
8731 setsuflen = 0;
8732 for (setsuf = p_su; *setsuf; )
8734 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
8735 if (setsuflen == 0)
8737 char_u *tail = gettail(fname);
8739 /* empty entry: match name without a '.' */
8740 if (vim_strchr(tail, '.') == NULL)
8742 setsuflen = 1;
8743 break;
8746 else
8748 if (fnamelen >= setsuflen
8749 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8750 (size_t)setsuflen) == 0)
8751 break;
8752 setsuflen = 0;
8755 return (setsuflen != 0);
8758 #if !defined(NO_EXPANDPATH) || defined(PROTO)
8760 # ifdef VIM_BACKTICK
8761 static int vim_backtick __ARGS((char_u *p));
8762 static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8763 # endif
8765 # if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8767 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8768 * it's shared between these systems.
8770 # if defined(DJGPP) || defined(PROTO)
8771 # define _cdecl /* DJGPP doesn't have this */
8772 # else
8773 # ifdef __BORLANDC__
8774 # define _cdecl _RTLENTRYF
8775 # endif
8776 # endif
8779 * comparison function for qsort in dos_expandpath()
8781 static int _cdecl
8782 pstrcmp(const void *a, const void *b)
8784 return (pathcmp(*(char **)a, *(char **)b, -1));
8787 # ifndef WIN3264
8788 static void
8789 namelowcpy(
8790 char_u *d,
8791 char_u *s)
8793 # ifdef DJGPP
8794 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8795 while (*s)
8796 *d++ = *s++;
8797 else
8798 # endif
8799 while (*s)
8800 *d++ = TOLOWER_LOC(*s++);
8801 *d = NUL;
8803 # endif
8806 * Recursively expand one path component into all matching files and/or
8807 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8808 * Return the number of matches found.
8809 * "path" has backslashes before chars that are not to be expanded, starting
8810 * at "path[wildoff]".
8811 * Return the number of matches found.
8812 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
8814 static int
8815 dos_expandpath(
8816 garray_T *gap,
8817 char_u *path,
8818 int wildoff,
8819 int flags, /* EW_* flags */
8820 int didstar) /* expanded "**" once already */
8822 char_u *buf;
8823 char_u *path_end;
8824 char_u *p, *s, *e;
8825 int start_len = gap->ga_len;
8826 char_u *pat;
8827 regmatch_T regmatch;
8828 int starts_with_dot;
8829 int matches;
8830 int len;
8831 int starstar = FALSE;
8832 static int stardepth = 0; /* depth for "**" expansion */
8833 #ifdef WIN3264
8834 WIN32_FIND_DATA fb;
8835 HANDLE hFind = (HANDLE)0;
8836 # ifdef FEAT_MBYTE
8837 WIN32_FIND_DATAW wfb;
8838 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8839 # endif
8840 #else
8841 struct ffblk fb;
8842 #endif
8843 char_u *matchname;
8844 int ok;
8846 /* Expanding "**" may take a long time, check for CTRL-C. */
8847 if (stardepth > 0)
8849 ui_breakcheck();
8850 if (got_int)
8851 return 0;
8854 /* make room for file name */
8855 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8856 if (buf == NULL)
8857 return 0;
8860 * Find the first part in the path name that contains a wildcard or a ~1.
8861 * Copy it into buf, including the preceding characters.
8863 p = buf;
8864 s = buf;
8865 e = NULL;
8866 path_end = path;
8867 while (*path_end != NUL)
8869 /* May ignore a wildcard that has a backslash before it; it will
8870 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8871 if (path_end >= path + wildoff && rem_backslash(path_end))
8872 *p++ = *path_end++;
8873 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8875 if (e != NULL)
8876 break;
8877 s = p + 1;
8879 else if (path_end >= path + wildoff
8880 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8881 e = p;
8882 #ifdef FEAT_MBYTE
8883 if (has_mbyte)
8885 len = (*mb_ptr2len)(path_end);
8886 STRNCPY(p, path_end, len);
8887 p += len;
8888 path_end += len;
8890 else
8891 #endif
8892 *p++ = *path_end++;
8894 e = p;
8895 *e = NUL;
8897 /* now we have one wildcard component between s and e */
8898 /* Remove backslashes between "wildoff" and the start of the wildcard
8899 * component. */
8900 for (p = buf + wildoff; p < s; ++p)
8901 if (rem_backslash(p))
8903 STRMOVE(p, p + 1);
8904 --e;
8905 --s;
8908 /* Check for "**" between "s" and "e". */
8909 for (p = s; p < e; ++p)
8910 if (p[0] == '*' && p[1] == '*')
8911 starstar = TRUE;
8913 starts_with_dot = (*s == '.');
8914 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8915 if (pat == NULL)
8917 vim_free(buf);
8918 return 0;
8921 /* compile the regexp into a program */
8922 regmatch.rm_ic = TRUE; /* Always ignore case */
8923 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8924 vim_free(pat);
8926 if (regmatch.regprog == NULL)
8928 vim_free(buf);
8929 return 0;
8932 /* remember the pattern or file name being looked for */
8933 matchname = vim_strsave(s);
8935 /* If "**" is by itself, this is the first time we encounter it and more
8936 * is following then find matches without any directory. */
8937 if (!didstar && stardepth < 100 && starstar && e - s == 2
8938 && *path_end == '/')
8940 STRCPY(s, path_end + 1);
8941 ++stardepth;
8942 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8943 --stardepth;
8946 /* Scan all files in the directory with "dir/ *.*" */
8947 STRCPY(s, "*.*");
8948 #ifdef WIN3264
8949 # ifdef FEAT_MBYTE
8950 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8952 /* The active codepage differs from 'encoding'. Attempt using the
8953 * wide function. If it fails because it is not implemented fall back
8954 * to the non-wide version (for Windows 98) */
8955 wn = enc_to_utf16(buf, NULL);
8956 if (wn != NULL)
8958 hFind = FindFirstFileW(wn, &wfb);
8959 if (hFind == INVALID_HANDLE_VALUE
8960 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8962 vim_free(wn);
8963 wn = NULL;
8968 if (wn == NULL)
8969 # endif
8970 hFind = FindFirstFile(buf, &fb);
8971 ok = (hFind != INVALID_HANDLE_VALUE);
8972 #else
8973 /* If we are expanding wildcards we try both files and directories */
8974 ok = (findfirst((char *)buf, &fb,
8975 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8976 #endif
8978 while (ok)
8980 #ifdef WIN3264
8981 # ifdef FEAT_MBYTE
8982 if (wn != NULL)
8983 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8984 else
8985 # endif
8986 p = (char_u *)fb.cFileName;
8987 #else
8988 p = (char_u *)fb.ff_name;
8989 #endif
8990 /* Ignore entries starting with a dot, unless when asked for. Accept
8991 * all entries found with "matchname". */
8992 if ((p[0] != '.' || starts_with_dot)
8993 && (matchname == NULL
8994 || vim_regexec(&regmatch, p, (colnr_T)0)))
8996 #ifdef WIN3264
8997 STRCPY(s, p);
8998 #else
8999 namelowcpy(s, p);
9000 #endif
9001 len = (int)STRLEN(buf);
9003 if (starstar && stardepth < 100)
9005 /* For "**" in the pattern first go deeper in the tree to
9006 * find matches. */
9007 STRCPY(buf + len, "/**");
9008 STRCPY(buf + len + 3, path_end);
9009 ++stardepth;
9010 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9011 --stardepth;
9014 STRCPY(buf + len, path_end);
9015 if (mch_has_exp_wildcard(path_end))
9017 /* need to expand another component of the path */
9018 /* remove backslashes for the remaining components only */
9019 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
9021 else
9023 /* no more wildcards, check if there is a match */
9024 /* remove backslashes for the remaining components only */
9025 if (*path_end != 0)
9026 backslash_halve(buf + len + 1);
9027 if (mch_getperm(buf) >= 0) /* add existing file */
9028 addfile(gap, buf, flags);
9032 #ifdef WIN3264
9033 # ifdef FEAT_MBYTE
9034 if (wn != NULL)
9036 vim_free(p);
9037 ok = FindNextFileW(hFind, &wfb);
9039 else
9040 # endif
9041 ok = FindNextFile(hFind, &fb);
9042 #else
9043 ok = (findnext(&fb) == 0);
9044 #endif
9046 /* If no more matches and no match was used, try expanding the name
9047 * itself. Finds the long name of a short filename. */
9048 if (!ok && matchname != NULL && gap->ga_len == start_len)
9050 STRCPY(s, matchname);
9051 #ifdef WIN3264
9052 FindClose(hFind);
9053 # ifdef FEAT_MBYTE
9054 if (wn != NULL)
9056 vim_free(wn);
9057 wn = enc_to_utf16(buf, NULL);
9058 if (wn != NULL)
9059 hFind = FindFirstFileW(wn, &wfb);
9061 if (wn == NULL)
9062 # endif
9063 hFind = FindFirstFile(buf, &fb);
9064 ok = (hFind != INVALID_HANDLE_VALUE);
9065 #else
9066 ok = (findfirst((char *)buf, &fb,
9067 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9068 #endif
9069 vim_free(matchname);
9070 matchname = NULL;
9074 #ifdef WIN3264
9075 FindClose(hFind);
9076 # ifdef FEAT_MBYTE
9077 vim_free(wn);
9078 # endif
9079 #endif
9080 vim_free(buf);
9081 vim_free(regmatch.regprog);
9082 vim_free(matchname);
9084 matches = gap->ga_len - start_len;
9085 if (matches > 0)
9086 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9087 sizeof(char_u *), pstrcmp);
9088 return matches;
9092 mch_expandpath(
9093 garray_T *gap,
9094 char_u *path,
9095 int flags) /* EW_* flags */
9097 return dos_expandpath(gap, path, 0, flags, FALSE);
9099 # endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9101 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9102 || defined(PROTO)
9104 * Unix style wildcard expansion code.
9105 * It's here because it's used both for Unix and Mac.
9107 static int pstrcmp __ARGS((const void *, const void *));
9109 static int
9110 pstrcmp(a, b)
9111 const void *a, *b;
9113 return (pathcmp(*(char **)a, *(char **)b, -1));
9117 * Recursively expand one path component into all matching files and/or
9118 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9119 * "path" has backslashes before chars that are not to be expanded, starting
9120 * at "path + wildoff".
9121 * Return the number of matches found.
9122 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9125 unix_expandpath(gap, path, wildoff, flags, didstar)
9126 garray_T *gap;
9127 char_u *path;
9128 int wildoff;
9129 int flags; /* EW_* flags */
9130 int didstar; /* expanded "**" once already */
9132 char_u *buf;
9133 char_u *path_end;
9134 char_u *p, *s, *e;
9135 int start_len = gap->ga_len;
9136 char_u *pat;
9137 regmatch_T regmatch;
9138 int starts_with_dot;
9139 int matches;
9140 int len;
9141 int starstar = FALSE;
9142 static int stardepth = 0; /* depth for "**" expansion */
9144 DIR *dirp;
9145 struct dirent *dp;
9147 /* Expanding "**" may take a long time, check for CTRL-C. */
9148 if (stardepth > 0)
9150 ui_breakcheck();
9151 if (got_int)
9152 return 0;
9155 /* make room for file name */
9156 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9157 if (buf == NULL)
9158 return 0;
9161 * Find the first part in the path name that contains a wildcard.
9162 * Copy it into "buf", including the preceding characters.
9164 p = buf;
9165 s = buf;
9166 e = NULL;
9167 path_end = path;
9168 while (*path_end != NUL)
9170 /* May ignore a wildcard that has a backslash before it; it will
9171 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9172 if (path_end >= path + wildoff && rem_backslash(path_end))
9173 *p++ = *path_end++;
9174 else if (*path_end == '/')
9176 if (e != NULL)
9177 break;
9178 s = p + 1;
9180 else if (path_end >= path + wildoff
9181 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
9182 e = p;
9183 #ifdef FEAT_MBYTE
9184 if (has_mbyte)
9186 len = (*mb_ptr2len)(path_end);
9187 STRNCPY(p, path_end, len);
9188 p += len;
9189 path_end += len;
9191 else
9192 #endif
9193 *p++ = *path_end++;
9195 e = p;
9196 *e = NUL;
9198 /* now we have one wildcard component between "s" and "e" */
9199 /* Remove backslashes between "wildoff" and the start of the wildcard
9200 * component. */
9201 for (p = buf + wildoff; p < s; ++p)
9202 if (rem_backslash(p))
9204 STRMOVE(p, p + 1);
9205 --e;
9206 --s;
9209 /* Check for "**" between "s" and "e". */
9210 for (p = s; p < e; ++p)
9211 if (p[0] == '*' && p[1] == '*')
9212 starstar = TRUE;
9214 /* convert the file pattern to a regexp pattern */
9215 starts_with_dot = (*s == '.');
9216 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9217 if (pat == NULL)
9219 vim_free(buf);
9220 return 0;
9223 /* compile the regexp into a program */
9224 #ifdef CASE_INSENSITIVE_FILENAME
9225 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9226 #else
9227 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9228 #endif
9229 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9230 vim_free(pat);
9232 if (regmatch.regprog == NULL)
9234 vim_free(buf);
9235 return 0;
9238 /* If "**" is by itself, this is the first time we encounter it and more
9239 * is following then find matches without any directory. */
9240 if (!didstar && stardepth < 100 && starstar && e - s == 2
9241 && *path_end == '/')
9243 STRCPY(s, path_end + 1);
9244 ++stardepth;
9245 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9246 --stardepth;
9249 /* open the directory for scanning */
9250 *s = NUL;
9251 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9253 /* Find all matching entries */
9254 if (dirp != NULL)
9256 for (;;)
9258 dp = readdir(dirp);
9259 if (dp == NULL)
9260 break;
9261 if ((dp->d_name[0] != '.' || starts_with_dot)
9262 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
9264 STRCPY(s, dp->d_name);
9265 len = STRLEN(buf);
9267 if (starstar && stardepth < 100)
9269 /* For "**" in the pattern first go deeper in the tree to
9270 * find matches. */
9271 STRCPY(buf + len, "/**");
9272 STRCPY(buf + len + 3, path_end);
9273 ++stardepth;
9274 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9275 --stardepth;
9278 STRCPY(buf + len, path_end);
9279 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9281 /* need to expand another component of the path */
9282 /* remove backslashes for the remaining components only */
9283 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9285 else
9287 /* no more wildcards, check if there is a match */
9288 /* remove backslashes for the remaining components only */
9289 if (*path_end != NUL)
9290 backslash_halve(buf + len + 1);
9291 if (mch_getperm(buf) >= 0) /* add existing file */
9293 #ifdef MACOS_CONVERT
9294 size_t precomp_len = STRLEN(buf)+1;
9295 char_u *precomp_buf =
9296 mac_precompose_path(buf, precomp_len, &precomp_len);
9298 if (precomp_buf)
9300 mch_memmove(buf, precomp_buf, precomp_len);
9301 vim_free(precomp_buf);
9303 #endif
9304 addfile(gap, buf, flags);
9310 closedir(dirp);
9313 vim_free(buf);
9314 vim_free(regmatch.regprog);
9316 matches = gap->ga_len - start_len;
9317 if (matches > 0)
9318 qsort(((char_u **)gap->ga_data) + start_len, matches,
9319 sizeof(char_u *), pstrcmp);
9320 return matches;
9322 #endif
9325 * Generic wildcard expansion code.
9327 * Characters in "pat" that should not be expanded must be preceded with a
9328 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9330 * Return FAIL when no single file was found. In this case "num_file" is not
9331 * set, and "file" may contain an error message.
9332 * Return OK when some files found. "num_file" is set to the number of
9333 * matches, "file" to the array of matches. Call FreeWild() later.
9336 gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9337 int num_pat; /* number of input patterns */
9338 char_u **pat; /* array of input patterns */
9339 int *num_file; /* resulting number of files */
9340 char_u ***file; /* array of resulting files */
9341 int flags; /* EW_* flags */
9343 int i;
9344 garray_T ga;
9345 char_u *p;
9346 static int recursive = FALSE;
9347 int add_pat;
9350 * expand_env() is called to expand things like "~user". If this fails,
9351 * it calls ExpandOne(), which brings us back here. In this case, always
9352 * call the machine specific expansion function, if possible. Otherwise,
9353 * return FAIL.
9355 if (recursive)
9356 #ifdef SPECIAL_WILDCHAR
9357 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9358 #else
9359 return FAIL;
9360 #endif
9362 #ifdef SPECIAL_WILDCHAR
9364 * If there are any special wildcard characters which we cannot handle
9365 * here, call machine specific function for all the expansion. This
9366 * avoids starting the shell for each argument separately.
9367 * For `=expr` do use the internal function.
9369 for (i = 0; i < num_pat; i++)
9371 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9372 # ifdef VIM_BACKTICK
9373 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9374 # endif
9376 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9378 #endif
9380 recursive = TRUE;
9383 * The matching file names are stored in a growarray. Init it empty.
9385 ga_init2(&ga, (int)sizeof(char_u *), 30);
9387 for (i = 0; i < num_pat; ++i)
9389 add_pat = -1;
9390 p = pat[i];
9392 #ifdef VIM_BACKTICK
9393 if (vim_backtick(p))
9394 add_pat = expand_backtick(&ga, p, flags);
9395 else
9396 #endif
9399 * First expand environment variables, "~/" and "~user/".
9401 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9403 p = expand_env_save_opt(p, TRUE);
9404 if (p == NULL)
9405 p = pat[i];
9406 #ifdef UNIX
9408 * On Unix, if expand_env() can't expand an environment
9409 * variable, use the shell to do that. Discard previously
9410 * found file names and start all over again.
9412 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9414 vim_free(p);
9415 ga_clear_strings(&ga);
9416 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9417 flags);
9418 recursive = FALSE;
9419 return i;
9421 #endif
9425 * If there are wildcards: Expand file names and add each match to
9426 * the list. If there is no match, and EW_NOTFOUND is given, add
9427 * the pattern.
9428 * If there are no wildcards: Add the file name if it exists or
9429 * when EW_NOTFOUND is given.
9431 if (mch_has_exp_wildcard(p))
9432 add_pat = mch_expandpath(&ga, p, flags);
9435 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9437 char_u *t = backslash_halve_save(p);
9439 #if defined(MACOS_CLASSIC)
9440 slash_to_colon(t);
9441 #endif
9442 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9443 * "vim c:/" work. */
9444 if (flags & EW_NOTFOUND)
9445 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9446 else if (mch_getperm(t) >= 0)
9447 addfile(&ga, t, flags);
9448 vim_free(t);
9451 if (p != pat[i])
9452 vim_free(p);
9455 *num_file = ga.ga_len;
9456 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9458 recursive = FALSE;
9460 return (ga.ga_data != NULL) ? OK : FAIL;
9463 # ifdef VIM_BACKTICK
9466 * Return TRUE if we can expand this backtick thing here.
9468 static int
9469 vim_backtick(p)
9470 char_u *p;
9472 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9476 * Expand an item in `backticks` by executing it as a command.
9477 * Currently only works when pat[] starts and ends with a `.
9478 * Returns number of file names found.
9480 static int
9481 expand_backtick(gap, pat, flags)
9482 garray_T *gap;
9483 char_u *pat;
9484 int flags; /* EW_* flags */
9486 char_u *p;
9487 char_u *cmd;
9488 char_u *buffer;
9489 int cnt = 0;
9490 int i;
9492 /* Create the command: lop off the backticks. */
9493 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9494 if (cmd == NULL)
9495 return 0;
9497 #ifdef FEAT_EVAL
9498 if (*cmd == '=') /* `={expr}`: Expand expression */
9499 buffer = eval_to_string(cmd + 1, &p, TRUE);
9500 else
9501 #endif
9502 buffer = get_cmd_output(cmd, NULL,
9503 (flags & EW_SILENT) ? SHELL_SILENT : 0);
9504 vim_free(cmd);
9505 if (buffer == NULL)
9506 return 0;
9508 cmd = buffer;
9509 while (*cmd != NUL)
9511 cmd = skipwhite(cmd); /* skip over white space */
9512 p = cmd;
9513 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9514 ++p;
9515 /* add an entry if it is not empty */
9516 if (p > cmd)
9518 i = *p;
9519 *p = NUL;
9520 addfile(gap, cmd, flags);
9521 *p = i;
9522 ++cnt;
9524 cmd = p;
9525 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9526 ++cmd;
9529 vim_free(buffer);
9530 return cnt;
9532 # endif /* VIM_BACKTICK */
9535 * Add a file to a file list. Accepted flags:
9536 * EW_DIR add directories
9537 * EW_FILE add files
9538 * EW_EXEC add executable files
9539 * EW_NOTFOUND add even when it doesn't exist
9540 * EW_ADDSLASH add slash after directory name
9542 void
9543 addfile(gap, f, flags)
9544 garray_T *gap;
9545 char_u *f; /* filename */
9546 int flags;
9548 char_u *p;
9549 int isdir;
9551 /* if the file/dir doesn't exist, may not add it */
9552 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9553 return;
9555 #ifdef FNAME_ILLEGAL
9556 /* if the file/dir contains illegal characters, don't add it */
9557 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9558 return;
9559 #endif
9561 isdir = mch_isdir(f);
9562 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9563 return;
9565 /* If the file isn't executable, may not add it. Do accept directories. */
9566 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9567 return;
9569 /* Make room for another item in the file list. */
9570 if (ga_grow(gap, 1) == FAIL)
9571 return;
9573 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9574 if (p == NULL)
9575 return;
9577 STRCPY(p, f);
9578 #ifdef BACKSLASH_IN_FILENAME
9579 slash_adjust(p);
9580 #endif
9582 * Append a slash or backslash after directory names if none is present.
9584 #ifndef DONT_ADD_PATHSEP_TO_DIR
9585 if (isdir && (flags & EW_ADDSLASH))
9586 add_pathsep(p);
9587 #endif
9588 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
9590 #endif /* !NO_EXPANDPATH */
9592 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9594 #ifndef SEEK_SET
9595 # define SEEK_SET 0
9596 #endif
9597 #ifndef SEEK_END
9598 # define SEEK_END 2
9599 #endif
9602 * Get the stdout of an external command.
9603 * Returns an allocated string, or NULL for error.
9605 char_u *
9606 get_cmd_output(cmd, infile, flags)
9607 char_u *cmd;
9608 char_u *infile; /* optional input file name */
9609 int flags; /* can be SHELL_SILENT */
9611 char_u *tempname;
9612 char_u *command;
9613 char_u *buffer = NULL;
9614 int len;
9615 int i = 0;
9616 FILE *fd;
9618 if (check_restricted() || check_secure())
9619 return NULL;
9621 /* get a name for the temp file */
9622 if ((tempname = vim_tempname('o')) == NULL)
9624 EMSG(_(e_notmp));
9625 return NULL;
9628 /* Add the redirection stuff */
9629 command = make_filter_cmd(cmd, infile, tempname);
9630 if (command == NULL)
9631 goto done;
9634 * Call the shell to execute the command (errors are ignored).
9635 * Don't check timestamps here.
9637 ++no_check_timestamps;
9638 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9639 --no_check_timestamps;
9641 vim_free(command);
9644 * read the names from the file into memory
9646 # ifdef VMS
9647 /* created temporary file is not always readable as binary */
9648 fd = mch_fopen((char *)tempname, "r");
9649 # else
9650 fd = mch_fopen((char *)tempname, READBIN);
9651 # endif
9653 if (fd == NULL)
9655 EMSG2(_(e_notopen), tempname);
9656 goto done;
9659 fseek(fd, 0L, SEEK_END);
9660 len = ftell(fd); /* get size of temp file */
9661 fseek(fd, 0L, SEEK_SET);
9663 buffer = alloc(len + 1);
9664 if (buffer != NULL)
9665 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9666 fclose(fd);
9667 mch_remove(tempname);
9668 if (buffer == NULL)
9669 goto done;
9670 #ifdef VMS
9671 len = i; /* VMS doesn't give us what we asked for... */
9672 #endif
9673 if (i != len)
9675 EMSG2(_(e_notread), tempname);
9676 vim_free(buffer);
9677 buffer = NULL;
9679 else
9680 buffer[len] = '\0'; /* make sure the buffer is terminated */
9682 done:
9683 vim_free(tempname);
9684 return buffer;
9686 #endif
9689 * Free the list of files returned by expand_wildcards() or other expansion
9690 * functions.
9692 void
9693 FreeWild(count, files)
9694 int count;
9695 char_u **files;
9697 if (count <= 0 || files == NULL)
9698 return;
9699 #if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9701 * Is this still OK for when other functions than expand_wildcards() have
9702 * been used???
9704 _fnexplodefree((char **)files);
9705 #else
9706 while (count--)
9707 vim_free(files[count]);
9708 vim_free(files);
9709 #endif
9713 * return TRUE when need to go to Insert mode because of 'insertmode'.
9714 * Don't do this when still processing a command or a mapping.
9715 * Don't do this when inside a ":normal" command.
9718 goto_im()
9720 return (p_im && stuff_empty() && typebuf_typed());