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