blob: 891fbb5ccc90483d207564e627f664c473987e1f [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
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 */
9
10/*
11 * misc1.c: functions that didn't seem to fit elsewhere
12 */
13
14#include "vim.h"
15#include "version.h"
16
17#ifdef HAVE_FCNTL_H
18# include <fcntl.h> /* for chdir() */
19#endif
20
21static char_u *vim_version_dir __ARGS((char_u *vimdir));
22static char_u *remove_tail __ARGS((char_u *p, char_u *pend, char_u *name));
23#if defined(USE_EXE_NAME) && defined(MACOS_X)
24static char_u *remove_tail_with_ext __ARGS((char_u *p, char_u *pend, char_u *ext));
25#endif
26static int get_indent_str __ARGS((char_u *ptr, int ts));
27static int copy_indent __ARGS((int size, char_u *src));
28
29/*
30 * Count the size (in window cells) of the indent in the current line.
31 */
32 int
33get_indent()
34{
35 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
36}
37
38/*
39 * Count the size (in window cells) of the indent in line "lnum".
40 */
41 int
42get_indent_lnum(lnum)
43 linenr_T lnum;
44{
45 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
46}
47
48#if defined(FEAT_FOLDING) || defined(PROTO)
49/*
50 * Count the size (in window cells) of the indent in line "lnum" of buffer
51 * "buf".
52 */
53 int
54get_indent_buf(buf, lnum)
55 buf_T *buf;
56 linenr_T lnum;
57{
58 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
59}
60#endif
61
62/*
63 * count the size (in window cells) of the indent in line "ptr", with
64 * 'tabstop' at "ts"
65 */
66 static int
67get_indent_str(ptr, ts)
68 char_u *ptr;
69 int ts;
70{
71 int count = 0;
72
73 for ( ; *ptr; ++ptr)
74 {
75 if (*ptr == TAB) /* count a tab for what it is worth */
76 count += ts - (count % ts);
77 else if (*ptr == ' ')
78 ++count; /* count a space for one */
79 else
80 break;
81 }
82 return (count);
83}
84
85/*
86 * Set the indent of the current line.
87 * Leaves the cursor on the first non-blank in the line.
88 * Caller must take care of undo.
89 * "flags":
90 * SIN_CHANGED: call changed_bytes() if the line was changed.
91 * SIN_INSERT: insert the indent in front of the line.
92 * SIN_UNDO: save line for undo before changing it.
93 * Returns TRUE if the line was changed.
94 */
95 int
96set_indent(size, flags)
97 int size;
98 int flags;
99{
100 char_u *p;
101 char_u *newline;
102 char_u *oldline;
103 char_u *s;
104 int todo;
105 int ind_len;
106 int line_len;
107 int doit = FALSE;
108 int ind_done;
109 int tab_pad;
110
111 /*
112 * First check if there is anything to do and compute the number of
113 * characters needed for the indent.
114 */
115 todo = size;
116 ind_len = 0;
117 p = oldline = ml_get_curline();
118
119 /* Calculate the buffer size for the new indent, and check to see if it
120 * isn't already set */
121
122 /* if 'expandtab' isn't set: use TABs */
123 if (!curbuf->b_p_et)
124 {
125 /* If 'preserveindent' is set then reuse as much as possible of
126 * the existing indent structure for the new indent */
127 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
128 {
129 ind_done = 0;
130
131 /* count as many characters as we can use */
132 while (todo > 0 && vim_iswhite(*p))
133 {
134 if (*p == TAB)
135 {
136 tab_pad = (int)curbuf->b_p_ts
137 - (ind_done % (int)curbuf->b_p_ts);
138 /* stop if this tab will overshoot the target */
139 if (todo < tab_pad)
140 break;
141 todo -= tab_pad;
142 ++ind_len;
143 ind_done += tab_pad;
144 }
145 else
146 {
147 --todo;
148 ++ind_len;
149 ++ind_done;
150 }
151 ++p;
152 }
153
154 /* Fill to next tabstop with a tab, if possible */
155 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
156 if (todo >= tab_pad)
157 {
158 doit = TRUE;
159 todo -= tab_pad;
160 ++ind_len;
161 /* ind_done += tab_pad; */
162 }
163 }
164
165 /* count tabs required for indent */
166 while (todo >= (int)curbuf->b_p_ts)
167 {
168 if (*p != TAB)
169 doit = TRUE;
170 else
171 ++p;
172 todo -= (int)curbuf->b_p_ts;
173 ++ind_len;
174 /* ind_done += (int)curbuf->b_p_ts; */
175 }
176 }
177 /* count spaces required for indent */
178 while (todo > 0)
179 {
180 if (*p != ' ')
181 doit = TRUE;
182 else
183 ++p;
184 --todo;
185 ++ind_len;
186 /* ++ind_done; */
187 }
188
189 /* Return if the indent is OK already. */
190 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
191 return FALSE;
192
193 /* Allocate memory for the new line. */
194 if (flags & SIN_INSERT)
195 p = oldline;
196 else
197 p = skipwhite(p);
198 line_len = (int)STRLEN(p) + 1;
199 newline = alloc(ind_len + line_len);
200 if (newline == NULL)
201 return FALSE;
202
203 /* Put the characters in the new line. */
204 s = newline;
205 todo = size;
206 /* if 'expandtab' isn't set: use TABs */
207 if (!curbuf->b_p_et)
208 {
209 /* If 'preserveindent' is set then reuse as much as possible of
210 * the existing indent structure for the new indent */
211 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
212 {
213 p = oldline;
214 ind_done = 0;
215
216 while (todo > 0 && vim_iswhite(*p))
217 {
218 if (*p == TAB)
219 {
220 tab_pad = (int)curbuf->b_p_ts
221 - (ind_done % (int)curbuf->b_p_ts);
222 /* stop if this tab will overshoot the target */
223 if (todo < tab_pad)
224 break;
225 todo -= tab_pad;
226 ind_done += tab_pad;
227 }
228 else
229 {
230 --todo;
231 ++ind_done;
232 }
233 *s++ = *p++;
234 }
235
236 /* Fill to next tabstop with a tab, if possible */
237 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
238 if (todo >= tab_pad)
239 {
240 *s++ = TAB;
241 todo -= tab_pad;
242 }
243
244 p = skipwhite(p);
245 }
246
247 while (todo >= (int)curbuf->b_p_ts)
248 {
249 *s++ = TAB;
250 todo -= (int)curbuf->b_p_ts;
251 }
252 }
253 while (todo > 0)
254 {
255 *s++ = ' ';
256 --todo;
257 }
258 mch_memmove(s, p, (size_t)line_len);
259
260 /* Replace the line (unless undo fails). */
261 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
262 {
263 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
264 if (flags & SIN_CHANGED)
265 changed_bytes(curwin->w_cursor.lnum, 0);
266 /* Correct saved cursor position if it's after the indent. */
267 if (saved_cursor.lnum == curwin->w_cursor.lnum
268 && saved_cursor.col >= (colnr_T)(p - oldline))
269 saved_cursor.col += ind_len - (p - oldline);
270 }
271 else
272 vim_free(newline);
273
274 curwin->w_cursor.col = ind_len;
275 return TRUE;
276}
277
278/*
279 * Copy the indent from ptr to the current line (and fill to size)
280 * Leaves the cursor on the first non-blank in the line.
281 * Returns TRUE if the line was changed.
282 */
283 static int
284copy_indent(size, src)
285 int size;
286 char_u *src;
287{
288 char_u *p = NULL;
289 char_u *line = NULL;
290 char_u *s;
291 int todo;
292 int ind_len;
293 int line_len = 0;
294 int tab_pad;
295 int ind_done;
296 int round;
297
298 /* Round 1: compute the number of characters needed for the indent
299 * Round 2: copy the characters. */
300 for (round = 1; round <= 2; ++round)
301 {
302 todo = size;
303 ind_len = 0;
304 ind_done = 0;
305 s = src;
306
307 /* Count/copy the usable portion of the source line */
308 while (todo > 0 && vim_iswhite(*s))
309 {
310 if (*s == TAB)
311 {
312 tab_pad = (int)curbuf->b_p_ts
313 - (ind_done % (int)curbuf->b_p_ts);
314 /* Stop if this tab will overshoot the target */
315 if (todo < tab_pad)
316 break;
317 todo -= tab_pad;
318 ind_done += tab_pad;
319 }
320 else
321 {
322 --todo;
323 ++ind_done;
324 }
325 ++ind_len;
326 if (round == 2)
327 *p++ = *s;
328 ++s;
329 }
330
331 /* Fill to next tabstop with a tab, if possible */
332 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
333 if (todo >= tab_pad)
334 {
335 todo -= tab_pad;
336 ++ind_len;
337 if (round == 2)
338 *p++ = TAB;
339 }
340
341 /* Add tabs required for indent */
342 while (todo >= (int)curbuf->b_p_ts)
343 {
344 todo -= (int)curbuf->b_p_ts;
345 ++ind_len;
346 if (round == 2)
347 *p++ = TAB;
348 }
349
350 /* Count/add spaces required for indent */
351 while (todo > 0)
352 {
353 --todo;
354 ++ind_len;
355 if (round == 2)
356 *p++ = ' ';
357 }
358
359 if (round == 1)
360 {
361 /* Allocate memory for the result: the copied indent, new indent
362 * and the rest of the line. */
363 line_len = (int)STRLEN(ml_get_curline()) + 1;
364 line = alloc(ind_len + line_len);
365 if (line == NULL)
366 return FALSE;
367 p = line;
368 }
369 }
370
371 /* Append the original line */
372 mch_memmove(p, ml_get_curline(), (size_t)line_len);
373
374 /* Replace the line */
375 ml_replace(curwin->w_cursor.lnum, line, FALSE);
376
377 /* Put the cursor after the indent. */
378 curwin->w_cursor.col = ind_len;
379 return TRUE;
380}
381
382/*
383 * Return the indent of the current line after a number. Return -1 if no
384 * number was found. Used for 'n' in 'formatoptions': numbered list.
385 */
386 int
387get_number_indent(lnum)
388 linenr_T lnum;
389{
390 char_u *line;
391 char_u *p;
392 colnr_T col;
393 pos_T pos;
394
395 if (lnum > curbuf->b_ml.ml_line_count)
396 return -1;
397 line = ml_get(lnum);
398 p = skipwhite(line);
399 if (!VIM_ISDIGIT(*p))
400 return -1;
401 p = skipdigits(p);
402 if (vim_strchr((char_u *)":.)]}\t ", *p) == NULL)
403 return -1;
404 p = skipwhite(p + 1);
405 if (*p == NUL)
406 return -1;
407 pos.lnum = lnum;
408 pos.col = (colnr_T)(p - line);
409 getvcol(curwin, &pos, &col, NULL, NULL);
410 return (int)col;
411}
412
413#if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
414
415static int cin_is_cinword __ARGS((char_u *line));
416
417/*
418 * Return TRUE if the string "line" starts with a word from 'cinwords'.
419 */
420 static int
421cin_is_cinword(line)
422 char_u *line;
423{
424 char_u *cinw;
425 char_u *cinw_buf;
426 int cinw_len;
427 int retval = FALSE;
428 int len;
429
430 cinw_len = (int)STRLEN(curbuf->b_p_cinw) + 1;
431 cinw_buf = alloc((unsigned)cinw_len);
432 if (cinw_buf != NULL)
433 {
434 line = skipwhite(line);
435 for (cinw = curbuf->b_p_cinw; *cinw; )
436 {
437 len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
438 if (STRNCMP(line, cinw_buf, len) == 0
439 && (!vim_iswordc(line[len]) || !vim_iswordc(line[len - 1])))
440 {
441 retval = TRUE;
442 break;
443 }
444 }
445 vim_free(cinw_buf);
446 }
447 return retval;
448}
449#endif
450
451/*
452 * open_line: Add a new line below or above the current line.
453 *
454 * For VREPLACE mode, we only add a new line when we get to the end of the
455 * file, otherwise we just start replacing the next line.
456 *
457 * Caller must take care of undo. Since VREPLACE may affect any number of
458 * lines however, it may call u_save_cursor() again when starting to change a
459 * new line.
460 * "flags": OPENLINE_DELSPACES delete spaces after cursor
461 * OPENLINE_DO_COM format comments
462 * OPENLINE_KEEPTRAIL keep trailing spaces
463 * OPENLINE_MARKFIX adjust mark positions after the line break
464 *
465 * Return TRUE for success, FALSE for failure
466 */
467 int
468open_line(dir, flags, old_indent)
469 int dir; /* FORWARD or BACKWARD */
470 int flags;
471 int old_indent; /* indent for after ^^D in Insert mode */
472{
473 char_u *saved_line; /* copy of the original line */
474 char_u *next_line = NULL; /* copy of the next line */
475 char_u *p_extra = NULL; /* what goes to next line */
476 int less_cols = 0; /* less columns for mark in new line */
477 int less_cols_off = 0; /* columns to skip for mark adjust */
478 pos_T old_cursor; /* old cursor position */
479 int newcol = 0; /* new cursor column */
480 int newindent = 0; /* auto-indent of the new line */
481 int n;
482 int trunc_line = FALSE; /* truncate current line afterwards */
483 int retval = FALSE; /* return value, default is FAIL */
484#ifdef FEAT_COMMENTS
485 int extra_len = 0; /* length of p_extra string */
486 int lead_len; /* length of comment leader */
487 char_u *lead_flags; /* position in 'comments' for comment leader */
488 char_u *leader = NULL; /* copy of comment leader */
489#endif
490 char_u *allocated = NULL; /* allocated memory */
491#if defined(FEAT_SMARTINDENT) || defined(FEAT_VREPLACE) || defined(FEAT_LISP) \
492 || defined(FEAT_CINDENT) || defined(FEAT_COMMENTS)
493 char_u *p;
494#endif
495 int saved_char = NUL; /* init for GCC */
496#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
497 pos_T *pos;
498#endif
499#ifdef FEAT_SMARTINDENT
500 int do_si = (!p_paste && curbuf->b_p_si
501# ifdef FEAT_CINDENT
502 && !curbuf->b_p_cin
503# endif
504 );
505 int no_si = FALSE; /* reset did_si afterwards */
506 int first_char = NUL; /* init for GCC */
507#endif
508#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
509 int vreplace_mode;
510#endif
511 int did_append; /* appended a new line */
512 int saved_pi = curbuf->b_p_pi; /* copy of preserveindent setting */
513
514 /*
515 * make a copy of the current line so we can mess with it
516 */
517 saved_line = vim_strsave(ml_get_curline());
518 if (saved_line == NULL) /* out of memory! */
519 return FALSE;
520
521#ifdef FEAT_VREPLACE
522 if (State & VREPLACE_FLAG)
523 {
524 /*
525 * With VREPLACE we make a copy of the next line, which we will be
526 * starting to replace. First make the new line empty and let vim play
527 * with the indenting and comment leader to its heart's content. Then
528 * we grab what it ended up putting on the new line, put back the
529 * original line, and call ins_char() to put each new character onto
530 * the line, replacing what was there before and pushing the right
531 * stuff onto the replace stack. -- webb.
532 */
533 if (curwin->w_cursor.lnum < orig_line_count)
534 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
535 else
536 next_line = vim_strsave((char_u *)"");
537 if (next_line == NULL) /* out of memory! */
538 goto theend;
539
540 /*
541 * In VREPLACE mode, a NL replaces the rest of the line, and starts
542 * replacing the next line, so push all of the characters left on the
543 * line onto the replace stack. We'll push any other characters that
544 * might be replaced at the start of the next line (due to autoindent
545 * etc) a bit later.
546 */
547 replace_push(NUL); /* Call twice because BS over NL expects it */
548 replace_push(NUL);
549 p = saved_line + curwin->w_cursor.col;
550 while (*p != NUL)
551 replace_push(*p++);
552 saved_line[curwin->w_cursor.col] = NUL;
553 }
554#endif
555
556 if ((State & INSERT)
557#ifdef FEAT_VREPLACE
558 && !(State & VREPLACE_FLAG)
559#endif
560 )
561 {
562 p_extra = saved_line + curwin->w_cursor.col;
563#ifdef FEAT_SMARTINDENT
564 if (do_si) /* need first char after new line break */
565 {
566 p = skipwhite(p_extra);
567 first_char = *p;
568 }
569#endif
570#ifdef FEAT_COMMENTS
571 extra_len = (int)STRLEN(p_extra);
572#endif
573 saved_char = *p_extra;
574 *p_extra = NUL;
575 }
576
577 u_clearline(); /* cannot do "U" command when adding lines */
578#ifdef FEAT_SMARTINDENT
579 did_si = FALSE;
580#endif
581 ai_col = 0;
582
583 /*
584 * If we just did an auto-indent, then we didn't type anything on
585 * the prior line, and it should be truncated. Do this even if 'ai' is not
586 * set because automatically inserting a comment leader also sets did_ai.
587 */
588 if (dir == FORWARD && did_ai)
589 trunc_line = TRUE;
590
591 /*
592 * If 'autoindent' and/or 'smartindent' is set, try to figure out what
593 * indent to use for the new line.
594 */
595 if (curbuf->b_p_ai
596#ifdef FEAT_SMARTINDENT
597 || do_si
598#endif
599 )
600 {
601 /*
602 * count white space on current line
603 */
604 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts);
605 if (newindent == 0)
606 newindent = old_indent; /* for ^^D command in insert mode */
607
608#ifdef FEAT_SMARTINDENT
609 /*
610 * Do smart indenting.
611 * In insert/replace mode (only when dir == FORWARD)
612 * we may move some text to the next line. If it starts with '{'
613 * don't add an indent. Fixes inserting a NL before '{' in line
614 * "if (condition) {"
615 */
616 if (!trunc_line && do_si && *saved_line != NUL
617 && (p_extra == NULL || first_char != '{'))
618 {
619 char_u *ptr;
620 char_u last_char;
621
622 old_cursor = curwin->w_cursor;
623 ptr = saved_line;
624# ifdef FEAT_COMMENTS
625 if (flags & OPENLINE_DO_COM)
626 lead_len = get_leader_len(ptr, NULL, FALSE);
627 else
628 lead_len = 0;
629# endif
630 if (dir == FORWARD)
631 {
632 /*
633 * Skip preprocessor directives, unless they are
634 * recognised as comments.
635 */
636 if (
637# ifdef FEAT_COMMENTS
638 lead_len == 0 &&
639# endif
640 ptr[0] == '#')
641 {
642 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
643 ptr = ml_get(--curwin->w_cursor.lnum);
644 newindent = get_indent();
645 }
646# ifdef FEAT_COMMENTS
647 if (flags & OPENLINE_DO_COM)
648 lead_len = get_leader_len(ptr, NULL, FALSE);
649 else
650 lead_len = 0;
651 if (lead_len > 0)
652 {
653 /*
654 * This case gets the following right:
655 * \*
656 * * A comment (read '\' as '/').
657 * *\
658 * #define IN_THE_WAY
659 * This should line up here;
660 */
661 p = skipwhite(ptr);
662 if (p[0] == '/' && p[1] == '*')
663 p++;
664 if (p[0] == '*')
665 {
666 for (p++; *p; p++)
667 {
668 if (p[0] == '/' && p[-1] == '*')
669 {
670 /*
671 * End of C comment, indent should line up
672 * with the line containing the start of
673 * the comment
674 */
675 curwin->w_cursor.col = (colnr_T)(p - ptr);
676 if ((pos = findmatch(NULL, NUL)) != NULL)
677 {
678 curwin->w_cursor.lnum = pos->lnum;
679 newindent = get_indent();
680 }
681 }
682 }
683 }
684 }
685 else /* Not a comment line */
686# endif
687 {
688 /* Find last non-blank in line */
689 p = ptr + STRLEN(ptr) - 1;
690 while (p > ptr && vim_iswhite(*p))
691 --p;
692 last_char = *p;
693
694 /*
695 * find the character just before the '{' or ';'
696 */
697 if (last_char == '{' || last_char == ';')
698 {
699 if (p > ptr)
700 --p;
701 while (p > ptr && vim_iswhite(*p))
702 --p;
703 }
704 /*
705 * Try to catch lines that are split over multiple
706 * lines. eg:
707 * if (condition &&
708 * condition) {
709 * Should line up here!
710 * }
711 */
712 if (*p == ')')
713 {
714 curwin->w_cursor.col = (colnr_T)(p - ptr);
715 if ((pos = findmatch(NULL, '(')) != NULL)
716 {
717 curwin->w_cursor.lnum = pos->lnum;
718 newindent = get_indent();
719 ptr = ml_get_curline();
720 }
721 }
722 /*
723 * If last character is '{' do indent, without
724 * checking for "if" and the like.
725 */
726 if (last_char == '{')
727 {
728 did_si = TRUE; /* do indent */
729 no_si = TRUE; /* don't delete it when '{' typed */
730 }
731 /*
732 * Look for "if" and the like, use 'cinwords'.
733 * Don't do this if the previous line ended in ';' or
734 * '}'.
735 */
736 else if (last_char != ';' && last_char != '}'
737 && cin_is_cinword(ptr))
738 did_si = TRUE;
739 }
740 }
741 else /* dir == BACKWARD */
742 {
743 /*
744 * Skip preprocessor directives, unless they are
745 * recognised as comments.
746 */
747 if (
748# ifdef FEAT_COMMENTS
749 lead_len == 0 &&
750# endif
751 ptr[0] == '#')
752 {
753 int was_backslashed = FALSE;
754
755 while ((ptr[0] == '#' || was_backslashed) &&
756 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
757 {
758 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
759 was_backslashed = TRUE;
760 else
761 was_backslashed = FALSE;
762 ptr = ml_get(++curwin->w_cursor.lnum);
763 }
764 if (was_backslashed)
765 newindent = 0; /* Got to end of file */
766 else
767 newindent = get_indent();
768 }
769 p = skipwhite(ptr);
770 if (*p == '}') /* if line starts with '}': do indent */
771 did_si = TRUE;
772 else /* can delete indent when '{' typed */
773 can_si_back = TRUE;
774 }
775 curwin->w_cursor = old_cursor;
776 }
777 if (do_si)
778 can_si = TRUE;
779#endif /* FEAT_SMARTINDENT */
780
781 did_ai = TRUE;
782 }
783
784#ifdef FEAT_COMMENTS
785 /*
786 * Find out if the current line starts with a comment leader.
787 * This may then be inserted in front of the new line.
788 */
789 end_comment_pending = NUL;
790 if (flags & OPENLINE_DO_COM)
791 lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD);
792 else
793 lead_len = 0;
794 if (lead_len > 0)
795 {
796 char_u *lead_repl = NULL; /* replaces comment leader */
797 int lead_repl_len = 0; /* length of *lead_repl */
798 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
799 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
800 char_u *comment_end = NULL; /* where lead_end has been found */
801 int extra_space = FALSE; /* append extra space */
802 int current_flag;
803 int require_blank = FALSE; /* requires blank after middle */
804 char_u *p2;
805
806 /*
807 * If the comment leader has the start, middle or end flag, it may not
808 * be used or may be replaced with the middle leader.
809 */
810 for (p = lead_flags; *p && *p != ':'; ++p)
811 {
812 if (*p == COM_BLANK)
813 {
814 require_blank = TRUE;
815 continue;
816 }
817 if (*p == COM_START || *p == COM_MIDDLE)
818 {
819 current_flag = *p;
820 if (*p == COM_START)
821 {
822 /*
823 * Doing "O" on a start of comment does not insert leader.
824 */
825 if (dir == BACKWARD)
826 {
827 lead_len = 0;
828 break;
829 }
830
831 /* find start of middle part */
832 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
833 require_blank = FALSE;
834 }
835
836 /*
837 * Isolate the strings of the middle and end leader.
838 */
839 while (*p && p[-1] != ':') /* find end of middle flags */
840 {
841 if (*p == COM_BLANK)
842 require_blank = TRUE;
843 ++p;
844 }
845 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
846
847 while (*p && p[-1] != ':') /* find end of end flags */
848 {
849 /* Check whether we allow automatic ending of comments */
850 if (*p == COM_AUTO_END)
851 end_comment_pending = -1; /* means we want to set it */
852 ++p;
853 }
854 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
855
856 if (end_comment_pending == -1) /* we can set it now */
857 end_comment_pending = lead_end[n - 1];
858
859 /*
860 * If the end of the comment is in the same line, don't use
861 * the comment leader.
862 */
863 if (dir == FORWARD)
864 {
865 for (p = saved_line + lead_len; *p; ++p)
866 if (STRNCMP(p, lead_end, n) == 0)
867 {
868 comment_end = p;
869 lead_len = 0;
870 break;
871 }
872 }
873
874 /*
875 * Doing "o" on a start of comment inserts the middle leader.
876 */
877 if (lead_len > 0)
878 {
879 if (current_flag == COM_START)
880 {
881 lead_repl = lead_middle;
882 lead_repl_len = (int)STRLEN(lead_middle);
883 }
884
885 /*
886 * If we have hit RETURN immediately after the start
887 * comment leader, then put a space after the middle
888 * comment leader on the next line.
889 */
890 if (!vim_iswhite(saved_line[lead_len - 1])
891 && ((p_extra != NULL
892 && (int)curwin->w_cursor.col == lead_len)
893 || (p_extra == NULL
894 && saved_line[lead_len] == NUL)
895 || require_blank))
896 extra_space = TRUE;
897 }
898 break;
899 }
900 if (*p == COM_END)
901 {
902 /*
903 * Doing "o" on the end of a comment does not insert leader.
904 * Remember where the end is, might want to use it to find the
905 * start (for C-comments).
906 */
907 if (dir == FORWARD)
908 {
909 comment_end = skipwhite(saved_line);
910 lead_len = 0;
911 break;
912 }
913
914 /*
915 * Doing "O" on the end of a comment inserts the middle leader.
916 * Find the string for the middle leader, searching backwards.
917 */
918 while (p > curbuf->b_p_com && *p != ',')
919 --p;
920 for (lead_repl = p; lead_repl > curbuf->b_p_com
921 && lead_repl[-1] != ':'; --lead_repl)
922 ;
923 lead_repl_len = (int)(p - lead_repl);
924
925 /* We can probably always add an extra space when doing "O" on
926 * the comment-end */
927 extra_space = TRUE;
928
929 /* Check whether we allow automatic ending of comments */
930 for (p2 = p; *p2 && *p2 != ':'; p2++)
931 {
932 if (*p2 == COM_AUTO_END)
933 end_comment_pending = -1; /* means we want to set it */
934 }
935 if (end_comment_pending == -1)
936 {
937 /* Find last character in end-comment string */
938 while (*p2 && *p2 != ',')
939 p2++;
940 end_comment_pending = p2[-1];
941 }
942 break;
943 }
944 if (*p == COM_FIRST)
945 {
946 /*
947 * Comment leader for first line only: Don't repeat leader
948 * when using "O", blank out leader when using "o".
949 */
950 if (dir == BACKWARD)
951 lead_len = 0;
952 else
953 {
954 lead_repl = (char_u *)"";
955 lead_repl_len = 0;
956 }
957 break;
958 }
959 }
960 if (lead_len)
961 {
962 /* allocate buffer (may concatenate p_exta later) */
963 leader = alloc(lead_len + lead_repl_len + extra_space +
964 extra_len + 1);
965 allocated = leader; /* remember to free it later */
966
967 if (leader == NULL)
968 lead_len = 0;
969 else
970 {
971 STRNCPY(leader, saved_line, lead_len);
972 leader[lead_len] = NUL;
973
974 /*
975 * Replace leader with lead_repl, right or left adjusted
976 */
977 if (lead_repl != NULL)
978 {
979 int c = 0;
980 int off = 0;
981
982 for (p = lead_flags; *p && *p != ':'; ++p)
983 {
984 if (*p == COM_RIGHT || *p == COM_LEFT)
985 c = *p;
986 else if (VIM_ISDIGIT(*p) || *p == '-')
987 off = getdigits(&p);
988 }
989 if (c == COM_RIGHT) /* right adjusted leader */
990 {
991 /* find last non-white in the leader to line up with */
992 for (p = leader + lead_len - 1; p > leader
993 && vim_iswhite(*p); --p)
994 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +0000996
997#ifdef FEAT_MBYTE
998 /* Compute the length of the replaced characters in
999 * screen characters, not bytes. */
1000 {
1001 int repl_size = vim_strnsize(lead_repl,
1002 lead_repl_len);
1003 int old_size = 0;
1004 char_u *endp = p;
1005 int l;
1006
1007 while (old_size < repl_size && p > leader)
1008 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001009 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001010 old_size += ptr2cells(p);
1011 }
1012 l = lead_repl_len - (endp - p);
1013 if (l != 0)
1014 mch_memmove(endp + l, endp,
1015 (size_t)((leader + lead_len) - endp));
1016 lead_len += l;
1017 }
1018#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 if (p < leader + lead_repl_len)
1020 p = leader;
1021 else
1022 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001023#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1025 if (p + lead_repl_len > leader + lead_len)
1026 p[lead_repl_len] = NUL;
1027
1028 /* blank-out any other chars from the old leader. */
1029 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001030 {
1031#ifdef FEAT_MBYTE
1032 int l = mb_head_off(leader, p);
1033
1034 if (l > 1)
1035 {
1036 p -= l;
1037 if (ptr2cells(p) > 1)
1038 {
1039 p[1] = ' ';
1040 --l;
1041 }
1042 mch_memmove(p + 1, p + l + 1,
1043 (size_t)((leader + lead_len) - (p + l + 1)));
1044 lead_len -= l;
1045 *p = ' ';
1046 }
1047 else
1048#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049 if (!vim_iswhite(*p))
1050 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001051 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052 }
1053 else /* left adjusted leader */
1054 {
1055 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001056#ifdef FEAT_MBYTE
1057 /* Compute the length of the replaced characters in
1058 * screen characters, not bytes. Move the part that is
1059 * not to be overwritten. */
1060 {
1061 int repl_size = vim_strnsize(lead_repl,
1062 lead_repl_len);
1063 int i;
1064 int l;
1065
1066 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1067 {
1068 l = mb_ptr2len_check(p + i);
1069 if (vim_strnsize(p, i + l) > repl_size)
1070 break;
1071 }
1072 if (i != lead_repl_len)
1073 {
1074 mch_memmove(p + lead_repl_len, p + i,
1075 (size_t)(lead_len - i - (leader - p)));
1076 lead_len += lead_repl_len - i;
1077 }
1078 }
1079#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1081
1082 /* Replace any remaining non-white chars in the old
1083 * leader by spaces. Keep Tabs, the indent must
1084 * remain the same. */
1085 for (p += lead_repl_len; p < leader + lead_len; ++p)
1086 if (!vim_iswhite(*p))
1087 {
1088 /* Don't put a space before a TAB. */
1089 if (p + 1 < leader + lead_len && p[1] == TAB)
1090 {
1091 --lead_len;
1092 mch_memmove(p, p + 1,
1093 (leader + lead_len) - p);
1094 }
1095 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001096 {
1097#ifdef FEAT_MBYTE
1098 int l = mb_ptr2len_check(p);
1099
1100 if (l > 1)
1101 {
1102 if (ptr2cells(p) > 1)
1103 {
1104 /* Replace a double-wide char with
1105 * two spaces */
1106 --l;
1107 *p++ = ' ';
1108 }
1109 mch_memmove(p + 1, p + l,
1110 (leader + lead_len) - p);
1111 lead_len -= l - 1;
1112 }
1113#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001114 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001115 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116 }
1117 *p = NUL;
1118 }
1119
1120 /* Recompute the indent, it may have changed. */
1121 if (curbuf->b_p_ai
1122#ifdef FEAT_SMARTINDENT
1123 || do_si
1124#endif
1125 )
1126 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1127
1128 /* Add the indent offset */
1129 if (newindent + off < 0)
1130 {
1131 off = -newindent;
1132 newindent = 0;
1133 }
1134 else
1135 newindent += off;
1136
1137 /* Correct trailing spaces for the shift, so that
1138 * alignment remains equal. */
1139 while (off > 0 && lead_len > 0
1140 && leader[lead_len - 1] == ' ')
1141 {
1142 /* Don't do it when there is a tab before the space */
1143 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1144 break;
1145 --lead_len;
1146 --off;
1147 }
1148
1149 /* If the leader ends in white space, don't add an
1150 * extra space */
1151 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1152 extra_space = FALSE;
1153 leader[lead_len] = NUL;
1154 }
1155
1156 if (extra_space)
1157 {
1158 leader[lead_len++] = ' ';
1159 leader[lead_len] = NUL;
1160 }
1161
1162 newcol = lead_len;
1163
1164 /*
1165 * if a new indent will be set below, remove the indent that
1166 * is in the comment leader
1167 */
1168 if (newindent
1169#ifdef FEAT_SMARTINDENT
1170 || did_si
1171#endif
1172 )
1173 {
1174 while (lead_len && vim_iswhite(*leader))
1175 {
1176 --lead_len;
1177 --newcol;
1178 ++leader;
1179 }
1180 }
1181
1182 }
1183#ifdef FEAT_SMARTINDENT
1184 did_si = can_si = FALSE;
1185#endif
1186 }
1187 else if (comment_end != NULL)
1188 {
1189 /*
1190 * We have finished a comment, so we don't use the leader.
1191 * If this was a C-comment and 'ai' or 'si' is set do a normal
1192 * indent to align with the line containing the start of the
1193 * comment.
1194 */
1195 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1196 (curbuf->b_p_ai
1197#ifdef FEAT_SMARTINDENT
1198 || do_si
1199#endif
1200 ))
1201 {
1202 old_cursor = curwin->w_cursor;
1203 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1204 if ((pos = findmatch(NULL, NUL)) != NULL)
1205 {
1206 curwin->w_cursor.lnum = pos->lnum;
1207 newindent = get_indent();
1208 }
1209 curwin->w_cursor = old_cursor;
1210 }
1211 }
1212 }
1213#endif
1214
1215 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1216 if (p_extra != NULL)
1217 {
1218 *p_extra = saved_char; /* restore char that NUL replaced */
1219
1220 /*
1221 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1222 * non-blank.
1223 *
1224 * When in REPLACE mode, put the deleted blanks on the replace stack,
1225 * preceded by a NUL, so they can be put back when a BS is entered.
1226 */
1227 if (REPLACE_NORMAL(State))
1228 replace_push(NUL); /* end of extra blanks */
1229 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1230 {
1231 while ((*p_extra == ' ' || *p_extra == '\t')
1232#ifdef FEAT_MBYTE
1233 && (!enc_utf8
1234 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1235#endif
1236 )
1237 {
1238 if (REPLACE_NORMAL(State))
1239 replace_push(*p_extra);
1240 ++p_extra;
1241 ++less_cols_off;
1242 }
1243 }
1244 if (*p_extra != NUL)
1245 did_ai = FALSE; /* append some text, don't truncate now */
1246
1247 /* columns for marks adjusted for removed columns */
1248 less_cols = (int)(p_extra - saved_line);
1249 }
1250
1251 if (p_extra == NULL)
1252 p_extra = (char_u *)""; /* append empty line */
1253
1254#ifdef FEAT_COMMENTS
1255 /* concatenate leader and p_extra, if there is a leader */
1256 if (lead_len)
1257 {
1258 STRCAT(leader, p_extra);
1259 p_extra = leader;
1260 did_ai = TRUE; /* So truncating blanks works with comments */
1261 less_cols -= lead_len;
1262 }
1263 else
1264 end_comment_pending = NUL; /* turns out there was no leader */
1265#endif
1266
1267 old_cursor = curwin->w_cursor;
1268 if (dir == BACKWARD)
1269 --curwin->w_cursor.lnum;
1270#ifdef FEAT_VREPLACE
1271 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1272#endif
1273 {
1274 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1275 == FAIL)
1276 goto theend;
1277 /* Postpone calling changed_lines(), because it would mess up folding
1278 * with markers. */
1279 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1280 did_append = TRUE;
1281 }
1282#ifdef FEAT_VREPLACE
1283 else
1284 {
1285 /*
1286 * In VREPLACE mode we are starting to replace the next line.
1287 */
1288 curwin->w_cursor.lnum++;
1289 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1290 {
1291 /* In case we NL to a new line, BS to the previous one, and NL
1292 * again, we don't want to save the new line for undo twice.
1293 */
1294 (void)u_save_cursor(); /* errors are ignored! */
1295 vr_lines_changed++;
1296 }
1297 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1298 changed_bytes(curwin->w_cursor.lnum, 0);
1299 curwin->w_cursor.lnum--;
1300 did_append = FALSE;
1301 }
1302#endif
1303
1304 if (newindent
1305#ifdef FEAT_SMARTINDENT
1306 || did_si
1307#endif
1308 )
1309 {
1310 ++curwin->w_cursor.lnum;
1311#ifdef FEAT_SMARTINDENT
1312 if (did_si)
1313 {
1314 if (p_sr)
1315 newindent -= newindent % (int)curbuf->b_p_sw;
1316 newindent += (int)curbuf->b_p_sw;
1317 }
1318#endif
1319 /* Copy the indent only if expand tab is disabled */
1320 if (curbuf->b_p_ci && !curbuf->b_p_et)
1321 {
1322 (void)copy_indent(newindent, saved_line);
1323
1324 /*
1325 * Set the 'preserveindent' option so that any further screwing
1326 * with the line doesn't entirely destroy our efforts to preserve
1327 * it. It gets restored at the function end.
1328 */
1329 curbuf->b_p_pi = TRUE;
1330 }
1331 else
1332 (void)set_indent(newindent, SIN_INSERT);
1333 less_cols -= curwin->w_cursor.col;
1334
1335 ai_col = curwin->w_cursor.col;
1336
1337 /*
1338 * In REPLACE mode, for each character in the new indent, there must
1339 * be a NUL on the replace stack, for when it is deleted with BS
1340 */
1341 if (REPLACE_NORMAL(State))
1342 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1343 replace_push(NUL);
1344 newcol += curwin->w_cursor.col;
1345#ifdef FEAT_SMARTINDENT
1346 if (no_si)
1347 did_si = FALSE;
1348#endif
1349 }
1350
1351#ifdef FEAT_COMMENTS
1352 /*
1353 * In REPLACE mode, for each character in the extra leader, there must be
1354 * a NUL on the replace stack, for when it is deleted with BS.
1355 */
1356 if (REPLACE_NORMAL(State))
1357 while (lead_len-- > 0)
1358 replace_push(NUL);
1359#endif
1360
1361 curwin->w_cursor = old_cursor;
1362
1363 if (dir == FORWARD)
1364 {
1365 if (trunc_line || (State & INSERT))
1366 {
1367 /* truncate current line at cursor */
1368 saved_line[curwin->w_cursor.col] = NUL;
1369 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1370 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1371 truncate_spaces(saved_line);
1372 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1373 saved_line = NULL;
1374 if (did_append)
1375 {
1376 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1377 curwin->w_cursor.lnum + 1, 1L);
1378 did_append = FALSE;
1379
1380 /* Move marks after the line break to the new line. */
1381 if (flags & OPENLINE_MARKFIX)
1382 mark_col_adjust(curwin->w_cursor.lnum,
1383 curwin->w_cursor.col + less_cols_off,
1384 1L, (long)-less_cols);
1385 }
1386 else
1387 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1388 }
1389
1390 /*
1391 * Put the cursor on the new line. Careful: the scrollup() above may
1392 * have moved w_cursor, we must use old_cursor.
1393 */
1394 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1395 }
1396 if (did_append)
1397 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1398
1399 curwin->w_cursor.col = newcol;
1400#ifdef FEAT_VIRTUALEDIT
1401 curwin->w_cursor.coladd = 0;
1402#endif
1403
1404#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1405 /*
1406 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1407 * fixthisline() from doing it (via change_indent()) by telling it we're in
1408 * normal INSERT mode.
1409 */
1410 if (State & VREPLACE_FLAG)
1411 {
1412 vreplace_mode = State; /* So we know to put things right later */
1413 State = INSERT;
1414 }
1415 else
1416 vreplace_mode = 0;
1417#endif
1418#ifdef FEAT_LISP
1419 /*
1420 * May do lisp indenting.
1421 */
1422 if (!p_paste
1423# ifdef FEAT_COMMENTS
1424 && leader == NULL
1425# endif
1426 && curbuf->b_p_lisp
1427 && curbuf->b_p_ai)
1428 {
1429 fixthisline(get_lisp_indent);
1430 p = ml_get_curline();
1431 ai_col = (colnr_T)(skipwhite(p) - p);
1432 }
1433#endif
1434#ifdef FEAT_CINDENT
1435 /*
1436 * May do indenting after opening a new line.
1437 */
1438 if (!p_paste
1439 && (curbuf->b_p_cin
1440# ifdef FEAT_EVAL
1441 || *curbuf->b_p_inde != NUL
1442# endif
1443 )
1444 && in_cinkeys(dir == FORWARD
1445 ? KEY_OPEN_FORW
1446 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1447 {
1448 do_c_expr_indent();
1449 p = ml_get_curline();
1450 ai_col = (colnr_T)(skipwhite(p) - p);
1451 }
1452#endif
1453#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1454 if (vreplace_mode != 0)
1455 State = vreplace_mode;
1456#endif
1457
1458#ifdef FEAT_VREPLACE
1459 /*
1460 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1461 * original line, and inserts the new stuff char by char, pushing old stuff
1462 * onto the replace stack (via ins_char()).
1463 */
1464 if (State & VREPLACE_FLAG)
1465 {
1466 /* Put new line in p_extra */
1467 p_extra = vim_strsave(ml_get_curline());
1468 if (p_extra == NULL)
1469 goto theend;
1470
1471 /* Put back original line */
1472 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1473
1474 /* Insert new stuff into line again */
1475 curwin->w_cursor.col = 0;
1476#ifdef FEAT_VIRTUALEDIT
1477 curwin->w_cursor.coladd = 0;
1478#endif
1479 ins_bytes(p_extra); /* will call changed_bytes() */
1480 vim_free(p_extra);
1481 next_line = NULL;
1482 }
1483#endif
1484
1485 retval = TRUE; /* success! */
1486theend:
1487 curbuf->b_p_pi = saved_pi;
1488 vim_free(saved_line);
1489 vim_free(next_line);
1490 vim_free(allocated);
1491 return retval;
1492}
1493
1494#if defined(FEAT_COMMENTS) || defined(PROTO)
1495/*
1496 * get_leader_len() returns the length of the prefix of the given string
1497 * which introduces a comment. If this string is not a comment then 0 is
1498 * returned.
1499 * When "flags" is not NULL, it is set to point to the flags of the recognized
1500 * comment leader.
1501 * "backward" must be true for the "O" command.
1502 */
1503 int
1504get_leader_len(line, flags, backward)
1505 char_u *line;
1506 char_u **flags;
1507 int backward;
1508{
1509 int i, j;
1510 int got_com = FALSE;
1511 int found_one;
1512 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1513 char_u *string; /* pointer to comment string */
1514 char_u *list;
1515
1516 i = 0;
1517 while (vim_iswhite(line[i])) /* leading white space is ignored */
1518 ++i;
1519
1520 /*
1521 * Repeat to match several nested comment strings.
1522 */
1523 while (line[i])
1524 {
1525 /*
1526 * scan through the 'comments' option for a match
1527 */
1528 found_one = FALSE;
1529 for (list = curbuf->b_p_com; *list; )
1530 {
1531 /*
1532 * Get one option part into part_buf[]. Advance list to next one.
1533 * put string at start of string.
1534 */
1535 if (!got_com && flags != NULL) /* remember where flags started */
1536 *flags = list;
1537 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1538 string = vim_strchr(part_buf, ':');
1539 if (string == NULL) /* missing ':', ignore this part */
1540 continue;
1541 *string++ = NUL; /* isolate flags from string */
1542
1543 /*
1544 * When already found a nested comment, only accept further
1545 * nested comments.
1546 */
1547 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1548 continue;
1549
1550 /* When 'O' flag used don't use for "O" command */
1551 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1552 continue;
1553
1554 /*
1555 * Line contents and string must match.
1556 * When string starts with white space, must have some white space
1557 * (but the amount does not need to match, there might be a mix of
1558 * TABs and spaces).
1559 */
1560 if (vim_iswhite(string[0]))
1561 {
1562 if (i == 0 || !vim_iswhite(line[i - 1]))
1563 continue;
1564 while (vim_iswhite(string[0]))
1565 ++string;
1566 }
1567 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1568 ;
1569 if (string[j] != NUL)
1570 continue;
1571
1572 /*
1573 * When 'b' flag used, there must be white space or an
1574 * end-of-line after the string in the line.
1575 */
1576 if (vim_strchr(part_buf, COM_BLANK) != NULL
1577 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1578 continue;
1579
1580 /*
1581 * We have found a match, stop searching.
1582 */
1583 i += j;
1584 got_com = TRUE;
1585 found_one = TRUE;
1586 break;
1587 }
1588
1589 /*
1590 * No match found, stop scanning.
1591 */
1592 if (!found_one)
1593 break;
1594
1595 /*
1596 * Include any trailing white space.
1597 */
1598 while (vim_iswhite(line[i]))
1599 ++i;
1600
1601 /*
1602 * If this comment doesn't nest, stop here.
1603 */
1604 if (vim_strchr(part_buf, COM_NEST) == NULL)
1605 break;
1606 }
1607 return (got_com ? i : 0);
1608}
1609#endif
1610
1611/*
1612 * Return the number of window lines occupied by buffer line "lnum".
1613 */
1614 int
1615plines(lnum)
1616 linenr_T lnum;
1617{
1618 return plines_win(curwin, lnum, TRUE);
1619}
1620
1621 int
1622plines_win(wp, lnum, winheight)
1623 win_T *wp;
1624 linenr_T lnum;
1625 int winheight; /* when TRUE limit to window height */
1626{
1627#if defined(FEAT_DIFF) || defined(PROTO)
1628 /* Check for filler lines above this buffer line. When folded the result
1629 * is one line anyway. */
1630 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1631}
1632
1633 int
1634plines_nofill(lnum)
1635 linenr_T lnum;
1636{
1637 return plines_win_nofill(curwin, lnum, TRUE);
1638}
1639
1640 int
1641plines_win_nofill(wp, lnum, winheight)
1642 win_T *wp;
1643 linenr_T lnum;
1644 int winheight; /* when TRUE limit to window height */
1645{
1646#endif
1647 int lines;
1648
1649 if (!wp->w_p_wrap)
1650 return 1;
1651
1652#ifdef FEAT_VERTSPLIT
1653 if (wp->w_width == 0)
1654 return 1;
1655#endif
1656
1657#ifdef FEAT_FOLDING
1658 /* A folded lines is handled just like an empty line. */
1659 /* NOTE: Caller must handle lines that are MAYBE folded. */
1660 if (lineFolded(wp, lnum) == TRUE)
1661 return 1;
1662#endif
1663
1664 lines = plines_win_nofold(wp, lnum);
1665 if (winheight > 0 && lines > wp->w_height)
1666 return (int)wp->w_height;
1667 return lines;
1668}
1669
1670/*
1671 * Return number of window lines physical line "lnum" will occupy in window
1672 * "wp". Does not care about folding, 'wrap' or 'diff'.
1673 */
1674 int
1675plines_win_nofold(wp, lnum)
1676 win_T *wp;
1677 linenr_T lnum;
1678{
1679 char_u *s;
1680 long col;
1681 int width;
1682
1683 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1684 if (*s == NUL) /* empty line */
1685 return 1;
1686 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1687
1688 /*
1689 * If list mode is on, then the '$' at the end of the line may take up one
1690 * extra column.
1691 */
1692 if (wp->w_p_list && lcs_eol != NUL)
1693 col += 1;
1694
1695 /*
1696 * Add column offset for 'number' and 'foldcolumn'.
1697 */
1698 width = W_WIDTH(wp) - win_col_off(wp);
1699 if (width <= 0)
1700 return 32000;
1701 if (col <= width)
1702 return 1;
1703 col -= width;
1704 width += win_col_off2(wp);
1705 return (col + (width - 1)) / width + 1;
1706}
1707
1708/*
1709 * Like plines_win(), but only reports the number of physical screen lines
1710 * used from the start of the line to the given column number.
1711 */
1712 int
1713plines_win_col(wp, lnum, column)
1714 win_T *wp;
1715 linenr_T lnum;
1716 long column;
1717{
1718 long col;
1719 char_u *s;
1720 int lines = 0;
1721 int width;
1722
1723#ifdef FEAT_DIFF
1724 /* Check for filler lines above this buffer line. When folded the result
1725 * is one line anyway. */
1726 lines = diff_check_fill(wp, lnum);
1727#endif
1728
1729 if (!wp->w_p_wrap)
1730 return lines + 1;
1731
1732#ifdef FEAT_VERTSPLIT
1733 if (wp->w_width == 0)
1734 return lines + 1;
1735#endif
1736
1737 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1738
1739 col = 0;
1740 while (*s != NUL && --column >= 0)
1741 {
1742 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001743 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 }
1745
1746 /*
1747 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1748 * INSERT mode, then col must be adjusted so that it represents the last
1749 * screen position of the TAB. This only fixes an error when the TAB wraps
1750 * from one screen line to the next (when 'columns' is not a multiple of
1751 * 'ts') -- webb.
1752 */
1753 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1754 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1755
1756 /*
1757 * Add column offset for 'number', 'foldcolumn', etc.
1758 */
1759 width = W_WIDTH(wp) - win_col_off(wp);
1760 if (width > 0)
1761 {
1762 lines += 1;
1763 if (col >= width)
1764 lines += (col - width) / (width + win_col_off2(wp));
1765 if (lines <= wp->w_height)
1766 return lines;
1767 }
1768 return (int)(wp->w_height); /* maximum length */
1769}
1770
1771 int
1772plines_m_win(wp, first, last)
1773 win_T *wp;
1774 linenr_T first, last;
1775{
1776 int count = 0;
1777
1778 while (first <= last)
1779 {
1780#ifdef FEAT_FOLDING
1781 int x;
1782
1783 /* Check if there are any really folded lines, but also included lines
1784 * that are maybe folded. */
1785 x = foldedCount(wp, first, NULL);
1786 if (x > 0)
1787 {
1788 ++count; /* count 1 for "+-- folded" line */
1789 first += x;
1790 }
1791 else
1792#endif
1793 {
1794#ifdef FEAT_DIFF
1795 if (first == wp->w_topline)
1796 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1797 else
1798#endif
1799 count += plines_win(wp, first, TRUE);
1800 ++first;
1801 }
1802 }
1803 return (count);
1804}
1805
1806#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1807/*
1808 * Insert string "p" at the cursor position. Stops at a NUL byte.
1809 * Handles Replace mode and multi-byte characters.
1810 */
1811 void
1812ins_bytes(p)
1813 char_u *p;
1814{
1815 ins_bytes_len(p, (int)STRLEN(p));
1816}
1817#endif
1818
1819#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1820 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1821/*
1822 * Insert string "p" with length "len" at the cursor position.
1823 * Handles Replace mode and multi-byte characters.
1824 */
1825 void
1826ins_bytes_len(p, len)
1827 char_u *p;
1828 int len;
1829{
1830 int i;
1831# ifdef FEAT_MBYTE
1832 int n;
1833
1834 for (i = 0; i < len; i += n)
1835 {
1836 n = (*mb_ptr2len_check)(p + i);
1837 ins_char_bytes(p + i, n);
1838 }
1839# else
1840 for (i = 0; i < len; ++i)
1841 ins_char(p[i]);
1842# endif
1843}
1844#endif
1845
1846/*
1847 * Insert or replace a single character at the cursor position.
1848 * When in REPLACE or VREPLACE mode, replace any existing character.
1849 * Caller must have prepared for undo.
1850 * For multi-byte characters we get the whole character, the caller must
1851 * convert bytes to a character.
1852 */
1853 void
1854ins_char(c)
1855 int c;
1856{
1857#if defined(FEAT_MBYTE) || defined(PROTO)
1858 char_u buf[MB_MAXBYTES];
1859 int n;
1860
1861 n = (*mb_char2bytes)(c, buf);
1862
1863 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1864 * Happens for CTRL-Vu9900. */
1865 if (buf[0] == 0)
1866 buf[0] = '\n';
1867
1868 ins_char_bytes(buf, n);
1869}
1870
1871 void
1872ins_char_bytes(buf, charlen)
1873 char_u *buf;
1874 int charlen;
1875{
1876 int c = buf[0];
1877 int l, j;
1878#endif
1879 int newlen; /* nr of bytes inserted */
1880 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1881 char_u *p;
1882 char_u *newp;
1883 char_u *oldp;
1884 int linelen; /* length of old line including NUL */
1885 colnr_T col;
1886 linenr_T lnum = curwin->w_cursor.lnum;
1887 int i;
1888
1889#ifdef FEAT_VIRTUALEDIT
1890 /* Break tabs if needed. */
1891 if (virtual_active() && curwin->w_cursor.coladd > 0)
1892 coladvance_force(getviscol());
1893#endif
1894
1895 col = curwin->w_cursor.col;
1896 oldp = ml_get(lnum);
1897 linelen = (int)STRLEN(oldp) + 1;
1898
1899 /* The lengths default to the values for when not replacing. */
1900 oldlen = 0;
1901#ifdef FEAT_MBYTE
1902 newlen = charlen;
1903#else
1904 newlen = 1;
1905#endif
1906
1907 if (State & REPLACE_FLAG)
1908 {
1909#ifdef FEAT_VREPLACE
1910 if (State & VREPLACE_FLAG)
1911 {
1912 colnr_T new_vcol = 0; /* init for GCC */
1913 colnr_T vcol;
1914 int old_list;
1915#ifndef FEAT_MBYTE
1916 char_u buf[2];
1917#endif
1918
1919 /*
1920 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1921 * Returns the old value of list, so when finished,
1922 * curwin->w_p_list should be set back to this.
1923 */
1924 old_list = curwin->w_p_list;
1925 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
1926 curwin->w_p_list = FALSE;
1927
1928 /*
1929 * In virtual replace mode each character may replace one or more
1930 * characters (zero if it's a TAB). Count the number of bytes to
1931 * be deleted to make room for the new character, counting screen
1932 * cells. May result in adding spaces to fill a gap.
1933 */
1934 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
1935#ifndef FEAT_MBYTE
1936 buf[0] = c;
1937 buf[1] = NUL;
1938#endif
1939 new_vcol = vcol + chartabsize(buf, vcol);
1940 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
1941 {
1942 vcol += chartabsize(oldp + col + oldlen, vcol);
1943 /* Don't need to remove a TAB that takes us to the right
1944 * position. */
1945 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
1946 break;
1947#ifdef FEAT_MBYTE
1948 oldlen += (*mb_ptr2len_check)(oldp + col + oldlen);
1949#else
1950 ++oldlen;
1951#endif
1952 /* Deleted a bit too much, insert spaces. */
1953 if (vcol > new_vcol)
1954 newlen += vcol - new_vcol;
1955 }
1956 curwin->w_p_list = old_list;
1957 }
1958 else
1959#endif
1960 if (oldp[col] != NUL)
1961 {
1962 /* normal replace */
1963#ifdef FEAT_MBYTE
1964 oldlen = (*mb_ptr2len_check)(oldp + col);
1965#else
1966 oldlen = 1;
1967#endif
1968 }
1969
1970
1971 /* Push the replaced bytes onto the replace stack, so that they can be
1972 * put back when BS is used. The bytes of a multi-byte character are
1973 * done the other way around, so that the first byte is popped off
1974 * first (it tells the byte length of the character). */
1975 replace_push(NUL);
1976 for (i = 0; i < oldlen; ++i)
1977 {
1978#ifdef FEAT_MBYTE
1979 l = (*mb_ptr2len_check)(oldp + col + i) - 1;
1980 for (j = l; j >= 0; --j)
1981 replace_push(oldp[col + i + j]);
1982 i += l;
1983#else
1984 replace_push(oldp[col + i]);
1985#endif
1986 }
1987 }
1988
1989 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
1990 if (newp == NULL)
1991 return;
1992
1993 /* Copy bytes before the cursor. */
1994 if (col > 0)
1995 mch_memmove(newp, oldp, (size_t)col);
1996
1997 /* Copy bytes after the changed character(s). */
1998 p = newp + col;
1999 mch_memmove(p + newlen, oldp + col + oldlen,
2000 (size_t)(linelen - col - oldlen));
2001
2002 /* Insert or overwrite the new character. */
2003#ifdef FEAT_MBYTE
2004 mch_memmove(p, buf, charlen);
2005 i = charlen;
2006#else
2007 *p = c;
2008 i = 1;
2009#endif
2010
2011 /* Fill with spaces when necessary. */
2012 while (i < newlen)
2013 p[i++] = ' ';
2014
2015 /* Replace the line in the buffer. */
2016 ml_replace(lnum, newp, FALSE);
2017
2018 /* mark the buffer as changed and prepare for displaying */
2019 changed_bytes(lnum, col);
2020
2021 /*
2022 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2023 * show the match for right parens and braces.
2024 */
2025 if (p_sm && (State & INSERT)
2026 && msg_silent == 0
2027#ifdef FEAT_MBYTE
2028 && charlen == 1
2029#endif
2030 )
2031 showmatch(c);
2032
2033#ifdef FEAT_RIGHTLEFT
2034 if (!p_ri || (State & REPLACE_FLAG))
2035#endif
2036 {
2037 /* Normal insert: move cursor right */
2038#ifdef FEAT_MBYTE
2039 curwin->w_cursor.col += charlen;
2040#else
2041 ++curwin->w_cursor.col;
2042#endif
2043 }
2044 /*
2045 * TODO: should try to update w_row here, to avoid recomputing it later.
2046 */
2047}
2048
2049/*
2050 * Insert a string at the cursor position.
2051 * Note: Does NOT handle Replace mode.
2052 * Caller must have prepared for undo.
2053 */
2054 void
2055ins_str(s)
2056 char_u *s;
2057{
2058 char_u *oldp, *newp;
2059 int newlen = (int)STRLEN(s);
2060 int oldlen;
2061 colnr_T col;
2062 linenr_T lnum = curwin->w_cursor.lnum;
2063
2064#ifdef FEAT_VIRTUALEDIT
2065 if (virtual_active() && curwin->w_cursor.coladd > 0)
2066 coladvance_force(getviscol());
2067#endif
2068
2069 col = curwin->w_cursor.col;
2070 oldp = ml_get(lnum);
2071 oldlen = (int)STRLEN(oldp);
2072
2073 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2074 if (newp == NULL)
2075 return;
2076 if (col > 0)
2077 mch_memmove(newp, oldp, (size_t)col);
2078 mch_memmove(newp + col, s, (size_t)newlen);
2079 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2080 ml_replace(lnum, newp, FALSE);
2081 changed_bytes(lnum, col);
2082 curwin->w_cursor.col += newlen;
2083}
2084
2085/*
2086 * Delete one character under the cursor.
2087 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2088 * Caller must have prepared for undo.
2089 *
2090 * return FAIL for failure, OK otherwise
2091 */
2092 int
2093del_char(fixpos)
2094 int fixpos;
2095{
2096#ifdef FEAT_MBYTE
2097 if (has_mbyte)
2098 {
2099 /* Make sure the cursor is at the start of a character. */
2100 mb_adjust_cursor();
2101 if (*ml_get_cursor() == NUL)
2102 return FAIL;
2103 return del_chars(1L, fixpos);
2104 }
2105#endif
2106 return del_bytes(1L, fixpos);
2107}
2108
2109#if defined(FEAT_MBYTE) || defined(PROTO)
2110/*
2111 * Like del_bytes(), but delete characters instead of bytes.
2112 */
2113 int
2114del_chars(count, fixpos)
2115 long count;
2116 int fixpos;
2117{
2118 long bytes = 0;
2119 long i;
2120 char_u *p;
2121 int l;
2122
2123 p = ml_get_cursor();
2124 for (i = 0; i < count && *p != NUL; ++i)
2125 {
2126 l = (*mb_ptr2len_check)(p);
2127 bytes += l;
2128 p += l;
2129 }
2130 return del_bytes(bytes, fixpos);
2131}
2132#endif
2133
2134/*
2135 * Delete "count" bytes under the cursor.
2136 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2137 * Caller must have prepared for undo.
2138 *
2139 * return FAIL for failure, OK otherwise
2140 */
2141 int
2142del_bytes(count, fixpos)
2143 long count;
2144 int fixpos;
2145{
2146 char_u *oldp, *newp;
2147 colnr_T oldlen;
2148 linenr_T lnum = curwin->w_cursor.lnum;
2149 colnr_T col = curwin->w_cursor.col;
2150 int was_alloced;
2151 long movelen;
2152
2153 oldp = ml_get(lnum);
2154 oldlen = (int)STRLEN(oldp);
2155
2156 /*
2157 * Can't do anything when the cursor is on the NUL after the line.
2158 */
2159 if (col >= oldlen)
2160 return FAIL;
2161
2162#ifdef FEAT_MBYTE
2163 /* If 'delcombine' is set and deleting (less than) one character, only
2164 * delete the last combining character. */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002165 if (p_deco && enc_utf8 && utfc_ptr2len_check(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002166 {
2167 int c1, c2;
2168 int n;
2169
2170 (void)utfc_ptr2char(oldp + col, &c1, &c2);
2171 if (c1 != NUL)
2172 {
2173 /* Find the last composing char, there can be several. */
2174 n = col;
2175 do
2176 {
2177 col = n;
2178 count = utf_ptr2len_check(oldp + n);
2179 n += count;
2180 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2181 fixpos = 0;
2182 }
2183 }
2184#endif
2185
2186 /*
2187 * When count is too big, reduce it.
2188 */
2189 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2190 if (movelen <= 1)
2191 {
2192 /*
2193 * If we just took off the last character of a non-blank line, and
2194 * fixpos is TRUE, we don't want to end up positioned at the NUL.
2195 */
2196 if (col > 0 && fixpos)
2197 {
2198 --curwin->w_cursor.col;
2199#ifdef FEAT_VIRTUALEDIT
2200 curwin->w_cursor.coladd = 0;
2201#endif
2202#ifdef FEAT_MBYTE
2203 if (has_mbyte)
2204 curwin->w_cursor.col -=
2205 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2206#endif
2207 }
2208 count = oldlen - col;
2209 movelen = 1;
2210 }
2211
2212 /*
2213 * If the old line has been allocated the deletion can be done in the
2214 * existing line. Otherwise a new line has to be allocated
2215 */
2216 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
2217#ifdef FEAT_NETBEANS_INTG
2218 if (was_alloced && usingNetbeans)
2219 netbeans_removed(curbuf, lnum, col, count);
2220 /* else is handled by ml_replace() */
2221#endif
2222 if (was_alloced)
2223 newp = oldp; /* use same allocated memory */
2224 else
2225 { /* need to allocate a new line */
2226 newp = alloc((unsigned)(oldlen + 1 - count));
2227 if (newp == NULL)
2228 return FAIL;
2229 mch_memmove(newp, oldp, (size_t)col);
2230 }
2231 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2232 if (!was_alloced)
2233 ml_replace(lnum, newp, FALSE);
2234
2235 /* mark the buffer as changed and prepare for displaying */
2236 changed_bytes(lnum, curwin->w_cursor.col);
2237
2238 return OK;
2239}
2240
2241/*
2242 * Delete from cursor to end of line.
2243 * Caller must have prepared for undo.
2244 *
2245 * return FAIL for failure, OK otherwise
2246 */
2247 int
2248truncate_line(fixpos)
2249 int fixpos; /* if TRUE fix the cursor position when done */
2250{
2251 char_u *newp;
2252 linenr_T lnum = curwin->w_cursor.lnum;
2253 colnr_T col = curwin->w_cursor.col;
2254
2255 if (col == 0)
2256 newp = vim_strsave((char_u *)"");
2257 else
2258 newp = vim_strnsave(ml_get(lnum), col);
2259
2260 if (newp == NULL)
2261 return FAIL;
2262
2263 ml_replace(lnum, newp, FALSE);
2264
2265 /* mark the buffer as changed and prepare for displaying */
2266 changed_bytes(lnum, curwin->w_cursor.col);
2267
2268 /*
2269 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2270 */
2271 if (fixpos && curwin->w_cursor.col > 0)
2272 --curwin->w_cursor.col;
2273
2274 return OK;
2275}
2276
2277/*
2278 * Delete "nlines" lines at the cursor.
2279 * Saves the lines for undo first if "undo" is TRUE.
2280 */
2281 void
2282del_lines(nlines, undo)
2283 long nlines; /* number of lines to delete */
2284 int undo; /* if TRUE, prepare for undo */
2285{
2286 long n;
2287
2288 if (nlines <= 0)
2289 return;
2290
2291 /* save the deleted lines for undo */
2292 if (undo && u_savedel(curwin->w_cursor.lnum, nlines) == FAIL)
2293 return;
2294
2295 for (n = 0; n < nlines; )
2296 {
2297 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2298 break;
2299
2300 ml_delete(curwin->w_cursor.lnum, TRUE);
2301 ++n;
2302
2303 /* If we delete the last line in the file, stop */
2304 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
2305 break;
2306 }
2307 /* adjust marks, mark the buffer as changed and prepare for displaying */
2308 deleted_lines_mark(curwin->w_cursor.lnum, n);
2309
2310 curwin->w_cursor.col = 0;
2311 check_cursor_lnum();
2312}
2313
2314 int
2315gchar_pos(pos)
2316 pos_T *pos;
2317{
2318 char_u *ptr = ml_get_pos(pos);
2319
2320#ifdef FEAT_MBYTE
2321 if (has_mbyte)
2322 return (*mb_ptr2char)(ptr);
2323#endif
2324 return (int)*ptr;
2325}
2326
2327 int
2328gchar_cursor()
2329{
2330#ifdef FEAT_MBYTE
2331 if (has_mbyte)
2332 return (*mb_ptr2char)(ml_get_cursor());
2333#endif
2334 return (int)*ml_get_cursor();
2335}
2336
2337/*
2338 * Write a character at the current cursor position.
2339 * It is directly written into the block.
2340 */
2341 void
2342pchar_cursor(c)
2343 int c;
2344{
2345 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2346 + curwin->w_cursor.col) = c;
2347}
2348
2349#if 0 /* not used */
2350/*
2351 * Put *pos at end of current buffer
2352 */
2353 void
2354goto_endofbuf(pos)
2355 pos_T *pos;
2356{
2357 char_u *p;
2358
2359 pos->lnum = curbuf->b_ml.ml_line_count;
2360 pos->col = 0;
2361 p = ml_get(pos->lnum);
2362 while (*p++)
2363 ++pos->col;
2364}
2365#endif
2366
2367/*
2368 * When extra == 0: Return TRUE if the cursor is before or on the first
2369 * non-blank in the line.
2370 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2371 * the line.
2372 */
2373 int
2374inindent(extra)
2375 int extra;
2376{
2377 char_u *ptr;
2378 colnr_T col;
2379
2380 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2381 ++ptr;
2382 if (col >= curwin->w_cursor.col + extra)
2383 return TRUE;
2384 else
2385 return FALSE;
2386}
2387
2388/*
2389 * Skip to next part of an option argument: Skip space and comma.
2390 */
2391 char_u *
2392skip_to_option_part(p)
2393 char_u *p;
2394{
2395 if (*p == ',')
2396 ++p;
2397 while (*p == ' ')
2398 ++p;
2399 return p;
2400}
2401
2402/*
2403 * changed() is called when something in the current buffer is changed.
2404 *
2405 * Most often called through changed_bytes() and changed_lines(), which also
2406 * mark the area of the display to be redrawn.
2407 */
2408 void
2409changed()
2410{
2411#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2412 /* The text of the preediting area is inserted, but this doesn't
2413 * mean a change of the buffer yet. That is delayed until the
2414 * text is committed. (this means preedit becomes empty) */
2415 if (im_is_preediting() && !xim_changed_while_preediting)
2416 return;
2417 xim_changed_while_preediting = FALSE;
2418#endif
2419
2420 if (!curbuf->b_changed)
2421 {
2422 int save_msg_scroll = msg_scroll;
2423
2424 change_warning(0);
2425 /* Create a swap file if that is wanted.
2426 * Don't do this for "nofile" and "nowrite" buffer types. */
2427 if (curbuf->b_may_swap
2428#ifdef FEAT_QUICKFIX
2429 && !bt_dontwrite(curbuf)
2430#endif
2431 )
2432 {
2433 ml_open_file(curbuf);
2434
2435 /* The ml_open_file() can cause an ATTENTION message.
2436 * Wait two seconds, to make sure the user reads this unexpected
2437 * message. Since we could be anywhere, call wait_return() now,
2438 * and don't let the emsg() set msg_scroll. */
2439 if (need_wait_return && emsg_silent == 0)
2440 {
2441 out_flush();
2442 ui_delay(2000L, TRUE);
2443 wait_return(TRUE);
2444 msg_scroll = save_msg_scroll;
2445 }
2446 }
2447 curbuf->b_changed = TRUE;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002448 ml_setflags(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002449#ifdef FEAT_WINDOWS
2450 check_status(curbuf);
2451#endif
2452#ifdef FEAT_TITLE
2453 need_maketitle = TRUE; /* set window title later */
2454#endif
2455 }
2456 ++curbuf->b_changedtick;
2457 ++global_changedtick;
2458}
2459
2460static void changedOneline __ARGS((linenr_T lnum));
2461static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2462
2463/*
2464 * Changed bytes within a single line for the current buffer.
2465 * - marks the windows on this buffer to be redisplayed
2466 * - marks the buffer changed by calling changed()
2467 * - invalidates cached values
2468 */
2469 void
2470changed_bytes(lnum, col)
2471 linenr_T lnum;
2472 colnr_T col;
2473{
2474 changedOneline(lnum);
2475 changed_common(lnum, col, lnum + 1, 0L);
2476}
2477
2478 static void
2479changedOneline(lnum)
2480 linenr_T lnum;
2481{
2482 if (curbuf->b_mod_set)
2483 {
2484 /* find the maximum area that must be redisplayed */
2485 if (lnum < curbuf->b_mod_top)
2486 curbuf->b_mod_top = lnum;
2487 else if (lnum >= curbuf->b_mod_bot)
2488 curbuf->b_mod_bot = lnum + 1;
2489 }
2490 else
2491 {
2492 /* set the area that must be redisplayed to one line */
2493 curbuf->b_mod_set = TRUE;
2494 curbuf->b_mod_top = lnum;
2495 curbuf->b_mod_bot = lnum + 1;
2496 curbuf->b_mod_xlines = 0;
2497 }
2498}
2499
2500/*
2501 * Appended "count" lines below line "lnum" in the current buffer.
2502 * Must be called AFTER the change and after mark_adjust().
2503 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2504 */
2505 void
2506appended_lines(lnum, count)
2507 linenr_T lnum;
2508 long count;
2509{
2510 changed_lines(lnum + 1, 0, lnum + 1, count);
2511}
2512
2513/*
2514 * Like appended_lines(), but adjust marks first.
2515 */
2516 void
2517appended_lines_mark(lnum, count)
2518 linenr_T lnum;
2519 long count;
2520{
2521 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2522 changed_lines(lnum + 1, 0, lnum + 1, count);
2523}
2524
2525/*
2526 * Deleted "count" lines at line "lnum" in the current buffer.
2527 * Must be called AFTER the change and after mark_adjust().
2528 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2529 */
2530 void
2531deleted_lines(lnum, count)
2532 linenr_T lnum;
2533 long count;
2534{
2535 changed_lines(lnum, 0, lnum + count, -count);
2536}
2537
2538/*
2539 * Like deleted_lines(), but adjust marks first.
2540 */
2541 void
2542deleted_lines_mark(lnum, count)
2543 linenr_T lnum;
2544 long count;
2545{
2546 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2547 changed_lines(lnum, 0, lnum + count, -count);
2548}
2549
2550/*
2551 * Changed lines for the current buffer.
2552 * Must be called AFTER the change and after mark_adjust().
2553 * - mark the buffer changed by calling changed()
2554 * - mark the windows on this buffer to be redisplayed
2555 * - invalidate cached values
2556 * "lnum" is the first line that needs displaying, "lnume" the first line
2557 * below the changed lines (BEFORE the change).
2558 * When only inserting lines, "lnum" and "lnume" are equal.
2559 * Takes care of calling changed() and updating b_mod_*.
2560 */
2561 void
2562changed_lines(lnum, col, lnume, xtra)
2563 linenr_T lnum; /* first line with change */
2564 colnr_T col; /* column in first line with change */
2565 linenr_T lnume; /* line below last changed line */
2566 long xtra; /* number of extra lines (negative when deleting) */
2567{
2568 if (curbuf->b_mod_set)
2569 {
2570 /* find the maximum area that must be redisplayed */
2571 if (lnum < curbuf->b_mod_top)
2572 curbuf->b_mod_top = lnum;
2573 if (lnum < curbuf->b_mod_bot)
2574 {
2575 /* adjust old bot position for xtra lines */
2576 curbuf->b_mod_bot += xtra;
2577 if (curbuf->b_mod_bot < lnum)
2578 curbuf->b_mod_bot = lnum;
2579 }
2580 if (lnume + xtra > curbuf->b_mod_bot)
2581 curbuf->b_mod_bot = lnume + xtra;
2582 curbuf->b_mod_xlines += xtra;
2583 }
2584 else
2585 {
2586 /* set the area that must be redisplayed */
2587 curbuf->b_mod_set = TRUE;
2588 curbuf->b_mod_top = lnum;
2589 curbuf->b_mod_bot = lnume + xtra;
2590 curbuf->b_mod_xlines = xtra;
2591 }
2592
2593 changed_common(lnum, col, lnume, xtra);
2594}
2595
2596 static void
2597changed_common(lnum, col, lnume, xtra)
2598 linenr_T lnum;
2599 colnr_T col;
2600 linenr_T lnume;
2601 long xtra;
2602{
2603 win_T *wp;
2604 int i;
2605#ifdef FEAT_JUMPLIST
2606 int cols;
2607 pos_T *p;
2608 int add;
2609#endif
2610
2611 /* mark the buffer as modified */
2612 changed();
2613
2614 /* set the '. mark */
2615 if (!cmdmod.keepjumps)
2616 {
2617 curbuf->b_last_change.lnum = lnum;
2618 curbuf->b_last_change.col = col;
2619
2620#ifdef FEAT_JUMPLIST
2621 /* Create a new entry if a new undo-able change was started or we
2622 * don't have an entry yet. */
2623 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2624 {
2625 if (curbuf->b_changelistlen == 0)
2626 add = TRUE;
2627 else
2628 {
2629 /* Don't create a new entry when the line number is the same
2630 * as the last one and the column is not too far away. Avoids
2631 * creating many entries for typing "xxxxx". */
2632 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2633 if (p->lnum != lnum)
2634 add = TRUE;
2635 else
2636 {
2637 cols = comp_textwidth(FALSE);
2638 if (cols == 0)
2639 cols = 79;
2640 add = (p->col + cols < col || col + cols < p->col);
2641 }
2642 }
2643 if (add)
2644 {
2645 /* This is the first of a new sequence of undo-able changes
2646 * and it's at some distance of the last change. Use a new
2647 * position in the changelist. */
2648 curbuf->b_new_change = FALSE;
2649
2650 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2651 {
2652 /* changelist is full: remove oldest entry */
2653 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2654 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2655 sizeof(pos_T) * (JUMPLISTSIZE - 1));
2656 FOR_ALL_WINDOWS(wp)
2657 {
2658 /* Correct position in changelist for other windows on
2659 * this buffer. */
2660 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2661 --wp->w_changelistidx;
2662 }
2663 }
2664 FOR_ALL_WINDOWS(wp)
2665 {
2666 /* For other windows, if the position in the changelist is
2667 * at the end it stays at the end. */
2668 if (wp->w_buffer == curbuf
2669 && wp->w_changelistidx == curbuf->b_changelistlen)
2670 ++wp->w_changelistidx;
2671 }
2672 ++curbuf->b_changelistlen;
2673 }
2674 }
2675 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2676 curbuf->b_last_change;
2677 /* The current window is always after the last change, so that "g,"
2678 * takes you back to it. */
2679 curwin->w_changelistidx = curbuf->b_changelistlen;
2680#endif
2681 }
2682
2683 FOR_ALL_WINDOWS(wp)
2684 {
2685 if (wp->w_buffer == curbuf)
2686 {
2687 /* Mark this window to be redrawn later. */
2688 if (wp->w_redr_type < VALID)
2689 wp->w_redr_type = VALID;
2690
2691 /* Check if a change in the buffer has invalidated the cached
2692 * values for the cursor. */
2693#ifdef FEAT_FOLDING
2694 /*
2695 * Update the folds for this window. Can't postpone this, because
2696 * a following operator might work on the whole fold: ">>dd".
2697 */
2698 foldUpdate(wp, lnum, lnume + xtra - 1);
2699
2700 /* The change may cause lines above or below the change to become
2701 * included in a fold. Set lnum/lnume to the first/last line that
2702 * might be displayed differently.
2703 * Set w_cline_folded here as an efficient way to update it when
2704 * inserting lines just above a closed fold. */
2705 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2706 if (wp->w_cursor.lnum == lnum)
2707 wp->w_cline_folded = i;
2708 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2709 if (wp->w_cursor.lnum == lnume)
2710 wp->w_cline_folded = i;
2711
2712 /* If the changed line is in a range of previously folded lines,
2713 * compare with the first line in that range. */
2714 if (wp->w_cursor.lnum <= lnum)
2715 {
2716 i = find_wl_entry(wp, lnum);
2717 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2718 changed_line_abv_curs_win(wp);
2719 }
2720#endif
2721
2722 if (wp->w_cursor.lnum > lnum)
2723 changed_line_abv_curs_win(wp);
2724 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2725 changed_cline_bef_curs_win(wp);
2726 if (wp->w_botline >= lnum)
2727 {
2728 /* Assume that botline doesn't change (inserted lines make
2729 * other lines scroll down below botline). */
2730 approximate_botline_win(wp);
2731 }
2732
2733 /* Check if any w_lines[] entries have become invalid.
2734 * For entries below the change: Correct the lnums for
2735 * inserted/deleted lines. Makes it possible to stop displaying
2736 * after the change. */
2737 for (i = 0; i < wp->w_lines_valid; ++i)
2738 if (wp->w_lines[i].wl_valid)
2739 {
2740 if (wp->w_lines[i].wl_lnum >= lnum)
2741 {
2742 if (wp->w_lines[i].wl_lnum < lnume)
2743 {
2744 /* line included in change */
2745 wp->w_lines[i].wl_valid = FALSE;
2746 }
2747 else if (xtra != 0)
2748 {
2749 /* line below change */
2750 wp->w_lines[i].wl_lnum += xtra;
2751#ifdef FEAT_FOLDING
2752 wp->w_lines[i].wl_lastlnum += xtra;
2753#endif
2754 }
2755 }
2756#ifdef FEAT_FOLDING
2757 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2758 {
2759 /* change somewhere inside this range of folded lines,
2760 * may need to be redrawn */
2761 wp->w_lines[i].wl_valid = FALSE;
2762 }
2763#endif
2764 }
2765 }
2766 }
2767
2768 /* Call update_screen() later, which checks out what needs to be redrawn,
2769 * since it notices b_mod_set and then uses b_mod_*. */
2770 if (must_redraw < VALID)
2771 must_redraw = VALID;
2772}
2773
2774/*
2775 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2776 */
2777 void
2778unchanged(buf, ff)
2779 buf_T *buf;
2780 int ff; /* also reset 'fileformat' */
2781{
2782 if (buf->b_changed || (ff && file_ff_differs(buf)))
2783 {
2784 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002785 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786 if (ff)
2787 save_file_ff(buf);
2788#ifdef FEAT_WINDOWS
2789 check_status(buf);
2790#endif
2791#ifdef FEAT_TITLE
2792 need_maketitle = TRUE; /* set window title later */
2793#endif
2794 }
2795 ++buf->b_changedtick;
2796 ++global_changedtick;
2797#ifdef FEAT_NETBEANS_INTG
2798 netbeans_unmodified(buf);
2799#endif
2800}
2801
2802#if defined(FEAT_WINDOWS) || defined(PROTO)
2803/*
2804 * check_status: called when the status bars for the buffer 'buf'
2805 * need to be updated
2806 */
2807 void
2808check_status(buf)
2809 buf_T *buf;
2810{
2811 win_T *wp;
2812
2813 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2814 if (wp->w_buffer == buf && wp->w_status_height)
2815 {
2816 wp->w_redr_status = TRUE;
2817 if (must_redraw < VALID)
2818 must_redraw = VALID;
2819 }
2820}
2821#endif
2822
2823/*
2824 * If the file is readonly, give a warning message with the first change.
2825 * Don't do this for autocommands.
2826 * Don't use emsg(), because it flushes the macro buffer.
2827 * If we have undone all changes b_changed will be FALSE, but b_did_warn
2828 * will be TRUE.
2829 */
2830 void
2831change_warning(col)
2832 int col; /* column for message; non-zero when in insert
2833 mode and 'showmode' is on */
2834{
2835 if (curbuf->b_did_warn == FALSE
2836 && curbufIsChanged() == 0
2837#ifdef FEAT_AUTOCMD
2838 && !autocmd_busy
2839#endif
2840 && curbuf->b_p_ro)
2841 {
2842#ifdef FEAT_AUTOCMD
2843 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
2844 if (!curbuf->b_p_ro)
2845 return;
2846#endif
2847 /*
2848 * Do what msg() does, but with a column offset if the warning should
2849 * be after the mode message.
2850 */
2851 msg_start();
2852 if (msg_row == Rows - 1)
2853 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00002854 msg_source(hl_attr(HLF_W));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002855 MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
2856 hl_attr(HLF_W) | MSG_HIST);
2857 msg_clr_eos();
2858 (void)msg_end();
2859 if (msg_silent == 0 && !silent_mode)
2860 {
2861 out_flush();
2862 ui_delay(1000L, TRUE); /* give the user time to think about it */
2863 }
2864 curbuf->b_did_warn = TRUE;
2865 redraw_cmdline = FALSE; /* don't redraw and erase the message */
2866 if (msg_row < Rows - 1)
2867 showmode();
2868 }
2869}
2870
2871/*
2872 * Ask for a reply from the user, a 'y' or a 'n'.
2873 * No other characters are accepted, the message is repeated until a valid
2874 * reply is entered or CTRL-C is hit.
2875 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
2876 * from any buffers but directly from the user.
2877 *
2878 * return the 'y' or 'n'
2879 */
2880 int
2881ask_yesno(str, direct)
2882 char_u *str;
2883 int direct;
2884{
2885 int r = ' ';
2886 int save_State = State;
2887
2888 if (exiting) /* put terminal in raw mode for this question */
2889 settmode(TMODE_RAW);
2890 ++no_wait_return;
2891#ifdef USE_ON_FLY_SCROLL
2892 dont_scroll = TRUE; /* disallow scrolling here */
2893#endif
2894 State = CONFIRM; /* mouse behaves like with :confirm */
2895#ifdef FEAT_MOUSE
2896 setmouse(); /* disables mouse for xterm */
2897#endif
2898 ++no_mapping;
2899 ++allow_keys; /* no mapping here, but recognize keys */
2900
2901 while (r != 'y' && r != 'n')
2902 {
2903 /* same highlighting as for wait_return */
2904 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
2905 if (direct)
2906 r = get_keystroke();
2907 else
2908 r = safe_vgetc();
2909 if (r == Ctrl_C || r == ESC)
2910 r = 'n';
2911 msg_putchar(r); /* show what you typed */
2912 out_flush();
2913 }
2914 --no_wait_return;
2915 State = save_State;
2916#ifdef FEAT_MOUSE
2917 setmouse();
2918#endif
2919 --no_mapping;
2920 --allow_keys;
2921
2922 return r;
2923}
2924
2925/*
2926 * Get a key stroke directly from the user.
2927 * Ignores mouse clicks and scrollbar events, except a click for the left
2928 * button (used at the more prompt).
2929 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
2930 * Disadvantage: typeahead is ignored.
2931 * Translates the interrupt character for unix to ESC.
2932 */
2933 int
2934get_keystroke()
2935{
2936#define CBUFLEN 151
2937 char_u buf[CBUFLEN];
2938 int len = 0;
2939 int n;
2940 int save_mapped_ctrl_c = mapped_ctrl_c;
2941
2942 mapped_ctrl_c = FALSE; /* mappings are not used here */
2943 for (;;)
2944 {
2945 cursor_on();
2946 out_flush();
2947
2948 /* First time: blocking wait. Second time: wait up to 100ms for a
2949 * terminal code to complete. Leave some room for check_termcode() to
2950 * insert a key code into (max 5 chars plus NUL). And
2951 * fix_input_buffer() can triple the number of bytes. */
2952 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
2953 len == 0 ? -1L : 100L, 0);
2954 if (n > 0)
2955 {
2956 /* Replace zero and CSI by a special key code. */
2957 n = fix_input_buffer(buf + len, n, FALSE);
2958 len += n;
2959 }
2960
2961 /* incomplete termcode: get more characters */
2962 if ((n = check_termcode(1, buf, len)) < 0)
2963 continue;
2964 /* found a termcode: adjust length */
2965 if (n > 0)
2966 len = n;
2967 if (len == 0) /* nothing typed yet */
2968 continue;
2969
2970 /* Handle modifier and/or special key code. */
2971 n = buf[0];
2972 if (n == K_SPECIAL)
2973 {
2974 n = TO_SPECIAL(buf[1], buf[2]);
2975 if (buf[1] == KS_MODIFIER
2976 || n == K_IGNORE
2977#ifdef FEAT_MOUSE
2978 || n == K_LEFTMOUSE_NM
2979 || n == K_LEFTDRAG
2980 || n == K_LEFTRELEASE
2981 || n == K_LEFTRELEASE_NM
2982 || n == K_MIDDLEMOUSE
2983 || n == K_MIDDLEDRAG
2984 || n == K_MIDDLERELEASE
2985 || n == K_RIGHTMOUSE
2986 || n == K_RIGHTDRAG
2987 || n == K_RIGHTRELEASE
2988 || n == K_MOUSEDOWN
2989 || n == K_MOUSEUP
2990 || n == K_X1MOUSE
2991 || n == K_X1DRAG
2992 || n == K_X1RELEASE
2993 || n == K_X2MOUSE
2994 || n == K_X2DRAG
2995 || n == K_X2RELEASE
2996# ifdef FEAT_GUI
2997 || n == K_VER_SCROLLBAR
2998 || n == K_HOR_SCROLLBAR
2999# endif
3000#endif
3001 )
3002 {
3003 if (buf[1] == KS_MODIFIER)
3004 mod_mask = buf[2];
3005 len -= 3;
3006 if (len > 0)
3007 mch_memmove(buf, buf + 3, (size_t)len);
3008 continue;
3009 }
3010 }
3011#ifdef FEAT_MBYTE
3012 if (has_mbyte)
3013 {
3014 if (MB_BYTE2LEN(n) > len)
3015 continue; /* more bytes to get */
3016 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3017 n = (*mb_ptr2char)(buf);
3018 }
3019#endif
3020#ifdef UNIX
3021 if (n == intr_char)
3022 n = ESC;
3023#endif
3024 break;
3025 }
3026
3027 mapped_ctrl_c = save_mapped_ctrl_c;
3028 return n;
3029}
3030
3031/*
3032 * get a number from the user
3033 */
3034 int
3035get_number(colon)
3036 int colon; /* allow colon to abort */
3037{
3038 int n = 0;
3039 int c;
3040
3041 /* When not printing messages, the user won't know what to type, return a
3042 * zero (as if CR was hit). */
3043 if (msg_silent != 0)
3044 return 0;
3045
3046#ifdef USE_ON_FLY_SCROLL
3047 dont_scroll = TRUE; /* disallow scrolling here */
3048#endif
3049 ++no_mapping;
3050 ++allow_keys; /* no mapping here, but recognize keys */
3051 for (;;)
3052 {
3053 windgoto(msg_row, msg_col);
3054 c = safe_vgetc();
3055 if (VIM_ISDIGIT(c))
3056 {
3057 n = n * 10 + c - '0';
3058 msg_putchar(c);
3059 }
3060 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3061 {
3062 n /= 10;
3063 MSG_PUTS("\b \b");
3064 }
3065 else if (n == 0 && c == ':' && colon)
3066 {
3067 stuffcharReadbuff(':');
3068 if (!exmode_active)
3069 cmdline_row = msg_row;
3070 skip_redraw = TRUE; /* skip redraw once */
3071 do_redraw = FALSE;
3072 break;
3073 }
3074 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3075 break;
3076 }
3077 --no_mapping;
3078 --allow_keys;
3079 return n;
3080}
3081
3082 void
3083msgmore(n)
3084 long n;
3085{
3086 long pn;
3087
3088 if (global_busy /* no messages now, wait until global is finished */
3089 || keep_msg != NULL /* there is a message already, skip this one */
3090 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3091 return;
3092
3093 if (n > 0)
3094 pn = n;
3095 else
3096 pn = -n;
3097
3098 if (pn > p_report)
3099 {
3100 if (pn == 1)
3101 {
3102 if (n > 0)
3103 STRCPY(msg_buf, _("1 more line"));
3104 else
3105 STRCPY(msg_buf, _("1 line less"));
3106 }
3107 else
3108 {
3109 if (n > 0)
3110 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3111 else
3112 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3113 }
3114 if (got_int)
3115 STRCAT(msg_buf, _(" (Interrupted)"));
3116 if (msg(msg_buf))
3117 {
3118 set_keep_msg(msg_buf);
3119 keep_msg_attr = 0;
3120 }
3121 }
3122}
3123
3124/*
3125 * flush map and typeahead buffers and give a warning for an error
3126 */
3127 void
3128beep_flush()
3129{
3130 if (emsg_silent == 0)
3131 {
3132 flush_buffers(FALSE);
3133 vim_beep();
3134 }
3135}
3136
3137/*
3138 * give a warning for an error
3139 */
3140 void
3141vim_beep()
3142{
3143 if (emsg_silent == 0)
3144 {
3145 if (p_vb
3146#ifdef FEAT_GUI
3147 /* While the GUI is starting up the termcap is set for the GUI
3148 * but the output still goes to a terminal. */
3149 && !(gui.in_use && gui.starting)
3150#endif
3151 )
3152 {
3153 out_str(T_VB);
3154 }
3155 else
3156 {
3157#ifdef MSDOS
3158 /*
3159 * The number of beeps outputted is reduced to avoid having to wait
3160 * for all the beeps to finish. This is only a problem on systems
3161 * where the beeps don't overlap.
3162 */
3163 if (beep_count == 0 || beep_count == 10)
3164 {
3165 out_char(BELL);
3166 beep_count = 1;
3167 }
3168 else
3169 ++beep_count;
3170#else
3171 out_char(BELL);
3172#endif
3173 }
3174 }
3175}
3176
3177/*
3178 * To get the "real" home directory:
3179 * - get value of $HOME
3180 * For Unix:
3181 * - go to that directory
3182 * - do mch_dirname() to get the real name of that directory.
3183 * This also works with mounts and links.
3184 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3185 */
3186static char_u *homedir = NULL;
3187
3188 void
3189init_homedir()
3190{
3191 char_u *var;
3192
3193#ifdef VMS
3194 var = mch_getenv((char_u *)"SYS$LOGIN");
3195#else
3196 var = mch_getenv((char_u *)"HOME");
3197#endif
3198
3199 if (var != NULL && *var == NUL) /* empty is same as not set */
3200 var = NULL;
3201
3202#ifdef WIN3264
3203 /*
3204 * Weird but true: $HOME may contain an indirect reference to another
3205 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3206 * when $HOME is being set.
3207 */
3208 if (var != NULL && *var == '%')
3209 {
3210 char_u *p;
3211 char_u *exp;
3212
3213 p = vim_strchr(var + 1, '%');
3214 if (p != NULL)
3215 {
3216 STRNCPY(NameBuff, var + 1, p - (var + 1));
3217 NameBuff[p - (var + 1)] = NUL;
3218 exp = mch_getenv(NameBuff);
3219 if (exp != NULL && *exp != NUL
3220 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3221 {
3222 sprintf((char *)NameBuff, "%s%s", exp, p + 1);
3223 var = NameBuff;
3224 /* Also set $HOME, it's needed for _viminfo. */
3225 vim_setenv((char_u *)"HOME", NameBuff);
3226 }
3227 }
3228 }
3229
3230 /*
3231 * Typically, $HOME is not defined on Windows, unless the user has
3232 * specifically defined it for Vim's sake. However, on Windows NT
3233 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3234 * each user. Try constructing $HOME from these.
3235 */
3236 if (var == NULL)
3237 {
3238 char_u *homedrive, *homepath;
3239
3240 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3241 homepath = mch_getenv((char_u *)"HOMEPATH");
3242 if (homedrive != NULL && homepath != NULL
3243 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3244 {
3245 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3246 if (NameBuff[0] != NUL)
3247 {
3248 var = NameBuff;
3249 /* Also set $HOME, it's needed for _viminfo. */
3250 vim_setenv((char_u *)"HOME", NameBuff);
3251 }
3252 }
3253 }
3254#endif
3255
3256#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3257 /*
3258 * Default home dir is C:/
3259 * Best assumption we can make in such a situation.
3260 */
3261 if (var == NULL)
3262 var = "C:/";
3263#endif
3264 if (var != NULL)
3265 {
3266#ifdef UNIX
3267 /*
3268 * Change to the directory and get the actual path. This resolves
3269 * links. Don't do it when we can't return.
3270 */
3271 if (mch_dirname(NameBuff, MAXPATHL) == OK
3272 && mch_chdir((char *)NameBuff) == 0)
3273 {
3274 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3275 var = IObuff;
3276 if (mch_chdir((char *)NameBuff) != 0)
3277 EMSG(_(e_prev_dir));
3278 }
3279#endif
3280 homedir = vim_strsave(var);
3281 }
3282}
3283
3284/*
3285 * Expand environment variable with path name.
3286 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3287 * Skips over "\ ", "\~" and "\$".
3288 * If anything fails no expansion is done and dst equals src.
3289 */
3290 void
3291expand_env(src, dst, dstlen)
3292 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3293 char_u *dst; /* where to put the result */
3294 int dstlen; /* maximum length of the result */
3295{
3296 expand_env_esc(src, dst, dstlen, FALSE);
3297}
3298
3299 void
3300expand_env_esc(src, dst, dstlen, esc)
3301 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3302 char_u *dst; /* where to put the result */
3303 int dstlen; /* maximum length of the result */
3304 int esc; /* escape spaces in expanded variables */
3305{
3306 char_u *tail;
3307 int c;
3308 char_u *var;
3309 int copy_char;
3310 int mustfree; /* var was allocated, need to free it later */
3311 int at_start = TRUE; /* at start of a name */
3312
3313 src = skipwhite(src);
3314 --dstlen; /* leave one char space for "\," */
3315 while (*src && dstlen > 0)
3316 {
3317 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003318 if ((*src == '$'
3319#ifdef VMS
3320 && at_start
3321#endif
3322 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003323#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3324 || *src == '%'
3325#endif
3326 || (*src == '~' && at_start))
3327 {
3328 mustfree = FALSE;
3329
3330 /*
3331 * The variable name is copied into dst temporarily, because it may
3332 * be a string in read-only memory and a NUL needs to be appended.
3333 */
3334 if (*src != '~') /* environment var */
3335 {
3336 tail = src + 1;
3337 var = dst;
3338 c = dstlen - 1;
3339
3340#ifdef UNIX
3341 /* Unix has ${var-name} type environment vars */
3342 if (*tail == '{' && !vim_isIDc('{'))
3343 {
3344 tail++; /* ignore '{' */
3345 while (c-- > 0 && *tail && *tail != '}')
3346 *var++ = *tail++;
3347 }
3348 else
3349#endif
3350 {
3351 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3352#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3353 || (*src == '%' && *tail != '%')
3354#endif
3355 ))
3356 {
3357#ifdef OS2 /* env vars only in uppercase */
3358 *var++ = TOUPPER_LOC(*tail);
3359 tail++; /* toupper() may be a macro! */
3360#else
3361 *var++ = *tail++;
3362#endif
3363 }
3364 }
3365
3366#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3367# ifdef UNIX
3368 if (src[1] == '{' && *tail != '}')
3369# else
3370 if (*src == '%' && *tail != '%')
3371# endif
3372 var = NULL;
3373 else
3374 {
3375# ifdef UNIX
3376 if (src[1] == '{')
3377# else
3378 if (*src == '%')
3379#endif
3380 ++tail;
3381#endif
3382 *var = NUL;
3383 var = vim_getenv(dst, &mustfree);
3384#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3385 }
3386#endif
3387 }
3388 /* home directory */
3389 else if ( src[1] == NUL
3390 || vim_ispathsep(src[1])
3391 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3392 {
3393 var = homedir;
3394 tail = src + 1;
3395 }
3396 else /* user directory */
3397 {
3398#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3399 /*
3400 * Copy ~user to dst[], so we can put a NUL after it.
3401 */
3402 tail = src;
3403 var = dst;
3404 c = dstlen - 1;
3405 while ( c-- > 0
3406 && *tail
3407 && vim_isfilec(*tail)
3408 && !vim_ispathsep(*tail))
3409 *var++ = *tail++;
3410 *var = NUL;
3411# ifdef UNIX
3412 /*
3413 * If the system supports getpwnam(), use it.
3414 * Otherwise, or if getpwnam() fails, the shell is used to
3415 * expand ~user. This is slower and may fail if the shell
3416 * does not support ~user (old versions of /bin/sh).
3417 */
3418# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3419 {
3420 struct passwd *pw;
3421
3422 pw = getpwnam((char *)dst + 1);
3423 if (pw != NULL)
3424 var = (char_u *)pw->pw_dir;
3425 else
3426 var = NULL;
3427 }
3428 if (var == NULL)
3429# endif
3430 {
3431 expand_T xpc;
3432
3433 ExpandInit(&xpc);
3434 xpc.xp_context = EXPAND_FILES;
3435 var = ExpandOne(&xpc, dst, NULL,
3436 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
3437 ExpandCleanup(&xpc);
3438 mustfree = TRUE;
3439 }
3440
3441# else /* !UNIX, thus VMS */
3442 /*
3443 * USER_HOME is a comma-separated list of
3444 * directories to search for the user account in.
3445 */
3446 {
3447 char_u test[MAXPATHL], paths[MAXPATHL];
3448 char_u *path, *next_path, *ptr;
3449 struct stat st;
3450
3451 STRCPY(paths, USER_HOME);
3452 next_path = paths;
3453 while (*next_path)
3454 {
3455 for (path = next_path; *next_path && *next_path != ',';
3456 next_path++);
3457 if (*next_path)
3458 *next_path++ = NUL;
3459 STRCPY(test, path);
3460 STRCAT(test, "/");
3461 STRCAT(test, dst + 1);
3462 if (mch_stat(test, &st) == 0)
3463 {
3464 var = alloc(STRLEN(test) + 1);
3465 STRCPY(var, test);
3466 mustfree = TRUE;
3467 break;
3468 }
3469 }
3470 }
3471# endif /* UNIX */
3472#else
3473 /* cannot expand user's home directory, so don't try */
3474 var = NULL;
3475 tail = (char_u *)""; /* for gcc */
3476#endif /* UNIX || VMS */
3477 }
3478
3479#ifdef BACKSLASH_IN_FILENAME
3480 /* If 'shellslash' is set change backslashes to forward slashes.
3481 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3482 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3483 {
3484 char_u *p = vim_strsave(var);
3485
3486 if (p != NULL)
3487 {
3488 if (mustfree)
3489 vim_free(var);
3490 var = p;
3491 mustfree = TRUE;
3492 forward_slash(var);
3493 }
3494 }
3495#endif
3496
3497 /* If "var" contains white space, escape it with a backslash.
3498 * Required for ":e ~/tt" when $HOME includes a space. */
3499 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3500 {
3501 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3502
3503 if (p != NULL)
3504 {
3505 if (mustfree)
3506 vim_free(var);
3507 var = p;
3508 mustfree = TRUE;
3509 }
3510 }
3511
3512 if (var != NULL && *var != NUL
3513 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3514 {
3515 STRCPY(dst, var);
3516 dstlen -= (int)STRLEN(var);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003517 c = STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518 /* if var[] ends in a path separator and tail[] starts
3519 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003520 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3522 && dst[-1] != ':'
3523#endif
3524 && vim_ispathsep(*tail))
3525 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003526 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527 src = tail;
3528 copy_char = FALSE;
3529 }
3530 if (mustfree)
3531 vim_free(var);
3532 }
3533
3534 if (copy_char) /* copy at least one char */
3535 {
3536 /*
3537 * Recogize the start of a new name, for '~'.
3538 */
3539 at_start = FALSE;
3540 if (src[0] == '\\' && src[1] != NUL)
3541 {
3542 *dst++ = *src++;
3543 --dstlen;
3544 }
3545 else if (src[0] == ' ' || src[0] == ',')
3546 at_start = TRUE;
3547 *dst++ = *src++;
3548 --dstlen;
3549 }
3550 }
3551 *dst = NUL;
3552}
3553
3554/*
3555 * Vim's version of getenv().
3556 * Special handling of $HOME, $VIM and $VIMRUNTIME.
3557 */
3558 char_u *
3559vim_getenv(name, mustfree)
3560 char_u *name;
3561 int *mustfree; /* set to TRUE when returned is allocated */
3562{
3563 char_u *p;
3564 char_u *pend;
3565 int vimruntime;
3566
3567#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3568 /* use "C:/" when $HOME is not set */
3569 if (STRCMP(name, "HOME") == 0)
3570 return homedir;
3571#endif
3572
3573 p = mch_getenv(name);
3574 if (p != NULL && *p == NUL) /* empty is the same as not set */
3575 p = NULL;
3576
3577 if (p != NULL)
3578 return p;
3579
3580 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3581 if (!vimruntime && STRCMP(name, "VIM") != 0)
3582 return NULL;
3583
3584 /*
3585 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3586 * Don't do this when default_vimruntime_dir is non-empty.
3587 */
3588 if (vimruntime
3589#ifdef HAVE_PATHDEF
3590 && *default_vimruntime_dir == NUL
3591#endif
3592 )
3593 {
3594 p = mch_getenv((char_u *)"VIM");
3595 if (p != NULL && *p == NUL) /* empty is the same as not set */
3596 p = NULL;
3597 if (p != NULL)
3598 {
3599 p = vim_version_dir(p);
3600 if (p != NULL)
3601 *mustfree = TRUE;
3602 else
3603 p = mch_getenv((char_u *)"VIM");
3604 }
3605 }
3606
3607 /*
3608 * When expanding $VIM or $VIMRUNTIME fails, try using:
3609 * - the directory name from 'helpfile' (unless it contains '$')
3610 * - the executable name from argv[0]
3611 */
3612 if (p == NULL)
3613 {
3614 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3615 p = p_hf;
3616#ifdef USE_EXE_NAME
3617 /*
3618 * Use the name of the executable, obtained from argv[0].
3619 */
3620 else
3621 p = exe_name;
3622#endif
3623 if (p != NULL)
3624 {
3625 /* remove the file name */
3626 pend = gettail(p);
3627
3628 /* remove "doc/" from 'helpfile', if present */
3629 if (p == p_hf)
3630 pend = remove_tail(p, pend, (char_u *)"doc");
3631
3632#ifdef USE_EXE_NAME
3633# ifdef MACOS_X
3634 /* remove "build/..." from exe_name, if present */
3635 if (p == exe_name)
3636 {
3637 char_u *pend1;
3638 char_u *pend2;
3639
3640 pend1 = remove_tail(p, pend, (char_u *)"Contents/MacOS");
3641 pend2 = remove_tail_with_ext(p, pend1, (char_u *)".app");
3642 pend = remove_tail(p, pend2, (char_u *)"build");
3643 /* When runnig from project builder get rid of the
3644 * build/???.app, otherwise keep the ???.app */
3645 if (pend2 == pend)
3646 pend = pend1;
3647 }
3648# endif
3649 /* remove "src/" from exe_name, if present */
3650 if (p == exe_name)
3651 pend = remove_tail(p, pend, (char_u *)"src");
3652#endif
3653
3654 /* for $VIM, remove "runtime/" or "vim54/", if present */
3655 if (!vimruntime)
3656 {
3657 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
3658 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
3659 }
3660
3661 /* remove trailing path separator */
3662#ifndef MACOS_CLASSIC
3663 /* With MacOS path (with colons) the final colon is required */
3664 /* to avoid confusion between absoulute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003665 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003666 --pend;
3667#endif
3668
3669 /* check that the result is a directory name */
3670 p = vim_strnsave(p, (int)(pend - p));
3671
3672 if (p != NULL && !mch_isdir(p))
3673 {
3674 vim_free(p);
3675 p = NULL;
3676 }
3677 else
3678 {
3679#ifdef USE_EXE_NAME
3680 /* may add "/vim54" or "/runtime" if it exists */
3681 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
3682 {
3683 vim_free(p);
3684 p = pend;
3685 }
3686#endif
3687 *mustfree = TRUE;
3688 }
3689 }
3690 }
3691
3692#ifdef HAVE_PATHDEF
3693 /* When there is a pathdef.c file we can use default_vim_dir and
3694 * default_vimruntime_dir */
3695 if (p == NULL)
3696 {
3697 /* Only use default_vimruntime_dir when it is not empty */
3698 if (vimruntime && *default_vimruntime_dir != NUL)
3699 {
3700 p = default_vimruntime_dir;
3701 *mustfree = FALSE;
3702 }
3703 else if (*default_vim_dir != NUL)
3704 {
3705 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
3706 *mustfree = TRUE;
3707 else
3708 {
3709 p = default_vim_dir;
3710 *mustfree = FALSE;
3711 }
3712 }
3713 }
3714#endif
3715
3716 /*
3717 * Set the environment variable, so that the new value can be found fast
3718 * next time, and others can also use it (e.g. Perl).
3719 */
3720 if (p != NULL)
3721 {
3722 if (vimruntime)
3723 {
3724 vim_setenv((char_u *)"VIMRUNTIME", p);
3725 didset_vimruntime = TRUE;
3726#ifdef FEAT_GETTEXT
3727 {
3728 char_u *buf = alloc((unsigned int)STRLEN(p) + 6);
3729
3730 if (buf != NULL)
3731 {
3732 STRCPY(buf, p);
3733 STRCAT(buf, "/lang");
3734 bindtextdomain(VIMPACKAGE, (char *)buf);
3735 vim_free(buf);
3736 }
3737 }
3738#endif
3739 }
3740 else
3741 {
3742 vim_setenv((char_u *)"VIM", p);
3743 didset_vim = TRUE;
3744 }
3745 }
3746 return p;
3747}
3748
3749/*
3750 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
3751 * Return NULL if not, return its name in allocated memory otherwise.
3752 */
3753 static char_u *
3754vim_version_dir(vimdir)
3755 char_u *vimdir;
3756{
3757 char_u *p;
3758
3759 if (vimdir == NULL || *vimdir == NUL)
3760 return NULL;
3761 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
3762 if (p != NULL && mch_isdir(p))
3763 return p;
3764 vim_free(p);
3765 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
3766 if (p != NULL && mch_isdir(p))
3767 return p;
3768 vim_free(p);
3769 return NULL;
3770}
3771
3772/*
3773 * If the string between "p" and "pend" ends in "name/", return "pend" minus
3774 * the length of "name/". Otherwise return "pend".
3775 */
3776 static char_u *
3777remove_tail(p, pend, name)
3778 char_u *p;
3779 char_u *pend;
3780 char_u *name;
3781{
3782 int len = (int)STRLEN(name) + 1;
3783 char_u *newend = pend - len;
3784
3785 if (newend >= p
3786 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003787 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788 return newend;
3789 return pend;
3790}
3791
3792#if defined(USE_EXE_NAME) && defined(MACOS_X)
3793/*
3794 * If the string between "p" and "pend" ends in "???.ext/", return "pend"
3795 * minus the length of "???.ext/". Otherwise return "pend".
3796 */
3797 static char_u *
3798remove_tail_with_ext(p, pend, ext)
3799 char_u *p;
3800 char_u *pend;
3801 char_u *ext;
3802{
3803 int len = (int)STRLEN(ext) + 1;
3804 char_u *newend = pend - len;
3805
3806 if (newend >= p && fnamencmp(newend, ext, len - 1) == 0)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003807 while (newend != p && !after_pathsep(newend))
3808 mb_ptr_back(newend);
3809 if (newend == p || after_pathsep(newend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810 return newend;
3811 return pend;
3812}
3813#endif
3814
3815/*
3816 * Call expand_env() and store the result in an allocated string.
3817 * This is not very memory efficient, this expects the result to be freed
3818 * again soon.
3819 */
3820 char_u *
3821expand_env_save(src)
3822 char_u *src;
3823{
3824 char_u *p;
3825
3826 p = alloc(MAXPATHL);
3827 if (p != NULL)
3828 expand_env(src, p, MAXPATHL);
3829 return p;
3830}
3831
3832/*
3833 * Our portable version of setenv.
3834 */
3835 void
3836vim_setenv(name, val)
3837 char_u *name;
3838 char_u *val;
3839{
3840#ifdef HAVE_SETENV
3841 mch_setenv((char *)name, (char *)val, 1);
3842#else
3843 char_u *envbuf;
3844
3845 /*
3846 * Putenv does not copy the string, it has to remain
3847 * valid. The allocated memory will never be freed.
3848 */
3849 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
3850 if (envbuf != NULL)
3851 {
3852 sprintf((char *)envbuf, "%s=%s", name, val);
3853 putenv((char *)envbuf);
3854 }
3855#endif
3856}
3857
3858#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3859/*
3860 * Function given to ExpandGeneric() to obtain an environment variable name.
3861 */
3862/*ARGSUSED*/
3863 char_u *
3864get_env_name(xp, idx)
3865 expand_T *xp;
3866 int idx;
3867{
3868# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
3869 /*
3870 * No environ[] on the Amiga and on the Mac (using MPW).
3871 */
3872 return NULL;
3873# else
3874# ifndef __WIN32__
3875 /* Borland C++ 5.2 has this in a header file. */
3876 extern char **environ;
3877# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003878# define ENVNAMELEN 100
3879 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880 char_u *str;
3881 int n;
3882
3883 str = (char_u *)environ[idx];
3884 if (str == NULL)
3885 return NULL;
3886
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003887 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888 {
3889 if (str[n] == '=' || str[n] == NUL)
3890 break;
3891 name[n] = str[n];
3892 }
3893 name[n] = NUL;
3894 return name;
3895# endif
3896}
3897#endif
3898
3899/*
3900 * Replace home directory by "~" in each space or comma separated file name in
3901 * 'src'.
3902 * If anything fails (except when out of space) dst equals src.
3903 */
3904 void
3905home_replace(buf, src, dst, dstlen, one)
3906 buf_T *buf; /* when not NULL, check for help files */
3907 char_u *src; /* input file name */
3908 char_u *dst; /* where to put the result */
3909 int dstlen; /* maximum length of the result */
3910 int one; /* if TRUE, only replace one file name, include
3911 spaces and commas in the file name. */
3912{
3913 size_t dirlen = 0, envlen = 0;
3914 size_t len;
3915 char_u *homedir_env;
3916 char_u *p;
3917
3918 if (src == NULL)
3919 {
3920 *dst = NUL;
3921 return;
3922 }
3923
3924 /*
3925 * If the file is a help file, remove the path completely.
3926 */
3927 if (buf != NULL && buf->b_help)
3928 {
3929 STRCPY(dst, gettail(src));
3930 return;
3931 }
3932
3933 /*
3934 * We check both the value of the $HOME environment variable and the
3935 * "real" home directory.
3936 */
3937 if (homedir != NULL)
3938 dirlen = STRLEN(homedir);
3939
3940#ifdef VMS
3941 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
3942#else
3943 homedir_env = mch_getenv((char_u *)"HOME");
3944#endif
3945
3946 if (homedir_env != NULL && *homedir_env == NUL)
3947 homedir_env = NULL;
3948 if (homedir_env != NULL)
3949 envlen = STRLEN(homedir_env);
3950
3951 if (!one)
3952 src = skipwhite(src);
3953 while (*src && dstlen > 0)
3954 {
3955 /*
3956 * Here we are at the beginning of a file name.
3957 * First, check to see if the beginning of the file name matches
3958 * $HOME or the "real" home directory. Check that there is a '/'
3959 * after the match (so that if e.g. the file is "/home/pieter/bla",
3960 * and the home directory is "/home/piet", the file does not end up
3961 * as "~er/bla" (which would seem to indicate the file "bla" in user
3962 * er's home directory)).
3963 */
3964 p = homedir;
3965 len = dirlen;
3966 for (;;)
3967 {
3968 if ( len
3969 && fnamencmp(src, p, len) == 0
3970 && (vim_ispathsep(src[len])
3971 || (!one && (src[len] == ',' || src[len] == ' '))
3972 || src[len] == NUL))
3973 {
3974 src += len;
3975 if (--dstlen > 0)
3976 *dst++ = '~';
3977
3978 /*
3979 * If it's just the home directory, add "/".
3980 */
3981 if (!vim_ispathsep(src[0]) && --dstlen > 0)
3982 *dst++ = '/';
3983 break;
3984 }
3985 if (p == homedir_env)
3986 break;
3987 p = homedir_env;
3988 len = envlen;
3989 }
3990
3991 /* if (!one) skip to separator: space or comma */
3992 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
3993 *dst++ = *src++;
3994 /* skip separator */
3995 while ((*src == ' ' || *src == ',') && --dstlen > 0)
3996 *dst++ = *src++;
3997 }
3998 /* if (dstlen == 0) out of space, what to do??? */
3999
4000 *dst = NUL;
4001}
4002
4003/*
4004 * Like home_replace, store the replaced string in allocated memory.
4005 * When something fails, NULL is returned.
4006 */
4007 char_u *
4008home_replace_save(buf, src)
4009 buf_T *buf; /* when not NULL, check for help files */
4010 char_u *src; /* input file name */
4011{
4012 char_u *dst;
4013 unsigned len;
4014
4015 len = 3; /* space for "~/" and trailing NUL */
4016 if (src != NULL) /* just in case */
4017 len += (unsigned)STRLEN(src);
4018 dst = alloc(len);
4019 if (dst != NULL)
4020 home_replace(buf, src, dst, len, TRUE);
4021 return dst;
4022}
4023
4024/*
4025 * Compare two file names and return:
4026 * FPC_SAME if they both exist and are the same file.
4027 * FPC_SAMEX if they both don't exist and have the same file name.
4028 * FPC_DIFF if they both exist and are different files.
4029 * FPC_NOTX if they both don't exist.
4030 * FPC_DIFFX if one of them doesn't exist.
4031 * For the first name environment variables are expanded
4032 */
4033 int
4034fullpathcmp(s1, s2, checkname)
4035 char_u *s1, *s2;
4036 int checkname; /* when both don't exist, check file names */
4037{
4038#ifdef UNIX
4039 char_u exp1[MAXPATHL];
4040 char_u full1[MAXPATHL];
4041 char_u full2[MAXPATHL];
4042 struct stat st1, st2;
4043 int r1, r2;
4044
4045 expand_env(s1, exp1, MAXPATHL);
4046 r1 = mch_stat((char *)exp1, &st1);
4047 r2 = mch_stat((char *)s2, &st2);
4048 if (r1 != 0 && r2 != 0)
4049 {
4050 /* if mch_stat() doesn't work, may compare the names */
4051 if (checkname)
4052 {
4053 if (fnamecmp(exp1, s2) == 0)
4054 return FPC_SAMEX;
4055 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4056 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4057 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4058 return FPC_SAMEX;
4059 }
4060 return FPC_NOTX;
4061 }
4062 if (r1 != 0 || r2 != 0)
4063 return FPC_DIFFX;
4064 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4065 return FPC_SAME;
4066 return FPC_DIFF;
4067#else
4068 char_u *exp1; /* expanded s1 */
4069 char_u *full1; /* full path of s1 */
4070 char_u *full2; /* full path of s2 */
4071 int retval = FPC_DIFF;
4072 int r1, r2;
4073
4074 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4075 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4076 {
4077 full1 = exp1 + MAXPATHL;
4078 full2 = full1 + MAXPATHL;
4079
4080 expand_env(s1, exp1, MAXPATHL);
4081 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4082 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4083
4084 /* If vim_FullName() fails, the file probably doesn't exist. */
4085 if (r1 != OK && r2 != OK)
4086 {
4087 if (checkname && fnamecmp(exp1, s2) == 0)
4088 retval = FPC_SAMEX;
4089 else
4090 retval = FPC_NOTX;
4091 }
4092 else if (r1 != OK || r2 != OK)
4093 retval = FPC_DIFFX;
4094 else if (fnamecmp(full1, full2))
4095 retval = FPC_DIFF;
4096 else
4097 retval = FPC_SAME;
4098 vim_free(exp1);
4099 }
4100 return retval;
4101#endif
4102}
4103
4104/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004105 * Get the tail of a path: the file name.
4106 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004107 */
4108 char_u *
4109gettail(fname)
4110 char_u *fname;
4111{
4112 char_u *p1, *p2;
4113
4114 if (fname == NULL)
4115 return (char_u *)"";
4116 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4117 {
4118 if (vim_ispathsep(*p2))
4119 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004120 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 }
4122 return p1;
4123}
4124
4125/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004126 * Get pointer to tail of "fname", including path separators. Putting a NUL
4127 * here leaves the directory name. Takes care of "c:/" and "//".
4128 * Always returns a valid pointer.
4129 */
4130 char_u *
4131gettail_sep(fname)
4132 char_u *fname;
4133{
4134 char_u *p;
4135 char_u *t;
4136
4137 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4138 t = gettail(fname);
4139 while (t > p && after_pathsep(fname, t))
4140 --t;
4141#ifdef VMS
4142 /* path separator is part of the path */
4143 ++t;
4144#endif
4145 return t;
4146}
4147
4148/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004149 * get the next path component (just after the next path separator).
4150 */
4151 char_u *
4152getnextcomp(fname)
4153 char_u *fname;
4154{
4155 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004156 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004157 if (*fname)
4158 ++fname;
4159 return fname;
4160}
4161
Bram Moolenaar071d4272004-06-13 20:20:40 +00004162/*
4163 * Get a pointer to one character past the head of a path name.
4164 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4165 * If there is no head, path is returned.
4166 */
4167 char_u *
4168get_past_head(path)
4169 char_u *path;
4170{
4171 char_u *retval;
4172
4173#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4174 /* may skip "c:" */
4175 if (isalpha(path[0]) && path[1] == ':')
4176 retval = path + 2;
4177 else
4178 retval = path;
4179#else
4180# if defined(AMIGA)
4181 /* may skip "label:" */
4182 retval = vim_strchr(path, ':');
4183 if (retval == NULL)
4184 retval = path;
4185# else /* Unix */
4186 retval = path;
4187# endif
4188#endif
4189
4190 while (vim_ispathsep(*retval))
4191 ++retval;
4192
4193 return retval;
4194}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004195
4196/*
4197 * return TRUE if 'c' is a path separator.
4198 */
4199 int
4200vim_ispathsep(c)
4201 int c;
4202{
4203#ifdef RISCOS
4204 return (c == '.' || c == ':');
4205#else
4206# ifdef UNIX
4207 return (c == '/'); /* UNIX has ':' inside file names */
4208# else
4209# ifdef BACKSLASH_IN_FILENAME
4210 return (c == ':' || c == '/' || c == '\\');
4211# else
4212# ifdef VMS
4213 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4214 return (c == ':' || c == '[' || c == ']' || c == '/'
4215 || c == '<' || c == '>' || c == '"' );
4216# else
4217# ifdef COLON_AS_PATHSEP
4218 return (c == ':');
4219# else /* Amiga */
4220 return (c == ':' || c == '/');
4221# endif
4222# endif /* VMS */
4223# endif
4224# endif
4225#endif /* RISC OS */
4226}
4227
4228#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4229/*
4230 * return TRUE if 'c' is a path list separator.
4231 */
4232 int
4233vim_ispathlistsep(c)
4234 int c;
4235{
4236#ifdef UNIX
4237 return (c == ':');
4238#else
4239 return (c == ';'); /* might not be rigth for every system... */
4240#endif
4241}
4242#endif
4243
4244#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4245 || defined(PROTO)
4246/*
4247 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4248 */
4249 int
4250vim_fnamecmp(x, y)
4251 char_u *x, *y;
4252{
4253 return vim_fnamencmp(x, y, MAXPATHL);
4254}
4255
4256 int
4257vim_fnamencmp(x, y, len)
4258 char_u *x, *y;
4259 size_t len;
4260{
4261 while (len > 0 && *x && *y)
4262 {
4263 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4264 && !(*x == '/' && *y == '\\')
4265 && !(*x == '\\' && *y == '/'))
4266 break;
4267 ++x;
4268 ++y;
4269 --len;
4270 }
4271 if (len == 0)
4272 return 0;
4273 return (*x - *y);
4274}
4275#endif
4276
4277/*
4278 * Concatenate file names fname1 and fname2 into allocated memory.
4279 * Only add a '/' or '\\' when 'sep' is TRUE and it is neccesary.
4280 */
4281 char_u *
4282concat_fnames(fname1, fname2, sep)
4283 char_u *fname1;
4284 char_u *fname2;
4285 int sep;
4286{
4287 char_u *dest;
4288
4289 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4290 if (dest != NULL)
4291 {
4292 STRCPY(dest, fname1);
4293 if (sep)
4294 add_pathsep(dest);
4295 STRCAT(dest, fname2);
4296 }
4297 return dest;
4298}
4299
4300/*
4301 * Add a path separator to a file name, unless it already ends in a path
4302 * separator.
4303 */
4304 void
4305add_pathsep(p)
4306 char_u *p;
4307{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004308 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004309 STRCAT(p, PATHSEPSTR);
4310}
4311
4312/*
4313 * FullName_save - Make an allocated copy of a full file name.
4314 * Returns NULL when out of memory.
4315 */
4316 char_u *
4317FullName_save(fname, force)
4318 char_u *fname;
4319 int force; /* force expansion, even when it already looks
4320 like a full path name */
4321{
4322 char_u *buf;
4323 char_u *new_fname = NULL;
4324
4325 if (fname == NULL)
4326 return NULL;
4327
4328 buf = alloc((unsigned)MAXPATHL);
4329 if (buf != NULL)
4330 {
4331 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4332 new_fname = vim_strsave(buf);
4333 else
4334 new_fname = vim_strsave(fname);
4335 vim_free(buf);
4336 }
4337 return new_fname;
4338}
4339
4340#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4341
4342static char_u *skip_string __ARGS((char_u *p));
4343
4344/*
4345 * Find the start of a comment, not knowing if we are in a comment right now.
4346 * Search starts at w_cursor.lnum and goes backwards.
4347 */
4348 pos_T *
4349find_start_comment(ind_maxcomment) /* XXX */
4350 int ind_maxcomment;
4351{
4352 pos_T *pos;
4353 char_u *line;
4354 char_u *p;
4355
4356 if ((pos = findmatchlimit(NULL, '*', FM_BACKWARD, ind_maxcomment)) == NULL)
4357 return NULL;
4358
4359 /*
4360 * Check if the comment start we found is inside a string.
4361 */
4362 line = ml_get(pos->lnum);
4363 for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
4364 p = skip_string(p);
4365 if ((unsigned)(p - line) > pos->col)
4366 return NULL;
4367 return pos;
4368}
4369
4370/*
4371 * Skip to the end of a "string" and a 'c' character.
4372 * If there is no string or character, return argument unmodified.
4373 */
4374 static char_u *
4375skip_string(p)
4376 char_u *p;
4377{
4378 int i;
4379
4380 /*
4381 * We loop, because strings may be concatenated: "date""time".
4382 */
4383 for ( ; ; ++p)
4384 {
4385 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4386 {
4387 if (!p[1]) /* ' at end of line */
4388 break;
4389 i = 2;
4390 if (p[1] == '\\') /* '\n' or '\000' */
4391 {
4392 ++i;
4393 while (vim_isdigit(p[i - 1])) /* '\000' */
4394 ++i;
4395 }
4396 if (p[i] == '\'') /* check for trailing ' */
4397 {
4398 p += i;
4399 continue;
4400 }
4401 }
4402 else if (p[0] == '"') /* start of string */
4403 {
4404 for (++p; p[0]; ++p)
4405 {
4406 if (p[0] == '\\' && p[1] != NUL)
4407 ++p;
4408 else if (p[0] == '"') /* end of string */
4409 break;
4410 }
4411 if (p[0] == '"')
4412 continue;
4413 }
4414 break; /* no string found */
4415 }
4416 if (!*p)
4417 --p; /* backup from NUL */
4418 return p;
4419}
4420#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4421
4422#if defined(FEAT_CINDENT) || defined(PROTO)
4423
4424/*
4425 * Do C or expression indenting on the current line.
4426 */
4427 void
4428do_c_expr_indent()
4429{
4430# ifdef FEAT_EVAL
4431 if (*curbuf->b_p_inde != NUL)
4432 fixthisline(get_expr_indent);
4433 else
4434# endif
4435 fixthisline(get_c_indent);
4436}
4437
4438/*
4439 * Functions for C-indenting.
4440 * Most of this originally comes from Eric Fischer.
4441 */
4442/*
4443 * Below "XXX" means that this function may unlock the current line.
4444 */
4445
4446static char_u *cin_skipcomment __ARGS((char_u *));
4447static int cin_nocode __ARGS((char_u *));
4448static pos_T *find_line_comment __ARGS((void));
4449static int cin_islabel_skip __ARGS((char_u **));
4450static int cin_isdefault __ARGS((char_u *));
4451static char_u *after_label __ARGS((char_u *l));
4452static int get_indent_nolabel __ARGS((linenr_T lnum));
4453static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4454static int cin_first_id_amount __ARGS((void));
4455static int cin_get_equal_amount __ARGS((linenr_T lnum));
4456static int cin_ispreproc __ARGS((char_u *));
4457static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4458static int cin_iscomment __ARGS((char_u *));
4459static int cin_islinecomment __ARGS((char_u *));
4460static int cin_isterminated __ARGS((char_u *, int, int));
4461static int cin_isinit __ARGS((void));
4462static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4463static int cin_isif __ARGS((char_u *));
4464static int cin_iselse __ARGS((char_u *));
4465static int cin_isdo __ARGS((char_u *));
4466static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
4467static int cin_isbreak __ARGS((char_u *));
4468static int cin_is_cpp_baseclass __ARGS((char_u *line, colnr_T *col));
4469static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4470static int cin_skip2pos __ARGS((pos_T *trypos));
4471static pos_T *find_start_brace __ARGS((int));
4472static pos_T *find_match_paren __ARGS((int, int));
4473static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4474static int find_last_paren __ARGS((char_u *l, int start, int end));
4475static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4476
4477/*
4478 * Skip over white space and C comments within the line.
4479 */
4480 static char_u *
4481cin_skipcomment(s)
4482 char_u *s;
4483{
4484 while (*s)
4485 {
4486 s = skipwhite(s);
4487 if (*s != '/')
4488 break;
4489 ++s;
4490 if (*s == '/') /* slash-slash comment continues till eol */
4491 {
4492 s += STRLEN(s);
4493 break;
4494 }
4495 if (*s != '*')
4496 break;
4497 for (++s; *s; ++s) /* skip slash-star comment */
4498 if (s[0] == '*' && s[1] == '/')
4499 {
4500 s += 2;
4501 break;
4502 }
4503 }
4504 return s;
4505}
4506
4507/*
4508 * Return TRUE if there there is no code at *s. White space and comments are
4509 * not considered code.
4510 */
4511 static int
4512cin_nocode(s)
4513 char_u *s;
4514{
4515 return *cin_skipcomment(s) == NUL;
4516}
4517
4518/*
4519 * Check previous lines for a "//" line comment, skipping over blank lines.
4520 */
4521 static pos_T *
4522find_line_comment() /* XXX */
4523{
4524 static pos_T pos;
4525 char_u *line;
4526 char_u *p;
4527
4528 pos = curwin->w_cursor;
4529 while (--pos.lnum > 0)
4530 {
4531 line = ml_get(pos.lnum);
4532 p = skipwhite(line);
4533 if (cin_islinecomment(p))
4534 {
4535 pos.col = (int)(p - line);
4536 return &pos;
4537 }
4538 if (*p != NUL)
4539 break;
4540 }
4541 return NULL;
4542}
4543
4544/*
4545 * Check if string matches "label:"; move to character after ':' if true.
4546 */
4547 static int
4548cin_islabel_skip(s)
4549 char_u **s;
4550{
4551 if (!vim_isIDc(**s)) /* need at least one ID character */
4552 return FALSE;
4553
4554 while (vim_isIDc(**s))
4555 (*s)++;
4556
4557 *s = cin_skipcomment(*s);
4558
4559 /* "::" is not a label, it's C++ */
4560 return (**s == ':' && *++*s != ':');
4561}
4562
4563/*
4564 * Recognize a label: "label:".
4565 * Note: curwin->w_cursor must be where we are looking for the label.
4566 */
4567 int
4568cin_islabel(ind_maxcomment) /* XXX */
4569 int ind_maxcomment;
4570{
4571 char_u *s;
4572
4573 s = cin_skipcomment(ml_get_curline());
4574
4575 /*
4576 * Exclude "default" from labels, since it should be indented
4577 * like a switch label. Same for C++ scope declarations.
4578 */
4579 if (cin_isdefault(s))
4580 return FALSE;
4581 if (cin_isscopedecl(s))
4582 return FALSE;
4583
4584 if (cin_islabel_skip(&s))
4585 {
4586 /*
4587 * Only accept a label if the previous line is terminated or is a case
4588 * label.
4589 */
4590 pos_T cursor_save;
4591 pos_T *trypos;
4592 char_u *line;
4593
4594 cursor_save = curwin->w_cursor;
4595 while (curwin->w_cursor.lnum > 1)
4596 {
4597 --curwin->w_cursor.lnum;
4598
4599 /*
4600 * If we're in a comment now, skip to the start of the comment.
4601 */
4602 curwin->w_cursor.col = 0;
4603 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
4604 curwin->w_cursor = *trypos;
4605
4606 line = ml_get_curline();
4607 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
4608 continue;
4609 if (*(line = cin_skipcomment(line)) == NUL)
4610 continue;
4611
4612 curwin->w_cursor = cursor_save;
4613 if (cin_isterminated(line, TRUE, FALSE)
4614 || cin_isscopedecl(line)
4615 || cin_iscase(line)
4616 || (cin_islabel_skip(&line) && cin_nocode(line)))
4617 return TRUE;
4618 return FALSE;
4619 }
4620 curwin->w_cursor = cursor_save;
4621 return TRUE; /* label at start of file??? */
4622 }
4623 return FALSE;
4624}
4625
4626/*
4627 * Recognize structure initialization and enumerations.
4628 * Q&D-Implementation:
4629 * check for "=" at end or "[typedef] enum" at beginning of line.
4630 */
4631 static int
4632cin_isinit(void)
4633{
4634 char_u *s;
4635
4636 s = cin_skipcomment(ml_get_curline());
4637
4638 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
4639 s = cin_skipcomment(s + 7);
4640
4641 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
4642 return TRUE;
4643
4644 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
4645 return TRUE;
4646
4647 return FALSE;
4648}
4649
4650/*
4651 * Recognize a switch label: "case .*:" or "default:".
4652 */
4653 int
4654cin_iscase(s)
4655 char_u *s;
4656{
4657 s = cin_skipcomment(s);
4658 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
4659 {
4660 for (s += 4; *s; ++s)
4661 {
4662 s = cin_skipcomment(s);
4663 if (*s == ':')
4664 {
4665 if (s[1] == ':') /* skip over "::" for C++ */
4666 ++s;
4667 else
4668 return TRUE;
4669 }
4670 if (*s == '\'' && s[1] && s[2] == '\'')
4671 s += 2; /* skip over '.' */
4672 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
4673 return FALSE; /* stop at comment */
4674 else if (*s == '"')
4675 return FALSE; /* stop at string */
4676 }
4677 return FALSE;
4678 }
4679
4680 if (cin_isdefault(s))
4681 return TRUE;
4682 return FALSE;
4683}
4684
4685/*
4686 * Recognize a "default" switch label.
4687 */
4688 static int
4689cin_isdefault(s)
4690 char_u *s;
4691{
4692 return (STRNCMP(s, "default", 7) == 0
4693 && *(s = cin_skipcomment(s + 7)) == ':'
4694 && s[1] != ':');
4695}
4696
4697/*
4698 * Recognize a "public/private/proctected" scope declaration label.
4699 */
4700 int
4701cin_isscopedecl(s)
4702 char_u *s;
4703{
4704 int i;
4705
4706 s = cin_skipcomment(s);
4707 if (STRNCMP(s, "public", 6) == 0)
4708 i = 6;
4709 else if (STRNCMP(s, "protected", 9) == 0)
4710 i = 9;
4711 else if (STRNCMP(s, "private", 7) == 0)
4712 i = 7;
4713 else
4714 return FALSE;
4715 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
4716}
4717
4718/*
4719 * Return a pointer to the first non-empty non-comment character after a ':'.
4720 * Return NULL if not found.
4721 * case 234: a = b;
4722 * ^
4723 */
4724 static char_u *
4725after_label(l)
4726 char_u *l;
4727{
4728 for ( ; *l; ++l)
4729 {
4730 if (*l == ':')
4731 {
4732 if (l[1] == ':') /* skip over "::" for C++ */
4733 ++l;
4734 else if (!cin_iscase(l + 1))
4735 break;
4736 }
4737 else if (*l == '\'' && l[1] && l[2] == '\'')
4738 l += 2; /* skip over 'x' */
4739 }
4740 if (*l == NUL)
4741 return NULL;
4742 l = cin_skipcomment(l + 1);
4743 if (*l == NUL)
4744 return NULL;
4745 return l;
4746}
4747
4748/*
4749 * Get indent of line "lnum", skipping a label.
4750 * Return 0 if there is nothing after the label.
4751 */
4752 static int
4753get_indent_nolabel(lnum) /* XXX */
4754 linenr_T lnum;
4755{
4756 char_u *l;
4757 pos_T fp;
4758 colnr_T col;
4759 char_u *p;
4760
4761 l = ml_get(lnum);
4762 p = after_label(l);
4763 if (p == NULL)
4764 return 0;
4765
4766 fp.col = (colnr_T)(p - l);
4767 fp.lnum = lnum;
4768 getvcol(curwin, &fp, &col, NULL, NULL);
4769 return (int)col;
4770}
4771
4772/*
4773 * Find indent for line "lnum", ignoring any case or jump label.
4774 * Also return a pointer to the text (after the label).
4775 * label: if (asdf && asdfasdf)
4776 * ^
4777 */
4778 static int
4779skip_label(lnum, pp, ind_maxcomment)
4780 linenr_T lnum;
4781 char_u **pp;
4782 int ind_maxcomment;
4783{
4784 char_u *l;
4785 int amount;
4786 pos_T cursor_save;
4787
4788 cursor_save = curwin->w_cursor;
4789 curwin->w_cursor.lnum = lnum;
4790 l = ml_get_curline();
4791 /* XXX */
4792 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
4793 {
4794 amount = get_indent_nolabel(lnum);
4795 l = after_label(ml_get_curline());
4796 if (l == NULL) /* just in case */
4797 l = ml_get_curline();
4798 }
4799 else
4800 {
4801 amount = get_indent();
4802 l = ml_get_curline();
4803 }
4804 *pp = l;
4805
4806 curwin->w_cursor = cursor_save;
4807 return amount;
4808}
4809
4810/*
4811 * Return the indent of the first variable name after a type in a declaration.
4812 * int a, indent of "a"
4813 * static struct foo b, indent of "b"
4814 * enum bla c, indent of "c"
4815 * Returns zero when it doesn't look like a declaration.
4816 */
4817 static int
4818cin_first_id_amount()
4819{
4820 char_u *line, *p, *s;
4821 int len;
4822 pos_T fp;
4823 colnr_T col;
4824
4825 line = ml_get_curline();
4826 p = skipwhite(line);
4827 len = skiptowhite(p) - p;
4828 if (len == 6 && STRNCMP(p, "static", 6) == 0)
4829 {
4830 p = skipwhite(p + 6);
4831 len = skiptowhite(p) - p;
4832 }
4833 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
4834 p = skipwhite(p + 6);
4835 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
4836 p = skipwhite(p + 4);
4837 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
4838 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
4839 {
4840 s = skipwhite(p + len);
4841 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
4842 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
4843 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
4844 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
4845 p = s;
4846 }
4847 for (len = 0; vim_isIDc(p[len]); ++len)
4848 ;
4849 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
4850 return 0;
4851
4852 p = skipwhite(p + len);
4853 fp.lnum = curwin->w_cursor.lnum;
4854 fp.col = (colnr_T)(p - line);
4855 getvcol(curwin, &fp, &col, NULL, NULL);
4856 return (int)col;
4857}
4858
4859/*
4860 * Return the indent of the first non-blank after an equal sign.
4861 * char *foo = "here";
4862 * Return zero if no (useful) equal sign found.
4863 * Return -1 if the line above "lnum" ends in a backslash.
4864 * foo = "asdf\
4865 * asdf\
4866 * here";
4867 */
4868 static int
4869cin_get_equal_amount(lnum)
4870 linenr_T lnum;
4871{
4872 char_u *line;
4873 char_u *s;
4874 colnr_T col;
4875 pos_T fp;
4876
4877 if (lnum > 1)
4878 {
4879 line = ml_get(lnum - 1);
4880 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
4881 return -1;
4882 }
4883
4884 line = s = ml_get(lnum);
4885 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
4886 {
4887 if (cin_iscomment(s)) /* ignore comments */
4888 s = cin_skipcomment(s);
4889 else
4890 ++s;
4891 }
4892 if (*s != '=')
4893 return 0;
4894
4895 s = skipwhite(s + 1);
4896 if (cin_nocode(s))
4897 return 0;
4898
4899 if (*s == '"') /* nice alignment for continued strings */
4900 ++s;
4901
4902 fp.lnum = lnum;
4903 fp.col = (colnr_T)(s - line);
4904 getvcol(curwin, &fp, &col, NULL, NULL);
4905 return (int)col;
4906}
4907
4908/*
4909 * Recognize a preprocessor statement: Any line that starts with '#'.
4910 */
4911 static int
4912cin_ispreproc(s)
4913 char_u *s;
4914{
4915 s = skipwhite(s);
4916 if (*s == '#')
4917 return TRUE;
4918 return FALSE;
4919}
4920
4921/*
4922 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
4923 * continuation line of a preprocessor statement. Decrease "*lnump" to the
4924 * start and return the line in "*pp".
4925 */
4926 static int
4927cin_ispreproc_cont(pp, lnump)
4928 char_u **pp;
4929 linenr_T *lnump;
4930{
4931 char_u *line = *pp;
4932 linenr_T lnum = *lnump;
4933 int retval = FALSE;
4934
4935 while (1)
4936 {
4937 if (cin_ispreproc(line))
4938 {
4939 retval = TRUE;
4940 *lnump = lnum;
4941 break;
4942 }
4943 if (lnum == 1)
4944 break;
4945 line = ml_get(--lnum);
4946 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
4947 break;
4948 }
4949
4950 if (lnum != *lnump)
4951 *pp = ml_get(*lnump);
4952 return retval;
4953}
4954
4955/*
4956 * Recognize the start of a C or C++ comment.
4957 */
4958 static int
4959cin_iscomment(p)
4960 char_u *p;
4961{
4962 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
4963}
4964
4965/*
4966 * Recognize the start of a "//" comment.
4967 */
4968 static int
4969cin_islinecomment(p)
4970 char_u *p;
4971{
4972 return (p[0] == '/' && p[1] == '/');
4973}
4974
4975/*
4976 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
4977 * Don't consider "} else" a terminated line.
4978 * Return the character terminating the line (ending char's have precedence if
4979 * both apply in order to determine initializations).
4980 */
4981 static int
4982cin_isterminated(s, incl_open, incl_comma)
4983 char_u *s;
4984 int incl_open; /* include '{' at the end as terminator */
4985 int incl_comma; /* recognize a trailing comma */
4986{
4987 char_u found_start = 0;
4988
4989 s = cin_skipcomment(s);
4990
4991 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
4992 found_start = *s;
4993
4994 while (*s)
4995 {
4996 /* skip over comments, "" strings and 'c'haracters */
4997 s = skip_string(cin_skipcomment(s));
4998 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
4999 || (incl_comma && *s == ','))
5000 && cin_nocode(s + 1))
5001 return *s;
5002
5003 if (*s)
5004 s++;
5005 }
5006 return found_start;
5007}
5008
5009/*
5010 * Recognize the basic picture of a function declaration -- it needs to
5011 * have an open paren somewhere and a close paren at the end of the line and
5012 * no semicolons anywhere.
5013 * When a line ends in a comma we continue looking in the next line.
5014 * "sp" points to a string with the line. When looking at other lines it must
5015 * be restored to the line. When it's NULL fetch lines here.
5016 * "lnum" is where we start looking.
5017 */
5018 static int
5019cin_isfuncdecl(sp, first_lnum)
5020 char_u **sp;
5021 linenr_T first_lnum;
5022{
5023 char_u *s;
5024 linenr_T lnum = first_lnum;
5025 int retval = FALSE;
5026
5027 if (sp == NULL)
5028 s = ml_get(lnum);
5029 else
5030 s = *sp;
5031
5032 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5033 {
5034 if (cin_iscomment(s)) /* ignore comments */
5035 s = cin_skipcomment(s);
5036 else
5037 ++s;
5038 }
5039 if (*s != '(')
5040 return FALSE; /* ';', ' or " before any () or no '(' */
5041
5042 while (*s && *s != ';' && *s != '\'' && *s != '"')
5043 {
5044 if (*s == ')' && cin_nocode(s + 1))
5045 {
5046 /* ')' at the end: may have found a match
5047 * Check for he previous line not to end in a backslash:
5048 * #if defined(x) && \
5049 * defined(y)
5050 */
5051 lnum = first_lnum - 1;
5052 s = ml_get(lnum);
5053 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5054 retval = TRUE;
5055 goto done;
5056 }
5057 if (*s == ',' && cin_nocode(s + 1))
5058 {
5059 /* ',' at the end: continue looking in the next line */
5060 if (lnum >= curbuf->b_ml.ml_line_count)
5061 break;
5062
5063 s = ml_get(++lnum);
5064 }
5065 else if (cin_iscomment(s)) /* ignore comments */
5066 s = cin_skipcomment(s);
5067 else
5068 ++s;
5069 }
5070
5071done:
5072 if (lnum != first_lnum && sp != NULL)
5073 *sp = ml_get(first_lnum);
5074
5075 return retval;
5076}
5077
5078 static int
5079cin_isif(p)
5080 char_u *p;
5081{
5082 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5083}
5084
5085 static int
5086cin_iselse(p)
5087 char_u *p;
5088{
5089 if (*p == '}') /* accept "} else" */
5090 p = cin_skipcomment(p + 1);
5091 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5092}
5093
5094 static int
5095cin_isdo(p)
5096 char_u *p;
5097{
5098 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5099}
5100
5101/*
5102 * Check if this is a "while" that should have a matching "do".
5103 * We only accept a "while (condition) ;", with only white space between the
5104 * ')' and ';'. The condition may be spread over several lines.
5105 */
5106 static int
5107cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5108 char_u *p;
5109 linenr_T lnum;
5110 int ind_maxparen;
5111{
5112 pos_T cursor_save;
5113 pos_T *trypos;
5114 int retval = FALSE;
5115
5116 p = cin_skipcomment(p);
5117 if (*p == '}') /* accept "} while (cond);" */
5118 p = cin_skipcomment(p + 1);
5119 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5120 {
5121 cursor_save = curwin->w_cursor;
5122 curwin->w_cursor.lnum = lnum;
5123 curwin->w_cursor.col = 0;
5124 p = ml_get_curline();
5125 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5126 {
5127 ++p;
5128 ++curwin->w_cursor.col;
5129 }
5130 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5131 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5132 retval = TRUE;
5133 curwin->w_cursor = cursor_save;
5134 }
5135 return retval;
5136}
5137
5138 static int
5139cin_isbreak(p)
5140 char_u *p;
5141{
5142 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5143}
5144
5145/* Find the position of a C++ base-class declaration or
5146 * constructor-initialization. eg:
5147 *
5148 * class MyClass :
5149 * baseClass <-- here
5150 * class MyClass : public baseClass,
5151 * anotherBaseClass <-- here (should probably lineup ??)
5152 * MyClass::MyClass(...) :
5153 * baseClass(...) <-- here (constructor-initialization)
5154 */
5155 static int
5156cin_is_cpp_baseclass(line, col)
5157 char_u *line;
5158 colnr_T *col;
5159{
5160 char_u *s;
5161 int class_or_struct, lookfor_ctor_init, cpp_base_class;
5162
5163 *col = 0;
5164
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005165 s = skipwhite(line);
5166 if (*s == '#') /* skip #define FOO x ? (x) : x */
5167 return FALSE;
5168 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005169 if (*s == NUL)
5170 return FALSE;
5171
5172 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5173
5174 while(*s != NUL)
5175 {
5176 if (s[0] == ':')
5177 {
5178 if (s[1] == ':')
5179 {
5180 /* skip double colon. It can't be a constructor
5181 * initialization any more */
5182 lookfor_ctor_init = FALSE;
5183 s = cin_skipcomment(s + 2);
5184 }
5185 else if (lookfor_ctor_init || class_or_struct)
5186 {
5187 /* we have something found, that looks like the start of
5188 * cpp-base-class-declaration or contructor-initialization */
5189 cpp_base_class = TRUE;
5190 lookfor_ctor_init = class_or_struct = FALSE;
5191 *col = 0;
5192 s = cin_skipcomment(s + 1);
5193 }
5194 else
5195 s = cin_skipcomment(s + 1);
5196 }
5197 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5198 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5199 {
5200 class_or_struct = TRUE;
5201 lookfor_ctor_init = FALSE;
5202
5203 if (*s == 'c')
5204 s = cin_skipcomment(s + 5);
5205 else
5206 s = cin_skipcomment(s + 6);
5207 }
5208 else
5209 {
5210 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5211 {
5212 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5213 }
5214 else if (s[0] == ')')
5215 {
5216 /* Constructor-initialization is assumed if we come across
5217 * something like "):" */
5218 class_or_struct = FALSE;
5219 lookfor_ctor_init = TRUE;
5220 }
5221 else if (!vim_isIDc(s[0]))
5222 {
5223 /* if it is not an identifier, we are wrong */
5224 class_or_struct = FALSE;
5225 lookfor_ctor_init = FALSE;
5226 }
5227 else if (*col == 0)
5228 {
5229 /* it can't be a constructor-initialization any more */
5230 lookfor_ctor_init = FALSE;
5231
5232 /* the first statement starts here: lineup with this one... */
5233 if (cpp_base_class && *col == 0)
5234 *col = (colnr_T)(s - line);
5235 }
5236
5237 s = cin_skipcomment(s + 1);
5238 }
5239 }
5240
5241 return cpp_base_class;
5242}
5243
5244/*
5245 * Return TRUE if string "s" ends with the string "find", possibly followed by
5246 * white space and comments. Skip strings and comments.
5247 * Ignore "ignore" after "find" if it's not NULL.
5248 */
5249 static int
5250cin_ends_in(s, find, ignore)
5251 char_u *s;
5252 char_u *find;
5253 char_u *ignore;
5254{
5255 char_u *p = s;
5256 char_u *r;
5257 int len = (int)STRLEN(find);
5258
5259 while (*p != NUL)
5260 {
5261 p = cin_skipcomment(p);
5262 if (STRNCMP(p, find, len) == 0)
5263 {
5264 r = skipwhite(p + len);
5265 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5266 r = skipwhite(r + STRLEN(ignore));
5267 if (cin_nocode(r))
5268 return TRUE;
5269 }
5270 if (*p != NUL)
5271 ++p;
5272 }
5273 return FALSE;
5274}
5275
5276/*
5277 * Skip strings, chars and comments until at or past "trypos".
5278 * Return the column found.
5279 */
5280 static int
5281cin_skip2pos(trypos)
5282 pos_T *trypos;
5283{
5284 char_u *line;
5285 char_u *p;
5286
5287 p = line = ml_get(trypos->lnum);
5288 while (*p && (colnr_T)(p - line) < trypos->col)
5289 {
5290 if (cin_iscomment(p))
5291 p = cin_skipcomment(p);
5292 else
5293 {
5294 p = skip_string(p);
5295 ++p;
5296 }
5297 }
5298 return (int)(p - line);
5299}
5300
5301/*
5302 * Find the '{' at the start of the block we are in.
5303 * Return NULL if no match found.
5304 * Ignore a '{' that is in a comment, makes indenting the next three lines
5305 * work. */
5306/* foo() */
5307/* { */
5308/* } */
5309
5310 static pos_T *
5311find_start_brace(ind_maxcomment) /* XXX */
5312 int ind_maxcomment;
5313{
5314 pos_T cursor_save;
5315 pos_T *trypos;
5316 pos_T *pos;
5317 static pos_T pos_copy;
5318
5319 cursor_save = curwin->w_cursor;
5320 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5321 {
5322 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5323 trypos = &pos_copy;
5324 curwin->w_cursor = *trypos;
5325 pos = NULL;
5326 /* ignore the { if it's in a // comment */
5327 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5328 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5329 break;
5330 if (pos != NULL)
5331 curwin->w_cursor.lnum = pos->lnum;
5332 }
5333 curwin->w_cursor = cursor_save;
5334 return trypos;
5335}
5336
5337/*
5338 * Find the matching '(', failing if it is in a comment.
5339 * Return NULL of no match found.
5340 */
5341 static pos_T *
5342find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5343 int ind_maxparen;
5344 int ind_maxcomment;
5345{
5346 pos_T cursor_save;
5347 pos_T *trypos;
5348 static pos_T pos_copy;
5349
5350 cursor_save = curwin->w_cursor;
5351 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5352 {
5353 /* check if the ( is in a // comment */
5354 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5355 trypos = NULL;
5356 else
5357 {
5358 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5359 trypos = &pos_copy;
5360 curwin->w_cursor = *trypos;
5361 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5362 trypos = NULL;
5363 }
5364 }
5365 curwin->w_cursor = cursor_save;
5366 return trypos;
5367}
5368
5369/*
5370 * Return ind_maxparen corrected for the difference in line number between the
5371 * cursor position and "startpos". This makes sure that searching for a
5372 * matching paren above the cursor line doesn't find a match because of
5373 * looking a few lines further.
5374 */
5375 static int
5376corr_ind_maxparen(ind_maxparen, startpos)
5377 int ind_maxparen;
5378 pos_T *startpos;
5379{
5380 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5381
5382 if (n > 0 && n < ind_maxparen / 2)
5383 return ind_maxparen - (int)n;
5384 return ind_maxparen;
5385}
5386
5387/*
5388 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5389 * line "l".
5390 */
5391 static int
5392find_last_paren(l, start, end)
5393 char_u *l;
5394 int start, end;
5395{
5396 int i;
5397 int retval = FALSE;
5398 int open_count = 0;
5399
5400 curwin->w_cursor.col = 0; /* default is start of line */
5401
5402 for (i = 0; l[i]; i++)
5403 {
5404 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5405 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5406 if (l[i] == start)
5407 ++open_count;
5408 else if (l[i] == end)
5409 {
5410 if (open_count > 0)
5411 --open_count;
5412 else
5413 {
5414 curwin->w_cursor.col = i;
5415 retval = TRUE;
5416 }
5417 }
5418 }
5419 return retval;
5420}
5421
5422 int
5423get_c_indent()
5424{
5425 /*
5426 * spaces from a block's opening brace the prevailing indent for that
5427 * block should be
5428 */
5429 int ind_level = curbuf->b_p_sw;
5430
5431 /*
5432 * spaces from the edge of the line an open brace that's at the end of a
5433 * line is imagined to be.
5434 */
5435 int ind_open_imag = 0;
5436
5437 /*
5438 * spaces from the prevailing indent for a line that is not precededof by
5439 * an opening brace.
5440 */
5441 int ind_no_brace = 0;
5442
5443 /*
5444 * column where the first { of a function should be located }
5445 */
5446 int ind_first_open = 0;
5447
5448 /*
5449 * spaces from the prevailing indent a leftmost open brace should be
5450 * located
5451 */
5452 int ind_open_extra = 0;
5453
5454 /*
5455 * spaces from the matching open brace (real location for one at the left
5456 * edge; imaginary location from one that ends a line) the matching close
5457 * brace should be located
5458 */
5459 int ind_close_extra = 0;
5460
5461 /*
5462 * spaces from the edge of the line an open brace sitting in the leftmost
5463 * column is imagined to be
5464 */
5465 int ind_open_left_imag = 0;
5466
5467 /*
5468 * spaces from the switch() indent a "case xx" label should be located
5469 */
5470 int ind_case = curbuf->b_p_sw;
5471
5472 /*
5473 * spaces from the "case xx:" code after a switch() should be located
5474 */
5475 int ind_case_code = curbuf->b_p_sw;
5476
5477 /*
5478 * lineup break at end of case in switch() with case label
5479 */
5480 int ind_case_break = 0;
5481
5482 /*
5483 * spaces from the class declaration indent a scope declaration label
5484 * should be located
5485 */
5486 int ind_scopedecl = curbuf->b_p_sw;
5487
5488 /*
5489 * spaces from the scope declaration label code should be located
5490 */
5491 int ind_scopedecl_code = curbuf->b_p_sw;
5492
5493 /*
5494 * amount K&R-style parameters should be indented
5495 */
5496 int ind_param = curbuf->b_p_sw;
5497
5498 /*
5499 * amount a function type spec should be indented
5500 */
5501 int ind_func_type = curbuf->b_p_sw;
5502
5503 /*
5504 * amount a cpp base class declaration or constructor initialization
5505 * should be indented
5506 */
5507 int ind_cpp_baseclass = curbuf->b_p_sw;
5508
5509 /*
5510 * additional spaces beyond the prevailing indent a continuation line
5511 * should be located
5512 */
5513 int ind_continuation = curbuf->b_p_sw;
5514
5515 /*
5516 * spaces from the indent of the line with an unclosed parentheses
5517 */
5518 int ind_unclosed = curbuf->b_p_sw * 2;
5519
5520 /*
5521 * spaces from the indent of the line with an unclosed parentheses, which
5522 * itself is also unclosed
5523 */
5524 int ind_unclosed2 = curbuf->b_p_sw;
5525
5526 /*
5527 * suppress ignoring spaces from the indent of a line starting with an
5528 * unclosed parentheses.
5529 */
5530 int ind_unclosed_noignore = 0;
5531
5532 /*
5533 * If the opening paren is the last nonwhite character on the line, and
5534 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
5535 * context (for very long lines).
5536 */
5537 int ind_unclosed_wrapped = 0;
5538
5539 /*
5540 * suppress ignoring white space when lining up with the character after
5541 * an unclosed parentheses.
5542 */
5543 int ind_unclosed_whiteok = 0;
5544
5545 /*
5546 * indent a closing parentheses under the line start of the matching
5547 * opening parentheses.
5548 */
5549 int ind_matching_paren = 0;
5550
5551 /*
5552 * Extra indent for comments.
5553 */
5554 int ind_comment = 0;
5555
5556 /*
5557 * spaces from the comment opener when there is nothing after it.
5558 */
5559 int ind_in_comment = 3;
5560
5561 /*
5562 * boolean: if non-zero, use ind_in_comment even if there is something
5563 * after the comment opener.
5564 */
5565 int ind_in_comment2 = 0;
5566
5567 /*
5568 * max lines to search for an open paren
5569 */
5570 int ind_maxparen = 20;
5571
5572 /*
5573 * max lines to search for an open comment
5574 */
5575 int ind_maxcomment = 70;
5576
5577 /*
5578 * handle braces for java code
5579 */
5580 int ind_java = 0;
5581
5582 /*
5583 * handle blocked cases correctly
5584 */
5585 int ind_keep_case_label = 0;
5586
5587 pos_T cur_curpos;
5588 int amount;
5589 int scope_amount;
5590 int cur_amount;
5591 colnr_T col;
5592 char_u *theline;
5593 char_u *linecopy;
5594 pos_T *trypos;
5595 pos_T *tryposBrace = NULL;
5596 pos_T our_paren_pos;
5597 char_u *start;
5598 int start_brace;
5599#define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
5600#define BRACE_AT_START 2 /* '{' is at start of line */
5601#define BRACE_AT_END 3 /* '{' is at end of line */
5602 linenr_T ourscope;
5603 char_u *l;
5604 char_u *look;
5605 char_u terminated;
5606 int lookfor;
5607#define LOOKFOR_INITIAL 0
5608#define LOOKFOR_IF 1
5609#define LOOKFOR_DO 2
5610#define LOOKFOR_CASE 3
5611#define LOOKFOR_ANY 4
5612#define LOOKFOR_TERM 5
5613#define LOOKFOR_UNTERM 6
5614#define LOOKFOR_SCOPEDECL 7
5615#define LOOKFOR_NOBREAK 8
5616#define LOOKFOR_CPP_BASECLASS 9
5617#define LOOKFOR_ENUM_OR_INIT 10
5618
5619 int whilelevel;
5620 linenr_T lnum;
5621 char_u *options;
5622 int fraction = 0; /* init for GCC */
5623 int divider;
5624 int n;
5625 int iscase;
5626 int lookfor_break;
5627 int cont_amount = 0; /* amount for continuation line */
5628
5629 for (options = curbuf->b_p_cino; *options; )
5630 {
5631 l = options++;
5632 if (*options == '-')
5633 ++options;
5634 n = getdigits(&options);
5635 divider = 0;
5636 if (*options == '.') /* ".5s" means a fraction */
5637 {
5638 fraction = atol((char *)++options);
5639 while (VIM_ISDIGIT(*options))
5640 {
5641 ++options;
5642 if (divider)
5643 divider *= 10;
5644 else
5645 divider = 10;
5646 }
5647 }
5648 if (*options == 's') /* "2s" means two times 'shiftwidth' */
5649 {
5650 if (n == 0 && fraction == 0)
5651 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
5652 else
5653 {
5654 n *= curbuf->b_p_sw;
5655 if (divider)
5656 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
5657 }
5658 ++options;
5659 }
5660 if (l[1] == '-')
5661 n = -n;
5662 /* When adding an entry here, also update the default 'cinoptions' in
5663 * change.txt, and add explanation for it! */
5664 switch (*l)
5665 {
5666 case '>': ind_level = n; break;
5667 case 'e': ind_open_imag = n; break;
5668 case 'n': ind_no_brace = n; break;
5669 case 'f': ind_first_open = n; break;
5670 case '{': ind_open_extra = n; break;
5671 case '}': ind_close_extra = n; break;
5672 case '^': ind_open_left_imag = n; break;
5673 case ':': ind_case = n; break;
5674 case '=': ind_case_code = n; break;
5675 case 'b': ind_case_break = n; break;
5676 case 'p': ind_param = n; break;
5677 case 't': ind_func_type = n; break;
5678 case '/': ind_comment = n; break;
5679 case 'c': ind_in_comment = n; break;
5680 case 'C': ind_in_comment2 = n; break;
5681 case 'i': ind_cpp_baseclass = n; break;
5682 case '+': ind_continuation = n; break;
5683 case '(': ind_unclosed = n; break;
5684 case 'u': ind_unclosed2 = n; break;
5685 case 'U': ind_unclosed_noignore = n; break;
5686 case 'W': ind_unclosed_wrapped = n; break;
5687 case 'w': ind_unclosed_whiteok = n; break;
5688 case 'm': ind_matching_paren = n; break;
5689 case ')': ind_maxparen = n; break;
5690 case '*': ind_maxcomment = n; break;
5691 case 'g': ind_scopedecl = n; break;
5692 case 'h': ind_scopedecl_code = n; break;
5693 case 'j': ind_java = n; break;
5694 case 'l': ind_keep_case_label = n; break;
5695 }
5696 }
5697
5698 /* remember where the cursor was when we started */
5699 cur_curpos = curwin->w_cursor;
5700
5701 /* Get a copy of the current contents of the line.
5702 * This is required, because only the most recent line obtained with
5703 * ml_get is valid! */
5704 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
5705 if (linecopy == NULL)
5706 return 0;
5707
5708 /*
5709 * In insert mode and the cursor is on a ')' truncate the line at the
5710 * cursor position. We don't want to line up with the matching '(' when
5711 * inserting new stuff.
5712 * For unknown reasons the cursor might be past the end of the line, thus
5713 * check for that.
5714 */
5715 if ((State & INSERT)
5716 && curwin->w_cursor.col < STRLEN(linecopy)
5717 && linecopy[curwin->w_cursor.col] == ')')
5718 linecopy[curwin->w_cursor.col] = NUL;
5719
5720 theline = skipwhite(linecopy);
5721
5722 /* move the cursor to the start of the line */
5723
5724 curwin->w_cursor.col = 0;
5725
5726 /*
5727 * #defines and so on always go at the left when included in 'cinkeys'.
5728 */
5729 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
5730 {
5731 amount = 0;
5732 }
5733
5734 /*
5735 * Is it a non-case label? Then that goes at the left margin too.
5736 */
5737 else if (cin_islabel(ind_maxcomment)) /* XXX */
5738 {
5739 amount = 0;
5740 }
5741
5742 /*
5743 * If we're inside a "//" comment and there is a "//" comment in a
5744 * previous line, lineup with that one.
5745 */
5746 else if (cin_islinecomment(theline)
5747 && (trypos = find_line_comment()) != NULL) /* XXX */
5748 {
5749 /* find how indented the line beginning the comment is */
5750 getvcol(curwin, trypos, &col, NULL, NULL);
5751 amount = col;
5752 }
5753
5754 /*
5755 * If we're inside a comment and not looking at the start of the
5756 * comment, try using the 'comments' option.
5757 */
5758 else if (!cin_iscomment(theline)
5759 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5760 {
5761 int lead_start_len = 2;
5762 int lead_middle_len = 1;
5763 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
5764 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
5765 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
5766 char_u *p;
5767 int start_align = 0;
5768 int start_off = 0;
5769 int done = FALSE;
5770
5771 /* find how indented the line beginning the comment is */
5772 getvcol(curwin, trypos, &col, NULL, NULL);
5773 amount = col;
5774
5775 p = curbuf->b_p_com;
5776 while (*p != NUL)
5777 {
5778 int align = 0;
5779 int off = 0;
5780 int what = 0;
5781
5782 while (*p != NUL && *p != ':')
5783 {
5784 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
5785 what = *p++;
5786 else if (*p == COM_LEFT || *p == COM_RIGHT)
5787 align = *p++;
5788 else if (VIM_ISDIGIT(*p) || *p == '-')
5789 off = getdigits(&p);
5790 else
5791 ++p;
5792 }
5793
5794 if (*p == ':')
5795 ++p;
5796 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5797 if (what == COM_START)
5798 {
5799 STRCPY(lead_start, lead_end);
5800 lead_start_len = (int)STRLEN(lead_start);
5801 start_off = off;
5802 start_align = align;
5803 }
5804 else if (what == COM_MIDDLE)
5805 {
5806 STRCPY(lead_middle, lead_end);
5807 lead_middle_len = (int)STRLEN(lead_middle);
5808 }
5809 else if (what == COM_END)
5810 {
5811 /* If our line starts with the middle comment string, line it
5812 * up with the comment opener per the 'comments' option. */
5813 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
5814 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
5815 {
5816 done = TRUE;
5817 if (curwin->w_cursor.lnum > 1)
5818 {
5819 /* If the start comment string matches in the previous
5820 * line, use the indent of that line pluss offset. If
5821 * the middle comment string matches in the previous
5822 * line, use the indent of that line. XXX */
5823 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
5824 if (STRNCMP(look, lead_start, lead_start_len) == 0)
5825 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
5826 else if (STRNCMP(look, lead_middle,
5827 lead_middle_len) == 0)
5828 {
5829 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
5830 break;
5831 }
5832 /* If the start comment string doesn't match with the
5833 * start of the comment, skip this entry. XXX */
5834 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
5835 lead_start, lead_start_len) != 0)
5836 continue;
5837 }
5838 if (start_off != 0)
5839 amount += start_off;
5840 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005841 amount += vim_strsize(lead_start)
5842 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005843 break;
5844 }
5845
5846 /* If our line starts with the end comment string, line it up
5847 * with the middle comment */
5848 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
5849 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
5850 {
5851 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
5852 /* XXX */
5853 if (off != 0)
5854 amount += off;
5855 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005856 amount += vim_strsize(lead_start)
5857 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005858 done = TRUE;
5859 break;
5860 }
5861 }
5862 }
5863
5864 /* If our line starts with an asterisk, line up with the
5865 * asterisk in the comment opener; otherwise, line up
5866 * with the first character of the comment text.
5867 */
5868 if (done)
5869 ;
5870 else if (theline[0] == '*')
5871 amount += 1;
5872 else
5873 {
5874 /*
5875 * If we are more than one line away from the comment opener, take
5876 * the indent of the previous non-empty line. If 'cino' has "CO"
5877 * and we are just below the comment opener and there are any
5878 * white characters after it line up with the text after it;
5879 * otherwise, add the amount specified by "c" in 'cino'
5880 */
5881 amount = -1;
5882 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
5883 {
5884 if (linewhite(lnum)) /* skip blank lines */
5885 continue;
5886 amount = get_indent_lnum(lnum); /* XXX */
5887 break;
5888 }
5889 if (amount == -1) /* use the comment opener */
5890 {
5891 if (!ind_in_comment2)
5892 {
5893 start = ml_get(trypos->lnum);
5894 look = start + trypos->col + 2; /* skip / and * */
5895 if (*look != NUL) /* if something after it */
5896 trypos->col = (colnr_T)(skipwhite(look) - start);
5897 }
5898 getvcol(curwin, trypos, &col, NULL, NULL);
5899 amount = col;
5900 if (ind_in_comment2 || *look == NUL)
5901 amount += ind_in_comment;
5902 }
5903 }
5904 }
5905
5906 /*
5907 * Are we inside parentheses or braces?
5908 */ /* XXX */
5909 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
5910 && ind_java == 0)
5911 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
5912 || trypos != NULL)
5913 {
5914 if (trypos != NULL && tryposBrace != NULL)
5915 {
5916 /* Both an unmatched '(' and '{' is found. Use the one which is
5917 * closer to the current cursor position, set the other to NULL. */
5918 if (trypos->lnum != tryposBrace->lnum
5919 ? trypos->lnum < tryposBrace->lnum
5920 : trypos->col < tryposBrace->col)
5921 trypos = NULL;
5922 else
5923 tryposBrace = NULL;
5924 }
5925
5926 if (trypos != NULL)
5927 {
5928 /*
5929 * If the matching paren is more than one line away, use the indent of
5930 * a previous non-empty line that matches the same paren.
5931 */
5932 amount = -1;
5933 cur_amount = MAXCOL;
5934 our_paren_pos = *trypos;
5935 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
5936 {
5937 l = skipwhite(ml_get(lnum));
5938 if (cin_nocode(l)) /* skip comment lines */
5939 continue;
5940 if (cin_ispreproc_cont(&l, &lnum)) /* ignore #defines, #if, etc. */
5941 continue;
5942 curwin->w_cursor.lnum = lnum;
5943
5944 /* Skip a comment. XXX */
5945 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
5946 {
5947 lnum = trypos->lnum + 1;
5948 continue;
5949 }
5950
5951 /* XXX */
5952 if ((trypos = find_match_paren(
5953 corr_ind_maxparen(ind_maxparen, &cur_curpos),
5954 ind_maxcomment)) != NULL
5955 && trypos->lnum == our_paren_pos.lnum
5956 && trypos->col == our_paren_pos.col)
5957 {
5958 amount = get_indent_lnum(lnum); /* XXX */
5959
5960 if (theline[0] == ')')
5961 {
5962 if (our_paren_pos.lnum != lnum && cur_amount > amount)
5963 cur_amount = amount;
5964 amount = -1;
5965 }
5966 break;
5967 }
5968 }
5969
5970 /*
5971 * Line up with line where the matching paren is. XXX
5972 * If the line starts with a '(' or the indent for unclosed
5973 * parentheses is zero, line up with the unclosed parentheses.
5974 */
5975 if (amount == -1)
5976 {
5977 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
5978 if (theline[0] == ')' || ind_unclosed == 0
5979 || (!ind_unclosed_noignore && *skipwhite(look) == '('))
5980 {
5981 /*
5982 * If we're looking at a close paren, line up right there;
5983 * otherwise, line up with the next (non-white) character.
5984 * When ind_unclosed_wrapped is set and the matching paren is
5985 * the last nonwhite character of the line, use either the
5986 * indent of the current line or the indentation of the next
5987 * outer paren and add ind_unclosed_wrapped (for very long
5988 * lines).
5989 */
5990 if (theline[0] != ')')
5991 {
5992 cur_amount = MAXCOL;
5993 l = ml_get(our_paren_pos.lnum);
5994 if (ind_unclosed_wrapped
5995 && cin_ends_in(l, (char_u *)"(", NULL))
5996 {
5997 /* look for opening unmatched paren, indent one level
5998 * for each additional level */
5999 n = 1;
6000 for (col = 0; col < our_paren_pos.col; ++col)
6001 {
6002 switch (l[col])
6003 {
6004 case '(':
6005 case '{': ++n;
6006 break;
6007
6008 case ')':
6009 case '}': if (n > 1)
6010 --n;
6011 break;
6012 }
6013 }
6014
6015 our_paren_pos.col = 0;
6016 amount += n * ind_unclosed_wrapped;
6017 }
6018 else if (ind_unclosed_whiteok)
6019 our_paren_pos.col++;
6020 else
6021 {
6022 col = our_paren_pos.col + 1;
6023 while (vim_iswhite(l[col]))
6024 col++;
6025 if (l[col] != NUL) /* In case of trailing space */
6026 our_paren_pos.col = col;
6027 else
6028 our_paren_pos.col++;
6029 }
6030 }
6031
6032 /*
6033 * Find how indented the paren is, or the character after it
6034 * if we did the above "if".
6035 */
6036 if (our_paren_pos.col > 0)
6037 {
6038 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6039 if (cur_amount > (int)col)
6040 cur_amount = col;
6041 }
6042 }
6043
6044 if (theline[0] == ')' && ind_matching_paren)
6045 {
6046 /* Line up with the start of the matching paren line. */
6047 }
6048 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
6049 && *skipwhite(look) == '('))
6050 {
6051 if (cur_amount != MAXCOL)
6052 amount = cur_amount;
6053 }
6054 else
6055 {
6056 /* add ind_unclosed2 for each '(' before our matching one */
6057 col = our_paren_pos.col;
6058 while (our_paren_pos.col > 0)
6059 {
6060 --our_paren_pos.col;
6061 switch (*ml_get_pos(&our_paren_pos))
6062 {
6063 case '(': amount += ind_unclosed2;
6064 col = our_paren_pos.col;
6065 break;
6066 case ')': amount -= ind_unclosed2;
6067 col = MAXCOL;
6068 break;
6069 }
6070 }
6071
6072 /* Use ind_unclosed once, when the first '(' is not inside
6073 * braces */
6074 if (col == MAXCOL)
6075 amount += ind_unclosed;
6076 else
6077 {
6078 curwin->w_cursor.lnum = our_paren_pos.lnum;
6079 curwin->w_cursor.col = col;
6080 if ((trypos = find_match_paren(ind_maxparen,
6081 ind_maxcomment)) != NULL)
6082 amount += ind_unclosed2;
6083 else
6084 amount += ind_unclosed;
6085 }
6086 /*
6087 * For a line starting with ')' use the minimum of the two
6088 * positions, to avoid giving it more indent than the previous
6089 * lines:
6090 * func_long_name( if (x
6091 * arg && yy
6092 * ) ^ not here ) ^ not here
6093 */
6094 if (cur_amount < amount)
6095 amount = cur_amount;
6096 }
6097 }
6098
6099 /* add extra indent for a comment */
6100 if (cin_iscomment(theline))
6101 amount += ind_comment;
6102 }
6103
6104 /*
6105 * Are we at least inside braces, then?
6106 */
6107 else
6108 {
6109 trypos = tryposBrace;
6110
6111 ourscope = trypos->lnum;
6112 start = ml_get(ourscope);
6113
6114 /*
6115 * Now figure out how indented the line is in general.
6116 * If the brace was at the start of the line, we use that;
6117 * otherwise, check out the indentation of the line as
6118 * a whole and then add the "imaginary indent" to that.
6119 */
6120 look = skipwhite(start);
6121 if (*look == '{')
6122 {
6123 getvcol(curwin, trypos, &col, NULL, NULL);
6124 amount = col;
6125 if (*start == '{')
6126 start_brace = BRACE_IN_COL0;
6127 else
6128 start_brace = BRACE_AT_START;
6129 }
6130 else
6131 {
6132 /*
6133 * that opening brace might have been on a continuation
6134 * line. if so, find the start of the line.
6135 */
6136 curwin->w_cursor.lnum = ourscope;
6137
6138 /*
6139 * position the cursor over the rightmost paren, so that
6140 * matching it will take us back to the start of the line.
6141 */
6142 lnum = ourscope;
6143 if (find_last_paren(start, '(', ')')
6144 && (trypos = find_match_paren(ind_maxparen,
6145 ind_maxcomment)) != NULL)
6146 lnum = trypos->lnum;
6147
6148 /*
6149 * It could have been something like
6150 * case 1: if (asdf &&
6151 * ldfd) {
6152 * }
6153 */
6154 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6155 amount = get_indent();
6156 else
6157 amount = skip_label(lnum, &l, ind_maxcomment);
6158
6159 start_brace = BRACE_AT_END;
6160 }
6161
6162 /*
6163 * if we're looking at a closing brace, that's where
6164 * we want to be. otherwise, add the amount of room
6165 * that an indent is supposed to be.
6166 */
6167 if (theline[0] == '}')
6168 {
6169 /*
6170 * they may want closing braces to line up with something
6171 * other than the open brace. indulge them, if so.
6172 */
6173 amount += ind_close_extra;
6174 }
6175 else
6176 {
6177 /*
6178 * If we're looking at an "else", try to find an "if"
6179 * to match it with.
6180 * If we're looking at a "while", try to find a "do"
6181 * to match it with.
6182 */
6183 lookfor = LOOKFOR_INITIAL;
6184 if (cin_iselse(theline))
6185 lookfor = LOOKFOR_IF;
6186 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6187 /* XXX */
6188 lookfor = LOOKFOR_DO;
6189 if (lookfor != LOOKFOR_INITIAL)
6190 {
6191 curwin->w_cursor.lnum = cur_curpos.lnum;
6192 if (find_match(lookfor, ourscope, ind_maxparen,
6193 ind_maxcomment) == OK)
6194 {
6195 amount = get_indent(); /* XXX */
6196 goto theend;
6197 }
6198 }
6199
6200 /*
6201 * We get here if we are not on an "while-of-do" or "else" (or
6202 * failed to find a matching "if").
6203 * Search backwards for something to line up with.
6204 * First set amount for when we don't find anything.
6205 */
6206
6207 /*
6208 * if the '{' is _really_ at the left margin, use the imaginary
6209 * location of a left-margin brace. Otherwise, correct the
6210 * location for ind_open_extra.
6211 */
6212
6213 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6214 {
6215 amount = ind_open_left_imag;
6216 }
6217 else
6218 {
6219 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6220 amount += ind_open_imag;
6221 else
6222 {
6223 /* Compensate for adding ind_open_extra later. */
6224 amount -= ind_open_extra;
6225 if (amount < 0)
6226 amount = 0;
6227 }
6228 }
6229
6230 lookfor_break = FALSE;
6231
6232 if (cin_iscase(theline)) /* it's a switch() label */
6233 {
6234 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6235 amount += ind_case;
6236 }
6237 else if (cin_isscopedecl(theline)) /* private:, ... */
6238 {
6239 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6240 amount += ind_scopedecl;
6241 }
6242 else
6243 {
6244 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6245 lookfor_break = TRUE;
6246
6247 lookfor = LOOKFOR_INITIAL;
6248 amount += ind_level; /* ind_level from start of block */
6249 }
6250 scope_amount = amount;
6251 whilelevel = 0;
6252
6253 /*
6254 * Search backwards. If we find something we recognize, line up
6255 * with that.
6256 *
6257 * if we're looking at an open brace, indent
6258 * the usual amount relative to the conditional
6259 * that opens the block.
6260 */
6261 curwin->w_cursor = cur_curpos;
6262 for (;;)
6263 {
6264 curwin->w_cursor.lnum--;
6265 curwin->w_cursor.col = 0;
6266
6267 /*
6268 * If we went all the way back to the start of our scope, line
6269 * up with it.
6270 */
6271 if (curwin->w_cursor.lnum <= ourscope)
6272 {
6273 /* we reached end of scope:
6274 * if looking for a enum or structure initialization
6275 * go further back:
6276 * if it is an initializer (enum xxx or xxx =), then
6277 * don't add ind_continuation, otherwise it is a variable
6278 * declaration:
6279 * int x,
6280 * here; <-- add ind_continuation
6281 */
6282 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6283 {
6284 if (curwin->w_cursor.lnum == 0
6285 || curwin->w_cursor.lnum
6286 < ourscope - ind_maxparen)
6287 {
6288 /* nothing found (abuse ind_maxparen as limit)
6289 * assume terminated line (i.e. a variable
6290 * initialization) */
6291 if (cont_amount > 0)
6292 amount = cont_amount;
6293 else
6294 amount += ind_continuation;
6295 break;
6296 }
6297
6298 l = ml_get_curline();
6299
6300 /*
6301 * If we're in a comment now, skip to the start of the
6302 * comment.
6303 */
6304 trypos = find_start_comment(ind_maxcomment);
6305 if (trypos != NULL)
6306 {
6307 curwin->w_cursor.lnum = trypos->lnum + 1;
6308 continue;
6309 }
6310
6311 /*
6312 * Skip preprocessor directives and blank lines.
6313 */
6314 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6315 continue;
6316
6317 if (cin_nocode(l))
6318 continue;
6319
6320 terminated = cin_isterminated(l, FALSE, TRUE);
6321
6322 /*
6323 * If we are at top level and the line looks like a
6324 * function declaration, we are done
6325 * (it's a variable declaration).
6326 */
6327 if (start_brace != BRACE_IN_COL0
6328 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6329 {
6330 /* if the line is terminated with another ','
6331 * it is a continued variable initialization.
6332 * don't add extra indent.
6333 * TODO: does not work, if a function
6334 * declaration is split over multiple lines:
6335 * cin_isfuncdecl returns FALSE then.
6336 */
6337 if (terminated == ',')
6338 break;
6339
6340 /* if it es a enum declaration or an assignment,
6341 * we are done.
6342 */
6343 if (terminated != ';' && cin_isinit())
6344 break;
6345
6346 /* nothing useful found */
6347 if (terminated == 0 || terminated == '{')
6348 continue;
6349 }
6350
6351 if (terminated != ';')
6352 {
6353 /* Skip parens and braces. Position the cursor
6354 * over the rightmost paren, so that matching it
6355 * will take us back to the start of the line.
6356 */ /* XXX */
6357 trypos = NULL;
6358 if (find_last_paren(l, '(', ')'))
6359 trypos = find_match_paren(ind_maxparen,
6360 ind_maxcomment);
6361
6362 if (trypos == NULL && find_last_paren(l, '{', '}'))
6363 trypos = find_start_brace(ind_maxcomment);
6364
6365 if (trypos != NULL)
6366 {
6367 curwin->w_cursor.lnum = trypos->lnum + 1;
6368 continue;
6369 }
6370 }
6371
6372 /* it's a variable declaration, add indentation
6373 * like in
6374 * int a,
6375 * b;
6376 */
6377 if (cont_amount > 0)
6378 amount = cont_amount;
6379 else
6380 amount += ind_continuation;
6381 }
6382 else if (lookfor == LOOKFOR_UNTERM)
6383 {
6384 if (cont_amount > 0)
6385 amount = cont_amount;
6386 else
6387 amount += ind_continuation;
6388 }
6389 else if (lookfor != LOOKFOR_TERM
6390 && lookfor != LOOKFOR_CPP_BASECLASS)
6391 {
6392 amount = scope_amount;
6393 if (theline[0] == '{')
6394 amount += ind_open_extra;
6395 }
6396 break;
6397 }
6398
6399 /*
6400 * If we're in a comment now, skip to the start of the comment.
6401 */ /* XXX */
6402 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6403 {
6404 curwin->w_cursor.lnum = trypos->lnum + 1;
6405 continue;
6406 }
6407
6408 l = ml_get_curline();
6409
6410 /*
6411 * If this is a switch() label, may line up relative to that.
6412 * if this is a C++ scope declaration, do the same.
6413 */
6414 iscase = cin_iscase(l);
6415 if (iscase || cin_isscopedecl(l))
6416 {
6417 /* we are only looking for cpp base class
6418 * declaration/initialization any longer */
6419 if (lookfor == LOOKFOR_CPP_BASECLASS)
6420 break;
6421
6422 /* When looking for a "do" we are not interested in
6423 * labels. */
6424 if (whilelevel > 0)
6425 continue;
6426
6427 /*
6428 * case xx:
6429 * c = 99 + <- this indent plus continuation
6430 *-> here;
6431 */
6432 if (lookfor == LOOKFOR_UNTERM
6433 || lookfor == LOOKFOR_ENUM_OR_INIT)
6434 {
6435 if (cont_amount > 0)
6436 amount = cont_amount;
6437 else
6438 amount += ind_continuation;
6439 break;
6440 }
6441
6442 /*
6443 * case xx: <- line up with this case
6444 * x = 333;
6445 * case yy:
6446 */
6447 if ( (iscase && lookfor == LOOKFOR_CASE)
6448 || (iscase && lookfor_break)
6449 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
6450 {
6451 /*
6452 * Check that this case label is not for another
6453 * switch()
6454 */ /* XXX */
6455 if ((trypos = find_start_brace(ind_maxcomment)) ==
6456 NULL || trypos->lnum == ourscope)
6457 {
6458 amount = get_indent(); /* XXX */
6459 break;
6460 }
6461 continue;
6462 }
6463
6464 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
6465
6466 /*
6467 * case xx: if (cond) <- line up with this if
6468 * y = y + 1;
6469 * -> s = 99;
6470 *
6471 * case xx:
6472 * if (cond) <- line up with this line
6473 * y = y + 1;
6474 * -> s = 99;
6475 */
6476 if (lookfor == LOOKFOR_TERM)
6477 {
6478 if (n)
6479 amount = n;
6480
6481 if (!lookfor_break)
6482 break;
6483 }
6484
6485 /*
6486 * case xx: x = x + 1; <- line up with this x
6487 * -> y = y + 1;
6488 *
6489 * case xx: if (cond) <- line up with this if
6490 * -> y = y + 1;
6491 */
6492 if (n)
6493 {
6494 amount = n;
6495 l = after_label(ml_get_curline());
6496 if (l != NULL && cin_is_cinword(l))
6497 amount += ind_level + ind_no_brace;
6498 break;
6499 }
6500
6501 /*
6502 * Try to get the indent of a statement before the switch
6503 * label. If nothing is found, line up relative to the
6504 * switch label.
6505 * break; <- may line up with this line
6506 * case xx:
6507 * -> y = 1;
6508 */
6509 scope_amount = get_indent() + (iscase /* XXX */
6510 ? ind_case_code : ind_scopedecl_code);
6511 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
6512 continue;
6513 }
6514
6515 /*
6516 * Looking for a switch() label or C++ scope declaration,
6517 * ignore other lines, skip {}-blocks.
6518 */
6519 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
6520 {
6521 if (find_last_paren(l, '{', '}') && (trypos =
6522 find_start_brace(ind_maxcomment)) != NULL)
6523 curwin->w_cursor.lnum = trypos->lnum + 1;
6524 continue;
6525 }
6526
6527 /*
6528 * Ignore jump labels with nothing after them.
6529 */
6530 if (cin_islabel(ind_maxcomment))
6531 {
6532 l = after_label(ml_get_curline());
6533 if (l == NULL || cin_nocode(l))
6534 continue;
6535 }
6536
6537 /*
6538 * Ignore #defines, #if, etc.
6539 * Ignore comment and empty lines.
6540 * (need to get the line again, cin_islabel() may have
6541 * unlocked it)
6542 */
6543 l = ml_get_curline();
6544 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
6545 || cin_nocode(l))
6546 continue;
6547
6548 /*
6549 * Are we at the start of a cpp base class declaration or
6550 * constructor initialization?
6551 */ /* XXX */
6552 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass
6553 && cin_is_cpp_baseclass(l, &col))
6554 {
6555 if (lookfor == LOOKFOR_UNTERM)
6556 {
6557 if (cont_amount > 0)
6558 amount = cont_amount;
6559 else
6560 amount += ind_continuation;
6561 }
6562 else if (col == 0 || theline[0] == '{')
6563 {
6564 amount = get_indent();
6565 if (find_last_paren(l, '(', ')')
6566 && (trypos = find_match_paren(ind_maxparen,
6567 ind_maxcomment)) != NULL)
6568 amount = get_indent_lnum(trypos->lnum); /* XXX */
6569 if (theline[0] != '{')
6570 amount += ind_cpp_baseclass;
6571 }
6572 else
6573 {
6574 curwin->w_cursor.col = col;
6575 getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL);
6576 amount = (int)col;
6577 }
6578 break;
6579 }
6580 else if (lookfor == LOOKFOR_CPP_BASECLASS)
6581 {
6582 /* only look, whether there is a cpp base class
6583 * declaration or initialization before the opening brace. */
6584 if (cin_isterminated(l, TRUE, FALSE))
6585 break;
6586 else
6587 continue;
6588 }
6589
6590 /*
6591 * What happens next depends on the line being terminated.
6592 * If terminated with a ',' only consider it terminating if
6593 * there is anoter unterminated statement behind, eg:
6594 * 123,
6595 * sizeof
6596 * here
6597 * Otherwise check whether it is a enumeration or structure
6598 * initialisation (not indented) or a variable declaration
6599 * (indented).
6600 */
6601 terminated = cin_isterminated(l, FALSE, TRUE);
6602
6603 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
6604 && terminated == ','))
6605 {
6606 /*
6607 * if we're in the middle of a paren thing,
6608 * go back to the line that starts it so
6609 * we can get the right prevailing indent
6610 * if ( foo &&
6611 * bar )
6612 */
6613 /*
6614 * position the cursor over the rightmost paren, so that
6615 * matching it will take us back to the start of the line.
6616 */
6617 (void)find_last_paren(l, '(', ')');
6618 trypos = find_match_paren(
6619 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6620 ind_maxcomment);
6621
6622 /*
6623 * If we are looking for ',', we also look for matching
6624 * braces.
6625 */
6626 if (trypos == NULL && find_last_paren(l, '{', '}'))
6627 trypos = find_start_brace(ind_maxcomment);
6628
6629 if (trypos != NULL)
6630 {
6631 /*
6632 * Check if we are on a case label now. This is
6633 * handled above.
6634 * case xx: if ( asdf &&
6635 * asdf)
6636 */
6637 curwin->w_cursor.lnum = trypos->lnum;
6638 l = ml_get_curline();
6639 if (cin_iscase(l) || cin_isscopedecl(l))
6640 {
6641 ++curwin->w_cursor.lnum;
6642 continue;
6643 }
6644 }
6645
6646 /*
6647 * Skip over continuation lines to find the one to get the
6648 * indent from
6649 * char *usethis = "bla\
6650 * bla",
6651 * here;
6652 */
6653 if (terminated == ',')
6654 {
6655 while (curwin->w_cursor.lnum > 1)
6656 {
6657 l = ml_get(curwin->w_cursor.lnum - 1);
6658 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
6659 break;
6660 --curwin->w_cursor.lnum;
6661 }
6662 }
6663
6664 /*
6665 * Get indent and pointer to text for current line,
6666 * ignoring any jump label. XXX
6667 */
6668 cur_amount = skip_label(curwin->w_cursor.lnum,
6669 &l, ind_maxcomment);
6670
6671 /*
6672 * If this is just above the line we are indenting, and it
6673 * starts with a '{', line it up with this line.
6674 * while (not)
6675 * -> {
6676 * }
6677 */
6678 if (terminated != ',' && lookfor != LOOKFOR_TERM
6679 && theline[0] == '{')
6680 {
6681 amount = cur_amount;
6682 /*
6683 * Only add ind_open_extra when the current line
6684 * doesn't start with a '{', which must have a match
6685 * in the same line (scope is the same). Probably:
6686 * { 1, 2 },
6687 * -> { 3, 4 }
6688 */
6689 if (*skipwhite(l) != '{')
6690 amount += ind_open_extra;
6691
6692 if (ind_cpp_baseclass)
6693 {
6694 /* have to look back, whether it is a cpp base
6695 * class declaration or initialization */
6696 lookfor = LOOKFOR_CPP_BASECLASS;
6697 continue;
6698 }
6699 break;
6700 }
6701
6702 /*
6703 * Check if we are after an "if", "while", etc.
6704 * Also allow " } else".
6705 */
6706 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
6707 {
6708 /*
6709 * Found an unterminated line after an if (), line up
6710 * with the last one.
6711 * if (cond)
6712 * 100 +
6713 * -> here;
6714 */
6715 if (lookfor == LOOKFOR_UNTERM
6716 || lookfor == LOOKFOR_ENUM_OR_INIT)
6717 {
6718 if (cont_amount > 0)
6719 amount = cont_amount;
6720 else
6721 amount += ind_continuation;
6722 break;
6723 }
6724
6725 /*
6726 * If this is just above the line we are indenting, we
6727 * are finished.
6728 * while (not)
6729 * -> here;
6730 * Otherwise this indent can be used when the line
6731 * before this is terminated.
6732 * yyy;
6733 * if (stat)
6734 * while (not)
6735 * xxx;
6736 * -> here;
6737 */
6738 amount = cur_amount;
6739 if (theline[0] == '{')
6740 amount += ind_open_extra;
6741 if (lookfor != LOOKFOR_TERM)
6742 {
6743 amount += ind_level + ind_no_brace;
6744 break;
6745 }
6746
6747 /*
6748 * Special trick: when expecting the while () after a
6749 * do, line up with the while()
6750 * do
6751 * x = 1;
6752 * -> here
6753 */
6754 l = skipwhite(ml_get_curline());
6755 if (cin_isdo(l))
6756 {
6757 if (whilelevel == 0)
6758 break;
6759 --whilelevel;
6760 }
6761
6762 /*
6763 * When searching for a terminated line, don't use the
6764 * one between the "if" and the "else".
6765 * Need to use the scope of this "else". XXX
6766 * If whilelevel != 0 continue looking for a "do {".
6767 */
6768 if (cin_iselse(l)
6769 && whilelevel == 0
6770 && ((trypos = find_start_brace(ind_maxcomment))
6771 == NULL
6772 || find_match(LOOKFOR_IF, trypos->lnum,
6773 ind_maxparen, ind_maxcomment) == FAIL))
6774 break;
6775 }
6776
6777 /*
6778 * If we're below an unterminated line that is not an
6779 * "if" or something, we may line up with this line or
6780 * add someting for a continuation line, depending on
6781 * the line before this one.
6782 */
6783 else
6784 {
6785 /*
6786 * Found two unterminated lines on a row, line up with
6787 * the last one.
6788 * c = 99 +
6789 * 100 +
6790 * -> here;
6791 */
6792 if (lookfor == LOOKFOR_UNTERM)
6793 {
6794 /* When line ends in a comma add extra indent */
6795 if (terminated == ',')
6796 amount += ind_continuation;
6797 break;
6798 }
6799
6800 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6801 {
6802 /* Found two lines ending in ',', lineup with the
6803 * lowest one, but check for cpp base class
6804 * declaration/initialization, if it is an
6805 * opening brace or we are looking just for
6806 * enumerations/initializations. */
6807 if (terminated == ',')
6808 {
6809 if (ind_cpp_baseclass == 0)
6810 break;
6811
6812 lookfor = LOOKFOR_CPP_BASECLASS;
6813 continue;
6814 }
6815
6816 /* Ignore unterminated lines in between, but
6817 * reduce indent. */
6818 if (amount > cur_amount)
6819 amount = cur_amount;
6820 }
6821 else
6822 {
6823 /*
6824 * Found first unterminated line on a row, may
6825 * line up with this line, remember its indent
6826 * 100 +
6827 * -> here;
6828 */
6829 amount = cur_amount;
6830
6831 /*
6832 * If previous line ends in ',', check whether we
6833 * are in an initialization or enum
6834 * struct xxx =
6835 * {
6836 * sizeof a,
6837 * 124 };
6838 * or a normal possible continuation line.
6839 * but only, of no other statement has been found
6840 * yet.
6841 */
6842 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
6843 {
6844 lookfor = LOOKFOR_ENUM_OR_INIT;
6845 cont_amount = cin_first_id_amount();
6846 }
6847 else
6848 {
6849 if (lookfor == LOOKFOR_INITIAL
6850 && *l != NUL
6851 && l[STRLEN(l) - 1] == '\\')
6852 /* XXX */
6853 cont_amount = cin_get_equal_amount(
6854 curwin->w_cursor.lnum);
6855 if (lookfor != LOOKFOR_TERM)
6856 lookfor = LOOKFOR_UNTERM;
6857 }
6858 }
6859 }
6860 }
6861
6862 /*
6863 * Check if we are after a while (cond);
6864 * If so: Ignore until the matching "do".
6865 */
6866 /* XXX */
6867 else if (cin_iswhileofdo(l,
6868 curwin->w_cursor.lnum, ind_maxparen))
6869 {
6870 /*
6871 * Found an unterminated line after a while ();, line up
6872 * with the last one.
6873 * while (cond);
6874 * 100 + <- line up with this one
6875 * -> here;
6876 */
6877 if (lookfor == LOOKFOR_UNTERM
6878 || lookfor == LOOKFOR_ENUM_OR_INIT)
6879 {
6880 if (cont_amount > 0)
6881 amount = cont_amount;
6882 else
6883 amount += ind_continuation;
6884 break;
6885 }
6886
6887 if (whilelevel == 0)
6888 {
6889 lookfor = LOOKFOR_TERM;
6890 amount = get_indent(); /* XXX */
6891 if (theline[0] == '{')
6892 amount += ind_open_extra;
6893 }
6894 ++whilelevel;
6895 }
6896
6897 /*
6898 * We are after a "normal" statement.
6899 * If we had another statement we can stop now and use the
6900 * indent of that other statement.
6901 * Otherwise the indent of the current statement may be used,
6902 * search backwards for the next "normal" statement.
6903 */
6904 else
6905 {
6906 /*
6907 * Skip single break line, if before a switch label. It
6908 * may be lined up with the case label.
6909 */
6910 if (lookfor == LOOKFOR_NOBREAK
6911 && cin_isbreak(skipwhite(ml_get_curline())))
6912 {
6913 lookfor = LOOKFOR_ANY;
6914 continue;
6915 }
6916
6917 /*
6918 * Handle "do {" line.
6919 */
6920 if (whilelevel > 0)
6921 {
6922 l = cin_skipcomment(ml_get_curline());
6923 if (cin_isdo(l))
6924 {
6925 amount = get_indent(); /* XXX */
6926 --whilelevel;
6927 continue;
6928 }
6929 }
6930
6931 /*
6932 * Found a terminated line above an unterminated line. Add
6933 * the amount for a continuation line.
6934 * x = 1;
6935 * y = foo +
6936 * -> here;
6937 * or
6938 * int x = 1;
6939 * int foo,
6940 * -> here;
6941 */
6942 if (lookfor == LOOKFOR_UNTERM
6943 || lookfor == LOOKFOR_ENUM_OR_INIT)
6944 {
6945 if (cont_amount > 0)
6946 amount = cont_amount;
6947 else
6948 amount += ind_continuation;
6949 break;
6950 }
6951
6952 /*
6953 * Found a terminated line above a terminated line or "if"
6954 * etc. line. Use the amount of the line below us.
6955 * x = 1; x = 1;
6956 * if (asdf) y = 2;
6957 * while (asdf) ->here;
6958 * here;
6959 * ->foo;
6960 */
6961 if (lookfor == LOOKFOR_TERM)
6962 {
6963 if (!lookfor_break && whilelevel == 0)
6964 break;
6965 }
6966
6967 /*
6968 * First line above the one we're indenting is terminated.
6969 * To know what needs to be done look further backward for
6970 * a terminated line.
6971 */
6972 else
6973 {
6974 /*
6975 * position the cursor over the rightmost paren, so
6976 * that matching it will take us back to the start of
6977 * the line. Helps for:
6978 * func(asdr,
6979 * asdfasdf);
6980 * here;
6981 */
6982term_again:
6983 l = ml_get_curline();
6984 if (find_last_paren(l, '(', ')')
6985 && (trypos = find_match_paren(ind_maxparen,
6986 ind_maxcomment)) != NULL)
6987 {
6988 /*
6989 * Check if we are on a case label now. This is
6990 * handled above.
6991 * case xx: if ( asdf &&
6992 * asdf)
6993 */
6994 curwin->w_cursor.lnum = trypos->lnum;
6995 l = ml_get_curline();
6996 if (cin_iscase(l) || cin_isscopedecl(l))
6997 {
6998 ++curwin->w_cursor.lnum;
6999 continue;
7000 }
7001 }
7002
7003 /* When aligning with the case statement, don't align
7004 * with a statement after it.
7005 * case 1: { <-- don't use this { position
7006 * stat;
7007 * }
7008 * case 2:
7009 * stat;
7010 * }
7011 */
7012 iscase = (ind_keep_case_label && cin_iscase(l));
7013
7014 /*
7015 * Get indent and pointer to text for current line,
7016 * ignoring any jump label.
7017 */
7018 amount = skip_label(curwin->w_cursor.lnum,
7019 &l, ind_maxcomment);
7020
7021 if (theline[0] == '{')
7022 amount += ind_open_extra;
7023 /* See remark above: "Only add ind_open_extra.." */
7024 if (*skipwhite(l) == '{')
7025 amount -= ind_open_extra;
7026 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7027
7028 /*
7029 * If we're at the end of a block, skip to the start of
7030 * that block.
7031 */
7032 curwin->w_cursor.col = 0;
7033 if (*cin_skipcomment(l) == '}'
7034 && (trypos = find_start_brace(ind_maxcomment))
7035 != NULL) /* XXX */
7036 {
7037 curwin->w_cursor.lnum = trypos->lnum;
7038 /* if not "else {" check for terminated again */
7039 /* but skip block for "} else {" */
7040 l = cin_skipcomment(ml_get_curline());
7041 if (*l == '}' || !cin_iselse(l))
7042 goto term_again;
7043 ++curwin->w_cursor.lnum;
7044 }
7045 }
7046 }
7047 }
7048 }
7049 }
7050
7051 /* add extra indent for a comment */
7052 if (cin_iscomment(theline))
7053 amount += ind_comment;
7054 }
7055
7056 /*
7057 * ok -- we're not inside any sort of structure at all!
7058 *
7059 * this means we're at the top level, and everything should
7060 * basically just match where the previous line is, except
7061 * for the lines immediately following a function declaration,
7062 * which are K&R-style parameters and need to be indented.
7063 */
7064 else
7065 {
7066 /*
7067 * if our line starts with an open brace, forget about any
7068 * prevailing indent and make sure it looks like the start
7069 * of a function
7070 */
7071
7072 if (theline[0] == '{')
7073 {
7074 amount = ind_first_open;
7075 }
7076
7077 /*
7078 * If the NEXT line is a function declaration, the current
7079 * line needs to be indented as a function type spec.
7080 * Don't do this if the current line looks like a comment
7081 * or if the current line is terminated, ie. ends in ';'.
7082 */
7083 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7084 && !cin_nocode(theline)
7085 && !cin_ends_in(theline, (char_u *)":", NULL)
7086 && !cin_ends_in(theline, (char_u *)",", NULL)
7087 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7088 && !cin_isterminated(theline, FALSE, TRUE))
7089 {
7090 amount = ind_func_type;
7091 }
7092 else
7093 {
7094 amount = 0;
7095 curwin->w_cursor = cur_curpos;
7096
7097 /* search backwards until we find something we recognize */
7098
7099 while (curwin->w_cursor.lnum > 1)
7100 {
7101 curwin->w_cursor.lnum--;
7102 curwin->w_cursor.col = 0;
7103
7104 l = ml_get_curline();
7105
7106 /*
7107 * If we're in a comment now, skip to the start of the comment.
7108 */ /* XXX */
7109 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7110 {
7111 curwin->w_cursor.lnum = trypos->lnum + 1;
7112 continue;
7113 }
7114
7115 /*
7116 * Are we at the start of a cpp base class declaration or constructor
7117 * initialization?
7118 */ /* XXX */
7119 if (ind_cpp_baseclass != 0 && theline[0] != '{'
7120 && cin_is_cpp_baseclass(l, &col))
7121 {
7122 if (col == 0)
7123 {
7124 amount = get_indent() + ind_cpp_baseclass; /* XXX */
7125 if (find_last_paren(l, '(', ')')
7126 && (trypos = find_match_paren(ind_maxparen,
7127 ind_maxcomment)) != NULL)
7128 amount = get_indent_lnum(trypos->lnum)
7129 + ind_cpp_baseclass; /* XXX */
7130 }
7131 else
7132 {
7133 curwin->w_cursor.col = col;
7134 getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL);
7135 amount = (int)col;
7136 }
7137 break;
7138 }
7139
7140 /*
7141 * Skip preprocessor directives and blank lines.
7142 */
7143 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7144 continue;
7145
7146 if (cin_nocode(l))
7147 continue;
7148
7149 /*
7150 * If the previous line ends in ',', use one level of
7151 * indentation:
7152 * int foo,
7153 * bar;
7154 * do this before checking for '}' in case of eg.
7155 * enum foobar
7156 * {
7157 * ...
7158 * } foo,
7159 * bar;
7160 */
7161 n = 0;
7162 if (cin_ends_in(l, (char_u *)",", NULL)
7163 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7164 {
7165 /* take us back to opening paren */
7166 if (find_last_paren(l, '(', ')')
7167 && (trypos = find_match_paren(ind_maxparen,
7168 ind_maxcomment)) != NULL)
7169 curwin->w_cursor.lnum = trypos->lnum;
7170
7171 /* For a line ending in ',' that is a continuation line go
7172 * back to the first line with a backslash:
7173 * char *foo = "bla\
7174 * bla",
7175 * here;
7176 */
7177 while (n == 0 && curwin->w_cursor.lnum > 1)
7178 {
7179 l = ml_get(curwin->w_cursor.lnum - 1);
7180 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7181 break;
7182 --curwin->w_cursor.lnum;
7183 }
7184
7185 amount = get_indent(); /* XXX */
7186
7187 if (amount == 0)
7188 amount = cin_first_id_amount();
7189 if (amount == 0)
7190 amount = ind_continuation;
7191 break;
7192 }
7193
7194 /*
7195 * If the line looks like a function declaration, and we're
7196 * not in a comment, put it the left margin.
7197 */
7198 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7199 break;
7200 l = ml_get_curline();
7201
7202 /*
7203 * Finding the closing '}' of a previous function. Put
7204 * current line at the left margin. For when 'cino' has "fs".
7205 */
7206 if (*skipwhite(l) == '}')
7207 break;
7208
7209 /* (matching {)
7210 * If the previous line ends on '};' (maybe followed by
7211 * comments) align at column 0. For example:
7212 * char *string_array[] = { "foo",
7213 * / * x * / "b};ar" }; / * foobar * /
7214 */
7215 if (cin_ends_in(l, (char_u *)"};", NULL))
7216 break;
7217
7218 /*
7219 * If the PREVIOUS line is a function declaration, the current
7220 * line (and the ones that follow) needs to be indented as
7221 * parameters.
7222 */
7223 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7224 {
7225 amount = ind_param;
7226 break;
7227 }
7228
7229 /*
7230 * If the previous line ends in ';' and the line before the
7231 * previous line ends in ',' or '\', ident to column zero:
7232 * int foo,
7233 * bar;
7234 * indent_to_0 here;
7235 */
7236 if (cin_ends_in(l, (char_u*)";", NULL))
7237 {
7238 l = ml_get(curwin->w_cursor.lnum - 1);
7239 if (cin_ends_in(l, (char_u *)",", NULL)
7240 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7241 break;
7242 l = ml_get_curline();
7243 }
7244
7245 /*
7246 * Doesn't look like anything interesting -- so just
7247 * use the indent of this line.
7248 *
7249 * Position the cursor over the rightmost paren, so that
7250 * matching it will take us back to the start of the line.
7251 */
7252 find_last_paren(l, '(', ')');
7253
7254 if ((trypos = find_match_paren(ind_maxparen,
7255 ind_maxcomment)) != NULL)
7256 curwin->w_cursor.lnum = trypos->lnum;
7257 amount = get_indent(); /* XXX */
7258 break;
7259 }
7260
7261 /* add extra indent for a comment */
7262 if (cin_iscomment(theline))
7263 amount += ind_comment;
7264
7265 /* add extra indent if the previous line ended in a backslash:
7266 * "asdfasdf\
7267 * here";
7268 * char *foo = "asdf\
7269 * here";
7270 */
7271 if (cur_curpos.lnum > 1)
7272 {
7273 l = ml_get(cur_curpos.lnum - 1);
7274 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7275 {
7276 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7277 if (cur_amount > 0)
7278 amount = cur_amount;
7279 else if (cur_amount == 0)
7280 amount += ind_continuation;
7281 }
7282 }
7283 }
7284 }
7285
7286theend:
7287 /* put the cursor back where it belongs */
7288 curwin->w_cursor = cur_curpos;
7289
7290 vim_free(linecopy);
7291
7292 if (amount < 0)
7293 return 0;
7294 return amount;
7295}
7296
7297 static int
7298find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7299 int lookfor;
7300 linenr_T ourscope;
7301 int ind_maxparen;
7302 int ind_maxcomment;
7303{
7304 char_u *look;
7305 pos_T *theirscope;
7306 char_u *mightbeif;
7307 int elselevel;
7308 int whilelevel;
7309
7310 if (lookfor == LOOKFOR_IF)
7311 {
7312 elselevel = 1;
7313 whilelevel = 0;
7314 }
7315 else
7316 {
7317 elselevel = 0;
7318 whilelevel = 1;
7319 }
7320
7321 curwin->w_cursor.col = 0;
7322
7323 while (curwin->w_cursor.lnum > ourscope + 1)
7324 {
7325 curwin->w_cursor.lnum--;
7326 curwin->w_cursor.col = 0;
7327
7328 look = cin_skipcomment(ml_get_curline());
7329 if (cin_iselse(look)
7330 || cin_isif(look)
7331 || cin_isdo(look) /* XXX */
7332 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7333 {
7334 /*
7335 * if we've gone outside the braces entirely,
7336 * we must be out of scope...
7337 */
7338 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7339 if (theirscope == NULL)
7340 break;
7341
7342 /*
7343 * and if the brace enclosing this is further
7344 * back than the one enclosing the else, we're
7345 * out of luck too.
7346 */
7347 if (theirscope->lnum < ourscope)
7348 break;
7349
7350 /*
7351 * and if they're enclosed in a *deeper* brace,
7352 * then we can ignore it because it's in a
7353 * different scope...
7354 */
7355 if (theirscope->lnum > ourscope)
7356 continue;
7357
7358 /*
7359 * if it was an "else" (that's not an "else if")
7360 * then we need to go back to another if, so
7361 * increment elselevel
7362 */
7363 look = cin_skipcomment(ml_get_curline());
7364 if (cin_iselse(look))
7365 {
7366 mightbeif = cin_skipcomment(look + 4);
7367 if (!cin_isif(mightbeif))
7368 ++elselevel;
7369 continue;
7370 }
7371
7372 /*
7373 * if it was a "while" then we need to go back to
7374 * another "do", so increment whilelevel. XXX
7375 */
7376 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7377 {
7378 ++whilelevel;
7379 continue;
7380 }
7381
7382 /* If it's an "if" decrement elselevel */
7383 look = cin_skipcomment(ml_get_curline());
7384 if (cin_isif(look))
7385 {
7386 elselevel--;
7387 /*
7388 * When looking for an "if" ignore "while"s that
7389 * get in the way.
7390 */
7391 if (elselevel == 0 && lookfor == LOOKFOR_IF)
7392 whilelevel = 0;
7393 }
7394
7395 /* If it's a "do" decrement whilelevel */
7396 if (cin_isdo(look))
7397 whilelevel--;
7398
7399 /*
7400 * if we've used up all the elses, then
7401 * this must be the if that we want!
7402 * match the indent level of that if.
7403 */
7404 if (elselevel <= 0 && whilelevel <= 0)
7405 {
7406 return OK;
7407 }
7408 }
7409 }
7410 return FAIL;
7411}
7412
7413# if defined(FEAT_EVAL) || defined(PROTO)
7414/*
7415 * Get indent level from 'indentexpr'.
7416 */
7417 int
7418get_expr_indent()
7419{
7420 int indent;
7421 pos_T pos;
7422 int save_State;
7423
7424 pos = curwin->w_cursor;
7425 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
7426 ++sandbox;
7427 indent = eval_to_number(curbuf->b_p_inde);
7428 --sandbox;
7429
7430 /* Restore the cursor position so that 'indentexpr' doesn't need to.
7431 * Pretend to be in Insert mode, allow cursor past end of line for "o"
7432 * command. */
7433 save_State = State;
7434 State = INSERT;
7435 curwin->w_cursor = pos;
7436 check_cursor();
7437 State = save_State;
7438
7439 /* If there is an error, just keep the current indent. */
7440 if (indent < 0)
7441 indent = get_indent();
7442
7443 return indent;
7444}
7445# endif
7446
7447#endif /* FEAT_CINDENT */
7448
7449#if defined(FEAT_LISP) || defined(PROTO)
7450
7451static int lisp_match __ARGS((char_u *p));
7452
7453 static int
7454lisp_match(p)
7455 char_u *p;
7456{
7457 char_u buf[LSIZE];
7458 int len;
7459 char_u *word = p_lispwords;
7460
7461 while (*word != NUL)
7462 {
7463 (void)copy_option_part(&word, buf, LSIZE, ",");
7464 len = (int)STRLEN(buf);
7465 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
7466 return TRUE;
7467 }
7468 return FALSE;
7469}
7470
7471/*
7472 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
7473 * The incompatible newer method is quite a bit better at indenting
7474 * code in lisp-like languages than the traditional one; it's still
7475 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
7476 *
7477 * TODO:
7478 * Findmatch() should be adapted for lisp, also to make showmatch
7479 * work correctly: now (v5.3) it seems all C/C++ oriented:
7480 * - it does not recognize the #\( and #\) notations as character literals
7481 * - it doesn't know about comments starting with a semicolon
7482 * - it incorrectly interprets '(' as a character literal
7483 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007484 * Update from Sergey Khorev:
7485 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007486 */
7487 int
7488get_lisp_indent()
7489{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007490 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007491 int amount;
7492 char_u *that;
7493 colnr_T col;
7494 colnr_T firsttry;
7495 int parencount, quotecount;
7496 int vi_lisp;
7497
7498 /* Set vi_lisp to use the vi-compatible method */
7499 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
7500
7501 realpos = curwin->w_cursor;
7502 curwin->w_cursor.col = 0;
7503
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007504 if ((pos = findmatch(NULL, '(')) == NULL)
7505 pos = findmatch(NULL, '[');
7506 else
7507 {
7508 paren = *pos;
7509 pos = findmatch(NULL, '[');
7510 if (pos == NULL || ltp(pos, &paren))
7511 pos = &paren;
7512 }
7513 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007514 {
7515 /* Extra trick: Take the indent of the first previous non-white
7516 * line that is at the same () level. */
7517 amount = -1;
7518 parencount = 0;
7519
7520 while (--curwin->w_cursor.lnum >= pos->lnum)
7521 {
7522 if (linewhite(curwin->w_cursor.lnum))
7523 continue;
7524 for (that = ml_get_curline(); *that != NUL; ++that)
7525 {
7526 if (*that == ';')
7527 {
7528 while (*(that + 1) != NUL)
7529 ++that;
7530 continue;
7531 }
7532 if (*that == '\\')
7533 {
7534 if (*(that + 1) != NUL)
7535 ++that;
7536 continue;
7537 }
7538 if (*that == '"' && *(that + 1) != NUL)
7539 {
7540 that++;
7541 while (*that && (*that != '"' || *(that - 1) == '\\'))
7542 ++that;
7543 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007544 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007545 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007546 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007547 --parencount;
7548 }
7549 if (parencount == 0)
7550 {
7551 amount = get_indent();
7552 break;
7553 }
7554 }
7555
7556 if (amount == -1)
7557 {
7558 curwin->w_cursor.lnum = pos->lnum;
7559 curwin->w_cursor.col = pos->col;
7560 col = pos->col;
7561
7562 that = ml_get_curline();
7563
7564 if (vi_lisp && get_indent() == 0)
7565 amount = 2;
7566 else
7567 {
7568 amount = 0;
7569 while (*that && col)
7570 {
7571 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
7572 col--;
7573 }
7574
7575 /*
7576 * Some keywords require "body" indenting rules (the
7577 * non-standard-lisp ones are Scheme special forms):
7578 *
7579 * (let ((a 1)) instead (let ((a 1))
7580 * (...)) of (...))
7581 */
7582
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007583 if (!vi_lisp && (*that == '(' || *that == '[')
7584 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007585 amount += 2;
7586 else
7587 {
7588 that++;
7589 amount++;
7590 firsttry = amount;
7591
7592 while (vim_iswhite(*that))
7593 {
7594 amount += lbr_chartabsize(that, (colnr_T)amount);
7595 ++that;
7596 }
7597
7598 if (*that && *that != ';') /* not a comment line */
7599 {
7600 /* test *that != '(' to accomodate first let/do
7601 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007602 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007603 firsttry++;
7604
7605 parencount = 0;
7606 quotecount = 0;
7607
7608 if (vi_lisp
7609 || (*that != '"'
7610 && *that != '\''
7611 && *that != '#'
7612 && (*that < '0' || *that > '9')))
7613 {
7614 while (*that
7615 && (!vim_iswhite(*that)
7616 || quotecount
7617 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007618 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619 && !quotecount
7620 && !parencount
7621 && vi_lisp)))
7622 {
7623 if (*that == '"')
7624 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007625 if ((*that == '(' || *that == '[')
7626 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007627 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007628 if ((*that == ')' || *that == ']')
7629 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 --parencount;
7631 if (*that == '\\' && *(that+1) != NUL)
7632 amount += lbr_chartabsize_adv(&that,
7633 (colnr_T)amount);
7634 amount += lbr_chartabsize_adv(&that,
7635 (colnr_T)amount);
7636 }
7637 }
7638 while (vim_iswhite(*that))
7639 {
7640 amount += lbr_chartabsize(that, (colnr_T)amount);
7641 that++;
7642 }
7643 if (!*that || *that == ';')
7644 amount = firsttry;
7645 }
7646 }
7647 }
7648 }
7649 }
7650 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007651 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007652
7653 curwin->w_cursor = realpos;
7654
7655 return amount;
7656}
7657#endif /* FEAT_LISP */
7658
7659 void
7660prepare_to_exit()
7661{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007662#if defined(SIGHUP) && defined(SIG_IGN)
7663 /* Ignore SIGHUP, because a dropped connection causes a read error, which
7664 * makes Vim exit and then handling SIGHUP causes various reentrance
7665 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00007666 signal(SIGHUP, SIG_IGN);
7667#endif
7668
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669#ifdef FEAT_GUI
7670 if (gui.in_use)
7671 {
7672 gui.dying = TRUE;
7673 out_trash(); /* trash any pending output */
7674 }
7675 else
7676#endif
7677 {
7678 windgoto((int)Rows - 1, 0);
7679
7680 /*
7681 * Switch terminal mode back now, so messages end up on the "normal"
7682 * screen (if there are two screens).
7683 */
7684 settmode(TMODE_COOK);
7685#ifdef WIN3264
7686 if (can_end_termcap_mode(FALSE) == TRUE)
7687#endif
7688 stoptermcap();
7689 out_flush();
7690 }
7691}
7692
7693/*
7694 * Preserve files and exit.
7695 * When called IObuff must contain a message.
7696 */
7697 void
7698preserve_exit()
7699{
7700 buf_T *buf;
7701
7702 prepare_to_exit();
7703
7704 out_str(IObuff);
7705 screen_start(); /* don't know where cursor is now */
7706 out_flush();
7707
7708 ml_close_notmod(); /* close all not-modified buffers */
7709
7710 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7711 {
7712 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
7713 {
7714 OUT_STR(_("Vim: preserving files...\n"));
7715 screen_start(); /* don't know where cursor is now */
7716 out_flush();
7717 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7718 break;
7719 }
7720 }
7721
7722 ml_close_all(FALSE); /* close all memfiles, without deleting */
7723
7724 OUT_STR(_("Vim: Finished.\n"));
7725
7726 getout(1);
7727}
7728
7729/*
7730 * return TRUE if "fname" exists.
7731 */
7732 int
7733vim_fexists(fname)
7734 char_u *fname;
7735{
7736 struct stat st;
7737
7738 if (mch_stat((char *)fname, &st))
7739 return FALSE;
7740 return TRUE;
7741}
7742
7743/*
7744 * Check for CTRL-C pressed, but only once in a while.
7745 * Should be used instead of ui_breakcheck() for functions that check for
7746 * each line in the file. Calling ui_breakcheck() each time takes too much
7747 * time, because it can be a system call.
7748 */
7749
7750#ifndef BREAKCHECK_SKIP
7751# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
7752# define BREAKCHECK_SKIP 200
7753# else
7754# define BREAKCHECK_SKIP 32
7755# endif
7756#endif
7757
7758static int breakcheck_count = 0;
7759
7760 void
7761line_breakcheck()
7762{
7763 if (++breakcheck_count >= BREAKCHECK_SKIP)
7764 {
7765 breakcheck_count = 0;
7766 ui_breakcheck();
7767 }
7768}
7769
7770/*
7771 * Like line_breakcheck() but check 10 times less often.
7772 */
7773 void
7774fast_breakcheck()
7775{
7776 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
7777 {
7778 breakcheck_count = 0;
7779 ui_breakcheck();
7780 }
7781}
7782
7783/*
7784 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
7785 * 'wildignore'.
7786 */
7787 int
7788expand_wildcards(num_pat, pat, num_file, file, flags)
7789 int num_pat; /* number of input patterns */
7790 char_u **pat; /* array of input patterns */
7791 int *num_file; /* resulting number of files */
7792 char_u ***file; /* array of resulting files */
7793 int flags; /* EW_DIR, etc. */
7794{
7795 int retval;
7796 int i, j;
7797 char_u *p;
7798 int non_suf_match; /* number without matching suffix */
7799
7800 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
7801
7802 /* When keeping all matches, return here */
7803 if (flags & EW_KEEPALL)
7804 return retval;
7805
7806#ifdef FEAT_WILDIGN
7807 /*
7808 * Remove names that match 'wildignore'.
7809 */
7810 if (*p_wig)
7811 {
7812 char_u *ffname;
7813
7814 /* check all files in (*file)[] */
7815 for (i = 0; i < *num_file; ++i)
7816 {
7817 ffname = FullName_save((*file)[i], FALSE);
7818 if (ffname == NULL) /* out of memory */
7819 break;
7820# ifdef VMS
7821 vms_remove_version(ffname);
7822# endif
7823 if (match_file_list(p_wig, (*file)[i], ffname))
7824 {
7825 /* remove this matching file from the list */
7826 vim_free((*file)[i]);
7827 for (j = i; j + 1 < *num_file; ++j)
7828 (*file)[j] = (*file)[j + 1];
7829 --*num_file;
7830 --i;
7831 }
7832 vim_free(ffname);
7833 }
7834 }
7835#endif
7836
7837 /*
7838 * Move the names where 'suffixes' match to the end.
7839 */
7840 if (*num_file > 1)
7841 {
7842 non_suf_match = 0;
7843 for (i = 0; i < *num_file; ++i)
7844 {
7845 if (!match_suffix((*file)[i]))
7846 {
7847 /*
7848 * Move the name without matching suffix to the front
7849 * of the list.
7850 */
7851 p = (*file)[i];
7852 for (j = i; j > non_suf_match; --j)
7853 (*file)[j] = (*file)[j - 1];
7854 (*file)[non_suf_match++] = p;
7855 }
7856 }
7857 }
7858
7859 return retval;
7860}
7861
7862/*
7863 * Return TRUE if "fname" matches with an entry in 'suffixes'.
7864 */
7865 int
7866match_suffix(fname)
7867 char_u *fname;
7868{
7869 int fnamelen, setsuflen;
7870 char_u *setsuf;
7871#define MAXSUFLEN 30 /* maximum length of a file suffix */
7872 char_u suf_buf[MAXSUFLEN];
7873
7874 fnamelen = (int)STRLEN(fname);
7875 setsuflen = 0;
7876 for (setsuf = p_su; *setsuf; )
7877 {
7878 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
7879 if (fnamelen >= setsuflen
7880 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
7881 (size_t)setsuflen) == 0)
7882 break;
7883 setsuflen = 0;
7884 }
7885 return (setsuflen != 0);
7886}
7887
7888#if !defined(NO_EXPANDPATH) || defined(PROTO)
7889
7890# ifdef VIM_BACKTICK
7891static int vim_backtick __ARGS((char_u *p));
7892static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
7893# endif
7894
7895# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
7896/*
7897 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
7898 * it's shared between these systems.
7899 */
7900# if defined(DJGPP) || defined(PROTO)
7901# define _cdecl /* DJGPP doesn't have this */
7902# else
7903# ifdef __BORLANDC__
7904# define _cdecl _RTLENTRYF
7905# endif
7906# endif
7907
7908/*
7909 * comparison function for qsort in dos_expandpath()
7910 */
7911 static int _cdecl
7912pstrcmp(const void *a, const void *b)
7913{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007914 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007915}
7916
7917# ifndef WIN3264
7918 static void
7919namelowcpy(
7920 char_u *d,
7921 char_u *s)
7922{
7923# ifdef DJGPP
7924 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
7925 while (*s)
7926 *d++ = *s++;
7927 else
7928# endif
7929 while (*s)
7930 *d++ = TOLOWER_LOC(*s++);
7931 *d = NUL;
7932}
7933# endif
7934
7935/*
7936 * Recursively build up a list of files in "gap" matching the first wildcard
7937 * in `path'. Called by expand_wildcards().
7938 * Return the number of matches found.
7939 * "path" has backslashes before chars that are not to be expanded, starting
7940 * at "path[wildoff]".
7941 */
7942 static int
7943dos_expandpath(
7944 garray_T *gap,
7945 char_u *path,
7946 int wildoff,
7947 int flags) /* EW_* flags */
7948{
7949 char_u *buf;
7950 char_u *path_end;
7951 char_u *p, *s, *e;
7952 int start_len = gap->ga_len;
7953 int ok;
7954#ifdef WIN3264
7955 WIN32_FIND_DATA fb;
7956 HANDLE hFind = (HANDLE)0;
7957# ifdef FEAT_MBYTE
7958 WIN32_FIND_DATAW wfb;
7959 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
7960# endif
7961#else
7962 struct ffblk fb;
7963#endif
7964 int matches;
7965 int starts_with_dot;
7966 int len;
7967 char_u *pat;
7968 regmatch_T regmatch;
7969 char_u *matchname;
7970
7971 /* make room for file name */
7972 buf = alloc((unsigned int)STRLEN(path) + BASENAMELEN + 5);
7973 if (buf == NULL)
7974 return 0;
7975
7976 /*
7977 * Find the first part in the path name that contains a wildcard or a ~1.
7978 * Copy it into buf, including the preceding characters.
7979 */
7980 p = buf;
7981 s = buf;
7982 e = NULL;
7983 path_end = path;
7984 while (*path_end != NUL)
7985 {
7986 /* May ignore a wildcard that has a backslash before it; it will
7987 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
7988 if (path_end >= path + wildoff && rem_backslash(path_end))
7989 *p++ = *path_end++;
7990 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
7991 {
7992 if (e != NULL)
7993 break;
7994 s = p + 1;
7995 }
7996 else if (path_end >= path + wildoff
7997 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
7998 e = p;
7999#ifdef FEAT_MBYTE
8000 if (has_mbyte)
8001 {
8002 len = (*mb_ptr2len_check)(path_end);
8003 STRNCPY(p, path_end, len);
8004 p += len;
8005 path_end += len;
8006 }
8007 else
8008#endif
8009 *p++ = *path_end++;
8010 }
8011 e = p;
8012 *e = NUL;
8013
8014 /* now we have one wildcard component between s and e */
8015 /* Remove backslashes between "wildoff" and the start of the wildcard
8016 * component. */
8017 for (p = buf + wildoff; p < s; ++p)
8018 if (rem_backslash(p))
8019 {
8020 STRCPY(p, p + 1);
8021 --e;
8022 --s;
8023 }
8024
8025 starts_with_dot = (*s == '.');
8026 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8027 if (pat == NULL)
8028 {
8029 vim_free(buf);
8030 return 0;
8031 }
8032
8033 /* compile the regexp into a program */
8034 regmatch.rm_ic = TRUE; /* Always ignore case */
8035 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8036 vim_free(pat);
8037
8038 if (regmatch.regprog == NULL)
8039 {
8040 vim_free(buf);
8041 return 0;
8042 }
8043
8044 /* remember the pattern or file name being looked for */
8045 matchname = vim_strsave(s);
8046
8047 /* Scan all files in the directory with "dir/ *.*" */
8048 STRCPY(s, "*.*");
8049#ifdef WIN3264
8050# ifdef FEAT_MBYTE
8051 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8052 {
8053 /* The active codepage differs from 'encoding'. Attempt using the
8054 * wide function. If it fails because it is not implemented fall back
8055 * to the non-wide version (for Windows 98) */
8056 wn = enc_to_ucs2(buf, NULL);
8057 if (wn != NULL)
8058 {
8059 hFind = FindFirstFileW(wn, &wfb);
8060 if (hFind == INVALID_HANDLE_VALUE
8061 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8062 {
8063 vim_free(wn);
8064 wn = NULL;
8065 }
8066 }
8067 }
8068
8069 if (wn == NULL)
8070# endif
8071 hFind = FindFirstFile(buf, &fb);
8072 ok = (hFind != INVALID_HANDLE_VALUE);
8073#else
8074 /* If we are expanding wildcards we try both files and directories */
8075 ok = (findfirst((char *)buf, &fb,
8076 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8077#endif
8078
8079 while (ok)
8080 {
8081#ifdef WIN3264
8082# ifdef FEAT_MBYTE
8083 if (wn != NULL)
8084 p = ucs2_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8085 else
8086# endif
8087 p = (char_u *)fb.cFileName;
8088#else
8089 p = (char_u *)fb.ff_name;
8090#endif
8091 /* Ignore entries starting with a dot, unless when asked for. Accept
8092 * all entries found with "matchname". */
8093 if ((p[0] != '.' || starts_with_dot)
8094 && (matchname == NULL
8095 || vim_regexec(&regmatch, p, (colnr_T)0)))
8096 {
8097#ifdef WIN3264
8098 STRCPY(s, p);
8099#else
8100 namelowcpy(s, p);
8101#endif
8102 len = (int)STRLEN(buf);
8103 STRCPY(buf + len, path_end);
8104 if (mch_has_exp_wildcard(path_end))
8105 {
8106 /* need to expand another component of the path */
8107 /* remove backslashes for the remaining components only */
8108 (void)dos_expandpath(gap, buf, len + 1, flags);
8109 }
8110 else
8111 {
8112 /* no more wildcards, check if there is a match */
8113 /* remove backslashes for the remaining components only */
8114 if (*path_end != 0)
8115 backslash_halve(buf + len + 1);
8116 if (mch_getperm(buf) >= 0) /* add existing file */
8117 addfile(gap, buf, flags);
8118 }
8119 }
8120
8121#ifdef WIN3264
8122# ifdef FEAT_MBYTE
8123 if (wn != NULL)
8124 {
8125 vim_free(p);
8126 ok = FindNextFileW(hFind, &wfb);
8127 }
8128 else
8129# endif
8130 ok = FindNextFile(hFind, &fb);
8131#else
8132 ok = (findnext(&fb) == 0);
8133#endif
8134
8135 /* If no more matches and no match was used, try expanding the name
8136 * itself. Finds the long name of a short filename. */
8137 if (!ok && matchname != NULL && gap->ga_len == start_len)
8138 {
8139 STRCPY(s, matchname);
8140#ifdef WIN3264
8141 FindClose(hFind);
8142# ifdef FEAT_MBYTE
8143 if (wn != NULL)
8144 {
8145 vim_free(wn);
8146 wn = enc_to_ucs2(buf, NULL);
8147 if (wn != NULL)
8148 hFind = FindFirstFileW(wn, &wfb);
8149 }
8150 if (wn == NULL)
8151# endif
8152 hFind = FindFirstFile(buf, &fb);
8153 ok = (hFind != INVALID_HANDLE_VALUE);
8154#else
8155 ok = (findfirst((char *)buf, &fb,
8156 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8157#endif
8158 vim_free(matchname);
8159 matchname = NULL;
8160 }
8161 }
8162
8163#ifdef WIN3264
8164 FindClose(hFind);
8165# ifdef FEAT_MBYTE
8166 vim_free(wn);
8167# endif
8168#endif
8169 vim_free(buf);
8170 vim_free(regmatch.regprog);
8171 vim_free(matchname);
8172
8173 matches = gap->ga_len - start_len;
8174 if (matches > 0)
8175 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8176 sizeof(char_u *), pstrcmp);
8177 return matches;
8178}
8179
8180 int
8181mch_expandpath(
8182 garray_T *gap,
8183 char_u *path,
8184 int flags) /* EW_* flags */
8185{
8186 return dos_expandpath(gap, path, 0, flags);
8187}
8188# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8189
8190/*
8191 * Generic wildcard expansion code.
8192 *
8193 * Characters in "pat" that should not be expanded must be preceded with a
8194 * backslash. E.g., "/path\ with\ spaces/my\*star*"
8195 *
8196 * Return FAIL when no single file was found. In this case "num_file" is not
8197 * set, and "file" may contain an error message.
8198 * Return OK when some files found. "num_file" is set to the number of
8199 * matches, "file" to the array of matches. Call FreeWild() later.
8200 */
8201 int
8202gen_expand_wildcards(num_pat, pat, num_file, file, flags)
8203 int num_pat; /* number of input patterns */
8204 char_u **pat; /* array of input patterns */
8205 int *num_file; /* resulting number of files */
8206 char_u ***file; /* array of resulting files */
8207 int flags; /* EW_* flags */
8208{
8209 int i;
8210 garray_T ga;
8211 char_u *p;
8212 static int recursive = FALSE;
8213 int add_pat;
8214
8215 /*
8216 * expand_env() is called to expand things like "~user". If this fails,
8217 * it calls ExpandOne(), which brings us back here. In this case, always
8218 * call the machine specific expansion function, if possible. Otherwise,
8219 * return FAIL.
8220 */
8221 if (recursive)
8222#ifdef SPECIAL_WILDCHAR
8223 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
8224#else
8225 return FAIL;
8226#endif
8227
8228#ifdef SPECIAL_WILDCHAR
8229 /*
8230 * If there are any special wildcard characters which we cannot handle
8231 * here, call machine specific function for all the expansion. This
8232 * avoids starting the shell for each argument separately.
8233 * For `=expr` do use the internal function.
8234 */
8235 for (i = 0; i < num_pat; i++)
8236 {
8237 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
8238# ifdef VIM_BACKTICK
8239 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
8240# endif
8241 )
8242 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
8243 }
8244#endif
8245
8246 recursive = TRUE;
8247
8248 /*
8249 * The matching file names are stored in a growarray. Init it empty.
8250 */
8251 ga_init2(&ga, (int)sizeof(char_u *), 30);
8252
8253 for (i = 0; i < num_pat; ++i)
8254 {
8255 add_pat = -1;
8256 p = pat[i];
8257
8258#ifdef VIM_BACKTICK
8259 if (vim_backtick(p))
8260 add_pat = expand_backtick(&ga, p, flags);
8261 else
8262#endif
8263 {
8264 /*
8265 * First expand environment variables, "~/" and "~user/".
8266 */
8267 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
8268 {
8269 p = expand_env_save(p);
8270 if (p == NULL)
8271 p = pat[i];
8272#ifdef UNIX
8273 /*
8274 * On Unix, if expand_env() can't expand an environment
8275 * variable, use the shell to do that. Discard previously
8276 * found file names and start all over again.
8277 */
8278 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
8279 {
8280 vim_free(p);
8281 ga_clear(&ga);
8282 i = mch_expand_wildcards(num_pat, pat, num_file, file,
8283 flags);
8284 recursive = FALSE;
8285 return i;
8286 }
8287#endif
8288 }
8289
8290 /*
8291 * If there are wildcards: Expand file names and add each match to
8292 * the list. If there is no match, and EW_NOTFOUND is given, add
8293 * the pattern.
8294 * If there are no wildcards: Add the file name if it exists or
8295 * when EW_NOTFOUND is given.
8296 */
8297 if (mch_has_exp_wildcard(p))
8298 add_pat = mch_expandpath(&ga, p, flags);
8299 }
8300
8301 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
8302 {
8303 char_u *t = backslash_halve_save(p);
8304
8305#if defined(MACOS_CLASSIC)
8306 slash_to_colon(t);
8307#endif
8308 /* When EW_NOTFOUND is used, always add files and dirs. Makes
8309 * "vim c:/" work. */
8310 if (flags & EW_NOTFOUND)
8311 addfile(&ga, t, flags | EW_DIR | EW_FILE);
8312 else if (mch_getperm(t) >= 0)
8313 addfile(&ga, t, flags);
8314 vim_free(t);
8315 }
8316
8317 if (p != pat[i])
8318 vim_free(p);
8319 }
8320
8321 *num_file = ga.ga_len;
8322 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
8323
8324 recursive = FALSE;
8325
8326 return (ga.ga_data != NULL) ? OK : FAIL;
8327}
8328
8329# ifdef VIM_BACKTICK
8330
8331/*
8332 * Return TRUE if we can expand this backtick thing here.
8333 */
8334 static int
8335vim_backtick(p)
8336 char_u *p;
8337{
8338 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
8339}
8340
8341/*
8342 * Expand an item in `backticks` by executing it as a command.
8343 * Currently only works when pat[] starts and ends with a `.
8344 * Returns number of file names found.
8345 */
8346 static int
8347expand_backtick(gap, pat, flags)
8348 garray_T *gap;
8349 char_u *pat;
8350 int flags; /* EW_* flags */
8351{
8352 char_u *p;
8353 char_u *cmd;
8354 char_u *buffer;
8355 int cnt = 0;
8356 int i;
8357
8358 /* Create the command: lop off the backticks. */
8359 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
8360 if (cmd == NULL)
8361 return 0;
8362
8363#ifdef FEAT_EVAL
8364 if (*cmd == '=') /* `={expr}`: Expand expression */
8365 buffer = eval_to_string(cmd + 1, &p);
8366 else
8367#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008368 buffer = get_cmd_output(cmd, NULL,
8369 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008370 vim_free(cmd);
8371 if (buffer == NULL)
8372 return 0;
8373
8374 cmd = buffer;
8375 while (*cmd != NUL)
8376 {
8377 cmd = skipwhite(cmd); /* skip over white space */
8378 p = cmd;
8379 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
8380 ++p;
8381 /* add an entry if it is not empty */
8382 if (p > cmd)
8383 {
8384 i = *p;
8385 *p = NUL;
8386 addfile(gap, cmd, flags);
8387 *p = i;
8388 ++cnt;
8389 }
8390 cmd = p;
8391 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
8392 ++cmd;
8393 }
8394
8395 vim_free(buffer);
8396 return cnt;
8397}
8398# endif /* VIM_BACKTICK */
8399
8400/*
8401 * Add a file to a file list. Accepted flags:
8402 * EW_DIR add directories
8403 * EW_FILE add files
8404 * EW_NOTFOUND add even when it doesn't exist
8405 * EW_ADDSLASH add slash after directory name
8406 */
8407 void
8408addfile(gap, f, flags)
8409 garray_T *gap;
8410 char_u *f; /* filename */
8411 int flags;
8412{
8413 char_u *p;
8414 int isdir;
8415
8416 /* if the file/dir doesn't exist, may not add it */
8417 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
8418 return;
8419
8420#ifdef FNAME_ILLEGAL
8421 /* if the file/dir contains illegal characters, don't add it */
8422 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
8423 return;
8424#endif
8425
8426 isdir = mch_isdir(f);
8427 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
8428 return;
8429
8430 /* Make room for another item in the file list. */
8431 if (ga_grow(gap, 1) == FAIL)
8432 return;
8433
8434 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
8435 if (p == NULL)
8436 return;
8437
8438 STRCPY(p, f);
8439#ifdef BACKSLASH_IN_FILENAME
8440 slash_adjust(p);
8441#endif
8442 /*
8443 * Append a slash or backslash after directory names if none is present.
8444 */
8445#ifndef DONT_ADD_PATHSEP_TO_DIR
8446 if (isdir && (flags & EW_ADDSLASH))
8447 add_pathsep(p);
8448#endif
8449 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
8450 --gap->ga_room;
8451}
8452#endif /* !NO_EXPANDPATH */
8453
8454#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
8455
8456#ifndef SEEK_SET
8457# define SEEK_SET 0
8458#endif
8459#ifndef SEEK_END
8460# define SEEK_END 2
8461#endif
8462
8463/*
8464 * Get the stdout of an external command.
8465 * Returns an allocated string, or NULL for error.
8466 */
8467 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008468get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008469 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008470 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008471 int flags; /* can be SHELL_SILENT */
8472{
8473 char_u *tempname;
8474 char_u *command;
8475 char_u *buffer = NULL;
8476 int len;
8477 int i = 0;
8478 FILE *fd;
8479
8480 if (check_restricted() || check_secure())
8481 return NULL;
8482
8483 /* get a name for the temp file */
8484 if ((tempname = vim_tempname('o')) == NULL)
8485 {
8486 EMSG(_(e_notmp));
8487 return NULL;
8488 }
8489
8490 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008491 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008492 if (command == NULL)
8493 goto done;
8494
8495 /*
8496 * Call the shell to execute the command (errors are ignored).
8497 * Don't check timestamps here.
8498 */
8499 ++no_check_timestamps;
8500 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
8501 --no_check_timestamps;
8502
8503 vim_free(command);
8504
8505 /*
8506 * read the names from the file into memory
8507 */
8508# ifdef VMS
8509 /* created temporary file is not allways readable as binary */
8510 fd = mch_fopen((char *)tempname, "r");
8511# else
8512 fd = mch_fopen((char *)tempname, READBIN);
8513# endif
8514
8515 if (fd == NULL)
8516 {
8517 EMSG2(_(e_notopen), tempname);
8518 goto done;
8519 }
8520
8521 fseek(fd, 0L, SEEK_END);
8522 len = ftell(fd); /* get size of temp file */
8523 fseek(fd, 0L, SEEK_SET);
8524
8525 buffer = alloc(len + 1);
8526 if (buffer != NULL)
8527 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
8528 fclose(fd);
8529 mch_remove(tempname);
8530 if (buffer == NULL)
8531 goto done;
8532#ifdef VMS
8533 len = i; /* VMS doesn't give us what we asked for... */
8534#endif
8535 if (i != len)
8536 {
8537 EMSG2(_(e_notread), tempname);
8538 vim_free(buffer);
8539 buffer = NULL;
8540 }
8541 else
8542 buffer[len] = '\0'; /* make sure the buffer is terminated */
8543
8544done:
8545 vim_free(tempname);
8546 return buffer;
8547}
8548#endif
8549
8550/*
8551 * Free the list of files returned by expand_wildcards() or other expansion
8552 * functions.
8553 */
8554 void
8555FreeWild(count, files)
8556 int count;
8557 char_u **files;
8558{
8559 if (files == NULL || count <= 0)
8560 return;
8561#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
8562 /*
8563 * Is this still OK for when other functions than expand_wildcards() have
8564 * been used???
8565 */
8566 _fnexplodefree((char **)files);
8567#else
8568 while (count--)
8569 vim_free(files[count]);
8570 vim_free(files);
8571#endif
8572}
8573
8574/*
8575 * return TRUE when need to go to Insert mode because of 'insertmode'.
8576 * Don't do this when still processing a command or a mapping.
8577 * Don't do this when inside a ":normal" command.
8578 */
8579 int
8580goto_im()
8581{
8582 return (p_im && stuff_empty() && typebuf_typed());
8583}