Merge branch 'vim-with-runtime' into feat/var-tabstops
[vim_extended.git] / src / misc1.c
blob0486ee67a2ed23b3438962ed9ae30647432082de
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;
6419 if (*options == ',')
6420 ++options;
6423 /* remember where the cursor was when we started */
6424 cur_curpos = curwin->w_cursor;
6426 /* Get a copy of the current contents of the line.
6427 * This is required, because only the most recent line obtained with
6428 * ml_get is valid! */
6429 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6430 if (linecopy == NULL)
6431 return 0;
6434 * In insert mode and the cursor is on a ')' truncate the line at the
6435 * cursor position. We don't want to line up with the matching '(' when
6436 * inserting new stuff.
6437 * For unknown reasons the cursor might be past the end of the line, thus
6438 * check for that.
6440 if ((State & INSERT)
6441 && curwin->w_cursor.col < (colnr_T)STRLEN(linecopy)
6442 && linecopy[curwin->w_cursor.col] == ')')
6443 linecopy[curwin->w_cursor.col] = NUL;
6445 theline = skipwhite(linecopy);
6447 /* move the cursor to the start of the line */
6449 curwin->w_cursor.col = 0;
6452 * #defines and so on always go at the left when included in 'cinkeys'.
6454 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6456 amount = 0;
6460 * Is it a non-case label? Then that goes at the left margin too.
6462 else if (cin_islabel(ind_maxcomment)) /* XXX */
6464 amount = 0;
6468 * If we're inside a "//" comment and there is a "//" comment in a
6469 * previous line, lineup with that one.
6471 else if (cin_islinecomment(theline)
6472 && (trypos = find_line_comment()) != NULL) /* XXX */
6474 /* find how indented the line beginning the comment is */
6475 getvcol(curwin, trypos, &col, NULL, NULL);
6476 amount = col;
6480 * If we're inside a comment and not looking at the start of the
6481 * comment, try using the 'comments' option.
6483 else if (!cin_iscomment(theline)
6484 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6486 int lead_start_len = 2;
6487 int lead_middle_len = 1;
6488 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6489 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6490 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6491 char_u *p;
6492 int start_align = 0;
6493 int start_off = 0;
6494 int done = FALSE;
6496 /* find how indented the line beginning the comment is */
6497 getvcol(curwin, trypos, &col, NULL, NULL);
6498 amount = col;
6500 p = curbuf->b_p_com;
6501 while (*p != NUL)
6503 int align = 0;
6504 int off = 0;
6505 int what = 0;
6507 while (*p != NUL && *p != ':')
6509 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6510 what = *p++;
6511 else if (*p == COM_LEFT || *p == COM_RIGHT)
6512 align = *p++;
6513 else if (VIM_ISDIGIT(*p) || *p == '-')
6514 off = getdigits(&p);
6515 else
6516 ++p;
6519 if (*p == ':')
6520 ++p;
6521 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6522 if (what == COM_START)
6524 STRCPY(lead_start, lead_end);
6525 lead_start_len = (int)STRLEN(lead_start);
6526 start_off = off;
6527 start_align = align;
6529 else if (what == COM_MIDDLE)
6531 STRCPY(lead_middle, lead_end);
6532 lead_middle_len = (int)STRLEN(lead_middle);
6534 else if (what == COM_END)
6536 /* If our line starts with the middle comment string, line it
6537 * up with the comment opener per the 'comments' option. */
6538 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6539 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6541 done = TRUE;
6542 if (curwin->w_cursor.lnum > 1)
6544 /* If the start comment string matches in the previous
6545 * line, use the indent of that line plus offset. If
6546 * the middle comment string matches in the previous
6547 * line, use the indent of that line. XXX */
6548 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6549 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6550 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6551 else if (STRNCMP(look, lead_middle,
6552 lead_middle_len) == 0)
6554 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6555 break;
6557 /* If the start comment string doesn't match with the
6558 * start of the comment, skip this entry. XXX */
6559 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6560 lead_start, lead_start_len) != 0)
6561 continue;
6563 if (start_off != 0)
6564 amount += start_off;
6565 else if (start_align == COM_RIGHT)
6566 amount += vim_strsize(lead_start)
6567 - vim_strsize(lead_middle);
6568 break;
6571 /* If our line starts with the end comment string, line it up
6572 * with the middle comment */
6573 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6574 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6576 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6577 /* XXX */
6578 if (off != 0)
6579 amount += off;
6580 else if (align == COM_RIGHT)
6581 amount += vim_strsize(lead_start)
6582 - vim_strsize(lead_middle);
6583 done = TRUE;
6584 break;
6589 /* If our line starts with an asterisk, line up with the
6590 * asterisk in the comment opener; otherwise, line up
6591 * with the first character of the comment text.
6593 if (done)
6595 else if (theline[0] == '*')
6596 amount += 1;
6597 else
6600 * If we are more than one line away from the comment opener, take
6601 * the indent of the previous non-empty line. If 'cino' has "CO"
6602 * and we are just below the comment opener and there are any
6603 * white characters after it line up with the text after it;
6604 * otherwise, add the amount specified by "c" in 'cino'
6606 amount = -1;
6607 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6609 if (linewhite(lnum)) /* skip blank lines */
6610 continue;
6611 amount = get_indent_lnum(lnum); /* XXX */
6612 break;
6614 if (amount == -1) /* use the comment opener */
6616 if (!ind_in_comment2)
6618 start = ml_get(trypos->lnum);
6619 look = start + trypos->col + 2; /* skip / and * */
6620 if (*look != NUL) /* if something after it */
6621 trypos->col = (colnr_T)(skipwhite(look) - start);
6623 getvcol(curwin, trypos, &col, NULL, NULL);
6624 amount = col;
6625 if (ind_in_comment2 || *look == NUL)
6626 amount += ind_in_comment;
6632 * Are we inside parentheses or braces?
6633 */ /* XXX */
6634 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6635 && ind_java == 0)
6636 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6637 || trypos != NULL)
6639 if (trypos != NULL && tryposBrace != NULL)
6641 /* Both an unmatched '(' and '{' is found. Use the one which is
6642 * closer to the current cursor position, set the other to NULL. */
6643 if (trypos->lnum != tryposBrace->lnum
6644 ? trypos->lnum < tryposBrace->lnum
6645 : trypos->col < tryposBrace->col)
6646 trypos = NULL;
6647 else
6648 tryposBrace = NULL;
6651 if (trypos != NULL)
6654 * If the matching paren is more than one line away, use the indent of
6655 * a previous non-empty line that matches the same paren.
6657 if (theline[0] == ')' && ind_paren_prev)
6659 /* Line up with the start of the matching paren line. */
6660 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6662 else
6664 amount = -1;
6665 our_paren_pos = *trypos;
6666 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
6668 l = skipwhite(ml_get(lnum));
6669 if (cin_nocode(l)) /* skip comment lines */
6670 continue;
6671 if (cin_ispreproc_cont(&l, &lnum))
6672 continue; /* ignore #define, #if, etc. */
6673 curwin->w_cursor.lnum = lnum;
6675 /* Skip a comment. XXX */
6676 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6678 lnum = trypos->lnum + 1;
6679 continue;
6682 /* XXX */
6683 if ((trypos = find_match_paren(
6684 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6685 ind_maxcomment)) != NULL
6686 && trypos->lnum == our_paren_pos.lnum
6687 && trypos->col == our_paren_pos.col)
6689 amount = get_indent_lnum(lnum); /* XXX */
6691 if (theline[0] == ')')
6693 if (our_paren_pos.lnum != lnum
6694 && cur_amount > amount)
6695 cur_amount = amount;
6696 amount = -1;
6698 break;
6704 * Line up with line where the matching paren is. XXX
6705 * If the line starts with a '(' or the indent for unclosed
6706 * parentheses is zero, line up with the unclosed parentheses.
6708 if (amount == -1)
6710 int ignore_paren_col = 0;
6712 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
6713 look = skipwhite(look);
6714 if (*look == '(')
6716 linenr_T save_lnum = curwin->w_cursor.lnum;
6717 char_u *line;
6718 int look_col;
6720 /* Ignore a '(' in front of the line that has a match before
6721 * our matching '('. */
6722 curwin->w_cursor.lnum = our_paren_pos.lnum;
6723 line = ml_get_curline();
6724 look_col = (int)(look - line);
6725 curwin->w_cursor.col = look_col + 1;
6726 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6727 != NULL
6728 && trypos->lnum == our_paren_pos.lnum
6729 && trypos->col < our_paren_pos.col)
6730 ignore_paren_col = trypos->col + 1;
6732 curwin->w_cursor.lnum = save_lnum;
6733 look = ml_get(our_paren_pos.lnum) + look_col;
6735 if (theline[0] == ')' || ind_unclosed == 0
6736 || (!ind_unclosed_noignore && *look == '('
6737 && ignore_paren_col == 0))
6740 * If we're looking at a close paren, line up right there;
6741 * otherwise, line up with the next (non-white) character.
6742 * When ind_unclosed_wrapped is set and the matching paren is
6743 * the last nonwhite character of the line, use either the
6744 * indent of the current line or the indentation of the next
6745 * outer paren and add ind_unclosed_wrapped (for very long
6746 * lines).
6748 if (theline[0] != ')')
6750 cur_amount = MAXCOL;
6751 l = ml_get(our_paren_pos.lnum);
6752 if (ind_unclosed_wrapped
6753 && cin_ends_in(l, (char_u *)"(", NULL))
6755 /* look for opening unmatched paren, indent one level
6756 * for each additional level */
6757 n = 1;
6758 for (col = 0; col < our_paren_pos.col; ++col)
6760 switch (l[col])
6762 case '(':
6763 case '{': ++n;
6764 break;
6766 case ')':
6767 case '}': if (n > 1)
6768 --n;
6769 break;
6773 our_paren_pos.col = 0;
6774 amount += n * ind_unclosed_wrapped;
6776 else if (ind_unclosed_whiteok)
6777 our_paren_pos.col++;
6778 else
6780 col = our_paren_pos.col + 1;
6781 while (vim_iswhite(l[col]))
6782 col++;
6783 if (l[col] != NUL) /* In case of trailing space */
6784 our_paren_pos.col = col;
6785 else
6786 our_paren_pos.col++;
6791 * Find how indented the paren is, or the character after it
6792 * if we did the above "if".
6794 if (our_paren_pos.col > 0)
6796 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6797 if (cur_amount > (int)col)
6798 cur_amount = col;
6802 if (theline[0] == ')' && ind_matching_paren)
6804 /* Line up with the start of the matching paren line. */
6806 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
6807 && *look == '(' && ignore_paren_col == 0))
6809 if (cur_amount != MAXCOL)
6810 amount = cur_amount;
6812 else
6814 /* Add ind_unclosed2 for each '(' before our matching one, but
6815 * ignore (void) before the line (ignore_paren_col). */
6816 col = our_paren_pos.col;
6817 while ((int)our_paren_pos.col > ignore_paren_col)
6819 --our_paren_pos.col;
6820 switch (*ml_get_pos(&our_paren_pos))
6822 case '(': amount += ind_unclosed2;
6823 col = our_paren_pos.col;
6824 break;
6825 case ')': amount -= ind_unclosed2;
6826 col = MAXCOL;
6827 break;
6831 /* Use ind_unclosed once, when the first '(' is not inside
6832 * braces */
6833 if (col == MAXCOL)
6834 amount += ind_unclosed;
6835 else
6837 curwin->w_cursor.lnum = our_paren_pos.lnum;
6838 curwin->w_cursor.col = col;
6839 if ((trypos = find_match_paren(ind_maxparen,
6840 ind_maxcomment)) != NULL)
6841 amount += ind_unclosed2;
6842 else
6843 amount += ind_unclosed;
6846 * For a line starting with ')' use the minimum of the two
6847 * positions, to avoid giving it more indent than the previous
6848 * lines:
6849 * func_long_name( if (x
6850 * arg && yy
6851 * ) ^ not here ) ^ not here
6853 if (cur_amount < amount)
6854 amount = cur_amount;
6858 /* add extra indent for a comment */
6859 if (cin_iscomment(theline))
6860 amount += ind_comment;
6864 * Are we at least inside braces, then?
6866 else
6868 trypos = tryposBrace;
6870 ourscope = trypos->lnum;
6871 start = ml_get(ourscope);
6874 * Now figure out how indented the line is in general.
6875 * If the brace was at the start of the line, we use that;
6876 * otherwise, check out the indentation of the line as
6877 * a whole and then add the "imaginary indent" to that.
6879 look = skipwhite(start);
6880 if (*look == '{')
6882 getvcol(curwin, trypos, &col, NULL, NULL);
6883 amount = col;
6884 if (*start == '{')
6885 start_brace = BRACE_IN_COL0;
6886 else
6887 start_brace = BRACE_AT_START;
6889 else
6892 * that opening brace might have been on a continuation
6893 * line. if so, find the start of the line.
6895 curwin->w_cursor.lnum = ourscope;
6898 * position the cursor over the rightmost paren, so that
6899 * matching it will take us back to the start of the line.
6901 lnum = ourscope;
6902 if (find_last_paren(start, '(', ')')
6903 && (trypos = find_match_paren(ind_maxparen,
6904 ind_maxcomment)) != NULL)
6905 lnum = trypos->lnum;
6908 * It could have been something like
6909 * case 1: if (asdf &&
6910 * ldfd) {
6913 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6914 amount = get_indent();
6915 else
6916 amount = skip_label(lnum, &l, ind_maxcomment);
6918 start_brace = BRACE_AT_END;
6922 * if we're looking at a closing brace, that's where
6923 * we want to be. otherwise, add the amount of room
6924 * that an indent is supposed to be.
6926 if (theline[0] == '}')
6929 * they may want closing braces to line up with something
6930 * other than the open brace. indulge them, if so.
6932 amount += ind_close_extra;
6934 else
6937 * If we're looking at an "else", try to find an "if"
6938 * to match it with.
6939 * If we're looking at a "while", try to find a "do"
6940 * to match it with.
6942 lookfor = LOOKFOR_INITIAL;
6943 if (cin_iselse(theline))
6944 lookfor = LOOKFOR_IF;
6945 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6946 /* XXX */
6947 lookfor = LOOKFOR_DO;
6948 if (lookfor != LOOKFOR_INITIAL)
6950 curwin->w_cursor.lnum = cur_curpos.lnum;
6951 if (find_match(lookfor, ourscope, ind_maxparen,
6952 ind_maxcomment) == OK)
6954 amount = get_indent(); /* XXX */
6955 goto theend;
6960 * We get here if we are not on an "while-of-do" or "else" (or
6961 * failed to find a matching "if").
6962 * Search backwards for something to line up with.
6963 * First set amount for when we don't find anything.
6967 * if the '{' is _really_ at the left margin, use the imaginary
6968 * location of a left-margin brace. Otherwise, correct the
6969 * location for ind_open_extra.
6972 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6974 amount = ind_open_left_imag;
6976 else
6978 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6979 amount += ind_open_imag;
6980 else
6982 /* Compensate for adding ind_open_extra later. */
6983 amount -= ind_open_extra;
6984 if (amount < 0)
6985 amount = 0;
6989 lookfor_break = FALSE;
6991 if (cin_iscase(theline)) /* it's a switch() label */
6993 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6994 amount += ind_case;
6996 else if (cin_isscopedecl(theline)) /* private:, ... */
6998 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6999 amount += ind_scopedecl;
7001 else
7003 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
7004 lookfor_break = TRUE;
7006 lookfor = LOOKFOR_INITIAL;
7007 amount += ind_level; /* ind_level from start of block */
7009 scope_amount = amount;
7010 whilelevel = 0;
7013 * Search backwards. If we find something we recognize, line up
7014 * with that.
7016 * if we're looking at an open brace, indent
7017 * the usual amount relative to the conditional
7018 * that opens the block.
7020 curwin->w_cursor = cur_curpos;
7021 for (;;)
7023 curwin->w_cursor.lnum--;
7024 curwin->w_cursor.col = 0;
7027 * If we went all the way back to the start of our scope, line
7028 * up with it.
7030 if (curwin->w_cursor.lnum <= ourscope)
7032 /* we reached end of scope:
7033 * if looking for a enum or structure initialization
7034 * go further back:
7035 * if it is an initializer (enum xxx or xxx =), then
7036 * don't add ind_continuation, otherwise it is a variable
7037 * declaration:
7038 * int x,
7039 * here; <-- add ind_continuation
7041 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7043 if (curwin->w_cursor.lnum == 0
7044 || curwin->w_cursor.lnum
7045 < ourscope - ind_maxparen)
7047 /* nothing found (abuse ind_maxparen as limit)
7048 * assume terminated line (i.e. a variable
7049 * initialization) */
7050 if (cont_amount > 0)
7051 amount = cont_amount;
7052 else
7053 amount += ind_continuation;
7054 break;
7057 l = ml_get_curline();
7060 * If we're in a comment now, skip to the start of the
7061 * comment.
7063 trypos = find_start_comment(ind_maxcomment);
7064 if (trypos != NULL)
7066 curwin->w_cursor.lnum = trypos->lnum + 1;
7067 curwin->w_cursor.col = 0;
7068 continue;
7072 * Skip preprocessor directives and blank lines.
7074 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7075 continue;
7077 if (cin_nocode(l))
7078 continue;
7080 terminated = cin_isterminated(l, FALSE, TRUE);
7083 * If we are at top level and the line looks like a
7084 * function declaration, we are done
7085 * (it's a variable declaration).
7087 if (start_brace != BRACE_IN_COL0
7088 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7090 /* if the line is terminated with another ','
7091 * it is a continued variable initialization.
7092 * don't add extra indent.
7093 * TODO: does not work, if a function
7094 * declaration is split over multiple lines:
7095 * cin_isfuncdecl returns FALSE then.
7097 if (terminated == ',')
7098 break;
7100 /* if it es a enum declaration or an assignment,
7101 * we are done.
7103 if (terminated != ';' && cin_isinit())
7104 break;
7106 /* nothing useful found */
7107 if (terminated == 0 || terminated == '{')
7108 continue;
7111 if (terminated != ';')
7113 /* Skip parens and braces. Position the cursor
7114 * over the rightmost paren, so that matching it
7115 * will take us back to the start of the line.
7116 */ /* XXX */
7117 trypos = NULL;
7118 if (find_last_paren(l, '(', ')'))
7119 trypos = find_match_paren(ind_maxparen,
7120 ind_maxcomment);
7122 if (trypos == NULL && find_last_paren(l, '{', '}'))
7123 trypos = find_start_brace(ind_maxcomment);
7125 if (trypos != NULL)
7127 curwin->w_cursor.lnum = trypos->lnum + 1;
7128 curwin->w_cursor.col = 0;
7129 continue;
7133 /* it's a variable declaration, add indentation
7134 * like in
7135 * int a,
7136 * b;
7138 if (cont_amount > 0)
7139 amount = cont_amount;
7140 else
7141 amount += ind_continuation;
7143 else if (lookfor == LOOKFOR_UNTERM)
7145 if (cont_amount > 0)
7146 amount = cont_amount;
7147 else
7148 amount += ind_continuation;
7150 else if (lookfor != LOOKFOR_TERM
7151 && lookfor != LOOKFOR_CPP_BASECLASS)
7153 amount = scope_amount;
7154 if (theline[0] == '{')
7155 amount += ind_open_extra;
7157 break;
7161 * If we're in a comment now, skip to the start of the comment.
7162 */ /* XXX */
7163 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7165 curwin->w_cursor.lnum = trypos->lnum + 1;
7166 curwin->w_cursor.col = 0;
7167 continue;
7170 l = ml_get_curline();
7173 * If this is a switch() label, may line up relative to that.
7174 * If this is a C++ scope declaration, do the same.
7176 iscase = cin_iscase(l);
7177 if (iscase || cin_isscopedecl(l))
7179 /* we are only looking for cpp base class
7180 * declaration/initialization any longer */
7181 if (lookfor == LOOKFOR_CPP_BASECLASS)
7182 break;
7184 /* When looking for a "do" we are not interested in
7185 * labels. */
7186 if (whilelevel > 0)
7187 continue;
7190 * case xx:
7191 * c = 99 + <- this indent plus continuation
7192 *-> here;
7194 if (lookfor == LOOKFOR_UNTERM
7195 || lookfor == LOOKFOR_ENUM_OR_INIT)
7197 if (cont_amount > 0)
7198 amount = cont_amount;
7199 else
7200 amount += ind_continuation;
7201 break;
7205 * case xx: <- line up with this case
7206 * x = 333;
7207 * case yy:
7209 if ( (iscase && lookfor == LOOKFOR_CASE)
7210 || (iscase && lookfor_break)
7211 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
7214 * Check that this case label is not for another
7215 * switch()
7216 */ /* XXX */
7217 if ((trypos = find_start_brace(ind_maxcomment)) ==
7218 NULL || trypos->lnum == ourscope)
7220 amount = get_indent(); /* XXX */
7221 break;
7223 continue;
7226 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
7229 * case xx: if (cond) <- line up with this if
7230 * y = y + 1;
7231 * -> s = 99;
7233 * case xx:
7234 * if (cond) <- line up with this line
7235 * y = y + 1;
7236 * -> s = 99;
7238 if (lookfor == LOOKFOR_TERM)
7240 if (n)
7241 amount = n;
7243 if (!lookfor_break)
7244 break;
7248 * case xx: x = x + 1; <- line up with this x
7249 * -> y = y + 1;
7251 * case xx: if (cond) <- line up with this if
7252 * -> y = y + 1;
7254 if (n)
7256 amount = n;
7257 l = after_label(ml_get_curline());
7258 if (l != NULL && cin_is_cinword(l))
7260 if (theline[0] == '{')
7261 amount += ind_open_extra;
7262 else
7263 amount += ind_level + ind_no_brace;
7265 break;
7269 * Try to get the indent of a statement before the switch
7270 * label. If nothing is found, line up relative to the
7271 * switch label.
7272 * break; <- may line up with this line
7273 * case xx:
7274 * -> y = 1;
7276 scope_amount = get_indent() + (iscase /* XXX */
7277 ? ind_case_code : ind_scopedecl_code);
7278 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7279 continue;
7283 * Looking for a switch() label or C++ scope declaration,
7284 * ignore other lines, skip {}-blocks.
7286 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7288 if (find_last_paren(l, '{', '}') && (trypos =
7289 find_start_brace(ind_maxcomment)) != NULL)
7291 curwin->w_cursor.lnum = trypos->lnum + 1;
7292 curwin->w_cursor.col = 0;
7294 continue;
7298 * Ignore jump labels with nothing after them.
7300 if (cin_islabel(ind_maxcomment))
7302 l = after_label(ml_get_curline());
7303 if (l == NULL || cin_nocode(l))
7304 continue;
7308 * Ignore #defines, #if, etc.
7309 * Ignore comment and empty lines.
7310 * (need to get the line again, cin_islabel() may have
7311 * unlocked it)
7313 l = ml_get_curline();
7314 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7315 || cin_nocode(l))
7316 continue;
7319 * Are we at the start of a cpp base class declaration or
7320 * constructor initialization?
7321 */ /* XXX */
7322 n = FALSE;
7323 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7325 n = cin_is_cpp_baseclass(&col);
7326 l = ml_get_curline();
7328 if (n)
7330 if (lookfor == LOOKFOR_UNTERM)
7332 if (cont_amount > 0)
7333 amount = cont_amount;
7334 else
7335 amount += ind_continuation;
7337 else if (theline[0] == '{')
7339 /* Need to find start of the declaration. */
7340 lookfor = LOOKFOR_UNTERM;
7341 ind_continuation = 0;
7342 continue;
7344 else
7345 /* XXX */
7346 amount = get_baseclass_amount(col, ind_maxparen,
7347 ind_maxcomment, ind_cpp_baseclass);
7348 break;
7350 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7352 /* only look, whether there is a cpp base class
7353 * declaration or initialization before the opening brace.
7355 if (cin_isterminated(l, TRUE, FALSE))
7356 break;
7357 else
7358 continue;
7362 * What happens next depends on the line being terminated.
7363 * If terminated with a ',' only consider it terminating if
7364 * there is another unterminated statement behind, eg:
7365 * 123,
7366 * sizeof
7367 * here
7368 * Otherwise check whether it is a enumeration or structure
7369 * initialisation (not indented) or a variable declaration
7370 * (indented).
7372 terminated = cin_isterminated(l, FALSE, TRUE);
7374 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7375 && terminated == ','))
7378 * if we're in the middle of a paren thing,
7379 * go back to the line that starts it so
7380 * we can get the right prevailing indent
7381 * if ( foo &&
7382 * bar )
7385 * position the cursor over the rightmost paren, so that
7386 * matching it will take us back to the start of the line.
7388 (void)find_last_paren(l, '(', ')');
7389 trypos = find_match_paren(
7390 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7391 ind_maxcomment);
7394 * If we are looking for ',', we also look for matching
7395 * braces.
7397 if (trypos == NULL && terminated == ','
7398 && find_last_paren(l, '{', '}'))
7399 trypos = find_start_brace(ind_maxcomment);
7401 if (trypos != NULL)
7404 * Check if we are on a case label now. This is
7405 * handled above.
7406 * case xx: if ( asdf &&
7407 * asdf)
7409 curwin->w_cursor = *trypos;
7410 l = ml_get_curline();
7411 if (cin_iscase(l) || cin_isscopedecl(l))
7413 ++curwin->w_cursor.lnum;
7414 curwin->w_cursor.col = 0;
7415 continue;
7420 * Skip over continuation lines to find the one to get the
7421 * indent from
7422 * char *usethis = "bla\
7423 * bla",
7424 * here;
7426 if (terminated == ',')
7428 while (curwin->w_cursor.lnum > 1)
7430 l = ml_get(curwin->w_cursor.lnum - 1);
7431 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7432 break;
7433 --curwin->w_cursor.lnum;
7434 curwin->w_cursor.col = 0;
7439 * Get indent and pointer to text for current line,
7440 * ignoring any jump label. XXX
7442 cur_amount = skip_label(curwin->w_cursor.lnum,
7443 &l, ind_maxcomment);
7446 * If this is just above the line we are indenting, and it
7447 * starts with a '{', line it up with this line.
7448 * while (not)
7449 * -> {
7452 if (terminated != ',' && lookfor != LOOKFOR_TERM
7453 && theline[0] == '{')
7455 amount = cur_amount;
7457 * Only add ind_open_extra when the current line
7458 * doesn't start with a '{', which must have a match
7459 * in the same line (scope is the same). Probably:
7460 * { 1, 2 },
7461 * -> { 3, 4 }
7463 if (*skipwhite(l) != '{')
7464 amount += ind_open_extra;
7466 if (ind_cpp_baseclass)
7468 /* have to look back, whether it is a cpp base
7469 * class declaration or initialization */
7470 lookfor = LOOKFOR_CPP_BASECLASS;
7471 continue;
7473 break;
7477 * Check if we are after an "if", "while", etc.
7478 * Also allow " } else".
7480 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7483 * Found an unterminated line after an if (), line up
7484 * with the last one.
7485 * if (cond)
7486 * 100 +
7487 * -> here;
7489 if (lookfor == LOOKFOR_UNTERM
7490 || lookfor == LOOKFOR_ENUM_OR_INIT)
7492 if (cont_amount > 0)
7493 amount = cont_amount;
7494 else
7495 amount += ind_continuation;
7496 break;
7500 * If this is just above the line we are indenting, we
7501 * are finished.
7502 * while (not)
7503 * -> here;
7504 * Otherwise this indent can be used when the line
7505 * before this is terminated.
7506 * yyy;
7507 * if (stat)
7508 * while (not)
7509 * xxx;
7510 * -> here;
7512 amount = cur_amount;
7513 if (theline[0] == '{')
7514 amount += ind_open_extra;
7515 if (lookfor != LOOKFOR_TERM)
7517 amount += ind_level + ind_no_brace;
7518 break;
7522 * Special trick: when expecting the while () after a
7523 * do, line up with the while()
7524 * do
7525 * x = 1;
7526 * -> here
7528 l = skipwhite(ml_get_curline());
7529 if (cin_isdo(l))
7531 if (whilelevel == 0)
7532 break;
7533 --whilelevel;
7537 * When searching for a terminated line, don't use the
7538 * one between the "if" and the "else".
7539 * Need to use the scope of this "else". XXX
7540 * If whilelevel != 0 continue looking for a "do {".
7542 if (cin_iselse(l)
7543 && whilelevel == 0
7544 && ((trypos = find_start_brace(ind_maxcomment))
7545 == NULL
7546 || find_match(LOOKFOR_IF, trypos->lnum,
7547 ind_maxparen, ind_maxcomment) == FAIL))
7548 break;
7552 * If we're below an unterminated line that is not an
7553 * "if" or something, we may line up with this line or
7554 * add something for a continuation line, depending on
7555 * the line before this one.
7557 else
7560 * Found two unterminated lines on a row, line up with
7561 * the last one.
7562 * c = 99 +
7563 * 100 +
7564 * -> here;
7566 if (lookfor == LOOKFOR_UNTERM)
7568 /* When line ends in a comma add extra indent */
7569 if (terminated == ',')
7570 amount += ind_continuation;
7571 break;
7574 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7576 /* Found two lines ending in ',', lineup with the
7577 * lowest one, but check for cpp base class
7578 * declaration/initialization, if it is an
7579 * opening brace or we are looking just for
7580 * enumerations/initializations. */
7581 if (terminated == ',')
7583 if (ind_cpp_baseclass == 0)
7584 break;
7586 lookfor = LOOKFOR_CPP_BASECLASS;
7587 continue;
7590 /* Ignore unterminated lines in between, but
7591 * reduce indent. */
7592 if (amount > cur_amount)
7593 amount = cur_amount;
7595 else
7598 * Found first unterminated line on a row, may
7599 * line up with this line, remember its indent
7600 * 100 +
7601 * -> here;
7603 amount = cur_amount;
7606 * If previous line ends in ',', check whether we
7607 * are in an initialization or enum
7608 * struct xxx =
7610 * sizeof a,
7611 * 124 };
7612 * or a normal possible continuation line.
7613 * but only, of no other statement has been found
7614 * yet.
7616 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7618 lookfor = LOOKFOR_ENUM_OR_INIT;
7619 cont_amount = cin_first_id_amount();
7621 else
7623 if (lookfor == LOOKFOR_INITIAL
7624 && *l != NUL
7625 && l[STRLEN(l) - 1] == '\\')
7626 /* XXX */
7627 cont_amount = cin_get_equal_amount(
7628 curwin->w_cursor.lnum);
7629 if (lookfor != LOOKFOR_TERM)
7630 lookfor = LOOKFOR_UNTERM;
7637 * Check if we are after a while (cond);
7638 * If so: Ignore until the matching "do".
7640 /* XXX */
7641 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7642 ind_maxcomment))
7645 * Found an unterminated line after a while ();, line up
7646 * with the last one.
7647 * while (cond);
7648 * 100 + <- line up with this one
7649 * -> here;
7651 if (lookfor == LOOKFOR_UNTERM
7652 || lookfor == LOOKFOR_ENUM_OR_INIT)
7654 if (cont_amount > 0)
7655 amount = cont_amount;
7656 else
7657 amount += ind_continuation;
7658 break;
7661 if (whilelevel == 0)
7663 lookfor = LOOKFOR_TERM;
7664 amount = get_indent(); /* XXX */
7665 if (theline[0] == '{')
7666 amount += ind_open_extra;
7668 ++whilelevel;
7672 * We are after a "normal" statement.
7673 * If we had another statement we can stop now and use the
7674 * indent of that other statement.
7675 * Otherwise the indent of the current statement may be used,
7676 * search backwards for the next "normal" statement.
7678 else
7681 * Skip single break line, if before a switch label. It
7682 * may be lined up with the case label.
7684 if (lookfor == LOOKFOR_NOBREAK
7685 && cin_isbreak(skipwhite(ml_get_curline())))
7687 lookfor = LOOKFOR_ANY;
7688 continue;
7692 * Handle "do {" line.
7694 if (whilelevel > 0)
7696 l = cin_skipcomment(ml_get_curline());
7697 if (cin_isdo(l))
7699 amount = get_indent(); /* XXX */
7700 --whilelevel;
7701 continue;
7706 * Found a terminated line above an unterminated line. Add
7707 * the amount for a continuation line.
7708 * x = 1;
7709 * y = foo +
7710 * -> here;
7711 * or
7712 * int x = 1;
7713 * int foo,
7714 * -> here;
7716 if (lookfor == LOOKFOR_UNTERM
7717 || lookfor == LOOKFOR_ENUM_OR_INIT)
7719 if (cont_amount > 0)
7720 amount = cont_amount;
7721 else
7722 amount += ind_continuation;
7723 break;
7727 * Found a terminated line above a terminated line or "if"
7728 * etc. line. Use the amount of the line below us.
7729 * x = 1; x = 1;
7730 * if (asdf) y = 2;
7731 * while (asdf) ->here;
7732 * here;
7733 * ->foo;
7735 if (lookfor == LOOKFOR_TERM)
7737 if (!lookfor_break && whilelevel == 0)
7738 break;
7742 * First line above the one we're indenting is terminated.
7743 * To know what needs to be done look further backward for
7744 * a terminated line.
7746 else
7749 * position the cursor over the rightmost paren, so
7750 * that matching it will take us back to the start of
7751 * the line. Helps for:
7752 * func(asdr,
7753 * asdfasdf);
7754 * here;
7756 term_again:
7757 l = ml_get_curline();
7758 if (find_last_paren(l, '(', ')')
7759 && (trypos = find_match_paren(ind_maxparen,
7760 ind_maxcomment)) != NULL)
7763 * Check if we are on a case label now. This is
7764 * handled above.
7765 * case xx: if ( asdf &&
7766 * asdf)
7768 curwin->w_cursor = *trypos;
7769 l = ml_get_curline();
7770 if (cin_iscase(l) || cin_isscopedecl(l))
7772 ++curwin->w_cursor.lnum;
7773 curwin->w_cursor.col = 0;
7774 continue;
7778 /* When aligning with the case statement, don't align
7779 * with a statement after it.
7780 * case 1: { <-- don't use this { position
7781 * stat;
7783 * case 2:
7784 * stat;
7787 iscase = (ind_keep_case_label && cin_iscase(l));
7790 * Get indent and pointer to text for current line,
7791 * ignoring any jump label.
7793 amount = skip_label(curwin->w_cursor.lnum,
7794 &l, ind_maxcomment);
7796 if (theline[0] == '{')
7797 amount += ind_open_extra;
7798 /* See remark above: "Only add ind_open_extra.." */
7799 l = skipwhite(l);
7800 if (*l == '{')
7801 amount -= ind_open_extra;
7802 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7805 * When a terminated line starts with "else" skip to
7806 * the matching "if":
7807 * else 3;
7808 * indent this;
7809 * Need to use the scope of this "else". XXX
7810 * If whilelevel != 0 continue looking for a "do {".
7812 if (lookfor == LOOKFOR_TERM
7813 && *l != '}'
7814 && cin_iselse(l)
7815 && whilelevel == 0)
7817 if ((trypos = find_start_brace(ind_maxcomment))
7818 == NULL
7819 || find_match(LOOKFOR_IF, trypos->lnum,
7820 ind_maxparen, ind_maxcomment) == FAIL)
7821 break;
7822 continue;
7826 * If we're at the end of a block, skip to the start of
7827 * that block.
7829 curwin->w_cursor.col = 0;
7830 if (*cin_skipcomment(l) == '}'
7831 && (trypos = find_start_brace(ind_maxcomment))
7832 != NULL) /* XXX */
7834 curwin->w_cursor = *trypos;
7835 /* if not "else {" check for terminated again */
7836 /* but skip block for "} else {" */
7837 l = cin_skipcomment(ml_get_curline());
7838 if (*l == '}' || !cin_iselse(l))
7839 goto term_again;
7840 ++curwin->w_cursor.lnum;
7841 curwin->w_cursor.col = 0;
7849 /* add extra indent for a comment */
7850 if (cin_iscomment(theline))
7851 amount += ind_comment;
7855 * ok -- we're not inside any sort of structure at all!
7857 * this means we're at the top level, and everything should
7858 * basically just match where the previous line is, except
7859 * for the lines immediately following a function declaration,
7860 * which are K&R-style parameters and need to be indented.
7862 else
7865 * if our line starts with an open brace, forget about any
7866 * prevailing indent and make sure it looks like the start
7867 * of a function
7870 if (theline[0] == '{')
7872 amount = ind_first_open;
7876 * If the NEXT line is a function declaration, the current
7877 * line needs to be indented as a function type spec.
7878 * Don't do this if the current line looks like a comment or if the
7879 * current line is terminated, ie. ends in ';', or if the current line
7880 * contains { or }: "void f() {\n if (1)"
7882 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7883 && !cin_nocode(theline)
7884 && vim_strchr(theline, '{') == NULL
7885 && vim_strchr(theline, '}') == NULL
7886 && !cin_ends_in(theline, (char_u *)":", NULL)
7887 && !cin_ends_in(theline, (char_u *)",", NULL)
7888 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7889 && !cin_isterminated(theline, FALSE, TRUE))
7891 amount = ind_func_type;
7893 else
7895 amount = 0;
7896 curwin->w_cursor = cur_curpos;
7898 /* search backwards until we find something we recognize */
7900 while (curwin->w_cursor.lnum > 1)
7902 curwin->w_cursor.lnum--;
7903 curwin->w_cursor.col = 0;
7905 l = ml_get_curline();
7908 * If we're in a comment now, skip to the start of the comment.
7909 */ /* XXX */
7910 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7912 curwin->w_cursor.lnum = trypos->lnum + 1;
7913 curwin->w_cursor.col = 0;
7914 continue;
7918 * Are we at the start of a cpp base class declaration or
7919 * constructor initialization?
7920 */ /* XXX */
7921 n = FALSE;
7922 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7924 n = cin_is_cpp_baseclass(&col);
7925 l = ml_get_curline();
7927 if (n)
7929 /* XXX */
7930 amount = get_baseclass_amount(col, ind_maxparen,
7931 ind_maxcomment, ind_cpp_baseclass);
7932 break;
7936 * Skip preprocessor directives and blank lines.
7938 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7939 continue;
7941 if (cin_nocode(l))
7942 continue;
7945 * If the previous line ends in ',', use one level of
7946 * indentation:
7947 * int foo,
7948 * bar;
7949 * do this before checking for '}' in case of eg.
7950 * enum foobar
7952 * ...
7953 * } foo,
7954 * bar;
7956 n = 0;
7957 if (cin_ends_in(l, (char_u *)",", NULL)
7958 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7960 /* take us back to opening paren */
7961 if (find_last_paren(l, '(', ')')
7962 && (trypos = find_match_paren(ind_maxparen,
7963 ind_maxcomment)) != NULL)
7964 curwin->w_cursor = *trypos;
7966 /* For a line ending in ',' that is a continuation line go
7967 * back to the first line with a backslash:
7968 * char *foo = "bla\
7969 * bla",
7970 * here;
7972 while (n == 0 && curwin->w_cursor.lnum > 1)
7974 l = ml_get(curwin->w_cursor.lnum - 1);
7975 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7976 break;
7977 --curwin->w_cursor.lnum;
7978 curwin->w_cursor.col = 0;
7981 amount = get_indent(); /* XXX */
7983 if (amount == 0)
7984 amount = cin_first_id_amount();
7985 if (amount == 0)
7986 amount = ind_continuation;
7987 break;
7991 * If the line looks like a function declaration, and we're
7992 * not in a comment, put it the left margin.
7994 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7995 break;
7996 l = ml_get_curline();
7999 * Finding the closing '}' of a previous function. Put
8000 * current line at the left margin. For when 'cino' has "fs".
8002 if (*skipwhite(l) == '}')
8003 break;
8005 /* (matching {)
8006 * If the previous line ends on '};' (maybe followed by
8007 * comments) align at column 0. For example:
8008 * char *string_array[] = { "foo",
8009 * / * x * / "b};ar" }; / * foobar * /
8011 if (cin_ends_in(l, (char_u *)"};", NULL))
8012 break;
8015 * If the PREVIOUS line is a function declaration, the current
8016 * line (and the ones that follow) needs to be indented as
8017 * parameters.
8019 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
8021 amount = ind_param;
8022 break;
8026 * If the previous line ends in ';' and the line before the
8027 * previous line ends in ',' or '\', ident to column zero:
8028 * int foo,
8029 * bar;
8030 * indent_to_0 here;
8032 if (cin_ends_in(l, (char_u *)";", NULL))
8034 l = ml_get(curwin->w_cursor.lnum - 1);
8035 if (cin_ends_in(l, (char_u *)",", NULL)
8036 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
8037 break;
8038 l = ml_get_curline();
8042 * Doesn't look like anything interesting -- so just
8043 * use the indent of this line.
8045 * Position the cursor over the rightmost paren, so that
8046 * matching it will take us back to the start of the line.
8048 find_last_paren(l, '(', ')');
8050 if ((trypos = find_match_paren(ind_maxparen,
8051 ind_maxcomment)) != NULL)
8052 curwin->w_cursor = *trypos;
8053 amount = get_indent(); /* XXX */
8054 break;
8057 /* add extra indent for a comment */
8058 if (cin_iscomment(theline))
8059 amount += ind_comment;
8061 /* add extra indent if the previous line ended in a backslash:
8062 * "asdfasdf\
8063 * here";
8064 * char *foo = "asdf\
8065 * here";
8067 if (cur_curpos.lnum > 1)
8069 l = ml_get(cur_curpos.lnum - 1);
8070 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
8072 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
8073 if (cur_amount > 0)
8074 amount = cur_amount;
8075 else if (cur_amount == 0)
8076 amount += ind_continuation;
8082 theend:
8083 /* put the cursor back where it belongs */
8084 curwin->w_cursor = cur_curpos;
8086 vim_free(linecopy);
8088 if (amount < 0)
8089 return 0;
8090 return amount;
8093 static int
8094 find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
8095 int lookfor;
8096 linenr_T ourscope;
8097 int ind_maxparen;
8098 int ind_maxcomment;
8100 char_u *look;
8101 pos_T *theirscope;
8102 char_u *mightbeif;
8103 int elselevel;
8104 int whilelevel;
8106 if (lookfor == LOOKFOR_IF)
8108 elselevel = 1;
8109 whilelevel = 0;
8111 else
8113 elselevel = 0;
8114 whilelevel = 1;
8117 curwin->w_cursor.col = 0;
8119 while (curwin->w_cursor.lnum > ourscope + 1)
8121 curwin->w_cursor.lnum--;
8122 curwin->w_cursor.col = 0;
8124 look = cin_skipcomment(ml_get_curline());
8125 if (cin_iselse(look)
8126 || cin_isif(look)
8127 || cin_isdo(look) /* XXX */
8128 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8131 * if we've gone outside the braces entirely,
8132 * we must be out of scope...
8134 theirscope = find_start_brace(ind_maxcomment); /* XXX */
8135 if (theirscope == NULL)
8136 break;
8139 * and if the brace enclosing this is further
8140 * back than the one enclosing the else, we're
8141 * out of luck too.
8143 if (theirscope->lnum < ourscope)
8144 break;
8147 * and if they're enclosed in a *deeper* brace,
8148 * then we can ignore it because it's in a
8149 * different scope...
8151 if (theirscope->lnum > ourscope)
8152 continue;
8155 * if it was an "else" (that's not an "else if")
8156 * then we need to go back to another if, so
8157 * increment elselevel
8159 look = cin_skipcomment(ml_get_curline());
8160 if (cin_iselse(look))
8162 mightbeif = cin_skipcomment(look + 4);
8163 if (!cin_isif(mightbeif))
8164 ++elselevel;
8165 continue;
8169 * if it was a "while" then we need to go back to
8170 * another "do", so increment whilelevel. XXX
8172 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
8174 ++whilelevel;
8175 continue;
8178 /* If it's an "if" decrement elselevel */
8179 look = cin_skipcomment(ml_get_curline());
8180 if (cin_isif(look))
8182 elselevel--;
8184 * When looking for an "if" ignore "while"s that
8185 * get in the way.
8187 if (elselevel == 0 && lookfor == LOOKFOR_IF)
8188 whilelevel = 0;
8191 /* If it's a "do" decrement whilelevel */
8192 if (cin_isdo(look))
8193 whilelevel--;
8196 * if we've used up all the elses, then
8197 * this must be the if that we want!
8198 * match the indent level of that if.
8200 if (elselevel <= 0 && whilelevel <= 0)
8202 return OK;
8206 return FAIL;
8209 # if defined(FEAT_EVAL) || defined(PROTO)
8211 * Get indent level from 'indentexpr'.
8214 get_expr_indent()
8216 int indent;
8217 pos_T pos;
8218 int save_State;
8219 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
8220 OPT_LOCAL);
8222 pos = curwin->w_cursor;
8223 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
8224 if (use_sandbox)
8225 ++sandbox;
8226 ++textlock;
8227 indent = eval_to_number(curbuf->b_p_inde);
8228 if (use_sandbox)
8229 --sandbox;
8230 --textlock;
8232 /* Restore the cursor position so that 'indentexpr' doesn't need to.
8233 * Pretend to be in Insert mode, allow cursor past end of line for "o"
8234 * command. */
8235 save_State = State;
8236 State = INSERT;
8237 curwin->w_cursor = pos;
8238 check_cursor();
8239 State = save_State;
8241 /* If there is an error, just keep the current indent. */
8242 if (indent < 0)
8243 indent = get_indent();
8245 return indent;
8247 # endif
8249 #endif /* FEAT_CINDENT */
8251 #if defined(FEAT_LISP) || defined(PROTO)
8253 static int lisp_match __ARGS((char_u *p));
8255 static int
8256 lisp_match(p)
8257 char_u *p;
8259 char_u buf[LSIZE];
8260 int len;
8261 char_u *word = p_lispwords;
8263 while (*word != NUL)
8265 (void)copy_option_part(&word, buf, LSIZE, ",");
8266 len = (int)STRLEN(buf);
8267 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8268 return TRUE;
8270 return FALSE;
8274 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8275 * The incompatible newer method is quite a bit better at indenting
8276 * code in lisp-like languages than the traditional one; it's still
8277 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8279 * TODO:
8280 * Findmatch() should be adapted for lisp, also to make showmatch
8281 * work correctly: now (v5.3) it seems all C/C++ oriented:
8282 * - it does not recognize the #\( and #\) notations as character literals
8283 * - it doesn't know about comments starting with a semicolon
8284 * - it incorrectly interprets '(' as a character literal
8285 * All this messes up get_lisp_indent in some rare cases.
8286 * Update from Sergey Khorev:
8287 * I tried to fix the first two issues.
8290 get_lisp_indent()
8292 pos_T *pos, realpos, paren;
8293 int amount;
8294 char_u *that;
8295 colnr_T col;
8296 colnr_T firsttry;
8297 int parencount, quotecount;
8298 int vi_lisp;
8300 /* Set vi_lisp to use the vi-compatible method */
8301 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8303 realpos = curwin->w_cursor;
8304 curwin->w_cursor.col = 0;
8306 if ((pos = findmatch(NULL, '(')) == NULL)
8307 pos = findmatch(NULL, '[');
8308 else
8310 paren = *pos;
8311 pos = findmatch(NULL, '[');
8312 if (pos == NULL || ltp(pos, &paren))
8313 pos = &paren;
8315 if (pos != NULL)
8317 /* Extra trick: Take the indent of the first previous non-white
8318 * line that is at the same () level. */
8319 amount = -1;
8320 parencount = 0;
8322 while (--curwin->w_cursor.lnum >= pos->lnum)
8324 if (linewhite(curwin->w_cursor.lnum))
8325 continue;
8326 for (that = ml_get_curline(); *that != NUL; ++that)
8328 if (*that == ';')
8330 while (*(that + 1) != NUL)
8331 ++that;
8332 continue;
8334 if (*that == '\\')
8336 if (*(that + 1) != NUL)
8337 ++that;
8338 continue;
8340 if (*that == '"' && *(that + 1) != NUL)
8342 while (*++that && *that != '"')
8344 /* skipping escaped characters in the string */
8345 if (*that == '\\')
8347 if (*++that == NUL)
8348 break;
8349 if (that[1] == NUL)
8351 ++that;
8352 break;
8357 if (*that == '(' || *that == '[')
8358 ++parencount;
8359 else if (*that == ')' || *that == ']')
8360 --parencount;
8362 if (parencount == 0)
8364 amount = get_indent();
8365 break;
8369 if (amount == -1)
8371 curwin->w_cursor.lnum = pos->lnum;
8372 curwin->w_cursor.col = pos->col;
8373 col = pos->col;
8375 that = ml_get_curline();
8377 if (vi_lisp && get_indent() == 0)
8378 amount = 2;
8379 else
8381 amount = 0;
8382 while (*that && col)
8384 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8385 col--;
8389 * Some keywords require "body" indenting rules (the
8390 * non-standard-lisp ones are Scheme special forms):
8392 * (let ((a 1)) instead (let ((a 1))
8393 * (...)) of (...))
8396 if (!vi_lisp && (*that == '(' || *that == '[')
8397 && lisp_match(that + 1))
8398 amount += 2;
8399 else
8401 that++;
8402 amount++;
8403 firsttry = amount;
8405 while (vim_iswhite(*that))
8407 amount += lbr_chartabsize(that, (colnr_T)amount);
8408 ++that;
8411 if (*that && *that != ';') /* not a comment line */
8413 /* test *that != '(' to accommodate first let/do
8414 * argument if it is more than one line */
8415 if (!vi_lisp && *that != '(' && *that != '[')
8416 firsttry++;
8418 parencount = 0;
8419 quotecount = 0;
8421 if (vi_lisp
8422 || (*that != '"'
8423 && *that != '\''
8424 && *that != '#'
8425 && (*that < '0' || *that > '9')))
8427 while (*that
8428 && (!vim_iswhite(*that)
8429 || quotecount
8430 || parencount)
8431 && (!((*that == '(' || *that == '[')
8432 && !quotecount
8433 && !parencount
8434 && vi_lisp)))
8436 if (*that == '"')
8437 quotecount = !quotecount;
8438 if ((*that == '(' || *that == '[')
8439 && !quotecount)
8440 ++parencount;
8441 if ((*that == ')' || *that == ']')
8442 && !quotecount)
8443 --parencount;
8444 if (*that == '\\' && *(that+1) != NUL)
8445 amount += lbr_chartabsize_adv(&that,
8446 (colnr_T)amount);
8447 amount += lbr_chartabsize_adv(&that,
8448 (colnr_T)amount);
8451 while (vim_iswhite(*that))
8453 amount += lbr_chartabsize(that, (colnr_T)amount);
8454 that++;
8456 if (!*that || *that == ';')
8457 amount = firsttry;
8463 else
8464 amount = 0; /* no matching '(' or '[' found, use zero indent */
8466 curwin->w_cursor = realpos;
8468 return amount;
8470 #endif /* FEAT_LISP */
8472 void
8473 prepare_to_exit()
8475 #if defined(SIGHUP) && defined(SIG_IGN)
8476 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8477 * makes Vim exit and then handling SIGHUP causes various reentrance
8478 * problems. */
8479 signal(SIGHUP, SIG_IGN);
8480 #endif
8482 #ifdef FEAT_GUI
8483 if (gui.in_use)
8485 gui.dying = TRUE;
8486 out_trash(); /* trash any pending output */
8488 else
8489 #endif
8491 windgoto((int)Rows - 1, 0);
8494 * Switch terminal mode back now, so messages end up on the "normal"
8495 * screen (if there are two screens).
8497 settmode(TMODE_COOK);
8498 #ifdef WIN3264
8499 if (can_end_termcap_mode(FALSE) == TRUE)
8500 #endif
8501 stoptermcap();
8502 out_flush();
8507 * Preserve files and exit.
8508 * When called IObuff must contain a message.
8510 void
8511 preserve_exit()
8513 buf_T *buf;
8515 prepare_to_exit();
8517 /* Setting this will prevent free() calls. That avoids calling free()
8518 * recursively when free() was invoked with a bad pointer. */
8519 really_exiting = TRUE;
8521 out_str(IObuff);
8522 screen_start(); /* don't know where cursor is now */
8523 out_flush();
8525 ml_close_notmod(); /* close all not-modified buffers */
8527 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8529 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8531 OUT_STR(_("Vim: preserving files...\n"));
8532 screen_start(); /* don't know where cursor is now */
8533 out_flush();
8534 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8535 break;
8539 ml_close_all(FALSE); /* close all memfiles, without deleting */
8541 OUT_STR(_("Vim: Finished.\n"));
8543 getout(1);
8547 * return TRUE if "fname" exists.
8550 vim_fexists(fname)
8551 char_u *fname;
8553 struct stat st;
8555 if (mch_stat((char *)fname, &st))
8556 return FALSE;
8557 return TRUE;
8561 * Check for CTRL-C pressed, but only once in a while.
8562 * Should be used instead of ui_breakcheck() for functions that check for
8563 * each line in the file. Calling ui_breakcheck() each time takes too much
8564 * time, because it can be a system call.
8567 #ifndef BREAKCHECK_SKIP
8568 # ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8569 # define BREAKCHECK_SKIP 200
8570 # else
8571 # define BREAKCHECK_SKIP 32
8572 # endif
8573 #endif
8575 static int breakcheck_count = 0;
8577 void
8578 line_breakcheck()
8580 if (++breakcheck_count >= BREAKCHECK_SKIP)
8582 breakcheck_count = 0;
8583 ui_breakcheck();
8588 * Like line_breakcheck() but check 10 times less often.
8590 void
8591 fast_breakcheck()
8593 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8595 breakcheck_count = 0;
8596 ui_breakcheck();
8601 * Invoke expand_wildcards() for one pattern.
8602 * Expand items like "%:h" before the expansion.
8603 * Returns OK or FAIL.
8606 expand_wildcards_eval(pat, num_file, file, flags)
8607 char_u **pat; /* pointer to input pattern */
8608 int *num_file; /* resulting number of files */
8609 char_u ***file; /* array of resulting files */
8610 int flags; /* EW_DIR, etc. */
8612 int ret = FAIL;
8613 char_u *eval_pat = NULL;
8614 char_u *exp_pat = *pat;
8615 char_u *ignored_msg;
8616 int usedlen;
8618 if (*exp_pat == '%' || *exp_pat == '#' || *exp_pat == '<')
8620 ++emsg_off;
8621 eval_pat = eval_vars(exp_pat, exp_pat, &usedlen,
8622 NULL, &ignored_msg, NULL);
8623 --emsg_off;
8624 if (eval_pat != NULL)
8625 exp_pat = concat_str(eval_pat, exp_pat + usedlen);
8628 if (exp_pat != NULL)
8629 ret = expand_wildcards(1, &exp_pat, num_file, file, flags);
8631 if (eval_pat != NULL)
8633 vim_free(exp_pat);
8634 vim_free(eval_pat);
8637 return ret;
8641 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8642 * 'wildignore'.
8643 * Returns OK or FAIL.
8646 expand_wildcards(num_pat, pat, num_file, file, flags)
8647 int num_pat; /* number of input patterns */
8648 char_u **pat; /* array of input patterns */
8649 int *num_file; /* resulting number of files */
8650 char_u ***file; /* array of resulting files */
8651 int flags; /* EW_DIR, etc. */
8653 int retval;
8654 int i, j;
8655 char_u *p;
8656 int non_suf_match; /* number without matching suffix */
8658 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8660 /* When keeping all matches, return here */
8661 if (flags & EW_KEEPALL)
8662 return retval;
8664 #ifdef FEAT_WILDIGN
8666 * Remove names that match 'wildignore'.
8668 if (*p_wig)
8670 char_u *ffname;
8672 /* check all files in (*file)[] */
8673 for (i = 0; i < *num_file; ++i)
8675 ffname = FullName_save((*file)[i], FALSE);
8676 if (ffname == NULL) /* out of memory */
8677 break;
8678 # ifdef VMS
8679 vms_remove_version(ffname);
8680 # endif
8681 if (match_file_list(p_wig, (*file)[i], ffname))
8683 /* remove this matching file from the list */
8684 vim_free((*file)[i]);
8685 for (j = i; j + 1 < *num_file; ++j)
8686 (*file)[j] = (*file)[j + 1];
8687 --*num_file;
8688 --i;
8690 vim_free(ffname);
8693 #endif
8696 * Move the names where 'suffixes' match to the end.
8698 if (*num_file > 1)
8700 non_suf_match = 0;
8701 for (i = 0; i < *num_file; ++i)
8703 if (!match_suffix((*file)[i]))
8706 * Move the name without matching suffix to the front
8707 * of the list.
8709 p = (*file)[i];
8710 for (j = i; j > non_suf_match; --j)
8711 (*file)[j] = (*file)[j - 1];
8712 (*file)[non_suf_match++] = p;
8717 return retval;
8721 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8724 match_suffix(fname)
8725 char_u *fname;
8727 int fnamelen, setsuflen;
8728 char_u *setsuf;
8729 #define MAXSUFLEN 30 /* maximum length of a file suffix */
8730 char_u suf_buf[MAXSUFLEN];
8732 fnamelen = (int)STRLEN(fname);
8733 setsuflen = 0;
8734 for (setsuf = p_su; *setsuf; )
8736 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
8737 if (setsuflen == 0)
8739 char_u *tail = gettail(fname);
8741 /* empty entry: match name without a '.' */
8742 if (vim_strchr(tail, '.') == NULL)
8744 setsuflen = 1;
8745 break;
8748 else
8750 if (fnamelen >= setsuflen
8751 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8752 (size_t)setsuflen) == 0)
8753 break;
8754 setsuflen = 0;
8757 return (setsuflen != 0);
8760 #if !defined(NO_EXPANDPATH) || defined(PROTO)
8762 # ifdef VIM_BACKTICK
8763 static int vim_backtick __ARGS((char_u *p));
8764 static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8765 # endif
8767 # if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8769 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8770 * it's shared between these systems.
8772 # if defined(DJGPP) || defined(PROTO)
8773 # define _cdecl /* DJGPP doesn't have this */
8774 # else
8775 # ifdef __BORLANDC__
8776 # define _cdecl _RTLENTRYF
8777 # endif
8778 # endif
8781 * comparison function for qsort in dos_expandpath()
8783 static int _cdecl
8784 pstrcmp(const void *a, const void *b)
8786 return (pathcmp(*(char **)a, *(char **)b, -1));
8789 # ifndef WIN3264
8790 static void
8791 namelowcpy(
8792 char_u *d,
8793 char_u *s)
8795 # ifdef DJGPP
8796 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8797 while (*s)
8798 *d++ = *s++;
8799 else
8800 # endif
8801 while (*s)
8802 *d++ = TOLOWER_LOC(*s++);
8803 *d = NUL;
8805 # endif
8808 * Recursively expand one path component into all matching files and/or
8809 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8810 * Return the number of matches found.
8811 * "path" has backslashes before chars that are not to be expanded, starting
8812 * at "path[wildoff]".
8813 * Return the number of matches found.
8814 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
8816 static int
8817 dos_expandpath(
8818 garray_T *gap,
8819 char_u *path,
8820 int wildoff,
8821 int flags, /* EW_* flags */
8822 int didstar) /* expanded "**" once already */
8824 char_u *buf;
8825 char_u *path_end;
8826 char_u *p, *s, *e;
8827 int start_len = gap->ga_len;
8828 char_u *pat;
8829 regmatch_T regmatch;
8830 int starts_with_dot;
8831 int matches;
8832 int len;
8833 int starstar = FALSE;
8834 static int stardepth = 0; /* depth for "**" expansion */
8835 #ifdef WIN3264
8836 WIN32_FIND_DATA fb;
8837 HANDLE hFind = (HANDLE)0;
8838 # ifdef FEAT_MBYTE
8839 WIN32_FIND_DATAW wfb;
8840 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8841 # endif
8842 #else
8843 struct ffblk fb;
8844 #endif
8845 char_u *matchname;
8846 int ok;
8848 /* Expanding "**" may take a long time, check for CTRL-C. */
8849 if (stardepth > 0)
8851 ui_breakcheck();
8852 if (got_int)
8853 return 0;
8856 /* make room for file name */
8857 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8858 if (buf == NULL)
8859 return 0;
8862 * Find the first part in the path name that contains a wildcard or a ~1.
8863 * Copy it into buf, including the preceding characters.
8865 p = buf;
8866 s = buf;
8867 e = NULL;
8868 path_end = path;
8869 while (*path_end != NUL)
8871 /* May ignore a wildcard that has a backslash before it; it will
8872 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8873 if (path_end >= path + wildoff && rem_backslash(path_end))
8874 *p++ = *path_end++;
8875 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8877 if (e != NULL)
8878 break;
8879 s = p + 1;
8881 else if (path_end >= path + wildoff
8882 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8883 e = p;
8884 #ifdef FEAT_MBYTE
8885 if (has_mbyte)
8887 len = (*mb_ptr2len)(path_end);
8888 STRNCPY(p, path_end, len);
8889 p += len;
8890 path_end += len;
8892 else
8893 #endif
8894 *p++ = *path_end++;
8896 e = p;
8897 *e = NUL;
8899 /* now we have one wildcard component between s and e */
8900 /* Remove backslashes between "wildoff" and the start of the wildcard
8901 * component. */
8902 for (p = buf + wildoff; p < s; ++p)
8903 if (rem_backslash(p))
8905 STRMOVE(p, p + 1);
8906 --e;
8907 --s;
8910 /* Check for "**" between "s" and "e". */
8911 for (p = s; p < e; ++p)
8912 if (p[0] == '*' && p[1] == '*')
8913 starstar = TRUE;
8915 starts_with_dot = (*s == '.');
8916 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8917 if (pat == NULL)
8919 vim_free(buf);
8920 return 0;
8923 /* compile the regexp into a program */
8924 regmatch.rm_ic = TRUE; /* Always ignore case */
8925 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8926 vim_free(pat);
8928 if (regmatch.regprog == NULL)
8930 vim_free(buf);
8931 return 0;
8934 /* remember the pattern or file name being looked for */
8935 matchname = vim_strsave(s);
8937 /* If "**" is by itself, this is the first time we encounter it and more
8938 * is following then find matches without any directory. */
8939 if (!didstar && stardepth < 100 && starstar && e - s == 2
8940 && *path_end == '/')
8942 STRCPY(s, path_end + 1);
8943 ++stardepth;
8944 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8945 --stardepth;
8948 /* Scan all files in the directory with "dir/ *.*" */
8949 STRCPY(s, "*.*");
8950 #ifdef WIN3264
8951 # ifdef FEAT_MBYTE
8952 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8954 /* The active codepage differs from 'encoding'. Attempt using the
8955 * wide function. If it fails because it is not implemented fall back
8956 * to the non-wide version (for Windows 98) */
8957 wn = enc_to_utf16(buf, NULL);
8958 if (wn != NULL)
8960 hFind = FindFirstFileW(wn, &wfb);
8961 if (hFind == INVALID_HANDLE_VALUE
8962 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8964 vim_free(wn);
8965 wn = NULL;
8970 if (wn == NULL)
8971 # endif
8972 hFind = FindFirstFile(buf, &fb);
8973 ok = (hFind != INVALID_HANDLE_VALUE);
8974 #else
8975 /* If we are expanding wildcards we try both files and directories */
8976 ok = (findfirst((char *)buf, &fb,
8977 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8978 #endif
8980 while (ok)
8982 #ifdef WIN3264
8983 # ifdef FEAT_MBYTE
8984 if (wn != NULL)
8985 p = utf16_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8986 else
8987 # endif
8988 p = (char_u *)fb.cFileName;
8989 #else
8990 p = (char_u *)fb.ff_name;
8991 #endif
8992 /* Ignore entries starting with a dot, unless when asked for. Accept
8993 * all entries found with "matchname". */
8994 if ((p[0] != '.' || starts_with_dot)
8995 && (matchname == NULL
8996 || vim_regexec(&regmatch, p, (colnr_T)0)))
8998 #ifdef WIN3264
8999 STRCPY(s, p);
9000 #else
9001 namelowcpy(s, p);
9002 #endif
9003 len = (int)STRLEN(buf);
9005 if (starstar && stardepth < 100)
9007 /* For "**" in the pattern first go deeper in the tree to
9008 * find matches. */
9009 STRCPY(buf + len, "/**");
9010 STRCPY(buf + len + 3, path_end);
9011 ++stardepth;
9012 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
9013 --stardepth;
9016 STRCPY(buf + len, path_end);
9017 if (mch_has_exp_wildcard(path_end))
9019 /* need to expand another component of the path */
9020 /* remove backslashes for the remaining components only */
9021 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
9023 else
9025 /* no more wildcards, check if there is a match */
9026 /* remove backslashes for the remaining components only */
9027 if (*path_end != 0)
9028 backslash_halve(buf + len + 1);
9029 if (mch_getperm(buf) >= 0) /* add existing file */
9030 addfile(gap, buf, flags);
9034 #ifdef WIN3264
9035 # ifdef FEAT_MBYTE
9036 if (wn != NULL)
9038 vim_free(p);
9039 ok = FindNextFileW(hFind, &wfb);
9041 else
9042 # endif
9043 ok = FindNextFile(hFind, &fb);
9044 #else
9045 ok = (findnext(&fb) == 0);
9046 #endif
9048 /* If no more matches and no match was used, try expanding the name
9049 * itself. Finds the long name of a short filename. */
9050 if (!ok && matchname != NULL && gap->ga_len == start_len)
9052 STRCPY(s, matchname);
9053 #ifdef WIN3264
9054 FindClose(hFind);
9055 # ifdef FEAT_MBYTE
9056 if (wn != NULL)
9058 vim_free(wn);
9059 wn = enc_to_utf16(buf, NULL);
9060 if (wn != NULL)
9061 hFind = FindFirstFileW(wn, &wfb);
9063 if (wn == NULL)
9064 # endif
9065 hFind = FindFirstFile(buf, &fb);
9066 ok = (hFind != INVALID_HANDLE_VALUE);
9067 #else
9068 ok = (findfirst((char *)buf, &fb,
9069 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
9070 #endif
9071 vim_free(matchname);
9072 matchname = NULL;
9076 #ifdef WIN3264
9077 FindClose(hFind);
9078 # ifdef FEAT_MBYTE
9079 vim_free(wn);
9080 # endif
9081 #endif
9082 vim_free(buf);
9083 vim_free(regmatch.regprog);
9084 vim_free(matchname);
9086 matches = gap->ga_len - start_len;
9087 if (matches > 0)
9088 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
9089 sizeof(char_u *), pstrcmp);
9090 return matches;
9094 mch_expandpath(
9095 garray_T *gap,
9096 char_u *path,
9097 int flags) /* EW_* flags */
9099 return dos_expandpath(gap, path, 0, flags, FALSE);
9101 # endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
9103 #if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
9104 || defined(PROTO)
9106 * Unix style wildcard expansion code.
9107 * It's here because it's used both for Unix and Mac.
9109 static int pstrcmp __ARGS((const void *, const void *));
9111 static int
9112 pstrcmp(a, b)
9113 const void *a, *b;
9115 return (pathcmp(*(char **)a, *(char **)b, -1));
9119 * Recursively expand one path component into all matching files and/or
9120 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
9121 * "path" has backslashes before chars that are not to be expanded, starting
9122 * at "path + wildoff".
9123 * Return the number of matches found.
9124 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
9127 unix_expandpath(gap, path, wildoff, flags, didstar)
9128 garray_T *gap;
9129 char_u *path;
9130 int wildoff;
9131 int flags; /* EW_* flags */
9132 int didstar; /* expanded "**" once already */
9134 char_u *buf;
9135 char_u *path_end;
9136 char_u *p, *s, *e;
9137 int start_len = gap->ga_len;
9138 char_u *pat;
9139 regmatch_T regmatch;
9140 int starts_with_dot;
9141 int matches;
9142 int len;
9143 int starstar = FALSE;
9144 static int stardepth = 0; /* depth for "**" expansion */
9146 DIR *dirp;
9147 struct dirent *dp;
9149 /* Expanding "**" may take a long time, check for CTRL-C. */
9150 if (stardepth > 0)
9152 ui_breakcheck();
9153 if (got_int)
9154 return 0;
9157 /* make room for file name */
9158 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
9159 if (buf == NULL)
9160 return 0;
9163 * Find the first part in the path name that contains a wildcard.
9164 * Copy it into "buf", including the preceding characters.
9166 p = buf;
9167 s = buf;
9168 e = NULL;
9169 path_end = path;
9170 while (*path_end != NUL)
9172 /* May ignore a wildcard that has a backslash before it; it will
9173 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
9174 if (path_end >= path + wildoff && rem_backslash(path_end))
9175 *p++ = *path_end++;
9176 else if (*path_end == '/')
9178 if (e != NULL)
9179 break;
9180 s = p + 1;
9182 else if (path_end >= path + wildoff
9183 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
9184 e = p;
9185 #ifdef FEAT_MBYTE
9186 if (has_mbyte)
9188 len = (*mb_ptr2len)(path_end);
9189 STRNCPY(p, path_end, len);
9190 p += len;
9191 path_end += len;
9193 else
9194 #endif
9195 *p++ = *path_end++;
9197 e = p;
9198 *e = NUL;
9200 /* now we have one wildcard component between "s" and "e" */
9201 /* Remove backslashes between "wildoff" and the start of the wildcard
9202 * component. */
9203 for (p = buf + wildoff; p < s; ++p)
9204 if (rem_backslash(p))
9206 STRMOVE(p, p + 1);
9207 --e;
9208 --s;
9211 /* Check for "**" between "s" and "e". */
9212 for (p = s; p < e; ++p)
9213 if (p[0] == '*' && p[1] == '*')
9214 starstar = TRUE;
9216 /* convert the file pattern to a regexp pattern */
9217 starts_with_dot = (*s == '.');
9218 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
9219 if (pat == NULL)
9221 vim_free(buf);
9222 return 0;
9225 /* compile the regexp into a program */
9226 #ifdef CASE_INSENSITIVE_FILENAME
9227 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
9228 #else
9229 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9230 #endif
9231 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
9232 vim_free(pat);
9234 if (regmatch.regprog == NULL)
9236 vim_free(buf);
9237 return 0;
9240 /* If "**" is by itself, this is the first time we encounter it and more
9241 * is following then find matches without any directory. */
9242 if (!didstar && stardepth < 100 && starstar && e - s == 2
9243 && *path_end == '/')
9245 STRCPY(s, path_end + 1);
9246 ++stardepth;
9247 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
9248 --stardepth;
9251 /* open the directory for scanning */
9252 *s = NUL;
9253 dirp = opendir(*buf == NUL ? "." : (char *)buf);
9255 /* Find all matching entries */
9256 if (dirp != NULL)
9258 for (;;)
9260 dp = readdir(dirp);
9261 if (dp == NULL)
9262 break;
9263 if ((dp->d_name[0] != '.' || starts_with_dot)
9264 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
9266 STRCPY(s, dp->d_name);
9267 len = STRLEN(buf);
9269 if (starstar && stardepth < 100)
9271 /* For "**" in the pattern first go deeper in the tree to
9272 * find matches. */
9273 STRCPY(buf + len, "/**");
9274 STRCPY(buf + len + 3, path_end);
9275 ++stardepth;
9276 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
9277 --stardepth;
9280 STRCPY(buf + len, path_end);
9281 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
9283 /* need to expand another component of the path */
9284 /* remove backslashes for the remaining components only */
9285 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
9287 else
9289 /* no more wildcards, check if there is a match */
9290 /* remove backslashes for the remaining components only */
9291 if (*path_end != NUL)
9292 backslash_halve(buf + len + 1);
9293 if (mch_getperm(buf) >= 0) /* add existing file */
9295 #ifdef MACOS_CONVERT
9296 size_t precomp_len = STRLEN(buf)+1;
9297 char_u *precomp_buf =
9298 mac_precompose_path(buf, precomp_len, &precomp_len);
9300 if (precomp_buf)
9302 mch_memmove(buf, precomp_buf, precomp_len);
9303 vim_free(precomp_buf);
9305 #endif
9306 addfile(gap, buf, flags);
9312 closedir(dirp);
9315 vim_free(buf);
9316 vim_free(regmatch.regprog);
9318 matches = gap->ga_len - start_len;
9319 if (matches > 0)
9320 qsort(((char_u **)gap->ga_data) + start_len, matches,
9321 sizeof(char_u *), pstrcmp);
9322 return matches;
9324 #endif
9327 * Generic wildcard expansion code.
9329 * Characters in "pat" that should not be expanded must be preceded with a
9330 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9332 * Return FAIL when no single file was found. In this case "num_file" is not
9333 * set, and "file" may contain an error message.
9334 * Return OK when some files found. "num_file" is set to the number of
9335 * matches, "file" to the array of matches. Call FreeWild() later.
9338 gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9339 int num_pat; /* number of input patterns */
9340 char_u **pat; /* array of input patterns */
9341 int *num_file; /* resulting number of files */
9342 char_u ***file; /* array of resulting files */
9343 int flags; /* EW_* flags */
9345 int i;
9346 garray_T ga;
9347 char_u *p;
9348 static int recursive = FALSE;
9349 int add_pat;
9352 * expand_env() is called to expand things like "~user". If this fails,
9353 * it calls ExpandOne(), which brings us back here. In this case, always
9354 * call the machine specific expansion function, if possible. Otherwise,
9355 * return FAIL.
9357 if (recursive)
9358 #ifdef SPECIAL_WILDCHAR
9359 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9360 #else
9361 return FAIL;
9362 #endif
9364 #ifdef SPECIAL_WILDCHAR
9366 * If there are any special wildcard characters which we cannot handle
9367 * here, call machine specific function for all the expansion. This
9368 * avoids starting the shell for each argument separately.
9369 * For `=expr` do use the internal function.
9371 for (i = 0; i < num_pat; i++)
9373 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9374 # ifdef VIM_BACKTICK
9375 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9376 # endif
9378 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9380 #endif
9382 recursive = TRUE;
9385 * The matching file names are stored in a growarray. Init it empty.
9387 ga_init2(&ga, (int)sizeof(char_u *), 30);
9389 for (i = 0; i < num_pat; ++i)
9391 add_pat = -1;
9392 p = pat[i];
9394 #ifdef VIM_BACKTICK
9395 if (vim_backtick(p))
9396 add_pat = expand_backtick(&ga, p, flags);
9397 else
9398 #endif
9401 * First expand environment variables, "~/" and "~user/".
9403 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9405 p = expand_env_save_opt(p, TRUE);
9406 if (p == NULL)
9407 p = pat[i];
9408 #ifdef UNIX
9410 * On Unix, if expand_env() can't expand an environment
9411 * variable, use the shell to do that. Discard previously
9412 * found file names and start all over again.
9414 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9416 vim_free(p);
9417 ga_clear_strings(&ga);
9418 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9419 flags);
9420 recursive = FALSE;
9421 return i;
9423 #endif
9427 * If there are wildcards: Expand file names and add each match to
9428 * the list. If there is no match, and EW_NOTFOUND is given, add
9429 * the pattern.
9430 * If there are no wildcards: Add the file name if it exists or
9431 * when EW_NOTFOUND is given.
9433 if (mch_has_exp_wildcard(p))
9434 add_pat = mch_expandpath(&ga, p, flags);
9437 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9439 char_u *t = backslash_halve_save(p);
9441 #if defined(MACOS_CLASSIC)
9442 slash_to_colon(t);
9443 #endif
9444 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9445 * "vim c:/" work. */
9446 if (flags & EW_NOTFOUND)
9447 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9448 else if (mch_getperm(t) >= 0)
9449 addfile(&ga, t, flags);
9450 vim_free(t);
9453 if (p != pat[i])
9454 vim_free(p);
9457 *num_file = ga.ga_len;
9458 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9460 recursive = FALSE;
9462 return (ga.ga_data != NULL) ? OK : FAIL;
9465 # ifdef VIM_BACKTICK
9468 * Return TRUE if we can expand this backtick thing here.
9470 static int
9471 vim_backtick(p)
9472 char_u *p;
9474 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9478 * Expand an item in `backticks` by executing it as a command.
9479 * Currently only works when pat[] starts and ends with a `.
9480 * Returns number of file names found.
9482 static int
9483 expand_backtick(gap, pat, flags)
9484 garray_T *gap;
9485 char_u *pat;
9486 int flags; /* EW_* flags */
9488 char_u *p;
9489 char_u *cmd;
9490 char_u *buffer;
9491 int cnt = 0;
9492 int i;
9494 /* Create the command: lop off the backticks. */
9495 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9496 if (cmd == NULL)
9497 return 0;
9499 #ifdef FEAT_EVAL
9500 if (*cmd == '=') /* `={expr}`: Expand expression */
9501 buffer = eval_to_string(cmd + 1, &p, TRUE);
9502 else
9503 #endif
9504 buffer = get_cmd_output(cmd, NULL,
9505 (flags & EW_SILENT) ? SHELL_SILENT : 0);
9506 vim_free(cmd);
9507 if (buffer == NULL)
9508 return 0;
9510 cmd = buffer;
9511 while (*cmd != NUL)
9513 cmd = skipwhite(cmd); /* skip over white space */
9514 p = cmd;
9515 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9516 ++p;
9517 /* add an entry if it is not empty */
9518 if (p > cmd)
9520 i = *p;
9521 *p = NUL;
9522 addfile(gap, cmd, flags);
9523 *p = i;
9524 ++cnt;
9526 cmd = p;
9527 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9528 ++cmd;
9531 vim_free(buffer);
9532 return cnt;
9534 # endif /* VIM_BACKTICK */
9537 * Add a file to a file list. Accepted flags:
9538 * EW_DIR add directories
9539 * EW_FILE add files
9540 * EW_EXEC add executable files
9541 * EW_NOTFOUND add even when it doesn't exist
9542 * EW_ADDSLASH add slash after directory name
9544 void
9545 addfile(gap, f, flags)
9546 garray_T *gap;
9547 char_u *f; /* filename */
9548 int flags;
9550 char_u *p;
9551 int isdir;
9553 /* if the file/dir doesn't exist, may not add it */
9554 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9555 return;
9557 #ifdef FNAME_ILLEGAL
9558 /* if the file/dir contains illegal characters, don't add it */
9559 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9560 return;
9561 #endif
9563 isdir = mch_isdir(f);
9564 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9565 return;
9567 /* If the file isn't executable, may not add it. Do accept directories. */
9568 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9569 return;
9571 /* Make room for another item in the file list. */
9572 if (ga_grow(gap, 1) == FAIL)
9573 return;
9575 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9576 if (p == NULL)
9577 return;
9579 STRCPY(p, f);
9580 #ifdef BACKSLASH_IN_FILENAME
9581 slash_adjust(p);
9582 #endif
9584 * Append a slash or backslash after directory names if none is present.
9586 #ifndef DONT_ADD_PATHSEP_TO_DIR
9587 if (isdir && (flags & EW_ADDSLASH))
9588 add_pathsep(p);
9589 #endif
9590 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
9592 #endif /* !NO_EXPANDPATH */
9594 #if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9596 #ifndef SEEK_SET
9597 # define SEEK_SET 0
9598 #endif
9599 #ifndef SEEK_END
9600 # define SEEK_END 2
9601 #endif
9604 * Get the stdout of an external command.
9605 * Returns an allocated string, or NULL for error.
9607 char_u *
9608 get_cmd_output(cmd, infile, flags)
9609 char_u *cmd;
9610 char_u *infile; /* optional input file name */
9611 int flags; /* can be SHELL_SILENT */
9613 char_u *tempname;
9614 char_u *command;
9615 char_u *buffer = NULL;
9616 int len;
9617 int i = 0;
9618 FILE *fd;
9620 if (check_restricted() || check_secure())
9621 return NULL;
9623 /* get a name for the temp file */
9624 if ((tempname = vim_tempname('o')) == NULL)
9626 EMSG(_(e_notmp));
9627 return NULL;
9630 /* Add the redirection stuff */
9631 command = make_filter_cmd(cmd, infile, tempname);
9632 if (command == NULL)
9633 goto done;
9636 * Call the shell to execute the command (errors are ignored).
9637 * Don't check timestamps here.
9639 ++no_check_timestamps;
9640 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9641 --no_check_timestamps;
9643 vim_free(command);
9646 * read the names from the file into memory
9648 # ifdef VMS
9649 /* created temporary file is not always readable as binary */
9650 fd = mch_fopen((char *)tempname, "r");
9651 # else
9652 fd = mch_fopen((char *)tempname, READBIN);
9653 # endif
9655 if (fd == NULL)
9657 EMSG2(_(e_notopen), tempname);
9658 goto done;
9661 fseek(fd, 0L, SEEK_END);
9662 len = ftell(fd); /* get size of temp file */
9663 fseek(fd, 0L, SEEK_SET);
9665 buffer = alloc(len + 1);
9666 if (buffer != NULL)
9667 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9668 fclose(fd);
9669 mch_remove(tempname);
9670 if (buffer == NULL)
9671 goto done;
9672 #ifdef VMS
9673 len = i; /* VMS doesn't give us what we asked for... */
9674 #endif
9675 if (i != len)
9677 EMSG2(_(e_notread), tempname);
9678 vim_free(buffer);
9679 buffer = NULL;
9681 else
9682 buffer[len] = '\0'; /* make sure the buffer is terminated */
9684 done:
9685 vim_free(tempname);
9686 return buffer;
9688 #endif
9691 * Free the list of files returned by expand_wildcards() or other expansion
9692 * functions.
9694 void
9695 FreeWild(count, files)
9696 int count;
9697 char_u **files;
9699 if (count <= 0 || files == NULL)
9700 return;
9701 #if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9703 * Is this still OK for when other functions than expand_wildcards() have
9704 * been used???
9706 _fnexplodefree((char **)files);
9707 #else
9708 while (count--)
9709 vim_free(files[count]);
9710 vim_free(files);
9711 #endif
9715 * return TRUE when need to go to Insert mode because of 'insertmode'.
9716 * Don't do this when still processing a command or a mapping.
9717 * Don't do this when inside a ":normal" command.
9720 goto_im()
9722 return (p_im && stuff_empty() && typebuf_typed());