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