blob: 4c2b55e918ccbdf1644a307e1e7bd8e220f6bd1c [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 {
Bram Moolenaard6754642005-01-17 22:18:45 +00003734 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735
3736 if (buf != NULL)
3737 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738 bindtextdomain(VIMPACKAGE, (char *)buf);
3739 vim_free(buf);
3740 }
3741 }
3742#endif
3743 }
3744 else
3745 {
3746 vim_setenv((char_u *)"VIM", p);
3747 didset_vim = TRUE;
3748 }
3749 }
3750 return p;
3751}
3752
3753/*
3754 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
3755 * Return NULL if not, return its name in allocated memory otherwise.
3756 */
3757 static char_u *
3758vim_version_dir(vimdir)
3759 char_u *vimdir;
3760{
3761 char_u *p;
3762
3763 if (vimdir == NULL || *vimdir == NUL)
3764 return NULL;
3765 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
3766 if (p != NULL && mch_isdir(p))
3767 return p;
3768 vim_free(p);
3769 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
3770 if (p != NULL && mch_isdir(p))
3771 return p;
3772 vim_free(p);
3773 return NULL;
3774}
3775
3776/*
3777 * If the string between "p" and "pend" ends in "name/", return "pend" minus
3778 * the length of "name/". Otherwise return "pend".
3779 */
3780 static char_u *
3781remove_tail(p, pend, name)
3782 char_u *p;
3783 char_u *pend;
3784 char_u *name;
3785{
3786 int len = (int)STRLEN(name) + 1;
3787 char_u *newend = pend - len;
3788
3789 if (newend >= p
3790 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003791 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792 return newend;
3793 return pend;
3794}
3795
3796#if defined(USE_EXE_NAME) && defined(MACOS_X)
3797/*
3798 * If the string between "p" and "pend" ends in "???.ext/", return "pend"
3799 * minus the length of "???.ext/". Otherwise return "pend".
3800 */
3801 static char_u *
3802remove_tail_with_ext(p, pend, ext)
3803 char_u *p;
3804 char_u *pend;
3805 char_u *ext;
3806{
3807 int len = (int)STRLEN(ext) + 1;
3808 char_u *newend = pend - len;
3809
3810 if (newend >= p && fnamencmp(newend, ext, len - 1) == 0)
Bram Moolenaar86b68352004-12-27 21:59:20 +00003811 while (newend > p && !after_pathsep(p, newend))
3812 mb_ptr_back(p, newend);
3813 if (newend == p || after_pathsep(p, newend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 return newend;
3815 return pend;
3816}
3817#endif
3818
3819/*
3820 * Call expand_env() and store the result in an allocated string.
3821 * This is not very memory efficient, this expects the result to be freed
3822 * again soon.
3823 */
3824 char_u *
3825expand_env_save(src)
3826 char_u *src;
3827{
3828 char_u *p;
3829
3830 p = alloc(MAXPATHL);
3831 if (p != NULL)
3832 expand_env(src, p, MAXPATHL);
3833 return p;
3834}
3835
3836/*
3837 * Our portable version of setenv.
3838 */
3839 void
3840vim_setenv(name, val)
3841 char_u *name;
3842 char_u *val;
3843{
3844#ifdef HAVE_SETENV
3845 mch_setenv((char *)name, (char *)val, 1);
3846#else
3847 char_u *envbuf;
3848
3849 /*
3850 * Putenv does not copy the string, it has to remain
3851 * valid. The allocated memory will never be freed.
3852 */
3853 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
3854 if (envbuf != NULL)
3855 {
3856 sprintf((char *)envbuf, "%s=%s", name, val);
3857 putenv((char *)envbuf);
3858 }
3859#endif
3860}
3861
3862#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
3863/*
3864 * Function given to ExpandGeneric() to obtain an environment variable name.
3865 */
3866/*ARGSUSED*/
3867 char_u *
3868get_env_name(xp, idx)
3869 expand_T *xp;
3870 int idx;
3871{
3872# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
3873 /*
3874 * No environ[] on the Amiga and on the Mac (using MPW).
3875 */
3876 return NULL;
3877# else
3878# ifndef __WIN32__
3879 /* Borland C++ 5.2 has this in a header file. */
3880 extern char **environ;
3881# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003882# define ENVNAMELEN 100
3883 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 char_u *str;
3885 int n;
3886
3887 str = (char_u *)environ[idx];
3888 if (str == NULL)
3889 return NULL;
3890
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003891 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 {
3893 if (str[n] == '=' || str[n] == NUL)
3894 break;
3895 name[n] = str[n];
3896 }
3897 name[n] = NUL;
3898 return name;
3899# endif
3900}
3901#endif
3902
3903/*
3904 * Replace home directory by "~" in each space or comma separated file name in
3905 * 'src'.
3906 * If anything fails (except when out of space) dst equals src.
3907 */
3908 void
3909home_replace(buf, src, dst, dstlen, one)
3910 buf_T *buf; /* when not NULL, check for help files */
3911 char_u *src; /* input file name */
3912 char_u *dst; /* where to put the result */
3913 int dstlen; /* maximum length of the result */
3914 int one; /* if TRUE, only replace one file name, include
3915 spaces and commas in the file name. */
3916{
3917 size_t dirlen = 0, envlen = 0;
3918 size_t len;
3919 char_u *homedir_env;
3920 char_u *p;
3921
3922 if (src == NULL)
3923 {
3924 *dst = NUL;
3925 return;
3926 }
3927
3928 /*
3929 * If the file is a help file, remove the path completely.
3930 */
3931 if (buf != NULL && buf->b_help)
3932 {
3933 STRCPY(dst, gettail(src));
3934 return;
3935 }
3936
3937 /*
3938 * We check both the value of the $HOME environment variable and the
3939 * "real" home directory.
3940 */
3941 if (homedir != NULL)
3942 dirlen = STRLEN(homedir);
3943
3944#ifdef VMS
3945 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
3946#else
3947 homedir_env = mch_getenv((char_u *)"HOME");
3948#endif
3949
3950 if (homedir_env != NULL && *homedir_env == NUL)
3951 homedir_env = NULL;
3952 if (homedir_env != NULL)
3953 envlen = STRLEN(homedir_env);
3954
3955 if (!one)
3956 src = skipwhite(src);
3957 while (*src && dstlen > 0)
3958 {
3959 /*
3960 * Here we are at the beginning of a file name.
3961 * First, check to see if the beginning of the file name matches
3962 * $HOME or the "real" home directory. Check that there is a '/'
3963 * after the match (so that if e.g. the file is "/home/pieter/bla",
3964 * and the home directory is "/home/piet", the file does not end up
3965 * as "~er/bla" (which would seem to indicate the file "bla" in user
3966 * er's home directory)).
3967 */
3968 p = homedir;
3969 len = dirlen;
3970 for (;;)
3971 {
3972 if ( len
3973 && fnamencmp(src, p, len) == 0
3974 && (vim_ispathsep(src[len])
3975 || (!one && (src[len] == ',' || src[len] == ' '))
3976 || src[len] == NUL))
3977 {
3978 src += len;
3979 if (--dstlen > 0)
3980 *dst++ = '~';
3981
3982 /*
3983 * If it's just the home directory, add "/".
3984 */
3985 if (!vim_ispathsep(src[0]) && --dstlen > 0)
3986 *dst++ = '/';
3987 break;
3988 }
3989 if (p == homedir_env)
3990 break;
3991 p = homedir_env;
3992 len = envlen;
3993 }
3994
3995 /* if (!one) skip to separator: space or comma */
3996 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
3997 *dst++ = *src++;
3998 /* skip separator */
3999 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4000 *dst++ = *src++;
4001 }
4002 /* if (dstlen == 0) out of space, what to do??? */
4003
4004 *dst = NUL;
4005}
4006
4007/*
4008 * Like home_replace, store the replaced string in allocated memory.
4009 * When something fails, NULL is returned.
4010 */
4011 char_u *
4012home_replace_save(buf, src)
4013 buf_T *buf; /* when not NULL, check for help files */
4014 char_u *src; /* input file name */
4015{
4016 char_u *dst;
4017 unsigned len;
4018
4019 len = 3; /* space for "~/" and trailing NUL */
4020 if (src != NULL) /* just in case */
4021 len += (unsigned)STRLEN(src);
4022 dst = alloc(len);
4023 if (dst != NULL)
4024 home_replace(buf, src, dst, len, TRUE);
4025 return dst;
4026}
4027
4028/*
4029 * Compare two file names and return:
4030 * FPC_SAME if they both exist and are the same file.
4031 * FPC_SAMEX if they both don't exist and have the same file name.
4032 * FPC_DIFF if they both exist and are different files.
4033 * FPC_NOTX if they both don't exist.
4034 * FPC_DIFFX if one of them doesn't exist.
4035 * For the first name environment variables are expanded
4036 */
4037 int
4038fullpathcmp(s1, s2, checkname)
4039 char_u *s1, *s2;
4040 int checkname; /* when both don't exist, check file names */
4041{
4042#ifdef UNIX
4043 char_u exp1[MAXPATHL];
4044 char_u full1[MAXPATHL];
4045 char_u full2[MAXPATHL];
4046 struct stat st1, st2;
4047 int r1, r2;
4048
4049 expand_env(s1, exp1, MAXPATHL);
4050 r1 = mch_stat((char *)exp1, &st1);
4051 r2 = mch_stat((char *)s2, &st2);
4052 if (r1 != 0 && r2 != 0)
4053 {
4054 /* if mch_stat() doesn't work, may compare the names */
4055 if (checkname)
4056 {
4057 if (fnamecmp(exp1, s2) == 0)
4058 return FPC_SAMEX;
4059 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4060 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4061 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4062 return FPC_SAMEX;
4063 }
4064 return FPC_NOTX;
4065 }
4066 if (r1 != 0 || r2 != 0)
4067 return FPC_DIFFX;
4068 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4069 return FPC_SAME;
4070 return FPC_DIFF;
4071#else
4072 char_u *exp1; /* expanded s1 */
4073 char_u *full1; /* full path of s1 */
4074 char_u *full2; /* full path of s2 */
4075 int retval = FPC_DIFF;
4076 int r1, r2;
4077
4078 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4079 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4080 {
4081 full1 = exp1 + MAXPATHL;
4082 full2 = full1 + MAXPATHL;
4083
4084 expand_env(s1, exp1, MAXPATHL);
4085 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4086 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4087
4088 /* If vim_FullName() fails, the file probably doesn't exist. */
4089 if (r1 != OK && r2 != OK)
4090 {
4091 if (checkname && fnamecmp(exp1, s2) == 0)
4092 retval = FPC_SAMEX;
4093 else
4094 retval = FPC_NOTX;
4095 }
4096 else if (r1 != OK || r2 != OK)
4097 retval = FPC_DIFFX;
4098 else if (fnamecmp(full1, full2))
4099 retval = FPC_DIFF;
4100 else
4101 retval = FPC_SAME;
4102 vim_free(exp1);
4103 }
4104 return retval;
4105#endif
4106}
4107
4108/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004109 * Get the tail of a path: the file name.
4110 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111 */
4112 char_u *
4113gettail(fname)
4114 char_u *fname;
4115{
4116 char_u *p1, *p2;
4117
4118 if (fname == NULL)
4119 return (char_u *)"";
4120 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4121 {
4122 if (vim_ispathsep(*p2))
4123 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004124 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004125 }
4126 return p1;
4127}
4128
4129/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004130 * Get pointer to tail of "fname", including path separators. Putting a NUL
4131 * here leaves the directory name. Takes care of "c:/" and "//".
4132 * Always returns a valid pointer.
4133 */
4134 char_u *
4135gettail_sep(fname)
4136 char_u *fname;
4137{
4138 char_u *p;
4139 char_u *t;
4140
4141 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4142 t = gettail(fname);
4143 while (t > p && after_pathsep(fname, t))
4144 --t;
4145#ifdef VMS
4146 /* path separator is part of the path */
4147 ++t;
4148#endif
4149 return t;
4150}
4151
4152/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 * get the next path component (just after the next path separator).
4154 */
4155 char_u *
4156getnextcomp(fname)
4157 char_u *fname;
4158{
4159 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004160 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 if (*fname)
4162 ++fname;
4163 return fname;
4164}
4165
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166/*
4167 * Get a pointer to one character past the head of a path name.
4168 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4169 * If there is no head, path is returned.
4170 */
4171 char_u *
4172get_past_head(path)
4173 char_u *path;
4174{
4175 char_u *retval;
4176
4177#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4178 /* may skip "c:" */
4179 if (isalpha(path[0]) && path[1] == ':')
4180 retval = path + 2;
4181 else
4182 retval = path;
4183#else
4184# if defined(AMIGA)
4185 /* may skip "label:" */
4186 retval = vim_strchr(path, ':');
4187 if (retval == NULL)
4188 retval = path;
4189# else /* Unix */
4190 retval = path;
4191# endif
4192#endif
4193
4194 while (vim_ispathsep(*retval))
4195 ++retval;
4196
4197 return retval;
4198}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199
4200/*
4201 * return TRUE if 'c' is a path separator.
4202 */
4203 int
4204vim_ispathsep(c)
4205 int c;
4206{
4207#ifdef RISCOS
4208 return (c == '.' || c == ':');
4209#else
4210# ifdef UNIX
4211 return (c == '/'); /* UNIX has ':' inside file names */
4212# else
4213# ifdef BACKSLASH_IN_FILENAME
4214 return (c == ':' || c == '/' || c == '\\');
4215# else
4216# ifdef VMS
4217 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4218 return (c == ':' || c == '[' || c == ']' || c == '/'
4219 || c == '<' || c == '>' || c == '"' );
4220# else
4221# ifdef COLON_AS_PATHSEP
4222 return (c == ':');
4223# else /* Amiga */
4224 return (c == ':' || c == '/');
4225# endif
4226# endif /* VMS */
4227# endif
4228# endif
4229#endif /* RISC OS */
4230}
4231
4232#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4233/*
4234 * return TRUE if 'c' is a path list separator.
4235 */
4236 int
4237vim_ispathlistsep(c)
4238 int c;
4239{
4240#ifdef UNIX
4241 return (c == ':');
4242#else
4243 return (c == ';'); /* might not be rigth for every system... */
4244#endif
4245}
4246#endif
4247
4248#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4249 || defined(PROTO)
4250/*
4251 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4252 */
4253 int
4254vim_fnamecmp(x, y)
4255 char_u *x, *y;
4256{
4257 return vim_fnamencmp(x, y, MAXPATHL);
4258}
4259
4260 int
4261vim_fnamencmp(x, y, len)
4262 char_u *x, *y;
4263 size_t len;
4264{
4265 while (len > 0 && *x && *y)
4266 {
4267 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4268 && !(*x == '/' && *y == '\\')
4269 && !(*x == '\\' && *y == '/'))
4270 break;
4271 ++x;
4272 ++y;
4273 --len;
4274 }
4275 if (len == 0)
4276 return 0;
4277 return (*x - *y);
4278}
4279#endif
4280
4281/*
4282 * Concatenate file names fname1 and fname2 into allocated memory.
4283 * Only add a '/' or '\\' when 'sep' is TRUE and it is neccesary.
4284 */
4285 char_u *
4286concat_fnames(fname1, fname2, sep)
4287 char_u *fname1;
4288 char_u *fname2;
4289 int sep;
4290{
4291 char_u *dest;
4292
4293 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4294 if (dest != NULL)
4295 {
4296 STRCPY(dest, fname1);
4297 if (sep)
4298 add_pathsep(dest);
4299 STRCAT(dest, fname2);
4300 }
4301 return dest;
4302}
4303
Bram Moolenaard6754642005-01-17 22:18:45 +00004304#if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4305/*
4306 * Concatenate two strings and return the result in allocated memory.
4307 * Returns NULL when out of memory.
4308 */
4309 char_u *
4310concat_str(str1, str2)
4311 char_u *str1;
4312 char_u *str2;
4313{
4314 char_u *dest;
4315 size_t l = STRLEN(str1);
4316
4317 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4318 if (dest != NULL)
4319 {
4320 STRCPY(dest, str1);
4321 STRCPY(dest + l, str2);
4322 }
4323 return dest;
4324}
4325#endif
4326
Bram Moolenaar071d4272004-06-13 20:20:40 +00004327/*
4328 * Add a path separator to a file name, unless it already ends in a path
4329 * separator.
4330 */
4331 void
4332add_pathsep(p)
4333 char_u *p;
4334{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004335 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336 STRCAT(p, PATHSEPSTR);
4337}
4338
4339/*
4340 * FullName_save - Make an allocated copy of a full file name.
4341 * Returns NULL when out of memory.
4342 */
4343 char_u *
4344FullName_save(fname, force)
4345 char_u *fname;
4346 int force; /* force expansion, even when it already looks
4347 like a full path name */
4348{
4349 char_u *buf;
4350 char_u *new_fname = NULL;
4351
4352 if (fname == NULL)
4353 return NULL;
4354
4355 buf = alloc((unsigned)MAXPATHL);
4356 if (buf != NULL)
4357 {
4358 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4359 new_fname = vim_strsave(buf);
4360 else
4361 new_fname = vim_strsave(fname);
4362 vim_free(buf);
4363 }
4364 return new_fname;
4365}
4366
4367#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4368
4369static char_u *skip_string __ARGS((char_u *p));
4370
4371/*
4372 * Find the start of a comment, not knowing if we are in a comment right now.
4373 * Search starts at w_cursor.lnum and goes backwards.
4374 */
4375 pos_T *
4376find_start_comment(ind_maxcomment) /* XXX */
4377 int ind_maxcomment;
4378{
4379 pos_T *pos;
4380 char_u *line;
4381 char_u *p;
4382
4383 if ((pos = findmatchlimit(NULL, '*', FM_BACKWARD, ind_maxcomment)) == NULL)
4384 return NULL;
4385
4386 /*
4387 * Check if the comment start we found is inside a string.
4388 */
4389 line = ml_get(pos->lnum);
4390 for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
4391 p = skip_string(p);
4392 if ((unsigned)(p - line) > pos->col)
4393 return NULL;
4394 return pos;
4395}
4396
4397/*
4398 * Skip to the end of a "string" and a 'c' character.
4399 * If there is no string or character, return argument unmodified.
4400 */
4401 static char_u *
4402skip_string(p)
4403 char_u *p;
4404{
4405 int i;
4406
4407 /*
4408 * We loop, because strings may be concatenated: "date""time".
4409 */
4410 for ( ; ; ++p)
4411 {
4412 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4413 {
4414 if (!p[1]) /* ' at end of line */
4415 break;
4416 i = 2;
4417 if (p[1] == '\\') /* '\n' or '\000' */
4418 {
4419 ++i;
4420 while (vim_isdigit(p[i - 1])) /* '\000' */
4421 ++i;
4422 }
4423 if (p[i] == '\'') /* check for trailing ' */
4424 {
4425 p += i;
4426 continue;
4427 }
4428 }
4429 else if (p[0] == '"') /* start of string */
4430 {
4431 for (++p; p[0]; ++p)
4432 {
4433 if (p[0] == '\\' && p[1] != NUL)
4434 ++p;
4435 else if (p[0] == '"') /* end of string */
4436 break;
4437 }
4438 if (p[0] == '"')
4439 continue;
4440 }
4441 break; /* no string found */
4442 }
4443 if (!*p)
4444 --p; /* backup from NUL */
4445 return p;
4446}
4447#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4448
4449#if defined(FEAT_CINDENT) || defined(PROTO)
4450
4451/*
4452 * Do C or expression indenting on the current line.
4453 */
4454 void
4455do_c_expr_indent()
4456{
4457# ifdef FEAT_EVAL
4458 if (*curbuf->b_p_inde != NUL)
4459 fixthisline(get_expr_indent);
4460 else
4461# endif
4462 fixthisline(get_c_indent);
4463}
4464
4465/*
4466 * Functions for C-indenting.
4467 * Most of this originally comes from Eric Fischer.
4468 */
4469/*
4470 * Below "XXX" means that this function may unlock the current line.
4471 */
4472
4473static char_u *cin_skipcomment __ARGS((char_u *));
4474static int cin_nocode __ARGS((char_u *));
4475static pos_T *find_line_comment __ARGS((void));
4476static int cin_islabel_skip __ARGS((char_u **));
4477static int cin_isdefault __ARGS((char_u *));
4478static char_u *after_label __ARGS((char_u *l));
4479static int get_indent_nolabel __ARGS((linenr_T lnum));
4480static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4481static int cin_first_id_amount __ARGS((void));
4482static int cin_get_equal_amount __ARGS((linenr_T lnum));
4483static int cin_ispreproc __ARGS((char_u *));
4484static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4485static int cin_iscomment __ARGS((char_u *));
4486static int cin_islinecomment __ARGS((char_u *));
4487static int cin_isterminated __ARGS((char_u *, int, int));
4488static int cin_isinit __ARGS((void));
4489static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4490static int cin_isif __ARGS((char_u *));
4491static int cin_iselse __ARGS((char_u *));
4492static int cin_isdo __ARGS((char_u *));
4493static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
4494static int cin_isbreak __ARGS((char_u *));
4495static int cin_is_cpp_baseclass __ARGS((char_u *line, colnr_T *col));
4496static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4497static int cin_skip2pos __ARGS((pos_T *trypos));
4498static pos_T *find_start_brace __ARGS((int));
4499static pos_T *find_match_paren __ARGS((int, int));
4500static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4501static int find_last_paren __ARGS((char_u *l, int start, int end));
4502static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4503
4504/*
4505 * Skip over white space and C comments within the line.
4506 */
4507 static char_u *
4508cin_skipcomment(s)
4509 char_u *s;
4510{
4511 while (*s)
4512 {
4513 s = skipwhite(s);
4514 if (*s != '/')
4515 break;
4516 ++s;
4517 if (*s == '/') /* slash-slash comment continues till eol */
4518 {
4519 s += STRLEN(s);
4520 break;
4521 }
4522 if (*s != '*')
4523 break;
4524 for (++s; *s; ++s) /* skip slash-star comment */
4525 if (s[0] == '*' && s[1] == '/')
4526 {
4527 s += 2;
4528 break;
4529 }
4530 }
4531 return s;
4532}
4533
4534/*
4535 * Return TRUE if there there is no code at *s. White space and comments are
4536 * not considered code.
4537 */
4538 static int
4539cin_nocode(s)
4540 char_u *s;
4541{
4542 return *cin_skipcomment(s) == NUL;
4543}
4544
4545/*
4546 * Check previous lines for a "//" line comment, skipping over blank lines.
4547 */
4548 static pos_T *
4549find_line_comment() /* XXX */
4550{
4551 static pos_T pos;
4552 char_u *line;
4553 char_u *p;
4554
4555 pos = curwin->w_cursor;
4556 while (--pos.lnum > 0)
4557 {
4558 line = ml_get(pos.lnum);
4559 p = skipwhite(line);
4560 if (cin_islinecomment(p))
4561 {
4562 pos.col = (int)(p - line);
4563 return &pos;
4564 }
4565 if (*p != NUL)
4566 break;
4567 }
4568 return NULL;
4569}
4570
4571/*
4572 * Check if string matches "label:"; move to character after ':' if true.
4573 */
4574 static int
4575cin_islabel_skip(s)
4576 char_u **s;
4577{
4578 if (!vim_isIDc(**s)) /* need at least one ID character */
4579 return FALSE;
4580
4581 while (vim_isIDc(**s))
4582 (*s)++;
4583
4584 *s = cin_skipcomment(*s);
4585
4586 /* "::" is not a label, it's C++ */
4587 return (**s == ':' && *++*s != ':');
4588}
4589
4590/*
4591 * Recognize a label: "label:".
4592 * Note: curwin->w_cursor must be where we are looking for the label.
4593 */
4594 int
4595cin_islabel(ind_maxcomment) /* XXX */
4596 int ind_maxcomment;
4597{
4598 char_u *s;
4599
4600 s = cin_skipcomment(ml_get_curline());
4601
4602 /*
4603 * Exclude "default" from labels, since it should be indented
4604 * like a switch label. Same for C++ scope declarations.
4605 */
4606 if (cin_isdefault(s))
4607 return FALSE;
4608 if (cin_isscopedecl(s))
4609 return FALSE;
4610
4611 if (cin_islabel_skip(&s))
4612 {
4613 /*
4614 * Only accept a label if the previous line is terminated or is a case
4615 * label.
4616 */
4617 pos_T cursor_save;
4618 pos_T *trypos;
4619 char_u *line;
4620
4621 cursor_save = curwin->w_cursor;
4622 while (curwin->w_cursor.lnum > 1)
4623 {
4624 --curwin->w_cursor.lnum;
4625
4626 /*
4627 * If we're in a comment now, skip to the start of the comment.
4628 */
4629 curwin->w_cursor.col = 0;
4630 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
4631 curwin->w_cursor = *trypos;
4632
4633 line = ml_get_curline();
4634 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
4635 continue;
4636 if (*(line = cin_skipcomment(line)) == NUL)
4637 continue;
4638
4639 curwin->w_cursor = cursor_save;
4640 if (cin_isterminated(line, TRUE, FALSE)
4641 || cin_isscopedecl(line)
4642 || cin_iscase(line)
4643 || (cin_islabel_skip(&line) && cin_nocode(line)))
4644 return TRUE;
4645 return FALSE;
4646 }
4647 curwin->w_cursor = cursor_save;
4648 return TRUE; /* label at start of file??? */
4649 }
4650 return FALSE;
4651}
4652
4653/*
4654 * Recognize structure initialization and enumerations.
4655 * Q&D-Implementation:
4656 * check for "=" at end or "[typedef] enum" at beginning of line.
4657 */
4658 static int
4659cin_isinit(void)
4660{
4661 char_u *s;
4662
4663 s = cin_skipcomment(ml_get_curline());
4664
4665 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
4666 s = cin_skipcomment(s + 7);
4667
4668 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
4669 return TRUE;
4670
4671 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
4672 return TRUE;
4673
4674 return FALSE;
4675}
4676
4677/*
4678 * Recognize a switch label: "case .*:" or "default:".
4679 */
4680 int
4681cin_iscase(s)
4682 char_u *s;
4683{
4684 s = cin_skipcomment(s);
4685 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
4686 {
4687 for (s += 4; *s; ++s)
4688 {
4689 s = cin_skipcomment(s);
4690 if (*s == ':')
4691 {
4692 if (s[1] == ':') /* skip over "::" for C++ */
4693 ++s;
4694 else
4695 return TRUE;
4696 }
4697 if (*s == '\'' && s[1] && s[2] == '\'')
4698 s += 2; /* skip over '.' */
4699 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
4700 return FALSE; /* stop at comment */
4701 else if (*s == '"')
4702 return FALSE; /* stop at string */
4703 }
4704 return FALSE;
4705 }
4706
4707 if (cin_isdefault(s))
4708 return TRUE;
4709 return FALSE;
4710}
4711
4712/*
4713 * Recognize a "default" switch label.
4714 */
4715 static int
4716cin_isdefault(s)
4717 char_u *s;
4718{
4719 return (STRNCMP(s, "default", 7) == 0
4720 && *(s = cin_skipcomment(s + 7)) == ':'
4721 && s[1] != ':');
4722}
4723
4724/*
4725 * Recognize a "public/private/proctected" scope declaration label.
4726 */
4727 int
4728cin_isscopedecl(s)
4729 char_u *s;
4730{
4731 int i;
4732
4733 s = cin_skipcomment(s);
4734 if (STRNCMP(s, "public", 6) == 0)
4735 i = 6;
4736 else if (STRNCMP(s, "protected", 9) == 0)
4737 i = 9;
4738 else if (STRNCMP(s, "private", 7) == 0)
4739 i = 7;
4740 else
4741 return FALSE;
4742 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
4743}
4744
4745/*
4746 * Return a pointer to the first non-empty non-comment character after a ':'.
4747 * Return NULL if not found.
4748 * case 234: a = b;
4749 * ^
4750 */
4751 static char_u *
4752after_label(l)
4753 char_u *l;
4754{
4755 for ( ; *l; ++l)
4756 {
4757 if (*l == ':')
4758 {
4759 if (l[1] == ':') /* skip over "::" for C++ */
4760 ++l;
4761 else if (!cin_iscase(l + 1))
4762 break;
4763 }
4764 else if (*l == '\'' && l[1] && l[2] == '\'')
4765 l += 2; /* skip over 'x' */
4766 }
4767 if (*l == NUL)
4768 return NULL;
4769 l = cin_skipcomment(l + 1);
4770 if (*l == NUL)
4771 return NULL;
4772 return l;
4773}
4774
4775/*
4776 * Get indent of line "lnum", skipping a label.
4777 * Return 0 if there is nothing after the label.
4778 */
4779 static int
4780get_indent_nolabel(lnum) /* XXX */
4781 linenr_T lnum;
4782{
4783 char_u *l;
4784 pos_T fp;
4785 colnr_T col;
4786 char_u *p;
4787
4788 l = ml_get(lnum);
4789 p = after_label(l);
4790 if (p == NULL)
4791 return 0;
4792
4793 fp.col = (colnr_T)(p - l);
4794 fp.lnum = lnum;
4795 getvcol(curwin, &fp, &col, NULL, NULL);
4796 return (int)col;
4797}
4798
4799/*
4800 * Find indent for line "lnum", ignoring any case or jump label.
4801 * Also return a pointer to the text (after the label).
4802 * label: if (asdf && asdfasdf)
4803 * ^
4804 */
4805 static int
4806skip_label(lnum, pp, ind_maxcomment)
4807 linenr_T lnum;
4808 char_u **pp;
4809 int ind_maxcomment;
4810{
4811 char_u *l;
4812 int amount;
4813 pos_T cursor_save;
4814
4815 cursor_save = curwin->w_cursor;
4816 curwin->w_cursor.lnum = lnum;
4817 l = ml_get_curline();
4818 /* XXX */
4819 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
4820 {
4821 amount = get_indent_nolabel(lnum);
4822 l = after_label(ml_get_curline());
4823 if (l == NULL) /* just in case */
4824 l = ml_get_curline();
4825 }
4826 else
4827 {
4828 amount = get_indent();
4829 l = ml_get_curline();
4830 }
4831 *pp = l;
4832
4833 curwin->w_cursor = cursor_save;
4834 return amount;
4835}
4836
4837/*
4838 * Return the indent of the first variable name after a type in a declaration.
4839 * int a, indent of "a"
4840 * static struct foo b, indent of "b"
4841 * enum bla c, indent of "c"
4842 * Returns zero when it doesn't look like a declaration.
4843 */
4844 static int
4845cin_first_id_amount()
4846{
4847 char_u *line, *p, *s;
4848 int len;
4849 pos_T fp;
4850 colnr_T col;
4851
4852 line = ml_get_curline();
4853 p = skipwhite(line);
4854 len = skiptowhite(p) - p;
4855 if (len == 6 && STRNCMP(p, "static", 6) == 0)
4856 {
4857 p = skipwhite(p + 6);
4858 len = skiptowhite(p) - p;
4859 }
4860 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
4861 p = skipwhite(p + 6);
4862 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
4863 p = skipwhite(p + 4);
4864 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
4865 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
4866 {
4867 s = skipwhite(p + len);
4868 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
4869 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
4870 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
4871 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
4872 p = s;
4873 }
4874 for (len = 0; vim_isIDc(p[len]); ++len)
4875 ;
4876 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
4877 return 0;
4878
4879 p = skipwhite(p + len);
4880 fp.lnum = curwin->w_cursor.lnum;
4881 fp.col = (colnr_T)(p - line);
4882 getvcol(curwin, &fp, &col, NULL, NULL);
4883 return (int)col;
4884}
4885
4886/*
4887 * Return the indent of the first non-blank after an equal sign.
4888 * char *foo = "here";
4889 * Return zero if no (useful) equal sign found.
4890 * Return -1 if the line above "lnum" ends in a backslash.
4891 * foo = "asdf\
4892 * asdf\
4893 * here";
4894 */
4895 static int
4896cin_get_equal_amount(lnum)
4897 linenr_T lnum;
4898{
4899 char_u *line;
4900 char_u *s;
4901 colnr_T col;
4902 pos_T fp;
4903
4904 if (lnum > 1)
4905 {
4906 line = ml_get(lnum - 1);
4907 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
4908 return -1;
4909 }
4910
4911 line = s = ml_get(lnum);
4912 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
4913 {
4914 if (cin_iscomment(s)) /* ignore comments */
4915 s = cin_skipcomment(s);
4916 else
4917 ++s;
4918 }
4919 if (*s != '=')
4920 return 0;
4921
4922 s = skipwhite(s + 1);
4923 if (cin_nocode(s))
4924 return 0;
4925
4926 if (*s == '"') /* nice alignment for continued strings */
4927 ++s;
4928
4929 fp.lnum = lnum;
4930 fp.col = (colnr_T)(s - line);
4931 getvcol(curwin, &fp, &col, NULL, NULL);
4932 return (int)col;
4933}
4934
4935/*
4936 * Recognize a preprocessor statement: Any line that starts with '#'.
4937 */
4938 static int
4939cin_ispreproc(s)
4940 char_u *s;
4941{
4942 s = skipwhite(s);
4943 if (*s == '#')
4944 return TRUE;
4945 return FALSE;
4946}
4947
4948/*
4949 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
4950 * continuation line of a preprocessor statement. Decrease "*lnump" to the
4951 * start and return the line in "*pp".
4952 */
4953 static int
4954cin_ispreproc_cont(pp, lnump)
4955 char_u **pp;
4956 linenr_T *lnump;
4957{
4958 char_u *line = *pp;
4959 linenr_T lnum = *lnump;
4960 int retval = FALSE;
4961
4962 while (1)
4963 {
4964 if (cin_ispreproc(line))
4965 {
4966 retval = TRUE;
4967 *lnump = lnum;
4968 break;
4969 }
4970 if (lnum == 1)
4971 break;
4972 line = ml_get(--lnum);
4973 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
4974 break;
4975 }
4976
4977 if (lnum != *lnump)
4978 *pp = ml_get(*lnump);
4979 return retval;
4980}
4981
4982/*
4983 * Recognize the start of a C or C++ comment.
4984 */
4985 static int
4986cin_iscomment(p)
4987 char_u *p;
4988{
4989 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
4990}
4991
4992/*
4993 * Recognize the start of a "//" comment.
4994 */
4995 static int
4996cin_islinecomment(p)
4997 char_u *p;
4998{
4999 return (p[0] == '/' && p[1] == '/');
5000}
5001
5002/*
5003 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5004 * Don't consider "} else" a terminated line.
5005 * Return the character terminating the line (ending char's have precedence if
5006 * both apply in order to determine initializations).
5007 */
5008 static int
5009cin_isterminated(s, incl_open, incl_comma)
5010 char_u *s;
5011 int incl_open; /* include '{' at the end as terminator */
5012 int incl_comma; /* recognize a trailing comma */
5013{
5014 char_u found_start = 0;
5015
5016 s = cin_skipcomment(s);
5017
5018 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5019 found_start = *s;
5020
5021 while (*s)
5022 {
5023 /* skip over comments, "" strings and 'c'haracters */
5024 s = skip_string(cin_skipcomment(s));
5025 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5026 || (incl_comma && *s == ','))
5027 && cin_nocode(s + 1))
5028 return *s;
5029
5030 if (*s)
5031 s++;
5032 }
5033 return found_start;
5034}
5035
5036/*
5037 * Recognize the basic picture of a function declaration -- it needs to
5038 * have an open paren somewhere and a close paren at the end of the line and
5039 * no semicolons anywhere.
5040 * When a line ends in a comma we continue looking in the next line.
5041 * "sp" points to a string with the line. When looking at other lines it must
5042 * be restored to the line. When it's NULL fetch lines here.
5043 * "lnum" is where we start looking.
5044 */
5045 static int
5046cin_isfuncdecl(sp, first_lnum)
5047 char_u **sp;
5048 linenr_T first_lnum;
5049{
5050 char_u *s;
5051 linenr_T lnum = first_lnum;
5052 int retval = FALSE;
5053
5054 if (sp == NULL)
5055 s = ml_get(lnum);
5056 else
5057 s = *sp;
5058
5059 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5060 {
5061 if (cin_iscomment(s)) /* ignore comments */
5062 s = cin_skipcomment(s);
5063 else
5064 ++s;
5065 }
5066 if (*s != '(')
5067 return FALSE; /* ';', ' or " before any () or no '(' */
5068
5069 while (*s && *s != ';' && *s != '\'' && *s != '"')
5070 {
5071 if (*s == ')' && cin_nocode(s + 1))
5072 {
5073 /* ')' at the end: may have found a match
5074 * Check for he previous line not to end in a backslash:
5075 * #if defined(x) && \
5076 * defined(y)
5077 */
5078 lnum = first_lnum - 1;
5079 s = ml_get(lnum);
5080 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5081 retval = TRUE;
5082 goto done;
5083 }
5084 if (*s == ',' && cin_nocode(s + 1))
5085 {
5086 /* ',' at the end: continue looking in the next line */
5087 if (lnum >= curbuf->b_ml.ml_line_count)
5088 break;
5089
5090 s = ml_get(++lnum);
5091 }
5092 else if (cin_iscomment(s)) /* ignore comments */
5093 s = cin_skipcomment(s);
5094 else
5095 ++s;
5096 }
5097
5098done:
5099 if (lnum != first_lnum && sp != NULL)
5100 *sp = ml_get(first_lnum);
5101
5102 return retval;
5103}
5104
5105 static int
5106cin_isif(p)
5107 char_u *p;
5108{
5109 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5110}
5111
5112 static int
5113cin_iselse(p)
5114 char_u *p;
5115{
5116 if (*p == '}') /* accept "} else" */
5117 p = cin_skipcomment(p + 1);
5118 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5119}
5120
5121 static int
5122cin_isdo(p)
5123 char_u *p;
5124{
5125 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5126}
5127
5128/*
5129 * Check if this is a "while" that should have a matching "do".
5130 * We only accept a "while (condition) ;", with only white space between the
5131 * ')' and ';'. The condition may be spread over several lines.
5132 */
5133 static int
5134cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5135 char_u *p;
5136 linenr_T lnum;
5137 int ind_maxparen;
5138{
5139 pos_T cursor_save;
5140 pos_T *trypos;
5141 int retval = FALSE;
5142
5143 p = cin_skipcomment(p);
5144 if (*p == '}') /* accept "} while (cond);" */
5145 p = cin_skipcomment(p + 1);
5146 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5147 {
5148 cursor_save = curwin->w_cursor;
5149 curwin->w_cursor.lnum = lnum;
5150 curwin->w_cursor.col = 0;
5151 p = ml_get_curline();
5152 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5153 {
5154 ++p;
5155 ++curwin->w_cursor.col;
5156 }
5157 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5158 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5159 retval = TRUE;
5160 curwin->w_cursor = cursor_save;
5161 }
5162 return retval;
5163}
5164
5165 static int
5166cin_isbreak(p)
5167 char_u *p;
5168{
5169 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5170}
5171
5172/* Find the position of a C++ base-class declaration or
5173 * constructor-initialization. eg:
5174 *
5175 * class MyClass :
5176 * baseClass <-- here
5177 * class MyClass : public baseClass,
5178 * anotherBaseClass <-- here (should probably lineup ??)
5179 * MyClass::MyClass(...) :
5180 * baseClass(...) <-- here (constructor-initialization)
5181 */
5182 static int
5183cin_is_cpp_baseclass(line, col)
5184 char_u *line;
5185 colnr_T *col;
5186{
5187 char_u *s;
5188 int class_or_struct, lookfor_ctor_init, cpp_base_class;
5189
5190 *col = 0;
5191
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005192 s = skipwhite(line);
5193 if (*s == '#') /* skip #define FOO x ? (x) : x */
5194 return FALSE;
5195 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005196 if (*s == NUL)
5197 return FALSE;
5198
5199 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5200
5201 while(*s != NUL)
5202 {
5203 if (s[0] == ':')
5204 {
5205 if (s[1] == ':')
5206 {
5207 /* skip double colon. It can't be a constructor
5208 * initialization any more */
5209 lookfor_ctor_init = FALSE;
5210 s = cin_skipcomment(s + 2);
5211 }
5212 else if (lookfor_ctor_init || class_or_struct)
5213 {
5214 /* we have something found, that looks like the start of
5215 * cpp-base-class-declaration or contructor-initialization */
5216 cpp_base_class = TRUE;
5217 lookfor_ctor_init = class_or_struct = FALSE;
5218 *col = 0;
5219 s = cin_skipcomment(s + 1);
5220 }
5221 else
5222 s = cin_skipcomment(s + 1);
5223 }
5224 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5225 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5226 {
5227 class_or_struct = TRUE;
5228 lookfor_ctor_init = FALSE;
5229
5230 if (*s == 'c')
5231 s = cin_skipcomment(s + 5);
5232 else
5233 s = cin_skipcomment(s + 6);
5234 }
5235 else
5236 {
5237 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5238 {
5239 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5240 }
5241 else if (s[0] == ')')
5242 {
5243 /* Constructor-initialization is assumed if we come across
5244 * something like "):" */
5245 class_or_struct = FALSE;
5246 lookfor_ctor_init = TRUE;
5247 }
5248 else if (!vim_isIDc(s[0]))
5249 {
5250 /* if it is not an identifier, we are wrong */
5251 class_or_struct = FALSE;
5252 lookfor_ctor_init = FALSE;
5253 }
5254 else if (*col == 0)
5255 {
5256 /* it can't be a constructor-initialization any more */
5257 lookfor_ctor_init = FALSE;
5258
5259 /* the first statement starts here: lineup with this one... */
5260 if (cpp_base_class && *col == 0)
5261 *col = (colnr_T)(s - line);
5262 }
5263
5264 s = cin_skipcomment(s + 1);
5265 }
5266 }
5267
5268 return cpp_base_class;
5269}
5270
5271/*
5272 * Return TRUE if string "s" ends with the string "find", possibly followed by
5273 * white space and comments. Skip strings and comments.
5274 * Ignore "ignore" after "find" if it's not NULL.
5275 */
5276 static int
5277cin_ends_in(s, find, ignore)
5278 char_u *s;
5279 char_u *find;
5280 char_u *ignore;
5281{
5282 char_u *p = s;
5283 char_u *r;
5284 int len = (int)STRLEN(find);
5285
5286 while (*p != NUL)
5287 {
5288 p = cin_skipcomment(p);
5289 if (STRNCMP(p, find, len) == 0)
5290 {
5291 r = skipwhite(p + len);
5292 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5293 r = skipwhite(r + STRLEN(ignore));
5294 if (cin_nocode(r))
5295 return TRUE;
5296 }
5297 if (*p != NUL)
5298 ++p;
5299 }
5300 return FALSE;
5301}
5302
5303/*
5304 * Skip strings, chars and comments until at or past "trypos".
5305 * Return the column found.
5306 */
5307 static int
5308cin_skip2pos(trypos)
5309 pos_T *trypos;
5310{
5311 char_u *line;
5312 char_u *p;
5313
5314 p = line = ml_get(trypos->lnum);
5315 while (*p && (colnr_T)(p - line) < trypos->col)
5316 {
5317 if (cin_iscomment(p))
5318 p = cin_skipcomment(p);
5319 else
5320 {
5321 p = skip_string(p);
5322 ++p;
5323 }
5324 }
5325 return (int)(p - line);
5326}
5327
5328/*
5329 * Find the '{' at the start of the block we are in.
5330 * Return NULL if no match found.
5331 * Ignore a '{' that is in a comment, makes indenting the next three lines
5332 * work. */
5333/* foo() */
5334/* { */
5335/* } */
5336
5337 static pos_T *
5338find_start_brace(ind_maxcomment) /* XXX */
5339 int ind_maxcomment;
5340{
5341 pos_T cursor_save;
5342 pos_T *trypos;
5343 pos_T *pos;
5344 static pos_T pos_copy;
5345
5346 cursor_save = curwin->w_cursor;
5347 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5348 {
5349 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5350 trypos = &pos_copy;
5351 curwin->w_cursor = *trypos;
5352 pos = NULL;
5353 /* ignore the { if it's in a // comment */
5354 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5355 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5356 break;
5357 if (pos != NULL)
5358 curwin->w_cursor.lnum = pos->lnum;
5359 }
5360 curwin->w_cursor = cursor_save;
5361 return trypos;
5362}
5363
5364/*
5365 * Find the matching '(', failing if it is in a comment.
5366 * Return NULL of no match found.
5367 */
5368 static pos_T *
5369find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5370 int ind_maxparen;
5371 int ind_maxcomment;
5372{
5373 pos_T cursor_save;
5374 pos_T *trypos;
5375 static pos_T pos_copy;
5376
5377 cursor_save = curwin->w_cursor;
5378 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5379 {
5380 /* check if the ( is in a // comment */
5381 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5382 trypos = NULL;
5383 else
5384 {
5385 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5386 trypos = &pos_copy;
5387 curwin->w_cursor = *trypos;
5388 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5389 trypos = NULL;
5390 }
5391 }
5392 curwin->w_cursor = cursor_save;
5393 return trypos;
5394}
5395
5396/*
5397 * Return ind_maxparen corrected for the difference in line number between the
5398 * cursor position and "startpos". This makes sure that searching for a
5399 * matching paren above the cursor line doesn't find a match because of
5400 * looking a few lines further.
5401 */
5402 static int
5403corr_ind_maxparen(ind_maxparen, startpos)
5404 int ind_maxparen;
5405 pos_T *startpos;
5406{
5407 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5408
5409 if (n > 0 && n < ind_maxparen / 2)
5410 return ind_maxparen - (int)n;
5411 return ind_maxparen;
5412}
5413
5414/*
5415 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5416 * line "l".
5417 */
5418 static int
5419find_last_paren(l, start, end)
5420 char_u *l;
5421 int start, end;
5422{
5423 int i;
5424 int retval = FALSE;
5425 int open_count = 0;
5426
5427 curwin->w_cursor.col = 0; /* default is start of line */
5428
5429 for (i = 0; l[i]; i++)
5430 {
5431 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5432 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5433 if (l[i] == start)
5434 ++open_count;
5435 else if (l[i] == end)
5436 {
5437 if (open_count > 0)
5438 --open_count;
5439 else
5440 {
5441 curwin->w_cursor.col = i;
5442 retval = TRUE;
5443 }
5444 }
5445 }
5446 return retval;
5447}
5448
5449 int
5450get_c_indent()
5451{
5452 /*
5453 * spaces from a block's opening brace the prevailing indent for that
5454 * block should be
5455 */
5456 int ind_level = curbuf->b_p_sw;
5457
5458 /*
5459 * spaces from the edge of the line an open brace that's at the end of a
5460 * line is imagined to be.
5461 */
5462 int ind_open_imag = 0;
5463
5464 /*
5465 * spaces from the prevailing indent for a line that is not precededof by
5466 * an opening brace.
5467 */
5468 int ind_no_brace = 0;
5469
5470 /*
5471 * column where the first { of a function should be located }
5472 */
5473 int ind_first_open = 0;
5474
5475 /*
5476 * spaces from the prevailing indent a leftmost open brace should be
5477 * located
5478 */
5479 int ind_open_extra = 0;
5480
5481 /*
5482 * spaces from the matching open brace (real location for one at the left
5483 * edge; imaginary location from one that ends a line) the matching close
5484 * brace should be located
5485 */
5486 int ind_close_extra = 0;
5487
5488 /*
5489 * spaces from the edge of the line an open brace sitting in the leftmost
5490 * column is imagined to be
5491 */
5492 int ind_open_left_imag = 0;
5493
5494 /*
5495 * spaces from the switch() indent a "case xx" label should be located
5496 */
5497 int ind_case = curbuf->b_p_sw;
5498
5499 /*
5500 * spaces from the "case xx:" code after a switch() should be located
5501 */
5502 int ind_case_code = curbuf->b_p_sw;
5503
5504 /*
5505 * lineup break at end of case in switch() with case label
5506 */
5507 int ind_case_break = 0;
5508
5509 /*
5510 * spaces from the class declaration indent a scope declaration label
5511 * should be located
5512 */
5513 int ind_scopedecl = curbuf->b_p_sw;
5514
5515 /*
5516 * spaces from the scope declaration label code should be located
5517 */
5518 int ind_scopedecl_code = curbuf->b_p_sw;
5519
5520 /*
5521 * amount K&R-style parameters should be indented
5522 */
5523 int ind_param = curbuf->b_p_sw;
5524
5525 /*
5526 * amount a function type spec should be indented
5527 */
5528 int ind_func_type = curbuf->b_p_sw;
5529
5530 /*
5531 * amount a cpp base class declaration or constructor initialization
5532 * should be indented
5533 */
5534 int ind_cpp_baseclass = curbuf->b_p_sw;
5535
5536 /*
5537 * additional spaces beyond the prevailing indent a continuation line
5538 * should be located
5539 */
5540 int ind_continuation = curbuf->b_p_sw;
5541
5542 /*
5543 * spaces from the indent of the line with an unclosed parentheses
5544 */
5545 int ind_unclosed = curbuf->b_p_sw * 2;
5546
5547 /*
5548 * spaces from the indent of the line with an unclosed parentheses, which
5549 * itself is also unclosed
5550 */
5551 int ind_unclosed2 = curbuf->b_p_sw;
5552
5553 /*
5554 * suppress ignoring spaces from the indent of a line starting with an
5555 * unclosed parentheses.
5556 */
5557 int ind_unclosed_noignore = 0;
5558
5559 /*
5560 * If the opening paren is the last nonwhite character on the line, and
5561 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
5562 * context (for very long lines).
5563 */
5564 int ind_unclosed_wrapped = 0;
5565
5566 /*
5567 * suppress ignoring white space when lining up with the character after
5568 * an unclosed parentheses.
5569 */
5570 int ind_unclosed_whiteok = 0;
5571
5572 /*
5573 * indent a closing parentheses under the line start of the matching
5574 * opening parentheses.
5575 */
5576 int ind_matching_paren = 0;
5577
5578 /*
5579 * Extra indent for comments.
5580 */
5581 int ind_comment = 0;
5582
5583 /*
5584 * spaces from the comment opener when there is nothing after it.
5585 */
5586 int ind_in_comment = 3;
5587
5588 /*
5589 * boolean: if non-zero, use ind_in_comment even if there is something
5590 * after the comment opener.
5591 */
5592 int ind_in_comment2 = 0;
5593
5594 /*
5595 * max lines to search for an open paren
5596 */
5597 int ind_maxparen = 20;
5598
5599 /*
5600 * max lines to search for an open comment
5601 */
5602 int ind_maxcomment = 70;
5603
5604 /*
5605 * handle braces for java code
5606 */
5607 int ind_java = 0;
5608
5609 /*
5610 * handle blocked cases correctly
5611 */
5612 int ind_keep_case_label = 0;
5613
5614 pos_T cur_curpos;
5615 int amount;
5616 int scope_amount;
5617 int cur_amount;
5618 colnr_T col;
5619 char_u *theline;
5620 char_u *linecopy;
5621 pos_T *trypos;
5622 pos_T *tryposBrace = NULL;
5623 pos_T our_paren_pos;
5624 char_u *start;
5625 int start_brace;
5626#define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
5627#define BRACE_AT_START 2 /* '{' is at start of line */
5628#define BRACE_AT_END 3 /* '{' is at end of line */
5629 linenr_T ourscope;
5630 char_u *l;
5631 char_u *look;
5632 char_u terminated;
5633 int lookfor;
5634#define LOOKFOR_INITIAL 0
5635#define LOOKFOR_IF 1
5636#define LOOKFOR_DO 2
5637#define LOOKFOR_CASE 3
5638#define LOOKFOR_ANY 4
5639#define LOOKFOR_TERM 5
5640#define LOOKFOR_UNTERM 6
5641#define LOOKFOR_SCOPEDECL 7
5642#define LOOKFOR_NOBREAK 8
5643#define LOOKFOR_CPP_BASECLASS 9
5644#define LOOKFOR_ENUM_OR_INIT 10
5645
5646 int whilelevel;
5647 linenr_T lnum;
5648 char_u *options;
5649 int fraction = 0; /* init for GCC */
5650 int divider;
5651 int n;
5652 int iscase;
5653 int lookfor_break;
5654 int cont_amount = 0; /* amount for continuation line */
5655
5656 for (options = curbuf->b_p_cino; *options; )
5657 {
5658 l = options++;
5659 if (*options == '-')
5660 ++options;
5661 n = getdigits(&options);
5662 divider = 0;
5663 if (*options == '.') /* ".5s" means a fraction */
5664 {
5665 fraction = atol((char *)++options);
5666 while (VIM_ISDIGIT(*options))
5667 {
5668 ++options;
5669 if (divider)
5670 divider *= 10;
5671 else
5672 divider = 10;
5673 }
5674 }
5675 if (*options == 's') /* "2s" means two times 'shiftwidth' */
5676 {
5677 if (n == 0 && fraction == 0)
5678 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
5679 else
5680 {
5681 n *= curbuf->b_p_sw;
5682 if (divider)
5683 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
5684 }
5685 ++options;
5686 }
5687 if (l[1] == '-')
5688 n = -n;
5689 /* When adding an entry here, also update the default 'cinoptions' in
5690 * change.txt, and add explanation for it! */
5691 switch (*l)
5692 {
5693 case '>': ind_level = n; break;
5694 case 'e': ind_open_imag = n; break;
5695 case 'n': ind_no_brace = n; break;
5696 case 'f': ind_first_open = n; break;
5697 case '{': ind_open_extra = n; break;
5698 case '}': ind_close_extra = n; break;
5699 case '^': ind_open_left_imag = n; break;
5700 case ':': ind_case = n; break;
5701 case '=': ind_case_code = n; break;
5702 case 'b': ind_case_break = n; break;
5703 case 'p': ind_param = n; break;
5704 case 't': ind_func_type = n; break;
5705 case '/': ind_comment = n; break;
5706 case 'c': ind_in_comment = n; break;
5707 case 'C': ind_in_comment2 = n; break;
5708 case 'i': ind_cpp_baseclass = n; break;
5709 case '+': ind_continuation = n; break;
5710 case '(': ind_unclosed = n; break;
5711 case 'u': ind_unclosed2 = n; break;
5712 case 'U': ind_unclosed_noignore = n; break;
5713 case 'W': ind_unclosed_wrapped = n; break;
5714 case 'w': ind_unclosed_whiteok = n; break;
5715 case 'm': ind_matching_paren = n; break;
5716 case ')': ind_maxparen = n; break;
5717 case '*': ind_maxcomment = n; break;
5718 case 'g': ind_scopedecl = n; break;
5719 case 'h': ind_scopedecl_code = n; break;
5720 case 'j': ind_java = n; break;
5721 case 'l': ind_keep_case_label = n; break;
5722 }
5723 }
5724
5725 /* remember where the cursor was when we started */
5726 cur_curpos = curwin->w_cursor;
5727
5728 /* Get a copy of the current contents of the line.
5729 * This is required, because only the most recent line obtained with
5730 * ml_get is valid! */
5731 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
5732 if (linecopy == NULL)
5733 return 0;
5734
5735 /*
5736 * In insert mode and the cursor is on a ')' truncate the line at the
5737 * cursor position. We don't want to line up with the matching '(' when
5738 * inserting new stuff.
5739 * For unknown reasons the cursor might be past the end of the line, thus
5740 * check for that.
5741 */
5742 if ((State & INSERT)
5743 && curwin->w_cursor.col < STRLEN(linecopy)
5744 && linecopy[curwin->w_cursor.col] == ')')
5745 linecopy[curwin->w_cursor.col] = NUL;
5746
5747 theline = skipwhite(linecopy);
5748
5749 /* move the cursor to the start of the line */
5750
5751 curwin->w_cursor.col = 0;
5752
5753 /*
5754 * #defines and so on always go at the left when included in 'cinkeys'.
5755 */
5756 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
5757 {
5758 amount = 0;
5759 }
5760
5761 /*
5762 * Is it a non-case label? Then that goes at the left margin too.
5763 */
5764 else if (cin_islabel(ind_maxcomment)) /* XXX */
5765 {
5766 amount = 0;
5767 }
5768
5769 /*
5770 * If we're inside a "//" comment and there is a "//" comment in a
5771 * previous line, lineup with that one.
5772 */
5773 else if (cin_islinecomment(theline)
5774 && (trypos = find_line_comment()) != NULL) /* XXX */
5775 {
5776 /* find how indented the line beginning the comment is */
5777 getvcol(curwin, trypos, &col, NULL, NULL);
5778 amount = col;
5779 }
5780
5781 /*
5782 * If we're inside a comment and not looking at the start of the
5783 * comment, try using the 'comments' option.
5784 */
5785 else if (!cin_iscomment(theline)
5786 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
5787 {
5788 int lead_start_len = 2;
5789 int lead_middle_len = 1;
5790 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
5791 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
5792 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
5793 char_u *p;
5794 int start_align = 0;
5795 int start_off = 0;
5796 int done = FALSE;
5797
5798 /* find how indented the line beginning the comment is */
5799 getvcol(curwin, trypos, &col, NULL, NULL);
5800 amount = col;
5801
5802 p = curbuf->b_p_com;
5803 while (*p != NUL)
5804 {
5805 int align = 0;
5806 int off = 0;
5807 int what = 0;
5808
5809 while (*p != NUL && *p != ':')
5810 {
5811 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
5812 what = *p++;
5813 else if (*p == COM_LEFT || *p == COM_RIGHT)
5814 align = *p++;
5815 else if (VIM_ISDIGIT(*p) || *p == '-')
5816 off = getdigits(&p);
5817 else
5818 ++p;
5819 }
5820
5821 if (*p == ':')
5822 ++p;
5823 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
5824 if (what == COM_START)
5825 {
5826 STRCPY(lead_start, lead_end);
5827 lead_start_len = (int)STRLEN(lead_start);
5828 start_off = off;
5829 start_align = align;
5830 }
5831 else if (what == COM_MIDDLE)
5832 {
5833 STRCPY(lead_middle, lead_end);
5834 lead_middle_len = (int)STRLEN(lead_middle);
5835 }
5836 else if (what == COM_END)
5837 {
5838 /* If our line starts with the middle comment string, line it
5839 * up with the comment opener per the 'comments' option. */
5840 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
5841 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
5842 {
5843 done = TRUE;
5844 if (curwin->w_cursor.lnum > 1)
5845 {
5846 /* If the start comment string matches in the previous
5847 * line, use the indent of that line pluss offset. If
5848 * the middle comment string matches in the previous
5849 * line, use the indent of that line. XXX */
5850 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
5851 if (STRNCMP(look, lead_start, lead_start_len) == 0)
5852 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
5853 else if (STRNCMP(look, lead_middle,
5854 lead_middle_len) == 0)
5855 {
5856 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
5857 break;
5858 }
5859 /* If the start comment string doesn't match with the
5860 * start of the comment, skip this entry. XXX */
5861 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
5862 lead_start, lead_start_len) != 0)
5863 continue;
5864 }
5865 if (start_off != 0)
5866 amount += start_off;
5867 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005868 amount += vim_strsize(lead_start)
5869 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005870 break;
5871 }
5872
5873 /* If our line starts with the end comment string, line it up
5874 * with the middle comment */
5875 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
5876 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
5877 {
5878 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
5879 /* XXX */
5880 if (off != 0)
5881 amount += off;
5882 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005883 amount += vim_strsize(lead_start)
5884 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005885 done = TRUE;
5886 break;
5887 }
5888 }
5889 }
5890
5891 /* If our line starts with an asterisk, line up with the
5892 * asterisk in the comment opener; otherwise, line up
5893 * with the first character of the comment text.
5894 */
5895 if (done)
5896 ;
5897 else if (theline[0] == '*')
5898 amount += 1;
5899 else
5900 {
5901 /*
5902 * If we are more than one line away from the comment opener, take
5903 * the indent of the previous non-empty line. If 'cino' has "CO"
5904 * and we are just below the comment opener and there are any
5905 * white characters after it line up with the text after it;
5906 * otherwise, add the amount specified by "c" in 'cino'
5907 */
5908 amount = -1;
5909 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
5910 {
5911 if (linewhite(lnum)) /* skip blank lines */
5912 continue;
5913 amount = get_indent_lnum(lnum); /* XXX */
5914 break;
5915 }
5916 if (amount == -1) /* use the comment opener */
5917 {
5918 if (!ind_in_comment2)
5919 {
5920 start = ml_get(trypos->lnum);
5921 look = start + trypos->col + 2; /* skip / and * */
5922 if (*look != NUL) /* if something after it */
5923 trypos->col = (colnr_T)(skipwhite(look) - start);
5924 }
5925 getvcol(curwin, trypos, &col, NULL, NULL);
5926 amount = col;
5927 if (ind_in_comment2 || *look == NUL)
5928 amount += ind_in_comment;
5929 }
5930 }
5931 }
5932
5933 /*
5934 * Are we inside parentheses or braces?
5935 */ /* XXX */
5936 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
5937 && ind_java == 0)
5938 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
5939 || trypos != NULL)
5940 {
5941 if (trypos != NULL && tryposBrace != NULL)
5942 {
5943 /* Both an unmatched '(' and '{' is found. Use the one which is
5944 * closer to the current cursor position, set the other to NULL. */
5945 if (trypos->lnum != tryposBrace->lnum
5946 ? trypos->lnum < tryposBrace->lnum
5947 : trypos->col < tryposBrace->col)
5948 trypos = NULL;
5949 else
5950 tryposBrace = NULL;
5951 }
5952
5953 if (trypos != NULL)
5954 {
5955 /*
5956 * If the matching paren is more than one line away, use the indent of
5957 * a previous non-empty line that matches the same paren.
5958 */
5959 amount = -1;
5960 cur_amount = MAXCOL;
5961 our_paren_pos = *trypos;
5962 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
5963 {
5964 l = skipwhite(ml_get(lnum));
5965 if (cin_nocode(l)) /* skip comment lines */
5966 continue;
5967 if (cin_ispreproc_cont(&l, &lnum)) /* ignore #defines, #if, etc. */
5968 continue;
5969 curwin->w_cursor.lnum = lnum;
5970
5971 /* Skip a comment. XXX */
5972 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
5973 {
5974 lnum = trypos->lnum + 1;
5975 continue;
5976 }
5977
5978 /* XXX */
5979 if ((trypos = find_match_paren(
5980 corr_ind_maxparen(ind_maxparen, &cur_curpos),
5981 ind_maxcomment)) != NULL
5982 && trypos->lnum == our_paren_pos.lnum
5983 && trypos->col == our_paren_pos.col)
5984 {
5985 amount = get_indent_lnum(lnum); /* XXX */
5986
5987 if (theline[0] == ')')
5988 {
5989 if (our_paren_pos.lnum != lnum && cur_amount > amount)
5990 cur_amount = amount;
5991 amount = -1;
5992 }
5993 break;
5994 }
5995 }
5996
5997 /*
5998 * Line up with line where the matching paren is. XXX
5999 * If the line starts with a '(' or the indent for unclosed
6000 * parentheses is zero, line up with the unclosed parentheses.
6001 */
6002 if (amount == -1)
6003 {
6004 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
6005 if (theline[0] == ')' || ind_unclosed == 0
6006 || (!ind_unclosed_noignore && *skipwhite(look) == '('))
6007 {
6008 /*
6009 * If we're looking at a close paren, line up right there;
6010 * otherwise, line up with the next (non-white) character.
6011 * When ind_unclosed_wrapped is set and the matching paren is
6012 * the last nonwhite character of the line, use either the
6013 * indent of the current line or the indentation of the next
6014 * outer paren and add ind_unclosed_wrapped (for very long
6015 * lines).
6016 */
6017 if (theline[0] != ')')
6018 {
6019 cur_amount = MAXCOL;
6020 l = ml_get(our_paren_pos.lnum);
6021 if (ind_unclosed_wrapped
6022 && cin_ends_in(l, (char_u *)"(", NULL))
6023 {
6024 /* look for opening unmatched paren, indent one level
6025 * for each additional level */
6026 n = 1;
6027 for (col = 0; col < our_paren_pos.col; ++col)
6028 {
6029 switch (l[col])
6030 {
6031 case '(':
6032 case '{': ++n;
6033 break;
6034
6035 case ')':
6036 case '}': if (n > 1)
6037 --n;
6038 break;
6039 }
6040 }
6041
6042 our_paren_pos.col = 0;
6043 amount += n * ind_unclosed_wrapped;
6044 }
6045 else if (ind_unclosed_whiteok)
6046 our_paren_pos.col++;
6047 else
6048 {
6049 col = our_paren_pos.col + 1;
6050 while (vim_iswhite(l[col]))
6051 col++;
6052 if (l[col] != NUL) /* In case of trailing space */
6053 our_paren_pos.col = col;
6054 else
6055 our_paren_pos.col++;
6056 }
6057 }
6058
6059 /*
6060 * Find how indented the paren is, or the character after it
6061 * if we did the above "if".
6062 */
6063 if (our_paren_pos.col > 0)
6064 {
6065 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6066 if (cur_amount > (int)col)
6067 cur_amount = col;
6068 }
6069 }
6070
6071 if (theline[0] == ')' && ind_matching_paren)
6072 {
6073 /* Line up with the start of the matching paren line. */
6074 }
6075 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
6076 && *skipwhite(look) == '('))
6077 {
6078 if (cur_amount != MAXCOL)
6079 amount = cur_amount;
6080 }
6081 else
6082 {
6083 /* add ind_unclosed2 for each '(' before our matching one */
6084 col = our_paren_pos.col;
6085 while (our_paren_pos.col > 0)
6086 {
6087 --our_paren_pos.col;
6088 switch (*ml_get_pos(&our_paren_pos))
6089 {
6090 case '(': amount += ind_unclosed2;
6091 col = our_paren_pos.col;
6092 break;
6093 case ')': amount -= ind_unclosed2;
6094 col = MAXCOL;
6095 break;
6096 }
6097 }
6098
6099 /* Use ind_unclosed once, when the first '(' is not inside
6100 * braces */
6101 if (col == MAXCOL)
6102 amount += ind_unclosed;
6103 else
6104 {
6105 curwin->w_cursor.lnum = our_paren_pos.lnum;
6106 curwin->w_cursor.col = col;
6107 if ((trypos = find_match_paren(ind_maxparen,
6108 ind_maxcomment)) != NULL)
6109 amount += ind_unclosed2;
6110 else
6111 amount += ind_unclosed;
6112 }
6113 /*
6114 * For a line starting with ')' use the minimum of the two
6115 * positions, to avoid giving it more indent than the previous
6116 * lines:
6117 * func_long_name( if (x
6118 * arg && yy
6119 * ) ^ not here ) ^ not here
6120 */
6121 if (cur_amount < amount)
6122 amount = cur_amount;
6123 }
6124 }
6125
6126 /* add extra indent for a comment */
6127 if (cin_iscomment(theline))
6128 amount += ind_comment;
6129 }
6130
6131 /*
6132 * Are we at least inside braces, then?
6133 */
6134 else
6135 {
6136 trypos = tryposBrace;
6137
6138 ourscope = trypos->lnum;
6139 start = ml_get(ourscope);
6140
6141 /*
6142 * Now figure out how indented the line is in general.
6143 * If the brace was at the start of the line, we use that;
6144 * otherwise, check out the indentation of the line as
6145 * a whole and then add the "imaginary indent" to that.
6146 */
6147 look = skipwhite(start);
6148 if (*look == '{')
6149 {
6150 getvcol(curwin, trypos, &col, NULL, NULL);
6151 amount = col;
6152 if (*start == '{')
6153 start_brace = BRACE_IN_COL0;
6154 else
6155 start_brace = BRACE_AT_START;
6156 }
6157 else
6158 {
6159 /*
6160 * that opening brace might have been on a continuation
6161 * line. if so, find the start of the line.
6162 */
6163 curwin->w_cursor.lnum = ourscope;
6164
6165 /*
6166 * position the cursor over the rightmost paren, so that
6167 * matching it will take us back to the start of the line.
6168 */
6169 lnum = ourscope;
6170 if (find_last_paren(start, '(', ')')
6171 && (trypos = find_match_paren(ind_maxparen,
6172 ind_maxcomment)) != NULL)
6173 lnum = trypos->lnum;
6174
6175 /*
6176 * It could have been something like
6177 * case 1: if (asdf &&
6178 * ldfd) {
6179 * }
6180 */
6181 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6182 amount = get_indent();
6183 else
6184 amount = skip_label(lnum, &l, ind_maxcomment);
6185
6186 start_brace = BRACE_AT_END;
6187 }
6188
6189 /*
6190 * if we're looking at a closing brace, that's where
6191 * we want to be. otherwise, add the amount of room
6192 * that an indent is supposed to be.
6193 */
6194 if (theline[0] == '}')
6195 {
6196 /*
6197 * they may want closing braces to line up with something
6198 * other than the open brace. indulge them, if so.
6199 */
6200 amount += ind_close_extra;
6201 }
6202 else
6203 {
6204 /*
6205 * If we're looking at an "else", try to find an "if"
6206 * to match it with.
6207 * If we're looking at a "while", try to find a "do"
6208 * to match it with.
6209 */
6210 lookfor = LOOKFOR_INITIAL;
6211 if (cin_iselse(theline))
6212 lookfor = LOOKFOR_IF;
6213 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6214 /* XXX */
6215 lookfor = LOOKFOR_DO;
6216 if (lookfor != LOOKFOR_INITIAL)
6217 {
6218 curwin->w_cursor.lnum = cur_curpos.lnum;
6219 if (find_match(lookfor, ourscope, ind_maxparen,
6220 ind_maxcomment) == OK)
6221 {
6222 amount = get_indent(); /* XXX */
6223 goto theend;
6224 }
6225 }
6226
6227 /*
6228 * We get here if we are not on an "while-of-do" or "else" (or
6229 * failed to find a matching "if").
6230 * Search backwards for something to line up with.
6231 * First set amount for when we don't find anything.
6232 */
6233
6234 /*
6235 * if the '{' is _really_ at the left margin, use the imaginary
6236 * location of a left-margin brace. Otherwise, correct the
6237 * location for ind_open_extra.
6238 */
6239
6240 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6241 {
6242 amount = ind_open_left_imag;
6243 }
6244 else
6245 {
6246 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6247 amount += ind_open_imag;
6248 else
6249 {
6250 /* Compensate for adding ind_open_extra later. */
6251 amount -= ind_open_extra;
6252 if (amount < 0)
6253 amount = 0;
6254 }
6255 }
6256
6257 lookfor_break = FALSE;
6258
6259 if (cin_iscase(theline)) /* it's a switch() label */
6260 {
6261 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6262 amount += ind_case;
6263 }
6264 else if (cin_isscopedecl(theline)) /* private:, ... */
6265 {
6266 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6267 amount += ind_scopedecl;
6268 }
6269 else
6270 {
6271 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6272 lookfor_break = TRUE;
6273
6274 lookfor = LOOKFOR_INITIAL;
6275 amount += ind_level; /* ind_level from start of block */
6276 }
6277 scope_amount = amount;
6278 whilelevel = 0;
6279
6280 /*
6281 * Search backwards. If we find something we recognize, line up
6282 * with that.
6283 *
6284 * if we're looking at an open brace, indent
6285 * the usual amount relative to the conditional
6286 * that opens the block.
6287 */
6288 curwin->w_cursor = cur_curpos;
6289 for (;;)
6290 {
6291 curwin->w_cursor.lnum--;
6292 curwin->w_cursor.col = 0;
6293
6294 /*
6295 * If we went all the way back to the start of our scope, line
6296 * up with it.
6297 */
6298 if (curwin->w_cursor.lnum <= ourscope)
6299 {
6300 /* we reached end of scope:
6301 * if looking for a enum or structure initialization
6302 * go further back:
6303 * if it is an initializer (enum xxx or xxx =), then
6304 * don't add ind_continuation, otherwise it is a variable
6305 * declaration:
6306 * int x,
6307 * here; <-- add ind_continuation
6308 */
6309 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6310 {
6311 if (curwin->w_cursor.lnum == 0
6312 || curwin->w_cursor.lnum
6313 < ourscope - ind_maxparen)
6314 {
6315 /* nothing found (abuse ind_maxparen as limit)
6316 * assume terminated line (i.e. a variable
6317 * initialization) */
6318 if (cont_amount > 0)
6319 amount = cont_amount;
6320 else
6321 amount += ind_continuation;
6322 break;
6323 }
6324
6325 l = ml_get_curline();
6326
6327 /*
6328 * If we're in a comment now, skip to the start of the
6329 * comment.
6330 */
6331 trypos = find_start_comment(ind_maxcomment);
6332 if (trypos != NULL)
6333 {
6334 curwin->w_cursor.lnum = trypos->lnum + 1;
6335 continue;
6336 }
6337
6338 /*
6339 * Skip preprocessor directives and blank lines.
6340 */
6341 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6342 continue;
6343
6344 if (cin_nocode(l))
6345 continue;
6346
6347 terminated = cin_isterminated(l, FALSE, TRUE);
6348
6349 /*
6350 * If we are at top level and the line looks like a
6351 * function declaration, we are done
6352 * (it's a variable declaration).
6353 */
6354 if (start_brace != BRACE_IN_COL0
6355 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6356 {
6357 /* if the line is terminated with another ','
6358 * it is a continued variable initialization.
6359 * don't add extra indent.
6360 * TODO: does not work, if a function
6361 * declaration is split over multiple lines:
6362 * cin_isfuncdecl returns FALSE then.
6363 */
6364 if (terminated == ',')
6365 break;
6366
6367 /* if it es a enum declaration or an assignment,
6368 * we are done.
6369 */
6370 if (terminated != ';' && cin_isinit())
6371 break;
6372
6373 /* nothing useful found */
6374 if (terminated == 0 || terminated == '{')
6375 continue;
6376 }
6377
6378 if (terminated != ';')
6379 {
6380 /* Skip parens and braces. Position the cursor
6381 * over the rightmost paren, so that matching it
6382 * will take us back to the start of the line.
6383 */ /* XXX */
6384 trypos = NULL;
6385 if (find_last_paren(l, '(', ')'))
6386 trypos = find_match_paren(ind_maxparen,
6387 ind_maxcomment);
6388
6389 if (trypos == NULL && find_last_paren(l, '{', '}'))
6390 trypos = find_start_brace(ind_maxcomment);
6391
6392 if (trypos != NULL)
6393 {
6394 curwin->w_cursor.lnum = trypos->lnum + 1;
6395 continue;
6396 }
6397 }
6398
6399 /* it's a variable declaration, add indentation
6400 * like in
6401 * int a,
6402 * b;
6403 */
6404 if (cont_amount > 0)
6405 amount = cont_amount;
6406 else
6407 amount += ind_continuation;
6408 }
6409 else if (lookfor == LOOKFOR_UNTERM)
6410 {
6411 if (cont_amount > 0)
6412 amount = cont_amount;
6413 else
6414 amount += ind_continuation;
6415 }
6416 else if (lookfor != LOOKFOR_TERM
6417 && lookfor != LOOKFOR_CPP_BASECLASS)
6418 {
6419 amount = scope_amount;
6420 if (theline[0] == '{')
6421 amount += ind_open_extra;
6422 }
6423 break;
6424 }
6425
6426 /*
6427 * If we're in a comment now, skip to the start of the comment.
6428 */ /* XXX */
6429 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6430 {
6431 curwin->w_cursor.lnum = trypos->lnum + 1;
6432 continue;
6433 }
6434
6435 l = ml_get_curline();
6436
6437 /*
6438 * If this is a switch() label, may line up relative to that.
6439 * if this is a C++ scope declaration, do the same.
6440 */
6441 iscase = cin_iscase(l);
6442 if (iscase || cin_isscopedecl(l))
6443 {
6444 /* we are only looking for cpp base class
6445 * declaration/initialization any longer */
6446 if (lookfor == LOOKFOR_CPP_BASECLASS)
6447 break;
6448
6449 /* When looking for a "do" we are not interested in
6450 * labels. */
6451 if (whilelevel > 0)
6452 continue;
6453
6454 /*
6455 * case xx:
6456 * c = 99 + <- this indent plus continuation
6457 *-> here;
6458 */
6459 if (lookfor == LOOKFOR_UNTERM
6460 || lookfor == LOOKFOR_ENUM_OR_INIT)
6461 {
6462 if (cont_amount > 0)
6463 amount = cont_amount;
6464 else
6465 amount += ind_continuation;
6466 break;
6467 }
6468
6469 /*
6470 * case xx: <- line up with this case
6471 * x = 333;
6472 * case yy:
6473 */
6474 if ( (iscase && lookfor == LOOKFOR_CASE)
6475 || (iscase && lookfor_break)
6476 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
6477 {
6478 /*
6479 * Check that this case label is not for another
6480 * switch()
6481 */ /* XXX */
6482 if ((trypos = find_start_brace(ind_maxcomment)) ==
6483 NULL || trypos->lnum == ourscope)
6484 {
6485 amount = get_indent(); /* XXX */
6486 break;
6487 }
6488 continue;
6489 }
6490
6491 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
6492
6493 /*
6494 * case xx: if (cond) <- line up with this if
6495 * y = y + 1;
6496 * -> s = 99;
6497 *
6498 * case xx:
6499 * if (cond) <- line up with this line
6500 * y = y + 1;
6501 * -> s = 99;
6502 */
6503 if (lookfor == LOOKFOR_TERM)
6504 {
6505 if (n)
6506 amount = n;
6507
6508 if (!lookfor_break)
6509 break;
6510 }
6511
6512 /*
6513 * case xx: x = x + 1; <- line up with this x
6514 * -> y = y + 1;
6515 *
6516 * case xx: if (cond) <- line up with this if
6517 * -> y = y + 1;
6518 */
6519 if (n)
6520 {
6521 amount = n;
6522 l = after_label(ml_get_curline());
6523 if (l != NULL && cin_is_cinword(l))
6524 amount += ind_level + ind_no_brace;
6525 break;
6526 }
6527
6528 /*
6529 * Try to get the indent of a statement before the switch
6530 * label. If nothing is found, line up relative to the
6531 * switch label.
6532 * break; <- may line up with this line
6533 * case xx:
6534 * -> y = 1;
6535 */
6536 scope_amount = get_indent() + (iscase /* XXX */
6537 ? ind_case_code : ind_scopedecl_code);
6538 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
6539 continue;
6540 }
6541
6542 /*
6543 * Looking for a switch() label or C++ scope declaration,
6544 * ignore other lines, skip {}-blocks.
6545 */
6546 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
6547 {
6548 if (find_last_paren(l, '{', '}') && (trypos =
6549 find_start_brace(ind_maxcomment)) != NULL)
6550 curwin->w_cursor.lnum = trypos->lnum + 1;
6551 continue;
6552 }
6553
6554 /*
6555 * Ignore jump labels with nothing after them.
6556 */
6557 if (cin_islabel(ind_maxcomment))
6558 {
6559 l = after_label(ml_get_curline());
6560 if (l == NULL || cin_nocode(l))
6561 continue;
6562 }
6563
6564 /*
6565 * Ignore #defines, #if, etc.
6566 * Ignore comment and empty lines.
6567 * (need to get the line again, cin_islabel() may have
6568 * unlocked it)
6569 */
6570 l = ml_get_curline();
6571 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
6572 || cin_nocode(l))
6573 continue;
6574
6575 /*
6576 * Are we at the start of a cpp base class declaration or
6577 * constructor initialization?
6578 */ /* XXX */
6579 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass
6580 && cin_is_cpp_baseclass(l, &col))
6581 {
6582 if (lookfor == LOOKFOR_UNTERM)
6583 {
6584 if (cont_amount > 0)
6585 amount = cont_amount;
6586 else
6587 amount += ind_continuation;
6588 }
6589 else if (col == 0 || theline[0] == '{')
6590 {
6591 amount = get_indent();
6592 if (find_last_paren(l, '(', ')')
6593 && (trypos = find_match_paren(ind_maxparen,
6594 ind_maxcomment)) != NULL)
6595 amount = get_indent_lnum(trypos->lnum); /* XXX */
6596 if (theline[0] != '{')
6597 amount += ind_cpp_baseclass;
6598 }
6599 else
6600 {
6601 curwin->w_cursor.col = col;
6602 getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL);
6603 amount = (int)col;
6604 }
6605 break;
6606 }
6607 else if (lookfor == LOOKFOR_CPP_BASECLASS)
6608 {
6609 /* only look, whether there is a cpp base class
6610 * declaration or initialization before the opening brace. */
6611 if (cin_isterminated(l, TRUE, FALSE))
6612 break;
6613 else
6614 continue;
6615 }
6616
6617 /*
6618 * What happens next depends on the line being terminated.
6619 * If terminated with a ',' only consider it terminating if
6620 * there is anoter unterminated statement behind, eg:
6621 * 123,
6622 * sizeof
6623 * here
6624 * Otherwise check whether it is a enumeration or structure
6625 * initialisation (not indented) or a variable declaration
6626 * (indented).
6627 */
6628 terminated = cin_isterminated(l, FALSE, TRUE);
6629
6630 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
6631 && terminated == ','))
6632 {
6633 /*
6634 * if we're in the middle of a paren thing,
6635 * go back to the line that starts it so
6636 * we can get the right prevailing indent
6637 * if ( foo &&
6638 * bar )
6639 */
6640 /*
6641 * position the cursor over the rightmost paren, so that
6642 * matching it will take us back to the start of the line.
6643 */
6644 (void)find_last_paren(l, '(', ')');
6645 trypos = find_match_paren(
6646 corr_ind_maxparen(ind_maxparen, &cur_curpos),
6647 ind_maxcomment);
6648
6649 /*
6650 * If we are looking for ',', we also look for matching
6651 * braces.
6652 */
6653 if (trypos == NULL && find_last_paren(l, '{', '}'))
6654 trypos = find_start_brace(ind_maxcomment);
6655
6656 if (trypos != NULL)
6657 {
6658 /*
6659 * Check if we are on a case label now. This is
6660 * handled above.
6661 * case xx: if ( asdf &&
6662 * asdf)
6663 */
6664 curwin->w_cursor.lnum = trypos->lnum;
6665 l = ml_get_curline();
6666 if (cin_iscase(l) || cin_isscopedecl(l))
6667 {
6668 ++curwin->w_cursor.lnum;
6669 continue;
6670 }
6671 }
6672
6673 /*
6674 * Skip over continuation lines to find the one to get the
6675 * indent from
6676 * char *usethis = "bla\
6677 * bla",
6678 * here;
6679 */
6680 if (terminated == ',')
6681 {
6682 while (curwin->w_cursor.lnum > 1)
6683 {
6684 l = ml_get(curwin->w_cursor.lnum - 1);
6685 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
6686 break;
6687 --curwin->w_cursor.lnum;
6688 }
6689 }
6690
6691 /*
6692 * Get indent and pointer to text for current line,
6693 * ignoring any jump label. XXX
6694 */
6695 cur_amount = skip_label(curwin->w_cursor.lnum,
6696 &l, ind_maxcomment);
6697
6698 /*
6699 * If this is just above the line we are indenting, and it
6700 * starts with a '{', line it up with this line.
6701 * while (not)
6702 * -> {
6703 * }
6704 */
6705 if (terminated != ',' && lookfor != LOOKFOR_TERM
6706 && theline[0] == '{')
6707 {
6708 amount = cur_amount;
6709 /*
6710 * Only add ind_open_extra when the current line
6711 * doesn't start with a '{', which must have a match
6712 * in the same line (scope is the same). Probably:
6713 * { 1, 2 },
6714 * -> { 3, 4 }
6715 */
6716 if (*skipwhite(l) != '{')
6717 amount += ind_open_extra;
6718
6719 if (ind_cpp_baseclass)
6720 {
6721 /* have to look back, whether it is a cpp base
6722 * class declaration or initialization */
6723 lookfor = LOOKFOR_CPP_BASECLASS;
6724 continue;
6725 }
6726 break;
6727 }
6728
6729 /*
6730 * Check if we are after an "if", "while", etc.
6731 * Also allow " } else".
6732 */
6733 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
6734 {
6735 /*
6736 * Found an unterminated line after an if (), line up
6737 * with the last one.
6738 * if (cond)
6739 * 100 +
6740 * -> here;
6741 */
6742 if (lookfor == LOOKFOR_UNTERM
6743 || lookfor == LOOKFOR_ENUM_OR_INIT)
6744 {
6745 if (cont_amount > 0)
6746 amount = cont_amount;
6747 else
6748 amount += ind_continuation;
6749 break;
6750 }
6751
6752 /*
6753 * If this is just above the line we are indenting, we
6754 * are finished.
6755 * while (not)
6756 * -> here;
6757 * Otherwise this indent can be used when the line
6758 * before this is terminated.
6759 * yyy;
6760 * if (stat)
6761 * while (not)
6762 * xxx;
6763 * -> here;
6764 */
6765 amount = cur_amount;
6766 if (theline[0] == '{')
6767 amount += ind_open_extra;
6768 if (lookfor != LOOKFOR_TERM)
6769 {
6770 amount += ind_level + ind_no_brace;
6771 break;
6772 }
6773
6774 /*
6775 * Special trick: when expecting the while () after a
6776 * do, line up with the while()
6777 * do
6778 * x = 1;
6779 * -> here
6780 */
6781 l = skipwhite(ml_get_curline());
6782 if (cin_isdo(l))
6783 {
6784 if (whilelevel == 0)
6785 break;
6786 --whilelevel;
6787 }
6788
6789 /*
6790 * When searching for a terminated line, don't use the
6791 * one between the "if" and the "else".
6792 * Need to use the scope of this "else". XXX
6793 * If whilelevel != 0 continue looking for a "do {".
6794 */
6795 if (cin_iselse(l)
6796 && whilelevel == 0
6797 && ((trypos = find_start_brace(ind_maxcomment))
6798 == NULL
6799 || find_match(LOOKFOR_IF, trypos->lnum,
6800 ind_maxparen, ind_maxcomment) == FAIL))
6801 break;
6802 }
6803
6804 /*
6805 * If we're below an unterminated line that is not an
6806 * "if" or something, we may line up with this line or
6807 * add someting for a continuation line, depending on
6808 * the line before this one.
6809 */
6810 else
6811 {
6812 /*
6813 * Found two unterminated lines on a row, line up with
6814 * the last one.
6815 * c = 99 +
6816 * 100 +
6817 * -> here;
6818 */
6819 if (lookfor == LOOKFOR_UNTERM)
6820 {
6821 /* When line ends in a comma add extra indent */
6822 if (terminated == ',')
6823 amount += ind_continuation;
6824 break;
6825 }
6826
6827 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6828 {
6829 /* Found two lines ending in ',', lineup with the
6830 * lowest one, but check for cpp base class
6831 * declaration/initialization, if it is an
6832 * opening brace or we are looking just for
6833 * enumerations/initializations. */
6834 if (terminated == ',')
6835 {
6836 if (ind_cpp_baseclass == 0)
6837 break;
6838
6839 lookfor = LOOKFOR_CPP_BASECLASS;
6840 continue;
6841 }
6842
6843 /* Ignore unterminated lines in between, but
6844 * reduce indent. */
6845 if (amount > cur_amount)
6846 amount = cur_amount;
6847 }
6848 else
6849 {
6850 /*
6851 * Found first unterminated line on a row, may
6852 * line up with this line, remember its indent
6853 * 100 +
6854 * -> here;
6855 */
6856 amount = cur_amount;
6857
6858 /*
6859 * If previous line ends in ',', check whether we
6860 * are in an initialization or enum
6861 * struct xxx =
6862 * {
6863 * sizeof a,
6864 * 124 };
6865 * or a normal possible continuation line.
6866 * but only, of no other statement has been found
6867 * yet.
6868 */
6869 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
6870 {
6871 lookfor = LOOKFOR_ENUM_OR_INIT;
6872 cont_amount = cin_first_id_amount();
6873 }
6874 else
6875 {
6876 if (lookfor == LOOKFOR_INITIAL
6877 && *l != NUL
6878 && l[STRLEN(l) - 1] == '\\')
6879 /* XXX */
6880 cont_amount = cin_get_equal_amount(
6881 curwin->w_cursor.lnum);
6882 if (lookfor != LOOKFOR_TERM)
6883 lookfor = LOOKFOR_UNTERM;
6884 }
6885 }
6886 }
6887 }
6888
6889 /*
6890 * Check if we are after a while (cond);
6891 * If so: Ignore until the matching "do".
6892 */
6893 /* XXX */
6894 else if (cin_iswhileofdo(l,
6895 curwin->w_cursor.lnum, ind_maxparen))
6896 {
6897 /*
6898 * Found an unterminated line after a while ();, line up
6899 * with the last one.
6900 * while (cond);
6901 * 100 + <- line up with this one
6902 * -> here;
6903 */
6904 if (lookfor == LOOKFOR_UNTERM
6905 || lookfor == LOOKFOR_ENUM_OR_INIT)
6906 {
6907 if (cont_amount > 0)
6908 amount = cont_amount;
6909 else
6910 amount += ind_continuation;
6911 break;
6912 }
6913
6914 if (whilelevel == 0)
6915 {
6916 lookfor = LOOKFOR_TERM;
6917 amount = get_indent(); /* XXX */
6918 if (theline[0] == '{')
6919 amount += ind_open_extra;
6920 }
6921 ++whilelevel;
6922 }
6923
6924 /*
6925 * We are after a "normal" statement.
6926 * If we had another statement we can stop now and use the
6927 * indent of that other statement.
6928 * Otherwise the indent of the current statement may be used,
6929 * search backwards for the next "normal" statement.
6930 */
6931 else
6932 {
6933 /*
6934 * Skip single break line, if before a switch label. It
6935 * may be lined up with the case label.
6936 */
6937 if (lookfor == LOOKFOR_NOBREAK
6938 && cin_isbreak(skipwhite(ml_get_curline())))
6939 {
6940 lookfor = LOOKFOR_ANY;
6941 continue;
6942 }
6943
6944 /*
6945 * Handle "do {" line.
6946 */
6947 if (whilelevel > 0)
6948 {
6949 l = cin_skipcomment(ml_get_curline());
6950 if (cin_isdo(l))
6951 {
6952 amount = get_indent(); /* XXX */
6953 --whilelevel;
6954 continue;
6955 }
6956 }
6957
6958 /*
6959 * Found a terminated line above an unterminated line. Add
6960 * the amount for a continuation line.
6961 * x = 1;
6962 * y = foo +
6963 * -> here;
6964 * or
6965 * int x = 1;
6966 * int foo,
6967 * -> here;
6968 */
6969 if (lookfor == LOOKFOR_UNTERM
6970 || lookfor == LOOKFOR_ENUM_OR_INIT)
6971 {
6972 if (cont_amount > 0)
6973 amount = cont_amount;
6974 else
6975 amount += ind_continuation;
6976 break;
6977 }
6978
6979 /*
6980 * Found a terminated line above a terminated line or "if"
6981 * etc. line. Use the amount of the line below us.
6982 * x = 1; x = 1;
6983 * if (asdf) y = 2;
6984 * while (asdf) ->here;
6985 * here;
6986 * ->foo;
6987 */
6988 if (lookfor == LOOKFOR_TERM)
6989 {
6990 if (!lookfor_break && whilelevel == 0)
6991 break;
6992 }
6993
6994 /*
6995 * First line above the one we're indenting is terminated.
6996 * To know what needs to be done look further backward for
6997 * a terminated line.
6998 */
6999 else
7000 {
7001 /*
7002 * position the cursor over the rightmost paren, so
7003 * that matching it will take us back to the start of
7004 * the line. Helps for:
7005 * func(asdr,
7006 * asdfasdf);
7007 * here;
7008 */
7009term_again:
7010 l = ml_get_curline();
7011 if (find_last_paren(l, '(', ')')
7012 && (trypos = find_match_paren(ind_maxparen,
7013 ind_maxcomment)) != NULL)
7014 {
7015 /*
7016 * Check if we are on a case label now. This is
7017 * handled above.
7018 * case xx: if ( asdf &&
7019 * asdf)
7020 */
7021 curwin->w_cursor.lnum = trypos->lnum;
7022 l = ml_get_curline();
7023 if (cin_iscase(l) || cin_isscopedecl(l))
7024 {
7025 ++curwin->w_cursor.lnum;
7026 continue;
7027 }
7028 }
7029
7030 /* When aligning with the case statement, don't align
7031 * with a statement after it.
7032 * case 1: { <-- don't use this { position
7033 * stat;
7034 * }
7035 * case 2:
7036 * stat;
7037 * }
7038 */
7039 iscase = (ind_keep_case_label && cin_iscase(l));
7040
7041 /*
7042 * Get indent and pointer to text for current line,
7043 * ignoring any jump label.
7044 */
7045 amount = skip_label(curwin->w_cursor.lnum,
7046 &l, ind_maxcomment);
7047
7048 if (theline[0] == '{')
7049 amount += ind_open_extra;
7050 /* See remark above: "Only add ind_open_extra.." */
7051 if (*skipwhite(l) == '{')
7052 amount -= ind_open_extra;
7053 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7054
7055 /*
7056 * If we're at the end of a block, skip to the start of
7057 * that block.
7058 */
7059 curwin->w_cursor.col = 0;
7060 if (*cin_skipcomment(l) == '}'
7061 && (trypos = find_start_brace(ind_maxcomment))
7062 != NULL) /* XXX */
7063 {
7064 curwin->w_cursor.lnum = trypos->lnum;
7065 /* if not "else {" check for terminated again */
7066 /* but skip block for "} else {" */
7067 l = cin_skipcomment(ml_get_curline());
7068 if (*l == '}' || !cin_iselse(l))
7069 goto term_again;
7070 ++curwin->w_cursor.lnum;
7071 }
7072 }
7073 }
7074 }
7075 }
7076 }
7077
7078 /* add extra indent for a comment */
7079 if (cin_iscomment(theline))
7080 amount += ind_comment;
7081 }
7082
7083 /*
7084 * ok -- we're not inside any sort of structure at all!
7085 *
7086 * this means we're at the top level, and everything should
7087 * basically just match where the previous line is, except
7088 * for the lines immediately following a function declaration,
7089 * which are K&R-style parameters and need to be indented.
7090 */
7091 else
7092 {
7093 /*
7094 * if our line starts with an open brace, forget about any
7095 * prevailing indent and make sure it looks like the start
7096 * of a function
7097 */
7098
7099 if (theline[0] == '{')
7100 {
7101 amount = ind_first_open;
7102 }
7103
7104 /*
7105 * If the NEXT line is a function declaration, the current
7106 * line needs to be indented as a function type spec.
7107 * Don't do this if the current line looks like a comment
7108 * or if the current line is terminated, ie. ends in ';'.
7109 */
7110 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7111 && !cin_nocode(theline)
7112 && !cin_ends_in(theline, (char_u *)":", NULL)
7113 && !cin_ends_in(theline, (char_u *)",", NULL)
7114 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7115 && !cin_isterminated(theline, FALSE, TRUE))
7116 {
7117 amount = ind_func_type;
7118 }
7119 else
7120 {
7121 amount = 0;
7122 curwin->w_cursor = cur_curpos;
7123
7124 /* search backwards until we find something we recognize */
7125
7126 while (curwin->w_cursor.lnum > 1)
7127 {
7128 curwin->w_cursor.lnum--;
7129 curwin->w_cursor.col = 0;
7130
7131 l = ml_get_curline();
7132
7133 /*
7134 * If we're in a comment now, skip to the start of the comment.
7135 */ /* XXX */
7136 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7137 {
7138 curwin->w_cursor.lnum = trypos->lnum + 1;
7139 continue;
7140 }
7141
7142 /*
7143 * Are we at the start of a cpp base class declaration or constructor
7144 * initialization?
7145 */ /* XXX */
7146 if (ind_cpp_baseclass != 0 && theline[0] != '{'
7147 && cin_is_cpp_baseclass(l, &col))
7148 {
7149 if (col == 0)
7150 {
7151 amount = get_indent() + ind_cpp_baseclass; /* XXX */
7152 if (find_last_paren(l, '(', ')')
7153 && (trypos = find_match_paren(ind_maxparen,
7154 ind_maxcomment)) != NULL)
7155 amount = get_indent_lnum(trypos->lnum)
7156 + ind_cpp_baseclass; /* XXX */
7157 }
7158 else
7159 {
7160 curwin->w_cursor.col = col;
7161 getvcol(curwin, &curwin->w_cursor, &col, NULL, NULL);
7162 amount = (int)col;
7163 }
7164 break;
7165 }
7166
7167 /*
7168 * Skip preprocessor directives and blank lines.
7169 */
7170 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7171 continue;
7172
7173 if (cin_nocode(l))
7174 continue;
7175
7176 /*
7177 * If the previous line ends in ',', use one level of
7178 * indentation:
7179 * int foo,
7180 * bar;
7181 * do this before checking for '}' in case of eg.
7182 * enum foobar
7183 * {
7184 * ...
7185 * } foo,
7186 * bar;
7187 */
7188 n = 0;
7189 if (cin_ends_in(l, (char_u *)",", NULL)
7190 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7191 {
7192 /* take us back to opening paren */
7193 if (find_last_paren(l, '(', ')')
7194 && (trypos = find_match_paren(ind_maxparen,
7195 ind_maxcomment)) != NULL)
7196 curwin->w_cursor.lnum = trypos->lnum;
7197
7198 /* For a line ending in ',' that is a continuation line go
7199 * back to the first line with a backslash:
7200 * char *foo = "bla\
7201 * bla",
7202 * here;
7203 */
7204 while (n == 0 && curwin->w_cursor.lnum > 1)
7205 {
7206 l = ml_get(curwin->w_cursor.lnum - 1);
7207 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7208 break;
7209 --curwin->w_cursor.lnum;
7210 }
7211
7212 amount = get_indent(); /* XXX */
7213
7214 if (amount == 0)
7215 amount = cin_first_id_amount();
7216 if (amount == 0)
7217 amount = ind_continuation;
7218 break;
7219 }
7220
7221 /*
7222 * If the line looks like a function declaration, and we're
7223 * not in a comment, put it the left margin.
7224 */
7225 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7226 break;
7227 l = ml_get_curline();
7228
7229 /*
7230 * Finding the closing '}' of a previous function. Put
7231 * current line at the left margin. For when 'cino' has "fs".
7232 */
7233 if (*skipwhite(l) == '}')
7234 break;
7235
7236 /* (matching {)
7237 * If the previous line ends on '};' (maybe followed by
7238 * comments) align at column 0. For example:
7239 * char *string_array[] = { "foo",
7240 * / * x * / "b};ar" }; / * foobar * /
7241 */
7242 if (cin_ends_in(l, (char_u *)"};", NULL))
7243 break;
7244
7245 /*
7246 * If the PREVIOUS line is a function declaration, the current
7247 * line (and the ones that follow) needs to be indented as
7248 * parameters.
7249 */
7250 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7251 {
7252 amount = ind_param;
7253 break;
7254 }
7255
7256 /*
7257 * If the previous line ends in ';' and the line before the
7258 * previous line ends in ',' or '\', ident to column zero:
7259 * int foo,
7260 * bar;
7261 * indent_to_0 here;
7262 */
7263 if (cin_ends_in(l, (char_u*)";", NULL))
7264 {
7265 l = ml_get(curwin->w_cursor.lnum - 1);
7266 if (cin_ends_in(l, (char_u *)",", NULL)
7267 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7268 break;
7269 l = ml_get_curline();
7270 }
7271
7272 /*
7273 * Doesn't look like anything interesting -- so just
7274 * use the indent of this line.
7275 *
7276 * Position the cursor over the rightmost paren, so that
7277 * matching it will take us back to the start of the line.
7278 */
7279 find_last_paren(l, '(', ')');
7280
7281 if ((trypos = find_match_paren(ind_maxparen,
7282 ind_maxcomment)) != NULL)
7283 curwin->w_cursor.lnum = trypos->lnum;
7284 amount = get_indent(); /* XXX */
7285 break;
7286 }
7287
7288 /* add extra indent for a comment */
7289 if (cin_iscomment(theline))
7290 amount += ind_comment;
7291
7292 /* add extra indent if the previous line ended in a backslash:
7293 * "asdfasdf\
7294 * here";
7295 * char *foo = "asdf\
7296 * here";
7297 */
7298 if (cur_curpos.lnum > 1)
7299 {
7300 l = ml_get(cur_curpos.lnum - 1);
7301 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7302 {
7303 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7304 if (cur_amount > 0)
7305 amount = cur_amount;
7306 else if (cur_amount == 0)
7307 amount += ind_continuation;
7308 }
7309 }
7310 }
7311 }
7312
7313theend:
7314 /* put the cursor back where it belongs */
7315 curwin->w_cursor = cur_curpos;
7316
7317 vim_free(linecopy);
7318
7319 if (amount < 0)
7320 return 0;
7321 return amount;
7322}
7323
7324 static int
7325find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7326 int lookfor;
7327 linenr_T ourscope;
7328 int ind_maxparen;
7329 int ind_maxcomment;
7330{
7331 char_u *look;
7332 pos_T *theirscope;
7333 char_u *mightbeif;
7334 int elselevel;
7335 int whilelevel;
7336
7337 if (lookfor == LOOKFOR_IF)
7338 {
7339 elselevel = 1;
7340 whilelevel = 0;
7341 }
7342 else
7343 {
7344 elselevel = 0;
7345 whilelevel = 1;
7346 }
7347
7348 curwin->w_cursor.col = 0;
7349
7350 while (curwin->w_cursor.lnum > ourscope + 1)
7351 {
7352 curwin->w_cursor.lnum--;
7353 curwin->w_cursor.col = 0;
7354
7355 look = cin_skipcomment(ml_get_curline());
7356 if (cin_iselse(look)
7357 || cin_isif(look)
7358 || cin_isdo(look) /* XXX */
7359 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7360 {
7361 /*
7362 * if we've gone outside the braces entirely,
7363 * we must be out of scope...
7364 */
7365 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7366 if (theirscope == NULL)
7367 break;
7368
7369 /*
7370 * and if the brace enclosing this is further
7371 * back than the one enclosing the else, we're
7372 * out of luck too.
7373 */
7374 if (theirscope->lnum < ourscope)
7375 break;
7376
7377 /*
7378 * and if they're enclosed in a *deeper* brace,
7379 * then we can ignore it because it's in a
7380 * different scope...
7381 */
7382 if (theirscope->lnum > ourscope)
7383 continue;
7384
7385 /*
7386 * if it was an "else" (that's not an "else if")
7387 * then we need to go back to another if, so
7388 * increment elselevel
7389 */
7390 look = cin_skipcomment(ml_get_curline());
7391 if (cin_iselse(look))
7392 {
7393 mightbeif = cin_skipcomment(look + 4);
7394 if (!cin_isif(mightbeif))
7395 ++elselevel;
7396 continue;
7397 }
7398
7399 /*
7400 * if it was a "while" then we need to go back to
7401 * another "do", so increment whilelevel. XXX
7402 */
7403 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7404 {
7405 ++whilelevel;
7406 continue;
7407 }
7408
7409 /* If it's an "if" decrement elselevel */
7410 look = cin_skipcomment(ml_get_curline());
7411 if (cin_isif(look))
7412 {
7413 elselevel--;
7414 /*
7415 * When looking for an "if" ignore "while"s that
7416 * get in the way.
7417 */
7418 if (elselevel == 0 && lookfor == LOOKFOR_IF)
7419 whilelevel = 0;
7420 }
7421
7422 /* If it's a "do" decrement whilelevel */
7423 if (cin_isdo(look))
7424 whilelevel--;
7425
7426 /*
7427 * if we've used up all the elses, then
7428 * this must be the if that we want!
7429 * match the indent level of that if.
7430 */
7431 if (elselevel <= 0 && whilelevel <= 0)
7432 {
7433 return OK;
7434 }
7435 }
7436 }
7437 return FAIL;
7438}
7439
7440# if defined(FEAT_EVAL) || defined(PROTO)
7441/*
7442 * Get indent level from 'indentexpr'.
7443 */
7444 int
7445get_expr_indent()
7446{
7447 int indent;
7448 pos_T pos;
7449 int save_State;
7450
7451 pos = curwin->w_cursor;
7452 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
7453 ++sandbox;
7454 indent = eval_to_number(curbuf->b_p_inde);
7455 --sandbox;
7456
7457 /* Restore the cursor position so that 'indentexpr' doesn't need to.
7458 * Pretend to be in Insert mode, allow cursor past end of line for "o"
7459 * command. */
7460 save_State = State;
7461 State = INSERT;
7462 curwin->w_cursor = pos;
7463 check_cursor();
7464 State = save_State;
7465
7466 /* If there is an error, just keep the current indent. */
7467 if (indent < 0)
7468 indent = get_indent();
7469
7470 return indent;
7471}
7472# endif
7473
7474#endif /* FEAT_CINDENT */
7475
7476#if defined(FEAT_LISP) || defined(PROTO)
7477
7478static int lisp_match __ARGS((char_u *p));
7479
7480 static int
7481lisp_match(p)
7482 char_u *p;
7483{
7484 char_u buf[LSIZE];
7485 int len;
7486 char_u *word = p_lispwords;
7487
7488 while (*word != NUL)
7489 {
7490 (void)copy_option_part(&word, buf, LSIZE, ",");
7491 len = (int)STRLEN(buf);
7492 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
7493 return TRUE;
7494 }
7495 return FALSE;
7496}
7497
7498/*
7499 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
7500 * The incompatible newer method is quite a bit better at indenting
7501 * code in lisp-like languages than the traditional one; it's still
7502 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
7503 *
7504 * TODO:
7505 * Findmatch() should be adapted for lisp, also to make showmatch
7506 * work correctly: now (v5.3) it seems all C/C++ oriented:
7507 * - it does not recognize the #\( and #\) notations as character literals
7508 * - it doesn't know about comments starting with a semicolon
7509 * - it incorrectly interprets '(' as a character literal
7510 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007511 * Update from Sergey Khorev:
7512 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513 */
7514 int
7515get_lisp_indent()
7516{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007517 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007518 int amount;
7519 char_u *that;
7520 colnr_T col;
7521 colnr_T firsttry;
7522 int parencount, quotecount;
7523 int vi_lisp;
7524
7525 /* Set vi_lisp to use the vi-compatible method */
7526 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
7527
7528 realpos = curwin->w_cursor;
7529 curwin->w_cursor.col = 0;
7530
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007531 if ((pos = findmatch(NULL, '(')) == NULL)
7532 pos = findmatch(NULL, '[');
7533 else
7534 {
7535 paren = *pos;
7536 pos = findmatch(NULL, '[');
7537 if (pos == NULL || ltp(pos, &paren))
7538 pos = &paren;
7539 }
7540 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541 {
7542 /* Extra trick: Take the indent of the first previous non-white
7543 * line that is at the same () level. */
7544 amount = -1;
7545 parencount = 0;
7546
7547 while (--curwin->w_cursor.lnum >= pos->lnum)
7548 {
7549 if (linewhite(curwin->w_cursor.lnum))
7550 continue;
7551 for (that = ml_get_curline(); *that != NUL; ++that)
7552 {
7553 if (*that == ';')
7554 {
7555 while (*(that + 1) != NUL)
7556 ++that;
7557 continue;
7558 }
7559 if (*that == '\\')
7560 {
7561 if (*(that + 1) != NUL)
7562 ++that;
7563 continue;
7564 }
7565 if (*that == '"' && *(that + 1) != NUL)
7566 {
7567 that++;
7568 while (*that && (*that != '"' || *(that - 1) == '\\'))
7569 ++that;
7570 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007571 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007572 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007573 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007574 --parencount;
7575 }
7576 if (parencount == 0)
7577 {
7578 amount = get_indent();
7579 break;
7580 }
7581 }
7582
7583 if (amount == -1)
7584 {
7585 curwin->w_cursor.lnum = pos->lnum;
7586 curwin->w_cursor.col = pos->col;
7587 col = pos->col;
7588
7589 that = ml_get_curline();
7590
7591 if (vi_lisp && get_indent() == 0)
7592 amount = 2;
7593 else
7594 {
7595 amount = 0;
7596 while (*that && col)
7597 {
7598 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
7599 col--;
7600 }
7601
7602 /*
7603 * Some keywords require "body" indenting rules (the
7604 * non-standard-lisp ones are Scheme special forms):
7605 *
7606 * (let ((a 1)) instead (let ((a 1))
7607 * (...)) of (...))
7608 */
7609
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007610 if (!vi_lisp && (*that == '(' || *that == '[')
7611 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007612 amount += 2;
7613 else
7614 {
7615 that++;
7616 amount++;
7617 firsttry = amount;
7618
7619 while (vim_iswhite(*that))
7620 {
7621 amount += lbr_chartabsize(that, (colnr_T)amount);
7622 ++that;
7623 }
7624
7625 if (*that && *that != ';') /* not a comment line */
7626 {
7627 /* test *that != '(' to accomodate first let/do
7628 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007629 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007630 firsttry++;
7631
7632 parencount = 0;
7633 quotecount = 0;
7634
7635 if (vi_lisp
7636 || (*that != '"'
7637 && *that != '\''
7638 && *that != '#'
7639 && (*that < '0' || *that > '9')))
7640 {
7641 while (*that
7642 && (!vim_iswhite(*that)
7643 || quotecount
7644 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007645 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007646 && !quotecount
7647 && !parencount
7648 && vi_lisp)))
7649 {
7650 if (*that == '"')
7651 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007652 if ((*that == '(' || *that == '[')
7653 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007654 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007655 if ((*that == ')' || *that == ']')
7656 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007657 --parencount;
7658 if (*that == '\\' && *(that+1) != NUL)
7659 amount += lbr_chartabsize_adv(&that,
7660 (colnr_T)amount);
7661 amount += lbr_chartabsize_adv(&that,
7662 (colnr_T)amount);
7663 }
7664 }
7665 while (vim_iswhite(*that))
7666 {
7667 amount += lbr_chartabsize(that, (colnr_T)amount);
7668 that++;
7669 }
7670 if (!*that || *that == ';')
7671 amount = firsttry;
7672 }
7673 }
7674 }
7675 }
7676 }
7677 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00007678 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007679
7680 curwin->w_cursor = realpos;
7681
7682 return amount;
7683}
7684#endif /* FEAT_LISP */
7685
7686 void
7687prepare_to_exit()
7688{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007689#if defined(SIGHUP) && defined(SIG_IGN)
7690 /* Ignore SIGHUP, because a dropped connection causes a read error, which
7691 * makes Vim exit and then handling SIGHUP causes various reentrance
7692 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00007693 signal(SIGHUP, SIG_IGN);
7694#endif
7695
Bram Moolenaar071d4272004-06-13 20:20:40 +00007696#ifdef FEAT_GUI
7697 if (gui.in_use)
7698 {
7699 gui.dying = TRUE;
7700 out_trash(); /* trash any pending output */
7701 }
7702 else
7703#endif
7704 {
7705 windgoto((int)Rows - 1, 0);
7706
7707 /*
7708 * Switch terminal mode back now, so messages end up on the "normal"
7709 * screen (if there are two screens).
7710 */
7711 settmode(TMODE_COOK);
7712#ifdef WIN3264
7713 if (can_end_termcap_mode(FALSE) == TRUE)
7714#endif
7715 stoptermcap();
7716 out_flush();
7717 }
7718}
7719
7720/*
7721 * Preserve files and exit.
7722 * When called IObuff must contain a message.
7723 */
7724 void
7725preserve_exit()
7726{
7727 buf_T *buf;
7728
7729 prepare_to_exit();
7730
7731 out_str(IObuff);
7732 screen_start(); /* don't know where cursor is now */
7733 out_flush();
7734
7735 ml_close_notmod(); /* close all not-modified buffers */
7736
7737 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
7738 {
7739 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
7740 {
7741 OUT_STR(_("Vim: preserving files...\n"));
7742 screen_start(); /* don't know where cursor is now */
7743 out_flush();
7744 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
7745 break;
7746 }
7747 }
7748
7749 ml_close_all(FALSE); /* close all memfiles, without deleting */
7750
7751 OUT_STR(_("Vim: Finished.\n"));
7752
7753 getout(1);
7754}
7755
7756/*
7757 * return TRUE if "fname" exists.
7758 */
7759 int
7760vim_fexists(fname)
7761 char_u *fname;
7762{
7763 struct stat st;
7764
7765 if (mch_stat((char *)fname, &st))
7766 return FALSE;
7767 return TRUE;
7768}
7769
7770/*
7771 * Check for CTRL-C pressed, but only once in a while.
7772 * Should be used instead of ui_breakcheck() for functions that check for
7773 * each line in the file. Calling ui_breakcheck() each time takes too much
7774 * time, because it can be a system call.
7775 */
7776
7777#ifndef BREAKCHECK_SKIP
7778# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
7779# define BREAKCHECK_SKIP 200
7780# else
7781# define BREAKCHECK_SKIP 32
7782# endif
7783#endif
7784
7785static int breakcheck_count = 0;
7786
7787 void
7788line_breakcheck()
7789{
7790 if (++breakcheck_count >= BREAKCHECK_SKIP)
7791 {
7792 breakcheck_count = 0;
7793 ui_breakcheck();
7794 }
7795}
7796
7797/*
7798 * Like line_breakcheck() but check 10 times less often.
7799 */
7800 void
7801fast_breakcheck()
7802{
7803 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
7804 {
7805 breakcheck_count = 0;
7806 ui_breakcheck();
7807 }
7808}
7809
7810/*
7811 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
7812 * 'wildignore'.
7813 */
7814 int
7815expand_wildcards(num_pat, pat, num_file, file, flags)
7816 int num_pat; /* number of input patterns */
7817 char_u **pat; /* array of input patterns */
7818 int *num_file; /* resulting number of files */
7819 char_u ***file; /* array of resulting files */
7820 int flags; /* EW_DIR, etc. */
7821{
7822 int retval;
7823 int i, j;
7824 char_u *p;
7825 int non_suf_match; /* number without matching suffix */
7826
7827 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
7828
7829 /* When keeping all matches, return here */
7830 if (flags & EW_KEEPALL)
7831 return retval;
7832
7833#ifdef FEAT_WILDIGN
7834 /*
7835 * Remove names that match 'wildignore'.
7836 */
7837 if (*p_wig)
7838 {
7839 char_u *ffname;
7840
7841 /* check all files in (*file)[] */
7842 for (i = 0; i < *num_file; ++i)
7843 {
7844 ffname = FullName_save((*file)[i], FALSE);
7845 if (ffname == NULL) /* out of memory */
7846 break;
7847# ifdef VMS
7848 vms_remove_version(ffname);
7849# endif
7850 if (match_file_list(p_wig, (*file)[i], ffname))
7851 {
7852 /* remove this matching file from the list */
7853 vim_free((*file)[i]);
7854 for (j = i; j + 1 < *num_file; ++j)
7855 (*file)[j] = (*file)[j + 1];
7856 --*num_file;
7857 --i;
7858 }
7859 vim_free(ffname);
7860 }
7861 }
7862#endif
7863
7864 /*
7865 * Move the names where 'suffixes' match to the end.
7866 */
7867 if (*num_file > 1)
7868 {
7869 non_suf_match = 0;
7870 for (i = 0; i < *num_file; ++i)
7871 {
7872 if (!match_suffix((*file)[i]))
7873 {
7874 /*
7875 * Move the name without matching suffix to the front
7876 * of the list.
7877 */
7878 p = (*file)[i];
7879 for (j = i; j > non_suf_match; --j)
7880 (*file)[j] = (*file)[j - 1];
7881 (*file)[non_suf_match++] = p;
7882 }
7883 }
7884 }
7885
7886 return retval;
7887}
7888
7889/*
7890 * Return TRUE if "fname" matches with an entry in 'suffixes'.
7891 */
7892 int
7893match_suffix(fname)
7894 char_u *fname;
7895{
7896 int fnamelen, setsuflen;
7897 char_u *setsuf;
7898#define MAXSUFLEN 30 /* maximum length of a file suffix */
7899 char_u suf_buf[MAXSUFLEN];
7900
7901 fnamelen = (int)STRLEN(fname);
7902 setsuflen = 0;
7903 for (setsuf = p_su; *setsuf; )
7904 {
7905 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
7906 if (fnamelen >= setsuflen
7907 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
7908 (size_t)setsuflen) == 0)
7909 break;
7910 setsuflen = 0;
7911 }
7912 return (setsuflen != 0);
7913}
7914
7915#if !defined(NO_EXPANDPATH) || defined(PROTO)
7916
7917# ifdef VIM_BACKTICK
7918static int vim_backtick __ARGS((char_u *p));
7919static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
7920# endif
7921
7922# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
7923/*
7924 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
7925 * it's shared between these systems.
7926 */
7927# if defined(DJGPP) || defined(PROTO)
7928# define _cdecl /* DJGPP doesn't have this */
7929# else
7930# ifdef __BORLANDC__
7931# define _cdecl _RTLENTRYF
7932# endif
7933# endif
7934
7935/*
7936 * comparison function for qsort in dos_expandpath()
7937 */
7938 static int _cdecl
7939pstrcmp(const void *a, const void *b)
7940{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007941 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007942}
7943
7944# ifndef WIN3264
7945 static void
7946namelowcpy(
7947 char_u *d,
7948 char_u *s)
7949{
7950# ifdef DJGPP
7951 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
7952 while (*s)
7953 *d++ = *s++;
7954 else
7955# endif
7956 while (*s)
7957 *d++ = TOLOWER_LOC(*s++);
7958 *d = NUL;
7959}
7960# endif
7961
7962/*
7963 * Recursively build up a list of files in "gap" matching the first wildcard
7964 * in `path'. Called by expand_wildcards().
7965 * Return the number of matches found.
7966 * "path" has backslashes before chars that are not to be expanded, starting
7967 * at "path[wildoff]".
7968 */
7969 static int
7970dos_expandpath(
7971 garray_T *gap,
7972 char_u *path,
7973 int wildoff,
7974 int flags) /* EW_* flags */
7975{
7976 char_u *buf;
7977 char_u *path_end;
7978 char_u *p, *s, *e;
7979 int start_len = gap->ga_len;
7980 int ok;
7981#ifdef WIN3264
7982 WIN32_FIND_DATA fb;
7983 HANDLE hFind = (HANDLE)0;
7984# ifdef FEAT_MBYTE
7985 WIN32_FIND_DATAW wfb;
7986 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
7987# endif
7988#else
7989 struct ffblk fb;
7990#endif
7991 int matches;
7992 int starts_with_dot;
7993 int len;
7994 char_u *pat;
7995 regmatch_T regmatch;
7996 char_u *matchname;
7997
7998 /* make room for file name */
7999 buf = alloc((unsigned int)STRLEN(path) + BASENAMELEN + 5);
8000 if (buf == NULL)
8001 return 0;
8002
8003 /*
8004 * Find the first part in the path name that contains a wildcard or a ~1.
8005 * Copy it into buf, including the preceding characters.
8006 */
8007 p = buf;
8008 s = buf;
8009 e = NULL;
8010 path_end = path;
8011 while (*path_end != NUL)
8012 {
8013 /* May ignore a wildcard that has a backslash before it; it will
8014 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8015 if (path_end >= path + wildoff && rem_backslash(path_end))
8016 *p++ = *path_end++;
8017 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8018 {
8019 if (e != NULL)
8020 break;
8021 s = p + 1;
8022 }
8023 else if (path_end >= path + wildoff
8024 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8025 e = p;
8026#ifdef FEAT_MBYTE
8027 if (has_mbyte)
8028 {
8029 len = (*mb_ptr2len_check)(path_end);
8030 STRNCPY(p, path_end, len);
8031 p += len;
8032 path_end += len;
8033 }
8034 else
8035#endif
8036 *p++ = *path_end++;
8037 }
8038 e = p;
8039 *e = NUL;
8040
8041 /* now we have one wildcard component between s and e */
8042 /* Remove backslashes between "wildoff" and the start of the wildcard
8043 * component. */
8044 for (p = buf + wildoff; p < s; ++p)
8045 if (rem_backslash(p))
8046 {
8047 STRCPY(p, p + 1);
8048 --e;
8049 --s;
8050 }
8051
8052 starts_with_dot = (*s == '.');
8053 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8054 if (pat == NULL)
8055 {
8056 vim_free(buf);
8057 return 0;
8058 }
8059
8060 /* compile the regexp into a program */
8061 regmatch.rm_ic = TRUE; /* Always ignore case */
8062 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8063 vim_free(pat);
8064
8065 if (regmatch.regprog == NULL)
8066 {
8067 vim_free(buf);
8068 return 0;
8069 }
8070
8071 /* remember the pattern or file name being looked for */
8072 matchname = vim_strsave(s);
8073
8074 /* Scan all files in the directory with "dir/ *.*" */
8075 STRCPY(s, "*.*");
8076#ifdef WIN3264
8077# ifdef FEAT_MBYTE
8078 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8079 {
8080 /* The active codepage differs from 'encoding'. Attempt using the
8081 * wide function. If it fails because it is not implemented fall back
8082 * to the non-wide version (for Windows 98) */
8083 wn = enc_to_ucs2(buf, NULL);
8084 if (wn != NULL)
8085 {
8086 hFind = FindFirstFileW(wn, &wfb);
8087 if (hFind == INVALID_HANDLE_VALUE
8088 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8089 {
8090 vim_free(wn);
8091 wn = NULL;
8092 }
8093 }
8094 }
8095
8096 if (wn == NULL)
8097# endif
8098 hFind = FindFirstFile(buf, &fb);
8099 ok = (hFind != INVALID_HANDLE_VALUE);
8100#else
8101 /* If we are expanding wildcards we try both files and directories */
8102 ok = (findfirst((char *)buf, &fb,
8103 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8104#endif
8105
8106 while (ok)
8107 {
8108#ifdef WIN3264
8109# ifdef FEAT_MBYTE
8110 if (wn != NULL)
8111 p = ucs2_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8112 else
8113# endif
8114 p = (char_u *)fb.cFileName;
8115#else
8116 p = (char_u *)fb.ff_name;
8117#endif
8118 /* Ignore entries starting with a dot, unless when asked for. Accept
8119 * all entries found with "matchname". */
8120 if ((p[0] != '.' || starts_with_dot)
8121 && (matchname == NULL
8122 || vim_regexec(&regmatch, p, (colnr_T)0)))
8123 {
8124#ifdef WIN3264
8125 STRCPY(s, p);
8126#else
8127 namelowcpy(s, p);
8128#endif
8129 len = (int)STRLEN(buf);
8130 STRCPY(buf + len, path_end);
8131 if (mch_has_exp_wildcard(path_end))
8132 {
8133 /* need to expand another component of the path */
8134 /* remove backslashes for the remaining components only */
8135 (void)dos_expandpath(gap, buf, len + 1, flags);
8136 }
8137 else
8138 {
8139 /* no more wildcards, check if there is a match */
8140 /* remove backslashes for the remaining components only */
8141 if (*path_end != 0)
8142 backslash_halve(buf + len + 1);
8143 if (mch_getperm(buf) >= 0) /* add existing file */
8144 addfile(gap, buf, flags);
8145 }
8146 }
8147
8148#ifdef WIN3264
8149# ifdef FEAT_MBYTE
8150 if (wn != NULL)
8151 {
8152 vim_free(p);
8153 ok = FindNextFileW(hFind, &wfb);
8154 }
8155 else
8156# endif
8157 ok = FindNextFile(hFind, &fb);
8158#else
8159 ok = (findnext(&fb) == 0);
8160#endif
8161
8162 /* If no more matches and no match was used, try expanding the name
8163 * itself. Finds the long name of a short filename. */
8164 if (!ok && matchname != NULL && gap->ga_len == start_len)
8165 {
8166 STRCPY(s, matchname);
8167#ifdef WIN3264
8168 FindClose(hFind);
8169# ifdef FEAT_MBYTE
8170 if (wn != NULL)
8171 {
8172 vim_free(wn);
8173 wn = enc_to_ucs2(buf, NULL);
8174 if (wn != NULL)
8175 hFind = FindFirstFileW(wn, &wfb);
8176 }
8177 if (wn == NULL)
8178# endif
8179 hFind = FindFirstFile(buf, &fb);
8180 ok = (hFind != INVALID_HANDLE_VALUE);
8181#else
8182 ok = (findfirst((char *)buf, &fb,
8183 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8184#endif
8185 vim_free(matchname);
8186 matchname = NULL;
8187 }
8188 }
8189
8190#ifdef WIN3264
8191 FindClose(hFind);
8192# ifdef FEAT_MBYTE
8193 vim_free(wn);
8194# endif
8195#endif
8196 vim_free(buf);
8197 vim_free(regmatch.regprog);
8198 vim_free(matchname);
8199
8200 matches = gap->ga_len - start_len;
8201 if (matches > 0)
8202 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8203 sizeof(char_u *), pstrcmp);
8204 return matches;
8205}
8206
8207 int
8208mch_expandpath(
8209 garray_T *gap,
8210 char_u *path,
8211 int flags) /* EW_* flags */
8212{
8213 return dos_expandpath(gap, path, 0, flags);
8214}
8215# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8216
8217/*
8218 * Generic wildcard expansion code.
8219 *
8220 * Characters in "pat" that should not be expanded must be preceded with a
8221 * backslash. E.g., "/path\ with\ spaces/my\*star*"
8222 *
8223 * Return FAIL when no single file was found. In this case "num_file" is not
8224 * set, and "file" may contain an error message.
8225 * Return OK when some files found. "num_file" is set to the number of
8226 * matches, "file" to the array of matches. Call FreeWild() later.
8227 */
8228 int
8229gen_expand_wildcards(num_pat, pat, num_file, file, flags)
8230 int num_pat; /* number of input patterns */
8231 char_u **pat; /* array of input patterns */
8232 int *num_file; /* resulting number of files */
8233 char_u ***file; /* array of resulting files */
8234 int flags; /* EW_* flags */
8235{
8236 int i;
8237 garray_T ga;
8238 char_u *p;
8239 static int recursive = FALSE;
8240 int add_pat;
8241
8242 /*
8243 * expand_env() is called to expand things like "~user". If this fails,
8244 * it calls ExpandOne(), which brings us back here. In this case, always
8245 * call the machine specific expansion function, if possible. Otherwise,
8246 * return FAIL.
8247 */
8248 if (recursive)
8249#ifdef SPECIAL_WILDCHAR
8250 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
8251#else
8252 return FAIL;
8253#endif
8254
8255#ifdef SPECIAL_WILDCHAR
8256 /*
8257 * If there are any special wildcard characters which we cannot handle
8258 * here, call machine specific function for all the expansion. This
8259 * avoids starting the shell for each argument separately.
8260 * For `=expr` do use the internal function.
8261 */
8262 for (i = 0; i < num_pat; i++)
8263 {
8264 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
8265# ifdef VIM_BACKTICK
8266 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
8267# endif
8268 )
8269 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
8270 }
8271#endif
8272
8273 recursive = TRUE;
8274
8275 /*
8276 * The matching file names are stored in a growarray. Init it empty.
8277 */
8278 ga_init2(&ga, (int)sizeof(char_u *), 30);
8279
8280 for (i = 0; i < num_pat; ++i)
8281 {
8282 add_pat = -1;
8283 p = pat[i];
8284
8285#ifdef VIM_BACKTICK
8286 if (vim_backtick(p))
8287 add_pat = expand_backtick(&ga, p, flags);
8288 else
8289#endif
8290 {
8291 /*
8292 * First expand environment variables, "~/" and "~user/".
8293 */
8294 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
8295 {
8296 p = expand_env_save(p);
8297 if (p == NULL)
8298 p = pat[i];
8299#ifdef UNIX
8300 /*
8301 * On Unix, if expand_env() can't expand an environment
8302 * variable, use the shell to do that. Discard previously
8303 * found file names and start all over again.
8304 */
8305 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
8306 {
8307 vim_free(p);
8308 ga_clear(&ga);
8309 i = mch_expand_wildcards(num_pat, pat, num_file, file,
8310 flags);
8311 recursive = FALSE;
8312 return i;
8313 }
8314#endif
8315 }
8316
8317 /*
8318 * If there are wildcards: Expand file names and add each match to
8319 * the list. If there is no match, and EW_NOTFOUND is given, add
8320 * the pattern.
8321 * If there are no wildcards: Add the file name if it exists or
8322 * when EW_NOTFOUND is given.
8323 */
8324 if (mch_has_exp_wildcard(p))
8325 add_pat = mch_expandpath(&ga, p, flags);
8326 }
8327
8328 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
8329 {
8330 char_u *t = backslash_halve_save(p);
8331
8332#if defined(MACOS_CLASSIC)
8333 slash_to_colon(t);
8334#endif
8335 /* When EW_NOTFOUND is used, always add files and dirs. Makes
8336 * "vim c:/" work. */
8337 if (flags & EW_NOTFOUND)
8338 addfile(&ga, t, flags | EW_DIR | EW_FILE);
8339 else if (mch_getperm(t) >= 0)
8340 addfile(&ga, t, flags);
8341 vim_free(t);
8342 }
8343
8344 if (p != pat[i])
8345 vim_free(p);
8346 }
8347
8348 *num_file = ga.ga_len;
8349 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
8350
8351 recursive = FALSE;
8352
8353 return (ga.ga_data != NULL) ? OK : FAIL;
8354}
8355
8356# ifdef VIM_BACKTICK
8357
8358/*
8359 * Return TRUE if we can expand this backtick thing here.
8360 */
8361 static int
8362vim_backtick(p)
8363 char_u *p;
8364{
8365 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
8366}
8367
8368/*
8369 * Expand an item in `backticks` by executing it as a command.
8370 * Currently only works when pat[] starts and ends with a `.
8371 * Returns number of file names found.
8372 */
8373 static int
8374expand_backtick(gap, pat, flags)
8375 garray_T *gap;
8376 char_u *pat;
8377 int flags; /* EW_* flags */
8378{
8379 char_u *p;
8380 char_u *cmd;
8381 char_u *buffer;
8382 int cnt = 0;
8383 int i;
8384
8385 /* Create the command: lop off the backticks. */
8386 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
8387 if (cmd == NULL)
8388 return 0;
8389
8390#ifdef FEAT_EVAL
8391 if (*cmd == '=') /* `={expr}`: Expand expression */
8392 buffer = eval_to_string(cmd + 1, &p);
8393 else
8394#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008395 buffer = get_cmd_output(cmd, NULL,
8396 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008397 vim_free(cmd);
8398 if (buffer == NULL)
8399 return 0;
8400
8401 cmd = buffer;
8402 while (*cmd != NUL)
8403 {
8404 cmd = skipwhite(cmd); /* skip over white space */
8405 p = cmd;
8406 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
8407 ++p;
8408 /* add an entry if it is not empty */
8409 if (p > cmd)
8410 {
8411 i = *p;
8412 *p = NUL;
8413 addfile(gap, cmd, flags);
8414 *p = i;
8415 ++cnt;
8416 }
8417 cmd = p;
8418 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
8419 ++cmd;
8420 }
8421
8422 vim_free(buffer);
8423 return cnt;
8424}
8425# endif /* VIM_BACKTICK */
8426
8427/*
8428 * Add a file to a file list. Accepted flags:
8429 * EW_DIR add directories
8430 * EW_FILE add files
8431 * EW_NOTFOUND add even when it doesn't exist
8432 * EW_ADDSLASH add slash after directory name
8433 */
8434 void
8435addfile(gap, f, flags)
8436 garray_T *gap;
8437 char_u *f; /* filename */
8438 int flags;
8439{
8440 char_u *p;
8441 int isdir;
8442
8443 /* if the file/dir doesn't exist, may not add it */
8444 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
8445 return;
8446
8447#ifdef FNAME_ILLEGAL
8448 /* if the file/dir contains illegal characters, don't add it */
8449 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
8450 return;
8451#endif
8452
8453 isdir = mch_isdir(f);
8454 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
8455 return;
8456
8457 /* Make room for another item in the file list. */
8458 if (ga_grow(gap, 1) == FAIL)
8459 return;
8460
8461 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
8462 if (p == NULL)
8463 return;
8464
8465 STRCPY(p, f);
8466#ifdef BACKSLASH_IN_FILENAME
8467 slash_adjust(p);
8468#endif
8469 /*
8470 * Append a slash or backslash after directory names if none is present.
8471 */
8472#ifndef DONT_ADD_PATHSEP_TO_DIR
8473 if (isdir && (flags & EW_ADDSLASH))
8474 add_pathsep(p);
8475#endif
8476 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008477}
8478#endif /* !NO_EXPANDPATH */
8479
8480#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
8481
8482#ifndef SEEK_SET
8483# define SEEK_SET 0
8484#endif
8485#ifndef SEEK_END
8486# define SEEK_END 2
8487#endif
8488
8489/*
8490 * Get the stdout of an external command.
8491 * Returns an allocated string, or NULL for error.
8492 */
8493 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008494get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008495 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008496 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008497 int flags; /* can be SHELL_SILENT */
8498{
8499 char_u *tempname;
8500 char_u *command;
8501 char_u *buffer = NULL;
8502 int len;
8503 int i = 0;
8504 FILE *fd;
8505
8506 if (check_restricted() || check_secure())
8507 return NULL;
8508
8509 /* get a name for the temp file */
8510 if ((tempname = vim_tempname('o')) == NULL)
8511 {
8512 EMSG(_(e_notmp));
8513 return NULL;
8514 }
8515
8516 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00008517 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008518 if (command == NULL)
8519 goto done;
8520
8521 /*
8522 * Call the shell to execute the command (errors are ignored).
8523 * Don't check timestamps here.
8524 */
8525 ++no_check_timestamps;
8526 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
8527 --no_check_timestamps;
8528
8529 vim_free(command);
8530
8531 /*
8532 * read the names from the file into memory
8533 */
8534# ifdef VMS
8535 /* created temporary file is not allways readable as binary */
8536 fd = mch_fopen((char *)tempname, "r");
8537# else
8538 fd = mch_fopen((char *)tempname, READBIN);
8539# endif
8540
8541 if (fd == NULL)
8542 {
8543 EMSG2(_(e_notopen), tempname);
8544 goto done;
8545 }
8546
8547 fseek(fd, 0L, SEEK_END);
8548 len = ftell(fd); /* get size of temp file */
8549 fseek(fd, 0L, SEEK_SET);
8550
8551 buffer = alloc(len + 1);
8552 if (buffer != NULL)
8553 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
8554 fclose(fd);
8555 mch_remove(tempname);
8556 if (buffer == NULL)
8557 goto done;
8558#ifdef VMS
8559 len = i; /* VMS doesn't give us what we asked for... */
8560#endif
8561 if (i != len)
8562 {
8563 EMSG2(_(e_notread), tempname);
8564 vim_free(buffer);
8565 buffer = NULL;
8566 }
8567 else
8568 buffer[len] = '\0'; /* make sure the buffer is terminated */
8569
8570done:
8571 vim_free(tempname);
8572 return buffer;
8573}
8574#endif
8575
8576/*
8577 * Free the list of files returned by expand_wildcards() or other expansion
8578 * functions.
8579 */
8580 void
8581FreeWild(count, files)
8582 int count;
8583 char_u **files;
8584{
8585 if (files == NULL || count <= 0)
8586 return;
8587#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
8588 /*
8589 * Is this still OK for when other functions than expand_wildcards() have
8590 * been used???
8591 */
8592 _fnexplodefree((char **)files);
8593#else
8594 while (count--)
8595 vim_free(files[count]);
8596 vim_free(files);
8597#endif
8598}
8599
8600/*
8601 * return TRUE when need to go to Insert mode because of 'insertmode'.
8602 * Don't do this when still processing a command or a mapping.
8603 * Don't do this when inside a ":normal" command.
8604 */
8605 int
8606goto_im()
8607{
8608 return (p_im && stuff_empty() && typebuf_typed());
8609}