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