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