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