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