blob: 78caa2081f4c8f6e60cae634d4fcd14251e46fe5 [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));
Bram Moolenaar071d4272004-06-13 20:20:40 +000023static int copy_indent __ARGS((int size, char_u *src));
24
25/*
26 * Count the size (in window cells) of the indent in the current line.
27 */
28 int
29get_indent()
30{
31 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts);
32}
33
34/*
35 * Count the size (in window cells) of the indent in line "lnum".
36 */
37 int
38get_indent_lnum(lnum)
39 linenr_T lnum;
40{
41 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts);
42}
43
44#if defined(FEAT_FOLDING) || defined(PROTO)
45/*
46 * Count the size (in window cells) of the indent in line "lnum" of buffer
47 * "buf".
48 */
49 int
50get_indent_buf(buf, lnum)
51 buf_T *buf;
52 linenr_T lnum;
53{
54 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts);
55}
56#endif
57
58/*
59 * count the size (in window cells) of the indent in line "ptr", with
60 * 'tabstop' at "ts"
61 */
Bram Moolenaar4399ef42005-02-12 14:29:27 +000062 int
Bram Moolenaar071d4272004-06-13 20:20:40 +000063get_indent_str(ptr, ts)
64 char_u *ptr;
65 int ts;
66{
67 int count = 0;
68
69 for ( ; *ptr; ++ptr)
70 {
71 if (*ptr == TAB) /* count a tab for what it is worth */
72 count += ts - (count % ts);
73 else if (*ptr == ' ')
74 ++count; /* count a space for one */
75 else
76 break;
77 }
Bram Moolenaar4399ef42005-02-12 14:29:27 +000078 return count;
Bram Moolenaar071d4272004-06-13 20:20:40 +000079}
80
81/*
82 * Set the indent of the current line.
83 * Leaves the cursor on the first non-blank in the line.
84 * Caller must take care of undo.
85 * "flags":
86 * SIN_CHANGED: call changed_bytes() if the line was changed.
87 * SIN_INSERT: insert the indent in front of the line.
88 * SIN_UNDO: save line for undo before changing it.
89 * Returns TRUE if the line was changed.
90 */
91 int
92set_indent(size, flags)
93 int size;
94 int flags;
95{
96 char_u *p;
97 char_u *newline;
98 char_u *oldline;
99 char_u *s;
100 int todo;
101 int ind_len;
102 int line_len;
103 int doit = FALSE;
104 int ind_done;
105 int tab_pad;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000106 int retval = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107
108 /*
109 * First check if there is anything to do and compute the number of
110 * characters needed for the indent.
111 */
112 todo = size;
113 ind_len = 0;
114 p = oldline = ml_get_curline();
115
116 /* Calculate the buffer size for the new indent, and check to see if it
117 * isn't already set */
118
119 /* if 'expandtab' isn't set: use TABs */
120 if (!curbuf->b_p_et)
121 {
122 /* If 'preserveindent' is set then reuse as much as possible of
123 * the existing indent structure for the new indent */
124 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
125 {
126 ind_done = 0;
127
128 /* count as many characters as we can use */
129 while (todo > 0 && vim_iswhite(*p))
130 {
131 if (*p == TAB)
132 {
133 tab_pad = (int)curbuf->b_p_ts
134 - (ind_done % (int)curbuf->b_p_ts);
135 /* stop if this tab will overshoot the target */
136 if (todo < tab_pad)
137 break;
138 todo -= tab_pad;
139 ++ind_len;
140 ind_done += tab_pad;
141 }
142 else
143 {
144 --todo;
145 ++ind_len;
146 ++ind_done;
147 }
148 ++p;
149 }
150
151 /* Fill to next tabstop with a tab, if possible */
152 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
153 if (todo >= tab_pad)
154 {
155 doit = TRUE;
156 todo -= tab_pad;
157 ++ind_len;
158 /* ind_done += tab_pad; */
159 }
160 }
161
162 /* count tabs required for indent */
163 while (todo >= (int)curbuf->b_p_ts)
164 {
165 if (*p != TAB)
166 doit = TRUE;
167 else
168 ++p;
169 todo -= (int)curbuf->b_p_ts;
170 ++ind_len;
171 /* ind_done += (int)curbuf->b_p_ts; */
172 }
173 }
174 /* count spaces required for indent */
175 while (todo > 0)
176 {
177 if (*p != ' ')
178 doit = TRUE;
179 else
180 ++p;
181 --todo;
182 ++ind_len;
183 /* ++ind_done; */
184 }
185
186 /* Return if the indent is OK already. */
187 if (!doit && !vim_iswhite(*p) && !(flags & SIN_INSERT))
188 return FALSE;
189
190 /* Allocate memory for the new line. */
191 if (flags & SIN_INSERT)
192 p = oldline;
193 else
194 p = skipwhite(p);
195 line_len = (int)STRLEN(p) + 1;
196 newline = alloc(ind_len + line_len);
197 if (newline == NULL)
198 return FALSE;
199
200 /* Put the characters in the new line. */
201 s = newline;
202 todo = size;
203 /* if 'expandtab' isn't set: use TABs */
204 if (!curbuf->b_p_et)
205 {
206 /* If 'preserveindent' is set then reuse as much as possible of
207 * the existing indent structure for the new indent */
208 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
209 {
210 p = oldline;
211 ind_done = 0;
212
213 while (todo > 0 && vim_iswhite(*p))
214 {
215 if (*p == TAB)
216 {
217 tab_pad = (int)curbuf->b_p_ts
218 - (ind_done % (int)curbuf->b_p_ts);
219 /* stop if this tab will overshoot the target */
220 if (todo < tab_pad)
221 break;
222 todo -= tab_pad;
223 ind_done += tab_pad;
224 }
225 else
226 {
227 --todo;
228 ++ind_done;
229 }
230 *s++ = *p++;
231 }
232
233 /* Fill to next tabstop with a tab, if possible */
234 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
235 if (todo >= tab_pad)
236 {
237 *s++ = TAB;
238 todo -= tab_pad;
239 }
240
241 p = skipwhite(p);
242 }
243
244 while (todo >= (int)curbuf->b_p_ts)
245 {
246 *s++ = TAB;
247 todo -= (int)curbuf->b_p_ts;
248 }
249 }
250 while (todo > 0)
251 {
252 *s++ = ' ';
253 --todo;
254 }
255 mch_memmove(s, p, (size_t)line_len);
256
257 /* Replace the line (unless undo fails). */
258 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
259 {
260 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
261 if (flags & SIN_CHANGED)
262 changed_bytes(curwin->w_cursor.lnum, 0);
263 /* Correct saved cursor position if it's after the indent. */
264 if (saved_cursor.lnum == curwin->w_cursor.lnum
265 && saved_cursor.col >= (colnr_T)(p - oldline))
Bram Moolenaara93fa7e2006-04-17 22:14:47 +0000266 saved_cursor.col += ind_len - (colnr_T)(p - oldline);
Bram Moolenaar5409c052005-03-18 20:27:04 +0000267 retval = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000268 }
269 else
270 vim_free(newline);
271
272 curwin->w_cursor.col = ind_len;
Bram Moolenaar5409c052005-03-18 20:27:04 +0000273 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000274}
275
276/*
277 * Copy the indent from ptr to the current line (and fill to size)
278 * Leaves the cursor on the first non-blank in the line.
279 * Returns TRUE if the line was changed.
280 */
281 static int
282copy_indent(size, src)
283 int size;
284 char_u *src;
285{
286 char_u *p = NULL;
287 char_u *line = NULL;
288 char_u *s;
289 int todo;
290 int ind_len;
291 int line_len = 0;
292 int tab_pad;
293 int ind_done;
294 int round;
295
296 /* Round 1: compute the number of characters needed for the indent
297 * Round 2: copy the characters. */
298 for (round = 1; round <= 2; ++round)
299 {
300 todo = size;
301 ind_len = 0;
302 ind_done = 0;
303 s = src;
304
305 /* Count/copy the usable portion of the source line */
306 while (todo > 0 && vim_iswhite(*s))
307 {
308 if (*s == TAB)
309 {
310 tab_pad = (int)curbuf->b_p_ts
311 - (ind_done % (int)curbuf->b_p_ts);
312 /* Stop if this tab will overshoot the target */
313 if (todo < tab_pad)
314 break;
315 todo -= tab_pad;
316 ind_done += tab_pad;
317 }
318 else
319 {
320 --todo;
321 ++ind_done;
322 }
323 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000324 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325 *p++ = *s;
326 ++s;
327 }
328
329 /* Fill to next tabstop with a tab, if possible */
330 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
331 if (todo >= tab_pad)
332 {
333 todo -= tab_pad;
334 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000335 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000336 *p++ = TAB;
337 }
338
339 /* Add tabs required for indent */
340 while (todo >= (int)curbuf->b_p_ts)
341 {
342 todo -= (int)curbuf->b_p_ts;
343 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000344 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000345 *p++ = TAB;
346 }
347
348 /* Count/add spaces required for indent */
349 while (todo > 0)
350 {
351 --todo;
352 ++ind_len;
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000353 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000354 *p++ = ' ';
355 }
356
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000357 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 {
359 /* Allocate memory for the result: the copied indent, new indent
360 * and the rest of the line. */
361 line_len = (int)STRLEN(ml_get_curline()) + 1;
362 line = alloc(ind_len + line_len);
363 if (line == NULL)
364 return FALSE;
365 p = line;
366 }
367 }
368
369 /* Append the original line */
370 mch_memmove(p, ml_get_curline(), (size_t)line_len);
371
372 /* Replace the line */
373 ml_replace(curwin->w_cursor.lnum, line, FALSE);
374
375 /* Put the cursor after the indent. */
376 curwin->w_cursor.col = ind_len;
377 return TRUE;
378}
379
380/*
381 * Return the indent of the current line after a number. Return -1 if no
382 * number was found. Used for 'n' in 'formatoptions': numbered list.
Bram Moolenaar86b68352004-12-27 21:59:20 +0000383 * Since a pattern is used it can actually handle more than numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000384 */
385 int
386get_number_indent(lnum)
387 linenr_T lnum;
388{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000389 colnr_T col;
390 pos_T pos;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000391 regmmatch_T regmatch;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392
393 if (lnum > curbuf->b_ml.ml_line_count)
394 return -1;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000395 pos.lnum = 0;
396 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
397 if (regmatch.regprog != NULL)
398 {
399 regmatch.rmm_ic = FALSE;
Bram Moolenaar3b56eb32005-07-11 22:40:32 +0000400 regmatch.rmm_maxcol = 0;
Bram Moolenaar86b68352004-12-27 21:59:20 +0000401 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 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +0000976 vim_strncpy(leader, saved_line, lead_len);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977
978 /*
979 * Replace leader with lead_repl, right or left adjusted
980 */
981 if (lead_repl != NULL)
982 {
983 int c = 0;
984 int off = 0;
985
986 for (p = lead_flags; *p && *p != ':'; ++p)
987 {
988 if (*p == COM_RIGHT || *p == COM_LEFT)
989 c = *p;
990 else if (VIM_ISDIGIT(*p) || *p == '-')
991 off = getdigits(&p);
992 }
993 if (c == COM_RIGHT) /* right adjusted leader */
994 {
995 /* find last non-white in the leader to line up with */
996 for (p = leader + lead_len - 1; p > leader
997 && vim_iswhite(*p); --p)
998 ;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 ++p;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001000
1001#ifdef FEAT_MBYTE
1002 /* Compute the length of the replaced characters in
1003 * screen characters, not bytes. */
1004 {
1005 int repl_size = vim_strnsize(lead_repl,
1006 lead_repl_len);
1007 int old_size = 0;
1008 char_u *endp = p;
1009 int l;
1010
1011 while (old_size < repl_size && p > leader)
1012 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001013 mb_ptr_back(leader, p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001014 old_size += ptr2cells(p);
1015 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001016 l = lead_repl_len - (int)(endp - p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001017 if (l != 0)
1018 mch_memmove(endp + l, endp,
1019 (size_t)((leader + lead_len) - endp));
1020 lead_len += l;
1021 }
1022#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023 if (p < leader + lead_repl_len)
1024 p = leader;
1025 else
1026 p -= lead_repl_len;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001027#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1029 if (p + lead_repl_len > leader + lead_len)
1030 p[lead_repl_len] = NUL;
1031
1032 /* blank-out any other chars from the old leader. */
1033 while (--p >= leader)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001034 {
1035#ifdef FEAT_MBYTE
1036 int l = mb_head_off(leader, p);
1037
1038 if (l > 1)
1039 {
1040 p -= l;
1041 if (ptr2cells(p) > 1)
1042 {
1043 p[1] = ' ';
1044 --l;
1045 }
1046 mch_memmove(p + 1, p + l + 1,
1047 (size_t)((leader + lead_len) - (p + l + 1)));
1048 lead_len -= l;
1049 *p = ' ';
1050 }
1051 else
1052#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053 if (!vim_iswhite(*p))
1054 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001055 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056 }
1057 else /* left adjusted leader */
1058 {
1059 p = skipwhite(leader);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001060#ifdef FEAT_MBYTE
1061 /* Compute the length of the replaced characters in
1062 * screen characters, not bytes. Move the part that is
1063 * not to be overwritten. */
1064 {
1065 int repl_size = vim_strnsize(lead_repl,
1066 lead_repl_len);
1067 int i;
1068 int l;
1069
1070 for (i = 0; p[i] != NUL && i < lead_len; i += l)
1071 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001072 l = (*mb_ptr2len)(p + i);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001073 if (vim_strnsize(p, i + l) > repl_size)
1074 break;
1075 }
1076 if (i != lead_repl_len)
1077 {
1078 mch_memmove(p + lead_repl_len, p + i,
1079 (size_t)(lead_len - i - (leader - p)));
1080 lead_len += lead_repl_len - i;
1081 }
1082 }
1083#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1085
1086 /* Replace any remaining non-white chars in the old
1087 * leader by spaces. Keep Tabs, the indent must
1088 * remain the same. */
1089 for (p += lead_repl_len; p < leader + lead_len; ++p)
1090 if (!vim_iswhite(*p))
1091 {
1092 /* Don't put a space before a TAB. */
1093 if (p + 1 < leader + lead_len && p[1] == TAB)
1094 {
1095 --lead_len;
1096 mch_memmove(p, p + 1,
1097 (leader + lead_len) - p);
1098 }
1099 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001100 {
1101#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001102 int l = (*mb_ptr2len)(p);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001103
1104 if (l > 1)
1105 {
1106 if (ptr2cells(p) > 1)
1107 {
1108 /* Replace a double-wide char with
1109 * two spaces */
1110 --l;
1111 *p++ = ' ';
1112 }
1113 mch_memmove(p + 1, p + l,
1114 (leader + lead_len) - p);
1115 lead_len -= l - 1;
1116 }
1117#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001118 *p = ' ';
Bram Moolenaar21cf8232004-07-16 20:18:37 +00001119 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120 }
1121 *p = NUL;
1122 }
1123
1124 /* Recompute the indent, it may have changed. */
1125 if (curbuf->b_p_ai
1126#ifdef FEAT_SMARTINDENT
1127 || do_si
1128#endif
1129 )
1130 newindent = get_indent_str(leader, (int)curbuf->b_p_ts);
1131
1132 /* Add the indent offset */
1133 if (newindent + off < 0)
1134 {
1135 off = -newindent;
1136 newindent = 0;
1137 }
1138 else
1139 newindent += off;
1140
1141 /* Correct trailing spaces for the shift, so that
1142 * alignment remains equal. */
1143 while (off > 0 && lead_len > 0
1144 && leader[lead_len - 1] == ' ')
1145 {
1146 /* Don't do it when there is a tab before the space */
1147 if (vim_strchr(skipwhite(leader), '\t') != NULL)
1148 break;
1149 --lead_len;
1150 --off;
1151 }
1152
1153 /* If the leader ends in white space, don't add an
1154 * extra space */
1155 if (lead_len > 0 && vim_iswhite(leader[lead_len - 1]))
1156 extra_space = FALSE;
1157 leader[lead_len] = NUL;
1158 }
1159
1160 if (extra_space)
1161 {
1162 leader[lead_len++] = ' ';
1163 leader[lead_len] = NUL;
1164 }
1165
1166 newcol = lead_len;
1167
1168 /*
1169 * if a new indent will be set below, remove the indent that
1170 * is in the comment leader
1171 */
1172 if (newindent
1173#ifdef FEAT_SMARTINDENT
1174 || did_si
1175#endif
1176 )
1177 {
1178 while (lead_len && vim_iswhite(*leader))
1179 {
1180 --lead_len;
1181 --newcol;
1182 ++leader;
1183 }
1184 }
1185
1186 }
1187#ifdef FEAT_SMARTINDENT
1188 did_si = can_si = FALSE;
1189#endif
1190 }
1191 else if (comment_end != NULL)
1192 {
1193 /*
1194 * We have finished a comment, so we don't use the leader.
1195 * If this was a C-comment and 'ai' or 'si' is set do a normal
1196 * indent to align with the line containing the start of the
1197 * comment.
1198 */
1199 if (comment_end[0] == '*' && comment_end[1] == '/' &&
1200 (curbuf->b_p_ai
1201#ifdef FEAT_SMARTINDENT
1202 || do_si
1203#endif
1204 ))
1205 {
1206 old_cursor = curwin->w_cursor;
1207 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1208 if ((pos = findmatch(NULL, NUL)) != NULL)
1209 {
1210 curwin->w_cursor.lnum = pos->lnum;
1211 newindent = get_indent();
1212 }
1213 curwin->w_cursor = old_cursor;
1214 }
1215 }
1216 }
1217#endif
1218
1219 /* (State == INSERT || State == REPLACE), only when dir == FORWARD */
1220 if (p_extra != NULL)
1221 {
1222 *p_extra = saved_char; /* restore char that NUL replaced */
1223
1224 /*
1225 * When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1226 * non-blank.
1227 *
1228 * When in REPLACE mode, put the deleted blanks on the replace stack,
1229 * preceded by a NUL, so they can be put back when a BS is entered.
1230 */
1231 if (REPLACE_NORMAL(State))
1232 replace_push(NUL); /* end of extra blanks */
1233 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
1234 {
1235 while ((*p_extra == ' ' || *p_extra == '\t')
1236#ifdef FEAT_MBYTE
1237 && (!enc_utf8
1238 || !utf_iscomposing(utf_ptr2char(p_extra + 1)))
1239#endif
1240 )
1241 {
1242 if (REPLACE_NORMAL(State))
1243 replace_push(*p_extra);
1244 ++p_extra;
1245 ++less_cols_off;
1246 }
1247 }
1248 if (*p_extra != NUL)
1249 did_ai = FALSE; /* append some text, don't truncate now */
1250
1251 /* columns for marks adjusted for removed columns */
1252 less_cols = (int)(p_extra - saved_line);
1253 }
1254
1255 if (p_extra == NULL)
1256 p_extra = (char_u *)""; /* append empty line */
1257
1258#ifdef FEAT_COMMENTS
1259 /* concatenate leader and p_extra, if there is a leader */
1260 if (lead_len)
1261 {
1262 STRCAT(leader, p_extra);
1263 p_extra = leader;
1264 did_ai = TRUE; /* So truncating blanks works with comments */
1265 less_cols -= lead_len;
1266 }
1267 else
1268 end_comment_pending = NUL; /* turns out there was no leader */
1269#endif
1270
1271 old_cursor = curwin->w_cursor;
1272 if (dir == BACKWARD)
1273 --curwin->w_cursor.lnum;
1274#ifdef FEAT_VREPLACE
1275 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
1276#endif
1277 {
1278 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
1279 == FAIL)
1280 goto theend;
1281 /* Postpone calling changed_lines(), because it would mess up folding
1282 * with markers. */
1283 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
1284 did_append = TRUE;
1285 }
1286#ifdef FEAT_VREPLACE
1287 else
1288 {
1289 /*
1290 * In VREPLACE mode we are starting to replace the next line.
1291 */
1292 curwin->w_cursor.lnum++;
1293 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
1294 {
1295 /* In case we NL to a new line, BS to the previous one, and NL
1296 * again, we don't want to save the new line for undo twice.
1297 */
1298 (void)u_save_cursor(); /* errors are ignored! */
1299 vr_lines_changed++;
1300 }
1301 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
1302 changed_bytes(curwin->w_cursor.lnum, 0);
1303 curwin->w_cursor.lnum--;
1304 did_append = FALSE;
1305 }
1306#endif
1307
1308 if (newindent
1309#ifdef FEAT_SMARTINDENT
1310 || did_si
1311#endif
1312 )
1313 {
1314 ++curwin->w_cursor.lnum;
1315#ifdef FEAT_SMARTINDENT
1316 if (did_si)
1317 {
1318 if (p_sr)
1319 newindent -= newindent % (int)curbuf->b_p_sw;
1320 newindent += (int)curbuf->b_p_sw;
1321 }
1322#endif
1323 /* Copy the indent only if expand tab is disabled */
1324 if (curbuf->b_p_ci && !curbuf->b_p_et)
1325 {
1326 (void)copy_indent(newindent, saved_line);
1327
1328 /*
1329 * Set the 'preserveindent' option so that any further screwing
1330 * with the line doesn't entirely destroy our efforts to preserve
1331 * it. It gets restored at the function end.
1332 */
1333 curbuf->b_p_pi = TRUE;
1334 }
1335 else
1336 (void)set_indent(newindent, SIN_INSERT);
1337 less_cols -= curwin->w_cursor.col;
1338
1339 ai_col = curwin->w_cursor.col;
1340
1341 /*
1342 * In REPLACE mode, for each character in the new indent, there must
1343 * be a NUL on the replace stack, for when it is deleted with BS
1344 */
1345 if (REPLACE_NORMAL(State))
1346 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
1347 replace_push(NUL);
1348 newcol += curwin->w_cursor.col;
1349#ifdef FEAT_SMARTINDENT
1350 if (no_si)
1351 did_si = FALSE;
1352#endif
1353 }
1354
1355#ifdef FEAT_COMMENTS
1356 /*
1357 * In REPLACE mode, for each character in the extra leader, there must be
1358 * a NUL on the replace stack, for when it is deleted with BS.
1359 */
1360 if (REPLACE_NORMAL(State))
1361 while (lead_len-- > 0)
1362 replace_push(NUL);
1363#endif
1364
1365 curwin->w_cursor = old_cursor;
1366
1367 if (dir == FORWARD)
1368 {
1369 if (trunc_line || (State & INSERT))
1370 {
1371 /* truncate current line at cursor */
1372 saved_line[curwin->w_cursor.col] = NUL;
1373 /* Remove trailing white space, unless OPENLINE_KEEPTRAIL used. */
1374 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
1375 truncate_spaces(saved_line);
1376 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
1377 saved_line = NULL;
1378 if (did_append)
1379 {
1380 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
1381 curwin->w_cursor.lnum + 1, 1L);
1382 did_append = FALSE;
1383
1384 /* Move marks after the line break to the new line. */
1385 if (flags & OPENLINE_MARKFIX)
1386 mark_col_adjust(curwin->w_cursor.lnum,
1387 curwin->w_cursor.col + less_cols_off,
1388 1L, (long)-less_cols);
1389 }
1390 else
1391 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1392 }
1393
1394 /*
1395 * Put the cursor on the new line. Careful: the scrollup() above may
1396 * have moved w_cursor, we must use old_cursor.
1397 */
1398 curwin->w_cursor.lnum = old_cursor.lnum + 1;
1399 }
1400 if (did_append)
1401 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
1402
1403 curwin->w_cursor.col = newcol;
1404#ifdef FEAT_VIRTUALEDIT
1405 curwin->w_cursor.coladd = 0;
1406#endif
1407
1408#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1409 /*
1410 * In VREPLACE mode, we are handling the replace stack ourselves, so stop
1411 * fixthisline() from doing it (via change_indent()) by telling it we're in
1412 * normal INSERT mode.
1413 */
1414 if (State & VREPLACE_FLAG)
1415 {
1416 vreplace_mode = State; /* So we know to put things right later */
1417 State = INSERT;
1418 }
1419 else
1420 vreplace_mode = 0;
1421#endif
1422#ifdef FEAT_LISP
1423 /*
1424 * May do lisp indenting.
1425 */
1426 if (!p_paste
1427# ifdef FEAT_COMMENTS
1428 && leader == NULL
1429# endif
1430 && curbuf->b_p_lisp
1431 && curbuf->b_p_ai)
1432 {
1433 fixthisline(get_lisp_indent);
1434 p = ml_get_curline();
1435 ai_col = (colnr_T)(skipwhite(p) - p);
1436 }
1437#endif
1438#ifdef FEAT_CINDENT
1439 /*
1440 * May do indenting after opening a new line.
1441 */
1442 if (!p_paste
1443 && (curbuf->b_p_cin
1444# ifdef FEAT_EVAL
1445 || *curbuf->b_p_inde != NUL
1446# endif
1447 )
1448 && in_cinkeys(dir == FORWARD
1449 ? KEY_OPEN_FORW
1450 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
1451 {
1452 do_c_expr_indent();
1453 p = ml_get_curline();
1454 ai_col = (colnr_T)(skipwhite(p) - p);
1455 }
1456#endif
1457#if defined(FEAT_VREPLACE) && (defined(FEAT_LISP) || defined(FEAT_CINDENT))
1458 if (vreplace_mode != 0)
1459 State = vreplace_mode;
1460#endif
1461
1462#ifdef FEAT_VREPLACE
1463 /*
1464 * Finally, VREPLACE gets the stuff on the new line, then puts back the
1465 * original line, and inserts the new stuff char by char, pushing old stuff
1466 * onto the replace stack (via ins_char()).
1467 */
1468 if (State & VREPLACE_FLAG)
1469 {
1470 /* Put new line in p_extra */
1471 p_extra = vim_strsave(ml_get_curline());
1472 if (p_extra == NULL)
1473 goto theend;
1474
1475 /* Put back original line */
1476 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
1477
1478 /* Insert new stuff into line again */
1479 curwin->w_cursor.col = 0;
1480#ifdef FEAT_VIRTUALEDIT
1481 curwin->w_cursor.coladd = 0;
1482#endif
1483 ins_bytes(p_extra); /* will call changed_bytes() */
1484 vim_free(p_extra);
1485 next_line = NULL;
1486 }
1487#endif
1488
1489 retval = TRUE; /* success! */
1490theend:
1491 curbuf->b_p_pi = saved_pi;
1492 vim_free(saved_line);
1493 vim_free(next_line);
1494 vim_free(allocated);
1495 return retval;
1496}
1497
1498#if defined(FEAT_COMMENTS) || defined(PROTO)
1499/*
1500 * get_leader_len() returns the length of the prefix of the given string
1501 * which introduces a comment. If this string is not a comment then 0 is
1502 * returned.
1503 * When "flags" is not NULL, it is set to point to the flags of the recognized
1504 * comment leader.
1505 * "backward" must be true for the "O" command.
1506 */
1507 int
1508get_leader_len(line, flags, backward)
1509 char_u *line;
1510 char_u **flags;
1511 int backward;
1512{
1513 int i, j;
1514 int got_com = FALSE;
1515 int found_one;
1516 char_u part_buf[COM_MAX_LEN]; /* buffer for one option part */
1517 char_u *string; /* pointer to comment string */
1518 char_u *list;
1519
1520 i = 0;
1521 while (vim_iswhite(line[i])) /* leading white space is ignored */
1522 ++i;
1523
1524 /*
1525 * Repeat to match several nested comment strings.
1526 */
1527 while (line[i])
1528 {
1529 /*
1530 * scan through the 'comments' option for a match
1531 */
1532 found_one = FALSE;
1533 for (list = curbuf->b_p_com; *list; )
1534 {
1535 /*
1536 * Get one option part into part_buf[]. Advance list to next one.
1537 * put string at start of string.
1538 */
1539 if (!got_com && flags != NULL) /* remember where flags started */
1540 *flags = list;
1541 (void)copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1542 string = vim_strchr(part_buf, ':');
1543 if (string == NULL) /* missing ':', ignore this part */
1544 continue;
1545 *string++ = NUL; /* isolate flags from string */
1546
1547 /*
1548 * When already found a nested comment, only accept further
1549 * nested comments.
1550 */
1551 if (got_com && vim_strchr(part_buf, COM_NEST) == NULL)
1552 continue;
1553
1554 /* When 'O' flag used don't use for "O" command */
1555 if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL)
1556 continue;
1557
1558 /*
1559 * Line contents and string must match.
1560 * When string starts with white space, must have some white space
1561 * (but the amount does not need to match, there might be a mix of
1562 * TABs and spaces).
1563 */
1564 if (vim_iswhite(string[0]))
1565 {
1566 if (i == 0 || !vim_iswhite(line[i - 1]))
1567 continue;
1568 while (vim_iswhite(string[0]))
1569 ++string;
1570 }
1571 for (j = 0; string[j] != NUL && string[j] == line[i + j]; ++j)
1572 ;
1573 if (string[j] != NUL)
1574 continue;
1575
1576 /*
1577 * When 'b' flag used, there must be white space or an
1578 * end-of-line after the string in the line.
1579 */
1580 if (vim_strchr(part_buf, COM_BLANK) != NULL
1581 && !vim_iswhite(line[i + j]) && line[i + j] != NUL)
1582 continue;
1583
1584 /*
1585 * We have found a match, stop searching.
1586 */
1587 i += j;
1588 got_com = TRUE;
1589 found_one = TRUE;
1590 break;
1591 }
1592
1593 /*
1594 * No match found, stop scanning.
1595 */
1596 if (!found_one)
1597 break;
1598
1599 /*
1600 * Include any trailing white space.
1601 */
1602 while (vim_iswhite(line[i]))
1603 ++i;
1604
1605 /*
1606 * If this comment doesn't nest, stop here.
1607 */
1608 if (vim_strchr(part_buf, COM_NEST) == NULL)
1609 break;
1610 }
1611 return (got_com ? i : 0);
1612}
1613#endif
1614
1615/*
1616 * Return the number of window lines occupied by buffer line "lnum".
1617 */
1618 int
1619plines(lnum)
1620 linenr_T lnum;
1621{
1622 return plines_win(curwin, lnum, TRUE);
1623}
1624
1625 int
1626plines_win(wp, lnum, winheight)
1627 win_T *wp;
1628 linenr_T lnum;
1629 int winheight; /* when TRUE limit to window height */
1630{
1631#if defined(FEAT_DIFF) || defined(PROTO)
1632 /* Check for filler lines above this buffer line. When folded the result
1633 * is one line anyway. */
1634 return plines_win_nofill(wp, lnum, winheight) + diff_check_fill(wp, lnum);
1635}
1636
1637 int
1638plines_nofill(lnum)
1639 linenr_T lnum;
1640{
1641 return plines_win_nofill(curwin, lnum, TRUE);
1642}
1643
1644 int
1645plines_win_nofill(wp, lnum, winheight)
1646 win_T *wp;
1647 linenr_T lnum;
1648 int winheight; /* when TRUE limit to window height */
1649{
1650#endif
1651 int lines;
1652
1653 if (!wp->w_p_wrap)
1654 return 1;
1655
1656#ifdef FEAT_VERTSPLIT
1657 if (wp->w_width == 0)
1658 return 1;
1659#endif
1660
1661#ifdef FEAT_FOLDING
1662 /* A folded lines is handled just like an empty line. */
1663 /* NOTE: Caller must handle lines that are MAYBE folded. */
1664 if (lineFolded(wp, lnum) == TRUE)
1665 return 1;
1666#endif
1667
1668 lines = plines_win_nofold(wp, lnum);
1669 if (winheight > 0 && lines > wp->w_height)
1670 return (int)wp->w_height;
1671 return lines;
1672}
1673
1674/*
1675 * Return number of window lines physical line "lnum" will occupy in window
1676 * "wp". Does not care about folding, 'wrap' or 'diff'.
1677 */
1678 int
1679plines_win_nofold(wp, lnum)
1680 win_T *wp;
1681 linenr_T lnum;
1682{
1683 char_u *s;
1684 long col;
1685 int width;
1686
1687 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1688 if (*s == NUL) /* empty line */
1689 return 1;
1690 col = win_linetabsize(wp, s, (colnr_T)MAXCOL);
1691
1692 /*
1693 * If list mode is on, then the '$' at the end of the line may take up one
1694 * extra column.
1695 */
1696 if (wp->w_p_list && lcs_eol != NUL)
1697 col += 1;
1698
1699 /*
1700 * Add column offset for 'number' and 'foldcolumn'.
1701 */
1702 width = W_WIDTH(wp) - win_col_off(wp);
1703 if (width <= 0)
1704 return 32000;
1705 if (col <= width)
1706 return 1;
1707 col -= width;
1708 width += win_col_off2(wp);
1709 return (col + (width - 1)) / width + 1;
1710}
1711
1712/*
1713 * Like plines_win(), but only reports the number of physical screen lines
1714 * used from the start of the line to the given column number.
1715 */
1716 int
1717plines_win_col(wp, lnum, column)
1718 win_T *wp;
1719 linenr_T lnum;
1720 long column;
1721{
1722 long col;
1723 char_u *s;
1724 int lines = 0;
1725 int width;
1726
1727#ifdef FEAT_DIFF
1728 /* Check for filler lines above this buffer line. When folded the result
1729 * is one line anyway. */
1730 lines = diff_check_fill(wp, lnum);
1731#endif
1732
1733 if (!wp->w_p_wrap)
1734 return lines + 1;
1735
1736#ifdef FEAT_VERTSPLIT
1737 if (wp->w_width == 0)
1738 return lines + 1;
1739#endif
1740
1741 s = ml_get_buf(wp->w_buffer, lnum, FALSE);
1742
1743 col = 0;
1744 while (*s != NUL && --column >= 0)
1745 {
1746 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001747 mb_ptr_adv(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001748 }
1749
1750 /*
1751 * If *s is a TAB, and the TAB is not displayed as ^I, and we're not in
1752 * INSERT mode, then col must be adjusted so that it represents the last
1753 * screen position of the TAB. This only fixes an error when the TAB wraps
1754 * from one screen line to the next (when 'columns' is not a multiple of
1755 * 'ts') -- webb.
1756 */
1757 if (*s == TAB && (State & NORMAL) && (!wp->w_p_list || lcs_tab1))
1758 col += win_lbr_chartabsize(wp, s, (colnr_T)col, NULL) - 1;
1759
1760 /*
1761 * Add column offset for 'number', 'foldcolumn', etc.
1762 */
1763 width = W_WIDTH(wp) - win_col_off(wp);
1764 if (width > 0)
1765 {
1766 lines += 1;
1767 if (col >= width)
1768 lines += (col - width) / (width + win_col_off2(wp));
1769 if (lines <= wp->w_height)
1770 return lines;
1771 }
1772 return (int)(wp->w_height); /* maximum length */
1773}
1774
1775 int
1776plines_m_win(wp, first, last)
1777 win_T *wp;
1778 linenr_T first, last;
1779{
1780 int count = 0;
1781
1782 while (first <= last)
1783 {
1784#ifdef FEAT_FOLDING
1785 int x;
1786
1787 /* Check if there are any really folded lines, but also included lines
1788 * that are maybe folded. */
1789 x = foldedCount(wp, first, NULL);
1790 if (x > 0)
1791 {
1792 ++count; /* count 1 for "+-- folded" line */
1793 first += x;
1794 }
1795 else
1796#endif
1797 {
1798#ifdef FEAT_DIFF
1799 if (first == wp->w_topline)
1800 count += plines_win_nofill(wp, first, TRUE) + wp->w_topfill;
1801 else
1802#endif
1803 count += plines_win(wp, first, TRUE);
1804 ++first;
1805 }
1806 }
1807 return (count);
1808}
1809
1810#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) || defined(PROTO)
1811/*
1812 * Insert string "p" at the cursor position. Stops at a NUL byte.
1813 * Handles Replace mode and multi-byte characters.
1814 */
1815 void
1816ins_bytes(p)
1817 char_u *p;
1818{
1819 ins_bytes_len(p, (int)STRLEN(p));
1820}
1821#endif
1822
1823#if defined(FEAT_VREPLACE) || defined(FEAT_INS_EXPAND) \
1824 || defined(FEAT_COMMENTS) || defined(FEAT_MBYTE) || defined(PROTO)
1825/*
1826 * Insert string "p" with length "len" at the cursor position.
1827 * Handles Replace mode and multi-byte characters.
1828 */
1829 void
1830ins_bytes_len(p, len)
1831 char_u *p;
1832 int len;
1833{
1834 int i;
1835# ifdef FEAT_MBYTE
1836 int n;
1837
1838 for (i = 0; i < len; i += n)
1839 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001840 n = (*mb_ptr2len)(p + i);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841 ins_char_bytes(p + i, n);
1842 }
1843# else
1844 for (i = 0; i < len; ++i)
1845 ins_char(p[i]);
1846# endif
1847}
1848#endif
1849
1850/*
1851 * Insert or replace a single character at the cursor position.
1852 * When in REPLACE or VREPLACE mode, replace any existing character.
1853 * Caller must have prepared for undo.
1854 * For multi-byte characters we get the whole character, the caller must
1855 * convert bytes to a character.
1856 */
1857 void
1858ins_char(c)
1859 int c;
1860{
1861#if defined(FEAT_MBYTE) || defined(PROTO)
1862 char_u buf[MB_MAXBYTES];
1863 int n;
1864
1865 n = (*mb_char2bytes)(c, buf);
1866
1867 /* When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
1868 * Happens for CTRL-Vu9900. */
1869 if (buf[0] == 0)
1870 buf[0] = '\n';
1871
1872 ins_char_bytes(buf, n);
1873}
1874
1875 void
1876ins_char_bytes(buf, charlen)
1877 char_u *buf;
1878 int charlen;
1879{
1880 int c = buf[0];
1881 int l, j;
1882#endif
1883 int newlen; /* nr of bytes inserted */
1884 int oldlen; /* nr of bytes deleted (0 when not replacing) */
1885 char_u *p;
1886 char_u *newp;
1887 char_u *oldp;
1888 int linelen; /* length of old line including NUL */
1889 colnr_T col;
1890 linenr_T lnum = curwin->w_cursor.lnum;
1891 int i;
1892
1893#ifdef FEAT_VIRTUALEDIT
1894 /* Break tabs if needed. */
1895 if (virtual_active() && curwin->w_cursor.coladd > 0)
1896 coladvance_force(getviscol());
1897#endif
1898
1899 col = curwin->w_cursor.col;
1900 oldp = ml_get(lnum);
1901 linelen = (int)STRLEN(oldp) + 1;
1902
1903 /* The lengths default to the values for when not replacing. */
1904 oldlen = 0;
1905#ifdef FEAT_MBYTE
1906 newlen = charlen;
1907#else
1908 newlen = 1;
1909#endif
1910
1911 if (State & REPLACE_FLAG)
1912 {
1913#ifdef FEAT_VREPLACE
1914 if (State & VREPLACE_FLAG)
1915 {
1916 colnr_T new_vcol = 0; /* init for GCC */
1917 colnr_T vcol;
1918 int old_list;
1919#ifndef FEAT_MBYTE
1920 char_u buf[2];
1921#endif
1922
1923 /*
1924 * Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
1925 * Returns the old value of list, so when finished,
1926 * curwin->w_p_list should be set back to this.
1927 */
1928 old_list = curwin->w_p_list;
1929 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
1930 curwin->w_p_list = FALSE;
1931
1932 /*
1933 * In virtual replace mode each character may replace one or more
1934 * characters (zero if it's a TAB). Count the number of bytes to
1935 * be deleted to make room for the new character, counting screen
1936 * cells. May result in adding spaces to fill a gap.
1937 */
1938 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
1939#ifndef FEAT_MBYTE
1940 buf[0] = c;
1941 buf[1] = NUL;
1942#endif
1943 new_vcol = vcol + chartabsize(buf, vcol);
1944 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
1945 {
1946 vcol += chartabsize(oldp + col + oldlen, vcol);
1947 /* Don't need to remove a TAB that takes us to the right
1948 * position. */
1949 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
1950 break;
1951#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001952 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953#else
1954 ++oldlen;
1955#endif
1956 /* Deleted a bit too much, insert spaces. */
1957 if (vcol > new_vcol)
1958 newlen += vcol - new_vcol;
1959 }
1960 curwin->w_p_list = old_list;
1961 }
1962 else
1963#endif
1964 if (oldp[col] != NUL)
1965 {
1966 /* normal replace */
1967#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001968 oldlen = (*mb_ptr2len)(oldp + col);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969#else
1970 oldlen = 1;
1971#endif
1972 }
1973
1974
1975 /* Push the replaced bytes onto the replace stack, so that they can be
1976 * put back when BS is used. The bytes of a multi-byte character are
1977 * done the other way around, so that the first byte is popped off
1978 * first (it tells the byte length of the character). */
1979 replace_push(NUL);
1980 for (i = 0; i < oldlen; ++i)
1981 {
1982#ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00001983 l = (*mb_ptr2len)(oldp + col + i) - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 for (j = l; j >= 0; --j)
1985 replace_push(oldp[col + i + j]);
1986 i += l;
1987#else
1988 replace_push(oldp[col + i]);
1989#endif
1990 }
1991 }
1992
1993 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
1994 if (newp == NULL)
1995 return;
1996
1997 /* Copy bytes before the cursor. */
1998 if (col > 0)
1999 mch_memmove(newp, oldp, (size_t)col);
2000
2001 /* Copy bytes after the changed character(s). */
2002 p = newp + col;
2003 mch_memmove(p + newlen, oldp + col + oldlen,
2004 (size_t)(linelen - col - oldlen));
2005
2006 /* Insert or overwrite the new character. */
2007#ifdef FEAT_MBYTE
2008 mch_memmove(p, buf, charlen);
2009 i = charlen;
2010#else
2011 *p = c;
2012 i = 1;
2013#endif
2014
2015 /* Fill with spaces when necessary. */
2016 while (i < newlen)
2017 p[i++] = ' ';
2018
2019 /* Replace the line in the buffer. */
2020 ml_replace(lnum, newp, FALSE);
2021
2022 /* mark the buffer as changed and prepare for displaying */
2023 changed_bytes(lnum, col);
2024
2025 /*
2026 * If we're in Insert or Replace mode and 'showmatch' is set, then briefly
2027 * show the match for right parens and braces.
2028 */
2029 if (p_sm && (State & INSERT)
2030 && msg_silent == 0
2031#ifdef FEAT_MBYTE
2032 && charlen == 1
2033#endif
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00002034#ifdef FEAT_INS_EXPAND
2035 && !ins_compl_active()
2036#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002037 )
2038 showmatch(c);
2039
2040#ifdef FEAT_RIGHTLEFT
2041 if (!p_ri || (State & REPLACE_FLAG))
2042#endif
2043 {
2044 /* Normal insert: move cursor right */
2045#ifdef FEAT_MBYTE
2046 curwin->w_cursor.col += charlen;
2047#else
2048 ++curwin->w_cursor.col;
2049#endif
2050 }
2051 /*
2052 * TODO: should try to update w_row here, to avoid recomputing it later.
2053 */
2054}
2055
2056/*
2057 * Insert a string at the cursor position.
2058 * Note: Does NOT handle Replace mode.
2059 * Caller must have prepared for undo.
2060 */
2061 void
2062ins_str(s)
2063 char_u *s;
2064{
2065 char_u *oldp, *newp;
2066 int newlen = (int)STRLEN(s);
2067 int oldlen;
2068 colnr_T col;
2069 linenr_T lnum = curwin->w_cursor.lnum;
2070
2071#ifdef FEAT_VIRTUALEDIT
2072 if (virtual_active() && curwin->w_cursor.coladd > 0)
2073 coladvance_force(getviscol());
2074#endif
2075
2076 col = curwin->w_cursor.col;
2077 oldp = ml_get(lnum);
2078 oldlen = (int)STRLEN(oldp);
2079
2080 newp = alloc_check((unsigned)(oldlen + newlen + 1));
2081 if (newp == NULL)
2082 return;
2083 if (col > 0)
2084 mch_memmove(newp, oldp, (size_t)col);
2085 mch_memmove(newp + col, s, (size_t)newlen);
2086 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
2087 ml_replace(lnum, newp, FALSE);
2088 changed_bytes(lnum, col);
2089 curwin->w_cursor.col += newlen;
2090}
2091
2092/*
2093 * Delete one character under the cursor.
2094 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2095 * Caller must have prepared for undo.
2096 *
2097 * return FAIL for failure, OK otherwise
2098 */
2099 int
2100del_char(fixpos)
2101 int fixpos;
2102{
2103#ifdef FEAT_MBYTE
2104 if (has_mbyte)
2105 {
2106 /* Make sure the cursor is at the start of a character. */
2107 mb_adjust_cursor();
2108 if (*ml_get_cursor() == NUL)
2109 return FAIL;
2110 return del_chars(1L, fixpos);
2111 }
2112#endif
Bram Moolenaare3226be2005-12-18 22:10:00 +00002113 return del_bytes(1L, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002114}
2115
2116#if defined(FEAT_MBYTE) || defined(PROTO)
2117/*
2118 * Like del_bytes(), but delete characters instead of bytes.
2119 */
2120 int
2121del_chars(count, fixpos)
2122 long count;
2123 int fixpos;
2124{
2125 long bytes = 0;
2126 long i;
2127 char_u *p;
2128 int l;
2129
2130 p = ml_get_cursor();
2131 for (i = 0; i < count && *p != NUL; ++i)
2132 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002133 l = (*mb_ptr2len)(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002134 bytes += l;
2135 p += l;
2136 }
Bram Moolenaare3226be2005-12-18 22:10:00 +00002137 return del_bytes(bytes, fixpos, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138}
2139#endif
2140
2141/*
2142 * Delete "count" bytes under the cursor.
2143 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
2144 * Caller must have prepared for undo.
2145 *
2146 * return FAIL for failure, OK otherwise
2147 */
Bram Moolenaara9b1e742005-12-19 22:14:58 +00002148/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149 int
Bram Moolenaarca003e12006-03-17 23:19:38 +00002150del_bytes(count, fixpos_arg, use_delcombine)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 long count;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002152 int fixpos_arg;
Bram Moolenaare3226be2005-12-18 22:10:00 +00002153 int use_delcombine; /* 'delcombine' option applies */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002154{
2155 char_u *oldp, *newp;
2156 colnr_T oldlen;
2157 linenr_T lnum = curwin->w_cursor.lnum;
2158 colnr_T col = curwin->w_cursor.col;
2159 int was_alloced;
2160 long movelen;
Bram Moolenaarca003e12006-03-17 23:19:38 +00002161 int fixpos = fixpos_arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002162
2163 oldp = ml_get(lnum);
2164 oldlen = (int)STRLEN(oldp);
2165
2166 /*
2167 * Can't do anything when the cursor is on the NUL after the line.
2168 */
2169 if (col >= oldlen)
2170 return FAIL;
2171
2172#ifdef FEAT_MBYTE
2173 /* If 'delcombine' is set and deleting (less than) one character, only
2174 * delete the last combining character. */
Bram Moolenaare3226be2005-12-18 22:10:00 +00002175 if (p_deco && use_delcombine && enc_utf8
2176 && utfc_ptr2len(oldp + col) >= count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177 {
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002178 int cc[MAX_MCO];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 int n;
2180
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002181 (void)utfc_ptr2char(oldp + col, cc);
2182 if (cc[0] != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183 {
2184 /* Find the last composing char, there can be several. */
2185 n = col;
2186 do
2187 {
2188 col = n;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002189 count = utf_ptr2len(oldp + n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002190 n += count;
2191 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
2192 fixpos = 0;
2193 }
2194 }
2195#endif
2196
2197 /*
2198 * When count is too big, reduce it.
2199 */
2200 movelen = (long)oldlen - (long)col - count + 1; /* includes trailing NUL */
2201 if (movelen <= 1)
2202 {
2203 /*
2204 * If we just took off the last character of a non-blank line, and
Bram Moolenaarca003e12006-03-17 23:19:38 +00002205 * fixpos is TRUE, we don't want to end up positioned at the NUL,
2206 * unless "restart_edit" is set or 'virtualedit' contains "onemore".
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207 */
Bram Moolenaarca003e12006-03-17 23:19:38 +00002208 if (col > 0 && fixpos && restart_edit == 0
2209#ifdef FEAT_VIRTUALEDIT
2210 && (ve_flags & VE_ONEMORE) == 0
2211#endif
2212 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00002213 {
2214 --curwin->w_cursor.col;
2215#ifdef FEAT_VIRTUALEDIT
2216 curwin->w_cursor.coladd = 0;
2217#endif
2218#ifdef FEAT_MBYTE
2219 if (has_mbyte)
2220 curwin->w_cursor.col -=
2221 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
2222#endif
2223 }
2224 count = oldlen - col;
2225 movelen = 1;
2226 }
2227
2228 /*
2229 * If the old line has been allocated the deletion can be done in the
2230 * existing line. Otherwise a new line has to be allocated
2231 */
2232 was_alloced = ml_line_alloced(); /* check if oldp was allocated */
2233#ifdef FEAT_NETBEANS_INTG
2234 if (was_alloced && usingNetbeans)
2235 netbeans_removed(curbuf, lnum, col, count);
2236 /* else is handled by ml_replace() */
2237#endif
2238 if (was_alloced)
2239 newp = oldp; /* use same allocated memory */
2240 else
2241 { /* need to allocate a new line */
2242 newp = alloc((unsigned)(oldlen + 1 - count));
2243 if (newp == NULL)
2244 return FAIL;
2245 mch_memmove(newp, oldp, (size_t)col);
2246 }
2247 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
2248 if (!was_alloced)
2249 ml_replace(lnum, newp, FALSE);
2250
2251 /* mark the buffer as changed and prepare for displaying */
2252 changed_bytes(lnum, curwin->w_cursor.col);
2253
2254 return OK;
2255}
2256
2257/*
2258 * Delete from cursor to end of line.
2259 * Caller must have prepared for undo.
2260 *
2261 * return FAIL for failure, OK otherwise
2262 */
2263 int
2264truncate_line(fixpos)
2265 int fixpos; /* if TRUE fix the cursor position when done */
2266{
2267 char_u *newp;
2268 linenr_T lnum = curwin->w_cursor.lnum;
2269 colnr_T col = curwin->w_cursor.col;
2270
2271 if (col == 0)
2272 newp = vim_strsave((char_u *)"");
2273 else
2274 newp = vim_strnsave(ml_get(lnum), col);
2275
2276 if (newp == NULL)
2277 return FAIL;
2278
2279 ml_replace(lnum, newp, FALSE);
2280
2281 /* mark the buffer as changed and prepare for displaying */
2282 changed_bytes(lnum, curwin->w_cursor.col);
2283
2284 /*
2285 * If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2286 */
2287 if (fixpos && curwin->w_cursor.col > 0)
2288 --curwin->w_cursor.col;
2289
2290 return OK;
2291}
2292
2293/*
2294 * Delete "nlines" lines at the cursor.
2295 * Saves the lines for undo first if "undo" is TRUE.
2296 */
2297 void
2298del_lines(nlines, undo)
2299 long nlines; /* number of lines to delete */
2300 int undo; /* if TRUE, prepare for undo */
2301{
2302 long n;
2303
2304 if (nlines <= 0)
2305 return;
2306
2307 /* save the deleted lines for undo */
2308 if (undo && u_savedel(curwin->w_cursor.lnum, nlines) == FAIL)
2309 return;
2310
2311 for (n = 0; n < nlines; )
2312 {
2313 if (curbuf->b_ml.ml_flags & ML_EMPTY) /* nothing to delete */
2314 break;
2315
2316 ml_delete(curwin->w_cursor.lnum, TRUE);
2317 ++n;
2318
2319 /* If we delete the last line in the file, stop */
2320 if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count)
2321 break;
2322 }
2323 /* adjust marks, mark the buffer as changed and prepare for displaying */
2324 deleted_lines_mark(curwin->w_cursor.lnum, n);
2325
2326 curwin->w_cursor.col = 0;
2327 check_cursor_lnum();
2328}
2329
2330 int
2331gchar_pos(pos)
2332 pos_T *pos;
2333{
2334 char_u *ptr = ml_get_pos(pos);
2335
2336#ifdef FEAT_MBYTE
2337 if (has_mbyte)
2338 return (*mb_ptr2char)(ptr);
2339#endif
2340 return (int)*ptr;
2341}
2342
2343 int
2344gchar_cursor()
2345{
2346#ifdef FEAT_MBYTE
2347 if (has_mbyte)
2348 return (*mb_ptr2char)(ml_get_cursor());
2349#endif
2350 return (int)*ml_get_cursor();
2351}
2352
2353/*
2354 * Write a character at the current cursor position.
2355 * It is directly written into the block.
2356 */
2357 void
2358pchar_cursor(c)
2359 int c;
2360{
2361 *(ml_get_buf(curbuf, curwin->w_cursor.lnum, TRUE)
2362 + curwin->w_cursor.col) = c;
2363}
2364
2365#if 0 /* not used */
2366/*
2367 * Put *pos at end of current buffer
2368 */
2369 void
2370goto_endofbuf(pos)
2371 pos_T *pos;
2372{
2373 char_u *p;
2374
2375 pos->lnum = curbuf->b_ml.ml_line_count;
2376 pos->col = 0;
2377 p = ml_get(pos->lnum);
2378 while (*p++)
2379 ++pos->col;
2380}
2381#endif
2382
2383/*
2384 * When extra == 0: Return TRUE if the cursor is before or on the first
2385 * non-blank in the line.
2386 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
2387 * the line.
2388 */
2389 int
2390inindent(extra)
2391 int extra;
2392{
2393 char_u *ptr;
2394 colnr_T col;
2395
2396 for (col = 0, ptr = ml_get_curline(); vim_iswhite(*ptr); ++col)
2397 ++ptr;
2398 if (col >= curwin->w_cursor.col + extra)
2399 return TRUE;
2400 else
2401 return FALSE;
2402}
2403
2404/*
2405 * Skip to next part of an option argument: Skip space and comma.
2406 */
2407 char_u *
2408skip_to_option_part(p)
2409 char_u *p;
2410{
2411 if (*p == ',')
2412 ++p;
2413 while (*p == ' ')
2414 ++p;
2415 return p;
2416}
2417
2418/*
2419 * changed() is called when something in the current buffer is changed.
2420 *
2421 * Most often called through changed_bytes() and changed_lines(), which also
2422 * mark the area of the display to be redrawn.
2423 */
2424 void
2425changed()
2426{
2427#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
2428 /* The text of the preediting area is inserted, but this doesn't
2429 * mean a change of the buffer yet. That is delayed until the
2430 * text is committed. (this means preedit becomes empty) */
2431 if (im_is_preediting() && !xim_changed_while_preediting)
2432 return;
2433 xim_changed_while_preediting = FALSE;
2434#endif
2435
2436 if (!curbuf->b_changed)
2437 {
2438 int save_msg_scroll = msg_scroll;
2439
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002440 /* Give a warning about changing a read-only file. This may also
2441 * check-out the file, thus change "curbuf"! */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 change_warning(0);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002443
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444 /* Create a swap file if that is wanted.
2445 * Don't do this for "nofile" and "nowrite" buffer types. */
2446 if (curbuf->b_may_swap
2447#ifdef FEAT_QUICKFIX
2448 && !bt_dontwrite(curbuf)
2449#endif
2450 )
2451 {
2452 ml_open_file(curbuf);
2453
2454 /* The ml_open_file() can cause an ATTENTION message.
2455 * Wait two seconds, to make sure the user reads this unexpected
2456 * message. Since we could be anywhere, call wait_return() now,
2457 * and don't let the emsg() set msg_scroll. */
2458 if (need_wait_return && emsg_silent == 0)
2459 {
2460 out_flush();
2461 ui_delay(2000L, TRUE);
2462 wait_return(TRUE);
2463 msg_scroll = save_msg_scroll;
2464 }
2465 }
2466 curbuf->b_changed = TRUE;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002467 ml_setflags(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002468#ifdef FEAT_WINDOWS
2469 check_status(curbuf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002470 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471#endif
2472#ifdef FEAT_TITLE
2473 need_maketitle = TRUE; /* set window title later */
2474#endif
2475 }
2476 ++curbuf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477}
2478
Bram Moolenaardba8a912005-04-24 22:08:39 +00002479static void changedOneline __ARGS((buf_T *buf, linenr_T lnum));
2480static void changed_lines_buf __ARGS((buf_T *buf, linenr_T lnum, linenr_T lnume, long xtra));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481static void changed_common __ARGS((linenr_T lnum, colnr_T col, linenr_T lnume, long xtra));
2482
2483/*
2484 * Changed bytes within a single line for the current buffer.
2485 * - marks the windows on this buffer to be redisplayed
2486 * - marks the buffer changed by calling changed()
2487 * - invalidates cached values
2488 */
2489 void
2490changed_bytes(lnum, col)
2491 linenr_T lnum;
2492 colnr_T col;
2493{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002494 changedOneline(curbuf, lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 changed_common(lnum, col, lnum + 1, 0L);
Bram Moolenaardba8a912005-04-24 22:08:39 +00002496
2497#ifdef FEAT_DIFF
2498 /* Diff highlighting in other diff windows may need to be updated too. */
2499 if (curwin->w_p_diff)
2500 {
2501 win_T *wp;
2502 linenr_T wlnum;
2503
2504 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2505 if (wp->w_p_diff && wp != curwin)
2506 {
2507 redraw_win_later(wp, VALID);
2508 wlnum = diff_lnum_win(lnum, wp);
2509 if (wlnum > 0)
2510 changedOneline(wp->w_buffer, wlnum);
2511 }
2512 }
2513#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514}
2515
2516 static void
Bram Moolenaardba8a912005-04-24 22:08:39 +00002517changedOneline(buf, lnum)
2518 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 linenr_T lnum;
2520{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002521 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 {
2523 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002524 if (lnum < buf->b_mod_top)
2525 buf->b_mod_top = lnum;
2526 else if (lnum >= buf->b_mod_bot)
2527 buf->b_mod_bot = lnum + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 }
2529 else
2530 {
2531 /* set the area that must be redisplayed to one line */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002532 buf->b_mod_set = TRUE;
2533 buf->b_mod_top = lnum;
2534 buf->b_mod_bot = lnum + 1;
2535 buf->b_mod_xlines = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 }
2537}
2538
2539/*
2540 * Appended "count" lines below line "lnum" in the current buffer.
2541 * Must be called AFTER the change and after mark_adjust().
2542 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2543 */
2544 void
2545appended_lines(lnum, count)
2546 linenr_T lnum;
2547 long count;
2548{
2549 changed_lines(lnum + 1, 0, lnum + 1, count);
2550}
2551
2552/*
2553 * Like appended_lines(), but adjust marks first.
2554 */
2555 void
2556appended_lines_mark(lnum, count)
2557 linenr_T lnum;
2558 long count;
2559{
2560 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
2561 changed_lines(lnum + 1, 0, lnum + 1, count);
2562}
2563
2564/*
2565 * Deleted "count" lines at line "lnum" in the current buffer.
2566 * Must be called AFTER the change and after mark_adjust().
2567 * Takes care of marking the buffer to be redrawn and sets the changed flag.
2568 */
2569 void
2570deleted_lines(lnum, count)
2571 linenr_T lnum;
2572 long count;
2573{
2574 changed_lines(lnum, 0, lnum + count, -count);
2575}
2576
2577/*
2578 * Like deleted_lines(), but adjust marks first.
2579 */
2580 void
2581deleted_lines_mark(lnum, count)
2582 linenr_T lnum;
2583 long count;
2584{
2585 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
2586 changed_lines(lnum, 0, lnum + count, -count);
2587}
2588
2589/*
2590 * Changed lines for the current buffer.
2591 * Must be called AFTER the change and after mark_adjust().
2592 * - mark the buffer changed by calling changed()
2593 * - mark the windows on this buffer to be redisplayed
2594 * - invalidate cached values
2595 * "lnum" is the first line that needs displaying, "lnume" the first line
2596 * below the changed lines (BEFORE the change).
2597 * When only inserting lines, "lnum" and "lnume" are equal.
2598 * Takes care of calling changed() and updating b_mod_*.
2599 */
2600 void
2601changed_lines(lnum, col, lnume, xtra)
2602 linenr_T lnum; /* first line with change */
2603 colnr_T col; /* column in first line with change */
2604 linenr_T lnume; /* line below last changed line */
2605 long xtra; /* number of extra lines (negative when deleting) */
2606{
Bram Moolenaardba8a912005-04-24 22:08:39 +00002607 changed_lines_buf(curbuf, lnum, lnume, xtra);
2608
2609#ifdef FEAT_DIFF
2610 if (xtra == 0 && curwin->w_p_diff)
2611 {
2612 /* When the number of lines doesn't change then mark_adjust() isn't
2613 * called and other diff buffers still need to be marked for
2614 * displaying. */
2615 win_T *wp;
2616 linenr_T wlnum;
2617
2618 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2619 if (wp->w_p_diff && wp != curwin)
2620 {
2621 redraw_win_later(wp, VALID);
2622 wlnum = diff_lnum_win(lnum, wp);
2623 if (wlnum > 0)
2624 changed_lines_buf(wp->w_buffer, wlnum,
2625 lnume - lnum + wlnum, 0L);
2626 }
2627 }
2628#endif
2629
2630 changed_common(lnum, col, lnume, xtra);
2631}
2632
2633 static void
2634changed_lines_buf(buf, lnum, lnume, xtra)
2635 buf_T *buf;
2636 linenr_T lnum; /* first line with change */
2637 linenr_T lnume; /* line below last changed line */
2638 long xtra; /* number of extra lines (negative when deleting) */
2639{
2640 if (buf->b_mod_set)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002641 {
2642 /* find the maximum area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002643 if (lnum < buf->b_mod_top)
2644 buf->b_mod_top = lnum;
2645 if (lnum < buf->b_mod_bot)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002646 {
2647 /* adjust old bot position for xtra lines */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002648 buf->b_mod_bot += xtra;
2649 if (buf->b_mod_bot < lnum)
2650 buf->b_mod_bot = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 }
Bram Moolenaardba8a912005-04-24 22:08:39 +00002652 if (lnume + xtra > buf->b_mod_bot)
2653 buf->b_mod_bot = lnume + xtra;
2654 buf->b_mod_xlines += xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002655 }
2656 else
2657 {
2658 /* set the area that must be redisplayed */
Bram Moolenaardba8a912005-04-24 22:08:39 +00002659 buf->b_mod_set = TRUE;
2660 buf->b_mod_top = lnum;
2661 buf->b_mod_bot = lnume + xtra;
2662 buf->b_mod_xlines = xtra;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664}
2665
2666 static void
2667changed_common(lnum, col, lnume, xtra)
2668 linenr_T lnum;
2669 colnr_T col;
2670 linenr_T lnume;
2671 long xtra;
2672{
2673 win_T *wp;
2674 int i;
2675#ifdef FEAT_JUMPLIST
2676 int cols;
2677 pos_T *p;
2678 int add;
2679#endif
2680
2681 /* mark the buffer as modified */
2682 changed();
2683
2684 /* set the '. mark */
2685 if (!cmdmod.keepjumps)
2686 {
2687 curbuf->b_last_change.lnum = lnum;
2688 curbuf->b_last_change.col = col;
2689
2690#ifdef FEAT_JUMPLIST
2691 /* Create a new entry if a new undo-able change was started or we
2692 * don't have an entry yet. */
2693 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
2694 {
2695 if (curbuf->b_changelistlen == 0)
2696 add = TRUE;
2697 else
2698 {
2699 /* Don't create a new entry when the line number is the same
2700 * as the last one and the column is not too far away. Avoids
2701 * creating many entries for typing "xxxxx". */
2702 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
2703 if (p->lnum != lnum)
2704 add = TRUE;
2705 else
2706 {
2707 cols = comp_textwidth(FALSE);
2708 if (cols == 0)
2709 cols = 79;
2710 add = (p->col + cols < col || col + cols < p->col);
2711 }
2712 }
2713 if (add)
2714 {
2715 /* This is the first of a new sequence of undo-able changes
2716 * and it's at some distance of the last change. Use a new
2717 * position in the changelist. */
2718 curbuf->b_new_change = FALSE;
2719
2720 if (curbuf->b_changelistlen == JUMPLISTSIZE)
2721 {
2722 /* changelist is full: remove oldest entry */
2723 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
2724 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
2725 sizeof(pos_T) * (JUMPLISTSIZE - 1));
2726 FOR_ALL_WINDOWS(wp)
2727 {
2728 /* Correct position in changelist for other windows on
2729 * this buffer. */
2730 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
2731 --wp->w_changelistidx;
2732 }
2733 }
2734 FOR_ALL_WINDOWS(wp)
2735 {
2736 /* For other windows, if the position in the changelist is
2737 * at the end it stays at the end. */
2738 if (wp->w_buffer == curbuf
2739 && wp->w_changelistidx == curbuf->b_changelistlen)
2740 ++wp->w_changelistidx;
2741 }
2742 ++curbuf->b_changelistlen;
2743 }
2744 }
2745 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
2746 curbuf->b_last_change;
2747 /* The current window is always after the last change, so that "g,"
2748 * takes you back to it. */
2749 curwin->w_changelistidx = curbuf->b_changelistlen;
2750#endif
2751 }
2752
2753 FOR_ALL_WINDOWS(wp)
2754 {
2755 if (wp->w_buffer == curbuf)
2756 {
2757 /* Mark this window to be redrawn later. */
2758 if (wp->w_redr_type < VALID)
2759 wp->w_redr_type = VALID;
2760
2761 /* Check if a change in the buffer has invalidated the cached
2762 * values for the cursor. */
2763#ifdef FEAT_FOLDING
2764 /*
2765 * Update the folds for this window. Can't postpone this, because
2766 * a following operator might work on the whole fold: ">>dd".
2767 */
2768 foldUpdate(wp, lnum, lnume + xtra - 1);
2769
2770 /* The change may cause lines above or below the change to become
2771 * included in a fold. Set lnum/lnume to the first/last line that
2772 * might be displayed differently.
2773 * Set w_cline_folded here as an efficient way to update it when
2774 * inserting lines just above a closed fold. */
2775 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
2776 if (wp->w_cursor.lnum == lnum)
2777 wp->w_cline_folded = i;
2778 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
2779 if (wp->w_cursor.lnum == lnume)
2780 wp->w_cline_folded = i;
2781
2782 /* If the changed line is in a range of previously folded lines,
2783 * compare with the first line in that range. */
2784 if (wp->w_cursor.lnum <= lnum)
2785 {
2786 i = find_wl_entry(wp, lnum);
2787 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
2788 changed_line_abv_curs_win(wp);
2789 }
2790#endif
2791
2792 if (wp->w_cursor.lnum > lnum)
2793 changed_line_abv_curs_win(wp);
2794 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
2795 changed_cline_bef_curs_win(wp);
2796 if (wp->w_botline >= lnum)
2797 {
2798 /* Assume that botline doesn't change (inserted lines make
2799 * other lines scroll down below botline). */
2800 approximate_botline_win(wp);
2801 }
2802
2803 /* Check if any w_lines[] entries have become invalid.
2804 * For entries below the change: Correct the lnums for
2805 * inserted/deleted lines. Makes it possible to stop displaying
2806 * after the change. */
2807 for (i = 0; i < wp->w_lines_valid; ++i)
2808 if (wp->w_lines[i].wl_valid)
2809 {
2810 if (wp->w_lines[i].wl_lnum >= lnum)
2811 {
2812 if (wp->w_lines[i].wl_lnum < lnume)
2813 {
2814 /* line included in change */
2815 wp->w_lines[i].wl_valid = FALSE;
2816 }
2817 else if (xtra != 0)
2818 {
2819 /* line below change */
2820 wp->w_lines[i].wl_lnum += xtra;
2821#ifdef FEAT_FOLDING
2822 wp->w_lines[i].wl_lastlnum += xtra;
2823#endif
2824 }
2825 }
2826#ifdef FEAT_FOLDING
2827 else if (wp->w_lines[i].wl_lastlnum >= lnum)
2828 {
2829 /* change somewhere inside this range of folded lines,
2830 * may need to be redrawn */
2831 wp->w_lines[i].wl_valid = FALSE;
2832 }
2833#endif
2834 }
2835 }
2836 }
2837
2838 /* Call update_screen() later, which checks out what needs to be redrawn,
2839 * since it notices b_mod_set and then uses b_mod_*. */
2840 if (must_redraw < VALID)
2841 must_redraw = VALID;
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002842
2843#ifdef FEAT_AUTOCMD
2844 /* when the cursor line is changed always trigger CursorMoved */
2845 if (lnum <= curwin->w_cursor.lnum && lnume > curwin->w_cursor.lnum)
2846 last_cursormoved.lnum = 0;
2847#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848}
2849
2850/*
2851 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2852 */
2853 void
2854unchanged(buf, ff)
2855 buf_T *buf;
2856 int ff; /* also reset 'fileformat' */
2857{
2858 if (buf->b_changed || (ff && file_ff_differs(buf)))
2859 {
2860 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002861 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862 if (ff)
2863 save_file_ff(buf);
2864#ifdef FEAT_WINDOWS
2865 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002866 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867#endif
2868#ifdef FEAT_TITLE
2869 need_maketitle = TRUE; /* set window title later */
2870#endif
2871 }
2872 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873#ifdef FEAT_NETBEANS_INTG
2874 netbeans_unmodified(buf);
2875#endif
2876}
2877
2878#if defined(FEAT_WINDOWS) || defined(PROTO)
2879/*
2880 * check_status: called when the status bars for the buffer 'buf'
2881 * need to be updated
2882 */
2883 void
2884check_status(buf)
2885 buf_T *buf;
2886{
2887 win_T *wp;
2888
2889 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2890 if (wp->w_buffer == buf && wp->w_status_height)
2891 {
2892 wp->w_redr_status = TRUE;
2893 if (must_redraw < VALID)
2894 must_redraw = VALID;
2895 }
2896}
2897#endif
2898
2899/*
2900 * If the file is readonly, give a warning message with the first change.
2901 * Don't do this for autocommands.
2902 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00002903 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 * will be TRUE.
2905 */
2906 void
2907change_warning(col)
2908 int col; /* column for message; non-zero when in insert
2909 mode and 'showmode' is on */
2910{
2911 if (curbuf->b_did_warn == FALSE
2912 && curbufIsChanged() == 0
2913#ifdef FEAT_AUTOCMD
2914 && !autocmd_busy
2915#endif
2916 && curbuf->b_p_ro)
2917 {
2918#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002919 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002921 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922 if (!curbuf->b_p_ro)
2923 return;
2924#endif
2925 /*
2926 * Do what msg() does, but with a column offset if the warning should
2927 * be after the mode message.
2928 */
2929 msg_start();
2930 if (msg_row == Rows - 1)
2931 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00002932 msg_source(hl_attr(HLF_W));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933 MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
2934 hl_attr(HLF_W) | MSG_HIST);
2935 msg_clr_eos();
2936 (void)msg_end();
2937 if (msg_silent == 0 && !silent_mode)
2938 {
2939 out_flush();
2940 ui_delay(1000L, TRUE); /* give the user time to think about it */
2941 }
2942 curbuf->b_did_warn = TRUE;
2943 redraw_cmdline = FALSE; /* don't redraw and erase the message */
2944 if (msg_row < Rows - 1)
2945 showmode();
2946 }
2947}
2948
2949/*
2950 * Ask for a reply from the user, a 'y' or a 'n'.
2951 * No other characters are accepted, the message is repeated until a valid
2952 * reply is entered or CTRL-C is hit.
2953 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
2954 * from any buffers but directly from the user.
2955 *
2956 * return the 'y' or 'n'
2957 */
2958 int
2959ask_yesno(str, direct)
2960 char_u *str;
2961 int direct;
2962{
2963 int r = ' ';
2964 int save_State = State;
2965
2966 if (exiting) /* put terminal in raw mode for this question */
2967 settmode(TMODE_RAW);
2968 ++no_wait_return;
2969#ifdef USE_ON_FLY_SCROLL
2970 dont_scroll = TRUE; /* disallow scrolling here */
2971#endif
2972 State = CONFIRM; /* mouse behaves like with :confirm */
2973#ifdef FEAT_MOUSE
2974 setmouse(); /* disables mouse for xterm */
2975#endif
2976 ++no_mapping;
2977 ++allow_keys; /* no mapping here, but recognize keys */
2978
2979 while (r != 'y' && r != 'n')
2980 {
2981 /* same highlighting as for wait_return */
2982 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
2983 if (direct)
2984 r = get_keystroke();
2985 else
2986 r = safe_vgetc();
2987 if (r == Ctrl_C || r == ESC)
2988 r = 'n';
2989 msg_putchar(r); /* show what you typed */
2990 out_flush();
2991 }
2992 --no_wait_return;
2993 State = save_State;
2994#ifdef FEAT_MOUSE
2995 setmouse();
2996#endif
2997 --no_mapping;
2998 --allow_keys;
2999
3000 return r;
3001}
3002
3003/*
3004 * Get a key stroke directly from the user.
3005 * Ignores mouse clicks and scrollbar events, except a click for the left
3006 * button (used at the more prompt).
3007 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3008 * Disadvantage: typeahead is ignored.
3009 * Translates the interrupt character for unix to ESC.
3010 */
3011 int
3012get_keystroke()
3013{
3014#define CBUFLEN 151
3015 char_u buf[CBUFLEN];
3016 int len = 0;
3017 int n;
3018 int save_mapped_ctrl_c = mapped_ctrl_c;
3019
3020 mapped_ctrl_c = FALSE; /* mappings are not used here */
3021 for (;;)
3022 {
3023 cursor_on();
3024 out_flush();
3025
3026 /* First time: blocking wait. Second time: wait up to 100ms for a
3027 * terminal code to complete. Leave some room for check_termcode() to
3028 * insert a key code into (max 5 chars plus NUL). And
3029 * fix_input_buffer() can triple the number of bytes. */
3030 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3031 len == 0 ? -1L : 100L, 0);
3032 if (n > 0)
3033 {
3034 /* Replace zero and CSI by a special key code. */
3035 n = fix_input_buffer(buf + len, n, FALSE);
3036 len += n;
3037 }
3038
3039 /* incomplete termcode: get more characters */
3040 if ((n = check_termcode(1, buf, len)) < 0)
3041 continue;
3042 /* found a termcode: adjust length */
3043 if (n > 0)
3044 len = n;
3045 if (len == 0) /* nothing typed yet */
3046 continue;
3047
3048 /* Handle modifier and/or special key code. */
3049 n = buf[0];
3050 if (n == K_SPECIAL)
3051 {
3052 n = TO_SPECIAL(buf[1], buf[2]);
3053 if (buf[1] == KS_MODIFIER
3054 || n == K_IGNORE
3055#ifdef FEAT_MOUSE
3056 || n == K_LEFTMOUSE_NM
3057 || n == K_LEFTDRAG
3058 || n == K_LEFTRELEASE
3059 || n == K_LEFTRELEASE_NM
3060 || n == K_MIDDLEMOUSE
3061 || n == K_MIDDLEDRAG
3062 || n == K_MIDDLERELEASE
3063 || n == K_RIGHTMOUSE
3064 || n == K_RIGHTDRAG
3065 || n == K_RIGHTRELEASE
3066 || n == K_MOUSEDOWN
3067 || n == K_MOUSEUP
3068 || n == K_X1MOUSE
3069 || n == K_X1DRAG
3070 || n == K_X1RELEASE
3071 || n == K_X2MOUSE
3072 || n == K_X2DRAG
3073 || n == K_X2RELEASE
3074# ifdef FEAT_GUI
3075 || n == K_VER_SCROLLBAR
3076 || n == K_HOR_SCROLLBAR
3077# endif
3078#endif
3079 )
3080 {
3081 if (buf[1] == KS_MODIFIER)
3082 mod_mask = buf[2];
3083 len -= 3;
3084 if (len > 0)
3085 mch_memmove(buf, buf + 3, (size_t)len);
3086 continue;
3087 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003088 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 }
3090#ifdef FEAT_MBYTE
3091 if (has_mbyte)
3092 {
3093 if (MB_BYTE2LEN(n) > len)
3094 continue; /* more bytes to get */
3095 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3096 n = (*mb_ptr2char)(buf);
3097 }
3098#endif
3099#ifdef UNIX
3100 if (n == intr_char)
3101 n = ESC;
3102#endif
3103 break;
3104 }
3105
3106 mapped_ctrl_c = save_mapped_ctrl_c;
3107 return n;
3108}
3109
3110/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003111 * Get a number from the user.
3112 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113 */
3114 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003115get_number(colon, mouse_used)
3116 int colon; /* allow colon to abort */
3117 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118{
3119 int n = 0;
3120 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003121 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003122
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003123 if (mouse_used != NULL)
3124 *mouse_used = FALSE;
3125
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126 /* When not printing messages, the user won't know what to type, return a
3127 * zero (as if CR was hit). */
3128 if (msg_silent != 0)
3129 return 0;
3130
3131#ifdef USE_ON_FLY_SCROLL
3132 dont_scroll = TRUE; /* disallow scrolling here */
3133#endif
3134 ++no_mapping;
3135 ++allow_keys; /* no mapping here, but recognize keys */
3136 for (;;)
3137 {
3138 windgoto(msg_row, msg_col);
3139 c = safe_vgetc();
3140 if (VIM_ISDIGIT(c))
3141 {
3142 n = n * 10 + c - '0';
3143 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003144 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003145 }
3146 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3147 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003148 if (typed > 0)
3149 {
3150 MSG_PUTS("\b \b");
3151 --typed;
3152 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003155#ifdef FEAT_MOUSE
3156 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3157 {
3158 *mouse_used = TRUE;
3159 n = mouse_row + 1;
3160 break;
3161 }
3162#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 else if (n == 0 && c == ':' && colon)
3164 {
3165 stuffcharReadbuff(':');
3166 if (!exmode_active)
3167 cmdline_row = msg_row;
3168 skip_redraw = TRUE; /* skip redraw once */
3169 do_redraw = FALSE;
3170 break;
3171 }
3172 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3173 break;
3174 }
3175 --no_mapping;
3176 --allow_keys;
3177 return n;
3178}
3179
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003180/*
3181 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003182 * When "mouse_used" is not NULL allow using the mouse and in that case return
3183 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003184 */
3185 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003186prompt_for_number(mouse_used)
3187 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003188{
3189 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003190 int save_cmdline_row;
3191 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003192
3193 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003194 if (mouse_used != NULL)
3195 MSG_PUTS(_("Type number or click with mouse (<Enter> cancels): "));
3196 else
3197 MSG_PUTS(_("Choice number (<Enter> cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003198
Bram Moolenaar203335e2006-09-03 14:35:42 +00003199 /* Set the state such that text can be selected/copied/pasted and we still
3200 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003201 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003202 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003203 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003204 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003205
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003206 i = get_number(TRUE, mouse_used);
3207 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003208 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003209 /* don't call wait_return() now */
3210 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003211 cmdline_row = msg_row - 1;
3212 need_wait_return = FALSE;
3213 msg_didany = FALSE;
3214 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003215 else
3216 cmdline_row = save_cmdline_row;
3217 State = save_State;
3218
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003219 return i;
3220}
3221
Bram Moolenaar071d4272004-06-13 20:20:40 +00003222 void
3223msgmore(n)
3224 long n;
3225{
3226 long pn;
3227
3228 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3230 return;
3231
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003232 /* We don't want to overwrite another important message, but do overwrite
3233 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3234 * then "put" reports the last action. */
3235 if (keep_msg != NULL && !keep_msg_more)
3236 return;
3237
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238 if (n > 0)
3239 pn = n;
3240 else
3241 pn = -n;
3242
3243 if (pn > p_report)
3244 {
3245 if (pn == 1)
3246 {
3247 if (n > 0)
3248 STRCPY(msg_buf, _("1 more line"));
3249 else
3250 STRCPY(msg_buf, _("1 line less"));
3251 }
3252 else
3253 {
3254 if (n > 0)
3255 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3256 else
3257 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3258 }
3259 if (got_int)
3260 STRCAT(msg_buf, _(" (Interrupted)"));
3261 if (msg(msg_buf))
3262 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003263 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003264 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 }
3266 }
3267}
3268
3269/*
3270 * flush map and typeahead buffers and give a warning for an error
3271 */
3272 void
3273beep_flush()
3274{
3275 if (emsg_silent == 0)
3276 {
3277 flush_buffers(FALSE);
3278 vim_beep();
3279 }
3280}
3281
3282/*
3283 * give a warning for an error
3284 */
3285 void
3286vim_beep()
3287{
3288 if (emsg_silent == 0)
3289 {
3290 if (p_vb
3291#ifdef FEAT_GUI
3292 /* While the GUI is starting up the termcap is set for the GUI
3293 * but the output still goes to a terminal. */
3294 && !(gui.in_use && gui.starting)
3295#endif
3296 )
3297 {
3298 out_str(T_VB);
3299 }
3300 else
3301 {
3302#ifdef MSDOS
3303 /*
3304 * The number of beeps outputted is reduced to avoid having to wait
3305 * for all the beeps to finish. This is only a problem on systems
3306 * where the beeps don't overlap.
3307 */
3308 if (beep_count == 0 || beep_count == 10)
3309 {
3310 out_char(BELL);
3311 beep_count = 1;
3312 }
3313 else
3314 ++beep_count;
3315#else
3316 out_char(BELL);
3317#endif
3318 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003319
3320 /* When 'verbose' is set and we are sourcing a script or executing a
3321 * function give the user a hint where the beep comes from. */
3322 if (vim_strchr(p_debug, 'e') != NULL)
3323 {
3324 msg_source(hl_attr(HLF_W));
3325 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3326 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003327 }
3328}
3329
3330/*
3331 * To get the "real" home directory:
3332 * - get value of $HOME
3333 * For Unix:
3334 * - go to that directory
3335 * - do mch_dirname() to get the real name of that directory.
3336 * This also works with mounts and links.
3337 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3338 */
3339static char_u *homedir = NULL;
3340
3341 void
3342init_homedir()
3343{
3344 char_u *var;
3345
Bram Moolenaar05159a02005-02-26 23:04:13 +00003346 /* In case we are called a second time (when 'encoding' changes). */
3347 vim_free(homedir);
3348 homedir = NULL;
3349
Bram Moolenaar071d4272004-06-13 20:20:40 +00003350#ifdef VMS
3351 var = mch_getenv((char_u *)"SYS$LOGIN");
3352#else
3353 var = mch_getenv((char_u *)"HOME");
3354#endif
3355
3356 if (var != NULL && *var == NUL) /* empty is same as not set */
3357 var = NULL;
3358
3359#ifdef WIN3264
3360 /*
3361 * Weird but true: $HOME may contain an indirect reference to another
3362 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3363 * when $HOME is being set.
3364 */
3365 if (var != NULL && *var == '%')
3366 {
3367 char_u *p;
3368 char_u *exp;
3369
3370 p = vim_strchr(var + 1, '%');
3371 if (p != NULL)
3372 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003373 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374 exp = mch_getenv(NameBuff);
3375 if (exp != NULL && *exp != NUL
3376 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3377 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003378 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 var = NameBuff;
3380 /* Also set $HOME, it's needed for _viminfo. */
3381 vim_setenv((char_u *)"HOME", NameBuff);
3382 }
3383 }
3384 }
3385
3386 /*
3387 * Typically, $HOME is not defined on Windows, unless the user has
3388 * specifically defined it for Vim's sake. However, on Windows NT
3389 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3390 * each user. Try constructing $HOME from these.
3391 */
3392 if (var == NULL)
3393 {
3394 char_u *homedrive, *homepath;
3395
3396 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3397 homepath = mch_getenv((char_u *)"HOMEPATH");
3398 if (homedrive != NULL && homepath != NULL
3399 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3400 {
3401 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3402 if (NameBuff[0] != NUL)
3403 {
3404 var = NameBuff;
3405 /* Also set $HOME, it's needed for _viminfo. */
3406 vim_setenv((char_u *)"HOME", NameBuff);
3407 }
3408 }
3409 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003410
3411# if defined(FEAT_MBYTE)
3412 if (enc_utf8 && var != NULL)
3413 {
3414 int len;
3415 char_u *pp;
3416
3417 /* Convert from active codepage to UTF-8. Other conversions are
3418 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003419 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003420 if (pp != NULL)
3421 {
3422 homedir = pp;
3423 return;
3424 }
3425 }
3426# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427#endif
3428
3429#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3430 /*
3431 * Default home dir is C:/
3432 * Best assumption we can make in such a situation.
3433 */
3434 if (var == NULL)
3435 var = "C:/";
3436#endif
3437 if (var != NULL)
3438 {
3439#ifdef UNIX
3440 /*
3441 * Change to the directory and get the actual path. This resolves
3442 * links. Don't do it when we can't return.
3443 */
3444 if (mch_dirname(NameBuff, MAXPATHL) == OK
3445 && mch_chdir((char *)NameBuff) == 0)
3446 {
3447 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3448 var = IObuff;
3449 if (mch_chdir((char *)NameBuff) != 0)
3450 EMSG(_(e_prev_dir));
3451 }
3452#endif
3453 homedir = vim_strsave(var);
3454 }
3455}
3456
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003457#if defined(EXITFREE) || defined(PROTO)
3458 void
3459free_homedir()
3460{
3461 vim_free(homedir);
3462}
3463#endif
3464
Bram Moolenaar071d4272004-06-13 20:20:40 +00003465/*
3466 * Expand environment variable with path name.
3467 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3468 * Skips over "\ ", "\~" and "\$".
3469 * If anything fails no expansion is done and dst equals src.
3470 */
3471 void
3472expand_env(src, dst, dstlen)
3473 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3474 char_u *dst; /* where to put the result */
3475 int dstlen; /* maximum length of the result */
3476{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003477 expand_env_esc(src, dst, dstlen, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003478}
3479
3480 void
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003481expand_env_esc(srcp, dst, dstlen, esc, startstr)
3482 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 char_u *dst; /* where to put the result */
3484 int dstlen; /* maximum length of the result */
3485 int esc; /* escape spaces in expanded variables */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003486 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003488 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 char_u *tail;
3490 int c;
3491 char_u *var;
3492 int copy_char;
3493 int mustfree; /* var was allocated, need to free it later */
3494 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003495 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003497 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003498 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003499
3500 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501 --dstlen; /* leave one char space for "\," */
3502 while (*src && dstlen > 0)
3503 {
3504 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003505 if ((*src == '$'
3506#ifdef VMS
3507 && at_start
3508#endif
3509 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3511 || *src == '%'
3512#endif
3513 || (*src == '~' && at_start))
3514 {
3515 mustfree = FALSE;
3516
3517 /*
3518 * The variable name is copied into dst temporarily, because it may
3519 * be a string in read-only memory and a NUL needs to be appended.
3520 */
3521 if (*src != '~') /* environment var */
3522 {
3523 tail = src + 1;
3524 var = dst;
3525 c = dstlen - 1;
3526
3527#ifdef UNIX
3528 /* Unix has ${var-name} type environment vars */
3529 if (*tail == '{' && !vim_isIDc('{'))
3530 {
3531 tail++; /* ignore '{' */
3532 while (c-- > 0 && *tail && *tail != '}')
3533 *var++ = *tail++;
3534 }
3535 else
3536#endif
3537 {
3538 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3539#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3540 || (*src == '%' && *tail != '%')
3541#endif
3542 ))
3543 {
3544#ifdef OS2 /* env vars only in uppercase */
3545 *var++ = TOUPPER_LOC(*tail);
3546 tail++; /* toupper() may be a macro! */
3547#else
3548 *var++ = *tail++;
3549#endif
3550 }
3551 }
3552
3553#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3554# ifdef UNIX
3555 if (src[1] == '{' && *tail != '}')
3556# else
3557 if (*src == '%' && *tail != '%')
3558# endif
3559 var = NULL;
3560 else
3561 {
3562# ifdef UNIX
3563 if (src[1] == '{')
3564# else
3565 if (*src == '%')
3566#endif
3567 ++tail;
3568#endif
3569 *var = NUL;
3570 var = vim_getenv(dst, &mustfree);
3571#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3572 }
3573#endif
3574 }
3575 /* home directory */
3576 else if ( src[1] == NUL
3577 || vim_ispathsep(src[1])
3578 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3579 {
3580 var = homedir;
3581 tail = src + 1;
3582 }
3583 else /* user directory */
3584 {
3585#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3586 /*
3587 * Copy ~user to dst[], so we can put a NUL after it.
3588 */
3589 tail = src;
3590 var = dst;
3591 c = dstlen - 1;
3592 while ( c-- > 0
3593 && *tail
3594 && vim_isfilec(*tail)
3595 && !vim_ispathsep(*tail))
3596 *var++ = *tail++;
3597 *var = NUL;
3598# ifdef UNIX
3599 /*
3600 * If the system supports getpwnam(), use it.
3601 * Otherwise, or if getpwnam() fails, the shell is used to
3602 * expand ~user. This is slower and may fail if the shell
3603 * does not support ~user (old versions of /bin/sh).
3604 */
3605# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3606 {
3607 struct passwd *pw;
3608
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003609 /* Note: memory allocated by getpwnam() is never freed.
3610 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611 pw = getpwnam((char *)dst + 1);
3612 if (pw != NULL)
3613 var = (char_u *)pw->pw_dir;
3614 else
3615 var = NULL;
3616 }
3617 if (var == NULL)
3618# endif
3619 {
3620 expand_T xpc;
3621
3622 ExpandInit(&xpc);
3623 xpc.xp_context = EXPAND_FILES;
3624 var = ExpandOne(&xpc, dst, NULL,
3625 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626 mustfree = TRUE;
3627 }
3628
3629# else /* !UNIX, thus VMS */
3630 /*
3631 * USER_HOME is a comma-separated list of
3632 * directories to search for the user account in.
3633 */
3634 {
3635 char_u test[MAXPATHL], paths[MAXPATHL];
3636 char_u *path, *next_path, *ptr;
3637 struct stat st;
3638
3639 STRCPY(paths, USER_HOME);
3640 next_path = paths;
3641 while (*next_path)
3642 {
3643 for (path = next_path; *next_path && *next_path != ',';
3644 next_path++);
3645 if (*next_path)
3646 *next_path++ = NUL;
3647 STRCPY(test, path);
3648 STRCAT(test, "/");
3649 STRCAT(test, dst + 1);
3650 if (mch_stat(test, &st) == 0)
3651 {
3652 var = alloc(STRLEN(test) + 1);
3653 STRCPY(var, test);
3654 mustfree = TRUE;
3655 break;
3656 }
3657 }
3658 }
3659# endif /* UNIX */
3660#else
3661 /* cannot expand user's home directory, so don't try */
3662 var = NULL;
3663 tail = (char_u *)""; /* for gcc */
3664#endif /* UNIX || VMS */
3665 }
3666
3667#ifdef BACKSLASH_IN_FILENAME
3668 /* If 'shellslash' is set change backslashes to forward slashes.
3669 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3670 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3671 {
3672 char_u *p = vim_strsave(var);
3673
3674 if (p != NULL)
3675 {
3676 if (mustfree)
3677 vim_free(var);
3678 var = p;
3679 mustfree = TRUE;
3680 forward_slash(var);
3681 }
3682 }
3683#endif
3684
3685 /* If "var" contains white space, escape it with a backslash.
3686 * Required for ":e ~/tt" when $HOME includes a space. */
3687 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3688 {
3689 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3690
3691 if (p != NULL)
3692 {
3693 if (mustfree)
3694 vim_free(var);
3695 var = p;
3696 mustfree = TRUE;
3697 }
3698 }
3699
3700 if (var != NULL && *var != NUL
3701 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3702 {
3703 STRCPY(dst, var);
3704 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003705 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706 /* if var[] ends in a path separator and tail[] starts
3707 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003708 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003709#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3710 && dst[-1] != ':'
3711#endif
3712 && vim_ispathsep(*tail))
3713 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003714 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003715 src = tail;
3716 copy_char = FALSE;
3717 }
3718 if (mustfree)
3719 vim_free(var);
3720 }
3721
3722 if (copy_char) /* copy at least one char */
3723 {
3724 /*
3725 * Recogize the start of a new name, for '~'.
3726 */
3727 at_start = FALSE;
3728 if (src[0] == '\\' && src[1] != NUL)
3729 {
3730 *dst++ = *src++;
3731 --dstlen;
3732 }
3733 else if (src[0] == ' ' || src[0] == ',')
3734 at_start = TRUE;
3735 *dst++ = *src++;
3736 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003737
3738 if (startstr != NULL && src - startstr_len >= srcp
3739 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3740 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741 }
3742 }
3743 *dst = NUL;
3744}
3745
3746/*
3747 * Vim's version of getenv().
3748 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00003749 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 */
3751 char_u *
3752vim_getenv(name, mustfree)
3753 char_u *name;
3754 int *mustfree; /* set to TRUE when returned is allocated */
3755{
3756 char_u *p;
3757 char_u *pend;
3758 int vimruntime;
3759
3760#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3761 /* use "C:/" when $HOME is not set */
3762 if (STRCMP(name, "HOME") == 0)
3763 return homedir;
3764#endif
3765
3766 p = mch_getenv(name);
3767 if (p != NULL && *p == NUL) /* empty is the same as not set */
3768 p = NULL;
3769
3770 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003771 {
3772#if defined(FEAT_MBYTE) && defined(WIN3264)
3773 if (enc_utf8)
3774 {
3775 int len;
3776 char_u *pp;
3777
3778 /* Convert from active codepage to UTF-8. Other conversions are
3779 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003780 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003781 if (pp != NULL)
3782 {
3783 p = pp;
3784 *mustfree = TRUE;
3785 }
3786 }
3787#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003789 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790
3791 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3792 if (!vimruntime && STRCMP(name, "VIM") != 0)
3793 return NULL;
3794
3795 /*
3796 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3797 * Don't do this when default_vimruntime_dir is non-empty.
3798 */
3799 if (vimruntime
3800#ifdef HAVE_PATHDEF
3801 && *default_vimruntime_dir == NUL
3802#endif
3803 )
3804 {
3805 p = mch_getenv((char_u *)"VIM");
3806 if (p != NULL && *p == NUL) /* empty is the same as not set */
3807 p = NULL;
3808 if (p != NULL)
3809 {
3810 p = vim_version_dir(p);
3811 if (p != NULL)
3812 *mustfree = TRUE;
3813 else
3814 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00003815
3816#if defined(FEAT_MBYTE) && defined(WIN3264)
3817 if (enc_utf8)
3818 {
3819 int len;
3820 char_u *pp;
3821
3822 /* Convert from active codepage to UTF-8. Other conversions
3823 * are not done, because they would fail for non-ASCII
3824 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003825 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003826 if (pp != NULL)
3827 {
3828 if (mustfree)
3829 vim_free(p);
3830 p = pp;
3831 *mustfree = TRUE;
3832 }
3833 }
3834#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835 }
3836 }
3837
3838 /*
3839 * When expanding $VIM or $VIMRUNTIME fails, try using:
3840 * - the directory name from 'helpfile' (unless it contains '$')
3841 * - the executable name from argv[0]
3842 */
3843 if (p == NULL)
3844 {
3845 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3846 p = p_hf;
3847#ifdef USE_EXE_NAME
3848 /*
3849 * Use the name of the executable, obtained from argv[0].
3850 */
3851 else
3852 p = exe_name;
3853#endif
3854 if (p != NULL)
3855 {
3856 /* remove the file name */
3857 pend = gettail(p);
3858
3859 /* remove "doc/" from 'helpfile', if present */
3860 if (p == p_hf)
3861 pend = remove_tail(p, pend, (char_u *)"doc");
3862
3863#ifdef USE_EXE_NAME
3864# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003865 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 if (p == exe_name)
3867 {
3868 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003869 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003870
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003871 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
3872 if (pend1 != pend)
3873 {
3874 pnew = alloc((unsigned)(pend1 - p) + 15);
3875 if (pnew != NULL)
3876 {
3877 STRNCPY(pnew, p, (pend1 - p));
3878 STRCPY(pnew + (pend1 - p), "Resources/vim");
3879 p = pnew;
3880 pend = p + STRLEN(p);
3881 }
3882 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 }
3884# endif
3885 /* remove "src/" from exe_name, if present */
3886 if (p == exe_name)
3887 pend = remove_tail(p, pend, (char_u *)"src");
3888#endif
3889
3890 /* for $VIM, remove "runtime/" or "vim54/", if present */
3891 if (!vimruntime)
3892 {
3893 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
3894 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
3895 }
3896
3897 /* remove trailing path separator */
3898#ifndef MACOS_CLASSIC
3899 /* With MacOS path (with colons) the final colon is required */
3900 /* to avoid confusion between absoulute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003901 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 --pend;
3903#endif
3904
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003905#ifdef MACOS_X
3906 if (p == exe_name || p == p_hf)
3907#endif
3908 /* check that the result is a directory name */
3909 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910
3911 if (p != NULL && !mch_isdir(p))
3912 {
3913 vim_free(p);
3914 p = NULL;
3915 }
3916 else
3917 {
3918#ifdef USE_EXE_NAME
3919 /* may add "/vim54" or "/runtime" if it exists */
3920 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
3921 {
3922 vim_free(p);
3923 p = pend;
3924 }
3925#endif
3926 *mustfree = TRUE;
3927 }
3928 }
3929 }
3930
3931#ifdef HAVE_PATHDEF
3932 /* When there is a pathdef.c file we can use default_vim_dir and
3933 * default_vimruntime_dir */
3934 if (p == NULL)
3935 {
3936 /* Only use default_vimruntime_dir when it is not empty */
3937 if (vimruntime && *default_vimruntime_dir != NUL)
3938 {
3939 p = default_vimruntime_dir;
3940 *mustfree = FALSE;
3941 }
3942 else if (*default_vim_dir != NUL)
3943 {
3944 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
3945 *mustfree = TRUE;
3946 else
3947 {
3948 p = default_vim_dir;
3949 *mustfree = FALSE;
3950 }
3951 }
3952 }
3953#endif
3954
3955 /*
3956 * Set the environment variable, so that the new value can be found fast
3957 * next time, and others can also use it (e.g. Perl).
3958 */
3959 if (p != NULL)
3960 {
3961 if (vimruntime)
3962 {
3963 vim_setenv((char_u *)"VIMRUNTIME", p);
3964 didset_vimruntime = TRUE;
3965#ifdef FEAT_GETTEXT
3966 {
Bram Moolenaard6754642005-01-17 22:18:45 +00003967 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968
3969 if (buf != NULL)
3970 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971 bindtextdomain(VIMPACKAGE, (char *)buf);
3972 vim_free(buf);
3973 }
3974 }
3975#endif
3976 }
3977 else
3978 {
3979 vim_setenv((char_u *)"VIM", p);
3980 didset_vim = TRUE;
3981 }
3982 }
3983 return p;
3984}
3985
3986/*
3987 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
3988 * Return NULL if not, return its name in allocated memory otherwise.
3989 */
3990 static char_u *
3991vim_version_dir(vimdir)
3992 char_u *vimdir;
3993{
3994 char_u *p;
3995
3996 if (vimdir == NULL || *vimdir == NUL)
3997 return NULL;
3998 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
3999 if (p != NULL && mch_isdir(p))
4000 return p;
4001 vim_free(p);
4002 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4003 if (p != NULL && mch_isdir(p))
4004 return p;
4005 vim_free(p);
4006 return NULL;
4007}
4008
4009/*
4010 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4011 * the length of "name/". Otherwise return "pend".
4012 */
4013 static char_u *
4014remove_tail(p, pend, name)
4015 char_u *p;
4016 char_u *pend;
4017 char_u *name;
4018{
4019 int len = (int)STRLEN(name) + 1;
4020 char_u *newend = pend - len;
4021
4022 if (newend >= p
4023 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004024 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004025 return newend;
4026 return pend;
4027}
4028
Bram Moolenaar071d4272004-06-13 20:20:40 +00004029/*
4030 * Call expand_env() and store the result in an allocated string.
4031 * This is not very memory efficient, this expects the result to be freed
4032 * again soon.
4033 */
4034 char_u *
4035expand_env_save(src)
4036 char_u *src;
4037{
4038 char_u *p;
4039
4040 p = alloc(MAXPATHL);
4041 if (p != NULL)
4042 expand_env(src, p, MAXPATHL);
4043 return p;
4044}
4045
4046/*
4047 * Our portable version of setenv.
4048 */
4049 void
4050vim_setenv(name, val)
4051 char_u *name;
4052 char_u *val;
4053{
4054#ifdef HAVE_SETENV
4055 mch_setenv((char *)name, (char *)val, 1);
4056#else
4057 char_u *envbuf;
4058
4059 /*
4060 * Putenv does not copy the string, it has to remain
4061 * valid. The allocated memory will never be freed.
4062 */
4063 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4064 if (envbuf != NULL)
4065 {
4066 sprintf((char *)envbuf, "%s=%s", name, val);
4067 putenv((char *)envbuf);
4068 }
4069#endif
4070}
4071
4072#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4073/*
4074 * Function given to ExpandGeneric() to obtain an environment variable name.
4075 */
4076/*ARGSUSED*/
4077 char_u *
4078get_env_name(xp, idx)
4079 expand_T *xp;
4080 int idx;
4081{
4082# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4083 /*
4084 * No environ[] on the Amiga and on the Mac (using MPW).
4085 */
4086 return NULL;
4087# else
4088# ifndef __WIN32__
4089 /* Borland C++ 5.2 has this in a header file. */
4090 extern char **environ;
4091# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004092# define ENVNAMELEN 100
4093 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004094 char_u *str;
4095 int n;
4096
4097 str = (char_u *)environ[idx];
4098 if (str == NULL)
4099 return NULL;
4100
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004101 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 {
4103 if (str[n] == '=' || str[n] == NUL)
4104 break;
4105 name[n] = str[n];
4106 }
4107 name[n] = NUL;
4108 return name;
4109# endif
4110}
4111#endif
4112
4113/*
4114 * Replace home directory by "~" in each space or comma separated file name in
4115 * 'src'.
4116 * If anything fails (except when out of space) dst equals src.
4117 */
4118 void
4119home_replace(buf, src, dst, dstlen, one)
4120 buf_T *buf; /* when not NULL, check for help files */
4121 char_u *src; /* input file name */
4122 char_u *dst; /* where to put the result */
4123 int dstlen; /* maximum length of the result */
4124 int one; /* if TRUE, only replace one file name, include
4125 spaces and commas in the file name. */
4126{
4127 size_t dirlen = 0, envlen = 0;
4128 size_t len;
4129 char_u *homedir_env;
4130 char_u *p;
4131
4132 if (src == NULL)
4133 {
4134 *dst = NUL;
4135 return;
4136 }
4137
4138 /*
4139 * If the file is a help file, remove the path completely.
4140 */
4141 if (buf != NULL && buf->b_help)
4142 {
4143 STRCPY(dst, gettail(src));
4144 return;
4145 }
4146
4147 /*
4148 * We check both the value of the $HOME environment variable and the
4149 * "real" home directory.
4150 */
4151 if (homedir != NULL)
4152 dirlen = STRLEN(homedir);
4153
4154#ifdef VMS
4155 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4156#else
4157 homedir_env = mch_getenv((char_u *)"HOME");
4158#endif
4159
4160 if (homedir_env != NULL && *homedir_env == NUL)
4161 homedir_env = NULL;
4162 if (homedir_env != NULL)
4163 envlen = STRLEN(homedir_env);
4164
4165 if (!one)
4166 src = skipwhite(src);
4167 while (*src && dstlen > 0)
4168 {
4169 /*
4170 * Here we are at the beginning of a file name.
4171 * First, check to see if the beginning of the file name matches
4172 * $HOME or the "real" home directory. Check that there is a '/'
4173 * after the match (so that if e.g. the file is "/home/pieter/bla",
4174 * and the home directory is "/home/piet", the file does not end up
4175 * as "~er/bla" (which would seem to indicate the file "bla" in user
4176 * er's home directory)).
4177 */
4178 p = homedir;
4179 len = dirlen;
4180 for (;;)
4181 {
4182 if ( len
4183 && fnamencmp(src, p, len) == 0
4184 && (vim_ispathsep(src[len])
4185 || (!one && (src[len] == ',' || src[len] == ' '))
4186 || src[len] == NUL))
4187 {
4188 src += len;
4189 if (--dstlen > 0)
4190 *dst++ = '~';
4191
4192 /*
4193 * If it's just the home directory, add "/".
4194 */
4195 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4196 *dst++ = '/';
4197 break;
4198 }
4199 if (p == homedir_env)
4200 break;
4201 p = homedir_env;
4202 len = envlen;
4203 }
4204
4205 /* if (!one) skip to separator: space or comma */
4206 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4207 *dst++ = *src++;
4208 /* skip separator */
4209 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4210 *dst++ = *src++;
4211 }
4212 /* if (dstlen == 0) out of space, what to do??? */
4213
4214 *dst = NUL;
4215}
4216
4217/*
4218 * Like home_replace, store the replaced string in allocated memory.
4219 * When something fails, NULL is returned.
4220 */
4221 char_u *
4222home_replace_save(buf, src)
4223 buf_T *buf; /* when not NULL, check for help files */
4224 char_u *src; /* input file name */
4225{
4226 char_u *dst;
4227 unsigned len;
4228
4229 len = 3; /* space for "~/" and trailing NUL */
4230 if (src != NULL) /* just in case */
4231 len += (unsigned)STRLEN(src);
4232 dst = alloc(len);
4233 if (dst != NULL)
4234 home_replace(buf, src, dst, len, TRUE);
4235 return dst;
4236}
4237
4238/*
4239 * Compare two file names and return:
4240 * FPC_SAME if they both exist and are the same file.
4241 * FPC_SAMEX if they both don't exist and have the same file name.
4242 * FPC_DIFF if they both exist and are different files.
4243 * FPC_NOTX if they both don't exist.
4244 * FPC_DIFFX if one of them doesn't exist.
4245 * For the first name environment variables are expanded
4246 */
4247 int
4248fullpathcmp(s1, s2, checkname)
4249 char_u *s1, *s2;
4250 int checkname; /* when both don't exist, check file names */
4251{
4252#ifdef UNIX
4253 char_u exp1[MAXPATHL];
4254 char_u full1[MAXPATHL];
4255 char_u full2[MAXPATHL];
4256 struct stat st1, st2;
4257 int r1, r2;
4258
4259 expand_env(s1, exp1, MAXPATHL);
4260 r1 = mch_stat((char *)exp1, &st1);
4261 r2 = mch_stat((char *)s2, &st2);
4262 if (r1 != 0 && r2 != 0)
4263 {
4264 /* if mch_stat() doesn't work, may compare the names */
4265 if (checkname)
4266 {
4267 if (fnamecmp(exp1, s2) == 0)
4268 return FPC_SAMEX;
4269 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4270 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4271 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4272 return FPC_SAMEX;
4273 }
4274 return FPC_NOTX;
4275 }
4276 if (r1 != 0 || r2 != 0)
4277 return FPC_DIFFX;
4278 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4279 return FPC_SAME;
4280 return FPC_DIFF;
4281#else
4282 char_u *exp1; /* expanded s1 */
4283 char_u *full1; /* full path of s1 */
4284 char_u *full2; /* full path of s2 */
4285 int retval = FPC_DIFF;
4286 int r1, r2;
4287
4288 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4289 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4290 {
4291 full1 = exp1 + MAXPATHL;
4292 full2 = full1 + MAXPATHL;
4293
4294 expand_env(s1, exp1, MAXPATHL);
4295 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4296 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4297
4298 /* If vim_FullName() fails, the file probably doesn't exist. */
4299 if (r1 != OK && r2 != OK)
4300 {
4301 if (checkname && fnamecmp(exp1, s2) == 0)
4302 retval = FPC_SAMEX;
4303 else
4304 retval = FPC_NOTX;
4305 }
4306 else if (r1 != OK || r2 != OK)
4307 retval = FPC_DIFFX;
4308 else if (fnamecmp(full1, full2))
4309 retval = FPC_DIFF;
4310 else
4311 retval = FPC_SAME;
4312 vim_free(exp1);
4313 }
4314 return retval;
4315#endif
4316}
4317
4318/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004319 * Get the tail of a path: the file name.
4320 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004321 */
4322 char_u *
4323gettail(fname)
4324 char_u *fname;
4325{
4326 char_u *p1, *p2;
4327
4328 if (fname == NULL)
4329 return (char_u *)"";
4330 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4331 {
4332 if (vim_ispathsep(*p2))
4333 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004334 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004335 }
4336 return p1;
4337}
4338
4339/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004340 * Get pointer to tail of "fname", including path separators. Putting a NUL
4341 * here leaves the directory name. Takes care of "c:/" and "//".
4342 * Always returns a valid pointer.
4343 */
4344 char_u *
4345gettail_sep(fname)
4346 char_u *fname;
4347{
4348 char_u *p;
4349 char_u *t;
4350
4351 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4352 t = gettail(fname);
4353 while (t > p && after_pathsep(fname, t))
4354 --t;
4355#ifdef VMS
4356 /* path separator is part of the path */
4357 ++t;
4358#endif
4359 return t;
4360}
4361
4362/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004363 * get the next path component (just after the next path separator).
4364 */
4365 char_u *
4366getnextcomp(fname)
4367 char_u *fname;
4368{
4369 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004370 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004371 if (*fname)
4372 ++fname;
4373 return fname;
4374}
4375
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376/*
4377 * Get a pointer to one character past the head of a path name.
4378 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4379 * If there is no head, path is returned.
4380 */
4381 char_u *
4382get_past_head(path)
4383 char_u *path;
4384{
4385 char_u *retval;
4386
4387#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4388 /* may skip "c:" */
4389 if (isalpha(path[0]) && path[1] == ':')
4390 retval = path + 2;
4391 else
4392 retval = path;
4393#else
4394# if defined(AMIGA)
4395 /* may skip "label:" */
4396 retval = vim_strchr(path, ':');
4397 if (retval == NULL)
4398 retval = path;
4399# else /* Unix */
4400 retval = path;
4401# endif
4402#endif
4403
4404 while (vim_ispathsep(*retval))
4405 ++retval;
4406
4407 return retval;
4408}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004409
4410/*
4411 * return TRUE if 'c' is a path separator.
4412 */
4413 int
4414vim_ispathsep(c)
4415 int c;
4416{
4417#ifdef RISCOS
4418 return (c == '.' || c == ':');
4419#else
4420# ifdef UNIX
4421 return (c == '/'); /* UNIX has ':' inside file names */
4422# else
4423# ifdef BACKSLASH_IN_FILENAME
4424 return (c == ':' || c == '/' || c == '\\');
4425# else
4426# ifdef VMS
4427 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4428 return (c == ':' || c == '[' || c == ']' || c == '/'
4429 || c == '<' || c == '>' || c == '"' );
Bram Moolenaar1056d982006-03-09 22:37:52 +00004430# else /* Amiga */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431 return (c == ':' || c == '/');
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432# endif /* VMS */
4433# endif
4434# endif
4435#endif /* RISC OS */
4436}
4437
4438#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4439/*
4440 * return TRUE if 'c' is a path list separator.
4441 */
4442 int
4443vim_ispathlistsep(c)
4444 int c;
4445{
4446#ifdef UNIX
4447 return (c == ':');
4448#else
4449 return (c == ';'); /* might not be rigth for every system... */
4450#endif
4451}
4452#endif
4453
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004454#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4455 || defined(FEAT_EVAL) || defined(PROTO)
4456/*
4457 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4458 * It's done in-place.
4459 */
4460 void
4461shorten_dir(str)
4462 char_u *str;
4463{
4464 char_u *tail, *s, *d;
4465 int skip = FALSE;
4466
4467 tail = gettail(str);
4468 d = str;
4469 for (s = str; ; ++s)
4470 {
4471 if (s >= tail) /* copy the whole tail */
4472 {
4473 *d++ = *s;
4474 if (*s == NUL)
4475 break;
4476 }
4477 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4478 {
4479 *d++ = *s;
4480 skip = FALSE;
4481 }
4482 else if (!skip)
4483 {
4484 *d++ = *s; /* copy next char */
4485 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4486 skip = TRUE;
4487# ifdef FEAT_MBYTE
4488 if (has_mbyte)
4489 {
4490 int l = mb_ptr2len(s);
4491
4492 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004493 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004494 }
4495# endif
4496 }
4497 }
4498}
4499#endif
4500
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004501/*
4502 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4503 * Also returns TRUE if there is no directory name.
4504 * "fname" must be writable!.
4505 */
4506 int
4507dir_of_file_exists(fname)
4508 char_u *fname;
4509{
4510 char_u *p;
4511 int c;
4512 int retval;
4513
4514 p = gettail_sep(fname);
4515 if (p == fname)
4516 return TRUE;
4517 c = *p;
4518 *p = NUL;
4519 retval = mch_isdir(fname);
4520 *p = c;
4521 return retval;
4522}
4523
Bram Moolenaar071d4272004-06-13 20:20:40 +00004524#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4525 || defined(PROTO)
4526/*
4527 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4528 */
4529 int
4530vim_fnamecmp(x, y)
4531 char_u *x, *y;
4532{
4533 return vim_fnamencmp(x, y, MAXPATHL);
4534}
4535
4536 int
4537vim_fnamencmp(x, y, len)
4538 char_u *x, *y;
4539 size_t len;
4540{
4541 while (len > 0 && *x && *y)
4542 {
4543 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4544 && !(*x == '/' && *y == '\\')
4545 && !(*x == '\\' && *y == '/'))
4546 break;
4547 ++x;
4548 ++y;
4549 --len;
4550 }
4551 if (len == 0)
4552 return 0;
4553 return (*x - *y);
4554}
4555#endif
4556
4557/*
4558 * Concatenate file names fname1 and fname2 into allocated memory.
4559 * Only add a '/' or '\\' when 'sep' is TRUE and it is neccesary.
4560 */
4561 char_u *
4562concat_fnames(fname1, fname2, sep)
4563 char_u *fname1;
4564 char_u *fname2;
4565 int sep;
4566{
4567 char_u *dest;
4568
4569 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4570 if (dest != NULL)
4571 {
4572 STRCPY(dest, fname1);
4573 if (sep)
4574 add_pathsep(dest);
4575 STRCAT(dest, fname2);
4576 }
4577 return dest;
4578}
4579
Bram Moolenaard6754642005-01-17 22:18:45 +00004580#if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4581/*
4582 * Concatenate two strings and return the result in allocated memory.
4583 * Returns NULL when out of memory.
4584 */
4585 char_u *
4586concat_str(str1, str2)
4587 char_u *str1;
4588 char_u *str2;
4589{
4590 char_u *dest;
4591 size_t l = STRLEN(str1);
4592
4593 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4594 if (dest != NULL)
4595 {
4596 STRCPY(dest, str1);
4597 STRCPY(dest + l, str2);
4598 }
4599 return dest;
4600}
4601#endif
4602
Bram Moolenaar071d4272004-06-13 20:20:40 +00004603/*
4604 * Add a path separator to a file name, unless it already ends in a path
4605 * separator.
4606 */
4607 void
4608add_pathsep(p)
4609 char_u *p;
4610{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004611 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004612 STRCAT(p, PATHSEPSTR);
4613}
4614
4615/*
4616 * FullName_save - Make an allocated copy of a full file name.
4617 * Returns NULL when out of memory.
4618 */
4619 char_u *
4620FullName_save(fname, force)
4621 char_u *fname;
4622 int force; /* force expansion, even when it already looks
4623 like a full path name */
4624{
4625 char_u *buf;
4626 char_u *new_fname = NULL;
4627
4628 if (fname == NULL)
4629 return NULL;
4630
4631 buf = alloc((unsigned)MAXPATHL);
4632 if (buf != NULL)
4633 {
4634 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4635 new_fname = vim_strsave(buf);
4636 else
4637 new_fname = vim_strsave(fname);
4638 vim_free(buf);
4639 }
4640 return new_fname;
4641}
4642
4643#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4644
4645static char_u *skip_string __ARGS((char_u *p));
4646
4647/*
4648 * Find the start of a comment, not knowing if we are in a comment right now.
4649 * Search starts at w_cursor.lnum and goes backwards.
4650 */
4651 pos_T *
4652find_start_comment(ind_maxcomment) /* XXX */
4653 int ind_maxcomment;
4654{
4655 pos_T *pos;
4656 char_u *line;
4657 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004658 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004660 for (;;)
4661 {
4662 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4663 if (pos == NULL)
4664 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004665
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004666 /*
4667 * Check if the comment start we found is inside a string.
4668 * If it is then restrict the search to below this line and try again.
4669 */
4670 line = ml_get(pos->lnum);
4671 for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
4672 p = skip_string(p);
4673 if ((unsigned)(p - line) <= pos->col)
4674 break;
4675 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4676 if (cur_maxcomment <= 0)
4677 {
4678 pos = NULL;
4679 break;
4680 }
4681 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004682 return pos;
4683}
4684
4685/*
4686 * Skip to the end of a "string" and a 'c' character.
4687 * If there is no string or character, return argument unmodified.
4688 */
4689 static char_u *
4690skip_string(p)
4691 char_u *p;
4692{
4693 int i;
4694
4695 /*
4696 * We loop, because strings may be concatenated: "date""time".
4697 */
4698 for ( ; ; ++p)
4699 {
4700 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4701 {
4702 if (!p[1]) /* ' at end of line */
4703 break;
4704 i = 2;
4705 if (p[1] == '\\') /* '\n' or '\000' */
4706 {
4707 ++i;
4708 while (vim_isdigit(p[i - 1])) /* '\000' */
4709 ++i;
4710 }
4711 if (p[i] == '\'') /* check for trailing ' */
4712 {
4713 p += i;
4714 continue;
4715 }
4716 }
4717 else if (p[0] == '"') /* start of string */
4718 {
4719 for (++p; p[0]; ++p)
4720 {
4721 if (p[0] == '\\' && p[1] != NUL)
4722 ++p;
4723 else if (p[0] == '"') /* end of string */
4724 break;
4725 }
4726 if (p[0] == '"')
4727 continue;
4728 }
4729 break; /* no string found */
4730 }
4731 if (!*p)
4732 --p; /* backup from NUL */
4733 return p;
4734}
4735#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4736
4737#if defined(FEAT_CINDENT) || defined(PROTO)
4738
4739/*
4740 * Do C or expression indenting on the current line.
4741 */
4742 void
4743do_c_expr_indent()
4744{
4745# ifdef FEAT_EVAL
4746 if (*curbuf->b_p_inde != NUL)
4747 fixthisline(get_expr_indent);
4748 else
4749# endif
4750 fixthisline(get_c_indent);
4751}
4752
4753/*
4754 * Functions for C-indenting.
4755 * Most of this originally comes from Eric Fischer.
4756 */
4757/*
4758 * Below "XXX" means that this function may unlock the current line.
4759 */
4760
4761static char_u *cin_skipcomment __ARGS((char_u *));
4762static int cin_nocode __ARGS((char_u *));
4763static pos_T *find_line_comment __ARGS((void));
4764static int cin_islabel_skip __ARGS((char_u **));
4765static int cin_isdefault __ARGS((char_u *));
4766static char_u *after_label __ARGS((char_u *l));
4767static int get_indent_nolabel __ARGS((linenr_T lnum));
4768static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4769static int cin_first_id_amount __ARGS((void));
4770static int cin_get_equal_amount __ARGS((linenr_T lnum));
4771static int cin_ispreproc __ARGS((char_u *));
4772static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4773static int cin_iscomment __ARGS((char_u *));
4774static int cin_islinecomment __ARGS((char_u *));
4775static int cin_isterminated __ARGS((char_u *, int, int));
4776static int cin_isinit __ARGS((void));
4777static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4778static int cin_isif __ARGS((char_u *));
4779static int cin_iselse __ARGS((char_u *));
4780static int cin_isdo __ARGS((char_u *));
4781static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004782static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783static int cin_isbreak __ARGS((char_u *));
4784static int cin_is_cpp_baseclass __ARGS((char_u *line, colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00004785static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4787static int cin_skip2pos __ARGS((pos_T *trypos));
4788static pos_T *find_start_brace __ARGS((int));
4789static pos_T *find_match_paren __ARGS((int, int));
4790static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4791static int find_last_paren __ARGS((char_u *l, int start, int end));
4792static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4793
4794/*
4795 * Skip over white space and C comments within the line.
4796 */
4797 static char_u *
4798cin_skipcomment(s)
4799 char_u *s;
4800{
4801 while (*s)
4802 {
4803 s = skipwhite(s);
4804 if (*s != '/')
4805 break;
4806 ++s;
4807 if (*s == '/') /* slash-slash comment continues till eol */
4808 {
4809 s += STRLEN(s);
4810 break;
4811 }
4812 if (*s != '*')
4813 break;
4814 for (++s; *s; ++s) /* skip slash-star comment */
4815 if (s[0] == '*' && s[1] == '/')
4816 {
4817 s += 2;
4818 break;
4819 }
4820 }
4821 return s;
4822}
4823
4824/*
4825 * Return TRUE if there there is no code at *s. White space and comments are
4826 * not considered code.
4827 */
4828 static int
4829cin_nocode(s)
4830 char_u *s;
4831{
4832 return *cin_skipcomment(s) == NUL;
4833}
4834
4835/*
4836 * Check previous lines for a "//" line comment, skipping over blank lines.
4837 */
4838 static pos_T *
4839find_line_comment() /* XXX */
4840{
4841 static pos_T pos;
4842 char_u *line;
4843 char_u *p;
4844
4845 pos = curwin->w_cursor;
4846 while (--pos.lnum > 0)
4847 {
4848 line = ml_get(pos.lnum);
4849 p = skipwhite(line);
4850 if (cin_islinecomment(p))
4851 {
4852 pos.col = (int)(p - line);
4853 return &pos;
4854 }
4855 if (*p != NUL)
4856 break;
4857 }
4858 return NULL;
4859}
4860
4861/*
4862 * Check if string matches "label:"; move to character after ':' if true.
4863 */
4864 static int
4865cin_islabel_skip(s)
4866 char_u **s;
4867{
4868 if (!vim_isIDc(**s)) /* need at least one ID character */
4869 return FALSE;
4870
4871 while (vim_isIDc(**s))
4872 (*s)++;
4873
4874 *s = cin_skipcomment(*s);
4875
4876 /* "::" is not a label, it's C++ */
4877 return (**s == ':' && *++*s != ':');
4878}
4879
4880/*
4881 * Recognize a label: "label:".
4882 * Note: curwin->w_cursor must be where we are looking for the label.
4883 */
4884 int
4885cin_islabel(ind_maxcomment) /* XXX */
4886 int ind_maxcomment;
4887{
4888 char_u *s;
4889
4890 s = cin_skipcomment(ml_get_curline());
4891
4892 /*
4893 * Exclude "default" from labels, since it should be indented
4894 * like a switch label. Same for C++ scope declarations.
4895 */
4896 if (cin_isdefault(s))
4897 return FALSE;
4898 if (cin_isscopedecl(s))
4899 return FALSE;
4900
4901 if (cin_islabel_skip(&s))
4902 {
4903 /*
4904 * Only accept a label if the previous line is terminated or is a case
4905 * label.
4906 */
4907 pos_T cursor_save;
4908 pos_T *trypos;
4909 char_u *line;
4910
4911 cursor_save = curwin->w_cursor;
4912 while (curwin->w_cursor.lnum > 1)
4913 {
4914 --curwin->w_cursor.lnum;
4915
4916 /*
4917 * If we're in a comment now, skip to the start of the comment.
4918 */
4919 curwin->w_cursor.col = 0;
4920 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
4921 curwin->w_cursor = *trypos;
4922
4923 line = ml_get_curline();
4924 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
4925 continue;
4926 if (*(line = cin_skipcomment(line)) == NUL)
4927 continue;
4928
4929 curwin->w_cursor = cursor_save;
4930 if (cin_isterminated(line, TRUE, FALSE)
4931 || cin_isscopedecl(line)
4932 || cin_iscase(line)
4933 || (cin_islabel_skip(&line) && cin_nocode(line)))
4934 return TRUE;
4935 return FALSE;
4936 }
4937 curwin->w_cursor = cursor_save;
4938 return TRUE; /* label at start of file??? */
4939 }
4940 return FALSE;
4941}
4942
4943/*
4944 * Recognize structure initialization and enumerations.
4945 * Q&D-Implementation:
4946 * check for "=" at end or "[typedef] enum" at beginning of line.
4947 */
4948 static int
4949cin_isinit(void)
4950{
4951 char_u *s;
4952
4953 s = cin_skipcomment(ml_get_curline());
4954
4955 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
4956 s = cin_skipcomment(s + 7);
4957
4958 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
4959 return TRUE;
4960
4961 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
4962 return TRUE;
4963
4964 return FALSE;
4965}
4966
4967/*
4968 * Recognize a switch label: "case .*:" or "default:".
4969 */
4970 int
4971cin_iscase(s)
4972 char_u *s;
4973{
4974 s = cin_skipcomment(s);
4975 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
4976 {
4977 for (s += 4; *s; ++s)
4978 {
4979 s = cin_skipcomment(s);
4980 if (*s == ':')
4981 {
4982 if (s[1] == ':') /* skip over "::" for C++ */
4983 ++s;
4984 else
4985 return TRUE;
4986 }
4987 if (*s == '\'' && s[1] && s[2] == '\'')
4988 s += 2; /* skip over '.' */
4989 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
4990 return FALSE; /* stop at comment */
4991 else if (*s == '"')
4992 return FALSE; /* stop at string */
4993 }
4994 return FALSE;
4995 }
4996
4997 if (cin_isdefault(s))
4998 return TRUE;
4999 return FALSE;
5000}
5001
5002/*
5003 * Recognize a "default" switch label.
5004 */
5005 static int
5006cin_isdefault(s)
5007 char_u *s;
5008{
5009 return (STRNCMP(s, "default", 7) == 0
5010 && *(s = cin_skipcomment(s + 7)) == ':'
5011 && s[1] != ':');
5012}
5013
5014/*
5015 * Recognize a "public/private/proctected" scope declaration label.
5016 */
5017 int
5018cin_isscopedecl(s)
5019 char_u *s;
5020{
5021 int i;
5022
5023 s = cin_skipcomment(s);
5024 if (STRNCMP(s, "public", 6) == 0)
5025 i = 6;
5026 else if (STRNCMP(s, "protected", 9) == 0)
5027 i = 9;
5028 else if (STRNCMP(s, "private", 7) == 0)
5029 i = 7;
5030 else
5031 return FALSE;
5032 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5033}
5034
5035/*
5036 * Return a pointer to the first non-empty non-comment character after a ':'.
5037 * Return NULL if not found.
5038 * case 234: a = b;
5039 * ^
5040 */
5041 static char_u *
5042after_label(l)
5043 char_u *l;
5044{
5045 for ( ; *l; ++l)
5046 {
5047 if (*l == ':')
5048 {
5049 if (l[1] == ':') /* skip over "::" for C++ */
5050 ++l;
5051 else if (!cin_iscase(l + 1))
5052 break;
5053 }
5054 else if (*l == '\'' && l[1] && l[2] == '\'')
5055 l += 2; /* skip over 'x' */
5056 }
5057 if (*l == NUL)
5058 return NULL;
5059 l = cin_skipcomment(l + 1);
5060 if (*l == NUL)
5061 return NULL;
5062 return l;
5063}
5064
5065/*
5066 * Get indent of line "lnum", skipping a label.
5067 * Return 0 if there is nothing after the label.
5068 */
5069 static int
5070get_indent_nolabel(lnum) /* XXX */
5071 linenr_T lnum;
5072{
5073 char_u *l;
5074 pos_T fp;
5075 colnr_T col;
5076 char_u *p;
5077
5078 l = ml_get(lnum);
5079 p = after_label(l);
5080 if (p == NULL)
5081 return 0;
5082
5083 fp.col = (colnr_T)(p - l);
5084 fp.lnum = lnum;
5085 getvcol(curwin, &fp, &col, NULL, NULL);
5086 return (int)col;
5087}
5088
5089/*
5090 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005091 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092 * label: if (asdf && asdfasdf)
5093 * ^
5094 */
5095 static int
5096skip_label(lnum, pp, ind_maxcomment)
5097 linenr_T lnum;
5098 char_u **pp;
5099 int ind_maxcomment;
5100{
5101 char_u *l;
5102 int amount;
5103 pos_T cursor_save;
5104
5105 cursor_save = curwin->w_cursor;
5106 curwin->w_cursor.lnum = lnum;
5107 l = ml_get_curline();
5108 /* XXX */
5109 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5110 {
5111 amount = get_indent_nolabel(lnum);
5112 l = after_label(ml_get_curline());
5113 if (l == NULL) /* just in case */
5114 l = ml_get_curline();
5115 }
5116 else
5117 {
5118 amount = get_indent();
5119 l = ml_get_curline();
5120 }
5121 *pp = l;
5122
5123 curwin->w_cursor = cursor_save;
5124 return amount;
5125}
5126
5127/*
5128 * Return the indent of the first variable name after a type in a declaration.
5129 * int a, indent of "a"
5130 * static struct foo b, indent of "b"
5131 * enum bla c, indent of "c"
5132 * Returns zero when it doesn't look like a declaration.
5133 */
5134 static int
5135cin_first_id_amount()
5136{
5137 char_u *line, *p, *s;
5138 int len;
5139 pos_T fp;
5140 colnr_T col;
5141
5142 line = ml_get_curline();
5143 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005144 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005145 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5146 {
5147 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005148 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005149 }
5150 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5151 p = skipwhite(p + 6);
5152 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5153 p = skipwhite(p + 4);
5154 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5155 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5156 {
5157 s = skipwhite(p + len);
5158 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5159 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5160 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5161 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5162 p = s;
5163 }
5164 for (len = 0; vim_isIDc(p[len]); ++len)
5165 ;
5166 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5167 return 0;
5168
5169 p = skipwhite(p + len);
5170 fp.lnum = curwin->w_cursor.lnum;
5171 fp.col = (colnr_T)(p - line);
5172 getvcol(curwin, &fp, &col, NULL, NULL);
5173 return (int)col;
5174}
5175
5176/*
5177 * Return the indent of the first non-blank after an equal sign.
5178 * char *foo = "here";
5179 * Return zero if no (useful) equal sign found.
5180 * Return -1 if the line above "lnum" ends in a backslash.
5181 * foo = "asdf\
5182 * asdf\
5183 * here";
5184 */
5185 static int
5186cin_get_equal_amount(lnum)
5187 linenr_T lnum;
5188{
5189 char_u *line;
5190 char_u *s;
5191 colnr_T col;
5192 pos_T fp;
5193
5194 if (lnum > 1)
5195 {
5196 line = ml_get(lnum - 1);
5197 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5198 return -1;
5199 }
5200
5201 line = s = ml_get(lnum);
5202 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5203 {
5204 if (cin_iscomment(s)) /* ignore comments */
5205 s = cin_skipcomment(s);
5206 else
5207 ++s;
5208 }
5209 if (*s != '=')
5210 return 0;
5211
5212 s = skipwhite(s + 1);
5213 if (cin_nocode(s))
5214 return 0;
5215
5216 if (*s == '"') /* nice alignment for continued strings */
5217 ++s;
5218
5219 fp.lnum = lnum;
5220 fp.col = (colnr_T)(s - line);
5221 getvcol(curwin, &fp, &col, NULL, NULL);
5222 return (int)col;
5223}
5224
5225/*
5226 * Recognize a preprocessor statement: Any line that starts with '#'.
5227 */
5228 static int
5229cin_ispreproc(s)
5230 char_u *s;
5231{
5232 s = skipwhite(s);
5233 if (*s == '#')
5234 return TRUE;
5235 return FALSE;
5236}
5237
5238/*
5239 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5240 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5241 * start and return the line in "*pp".
5242 */
5243 static int
5244cin_ispreproc_cont(pp, lnump)
5245 char_u **pp;
5246 linenr_T *lnump;
5247{
5248 char_u *line = *pp;
5249 linenr_T lnum = *lnump;
5250 int retval = FALSE;
5251
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005252 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005253 {
5254 if (cin_ispreproc(line))
5255 {
5256 retval = TRUE;
5257 *lnump = lnum;
5258 break;
5259 }
5260 if (lnum == 1)
5261 break;
5262 line = ml_get(--lnum);
5263 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5264 break;
5265 }
5266
5267 if (lnum != *lnump)
5268 *pp = ml_get(*lnump);
5269 return retval;
5270}
5271
5272/*
5273 * Recognize the start of a C or C++ comment.
5274 */
5275 static int
5276cin_iscomment(p)
5277 char_u *p;
5278{
5279 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5280}
5281
5282/*
5283 * Recognize the start of a "//" comment.
5284 */
5285 static int
5286cin_islinecomment(p)
5287 char_u *p;
5288{
5289 return (p[0] == '/' && p[1] == '/');
5290}
5291
5292/*
5293 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5294 * Don't consider "} else" a terminated line.
5295 * Return the character terminating the line (ending char's have precedence if
5296 * both apply in order to determine initializations).
5297 */
5298 static int
5299cin_isterminated(s, incl_open, incl_comma)
5300 char_u *s;
5301 int incl_open; /* include '{' at the end as terminator */
5302 int incl_comma; /* recognize a trailing comma */
5303{
5304 char_u found_start = 0;
5305
5306 s = cin_skipcomment(s);
5307
5308 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5309 found_start = *s;
5310
5311 while (*s)
5312 {
5313 /* skip over comments, "" strings and 'c'haracters */
5314 s = skip_string(cin_skipcomment(s));
5315 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5316 || (incl_comma && *s == ','))
5317 && cin_nocode(s + 1))
5318 return *s;
5319
5320 if (*s)
5321 s++;
5322 }
5323 return found_start;
5324}
5325
5326/*
5327 * Recognize the basic picture of a function declaration -- it needs to
5328 * have an open paren somewhere and a close paren at the end of the line and
5329 * no semicolons anywhere.
5330 * When a line ends in a comma we continue looking in the next line.
5331 * "sp" points to a string with the line. When looking at other lines it must
5332 * be restored to the line. When it's NULL fetch lines here.
5333 * "lnum" is where we start looking.
5334 */
5335 static int
5336cin_isfuncdecl(sp, first_lnum)
5337 char_u **sp;
5338 linenr_T first_lnum;
5339{
5340 char_u *s;
5341 linenr_T lnum = first_lnum;
5342 int retval = FALSE;
5343
5344 if (sp == NULL)
5345 s = ml_get(lnum);
5346 else
5347 s = *sp;
5348
5349 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5350 {
5351 if (cin_iscomment(s)) /* ignore comments */
5352 s = cin_skipcomment(s);
5353 else
5354 ++s;
5355 }
5356 if (*s != '(')
5357 return FALSE; /* ';', ' or " before any () or no '(' */
5358
5359 while (*s && *s != ';' && *s != '\'' && *s != '"')
5360 {
5361 if (*s == ')' && cin_nocode(s + 1))
5362 {
5363 /* ')' at the end: may have found a match
5364 * Check for he previous line not to end in a backslash:
5365 * #if defined(x) && \
5366 * defined(y)
5367 */
5368 lnum = first_lnum - 1;
5369 s = ml_get(lnum);
5370 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5371 retval = TRUE;
5372 goto done;
5373 }
5374 if (*s == ',' && cin_nocode(s + 1))
5375 {
5376 /* ',' at the end: continue looking in the next line */
5377 if (lnum >= curbuf->b_ml.ml_line_count)
5378 break;
5379
5380 s = ml_get(++lnum);
5381 }
5382 else if (cin_iscomment(s)) /* ignore comments */
5383 s = cin_skipcomment(s);
5384 else
5385 ++s;
5386 }
5387
5388done:
5389 if (lnum != first_lnum && sp != NULL)
5390 *sp = ml_get(first_lnum);
5391
5392 return retval;
5393}
5394
5395 static int
5396cin_isif(p)
5397 char_u *p;
5398{
5399 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5400}
5401
5402 static int
5403cin_iselse(p)
5404 char_u *p;
5405{
5406 if (*p == '}') /* accept "} else" */
5407 p = cin_skipcomment(p + 1);
5408 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5409}
5410
5411 static int
5412cin_isdo(p)
5413 char_u *p;
5414{
5415 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5416}
5417
5418/*
5419 * Check if this is a "while" that should have a matching "do".
5420 * We only accept a "while (condition) ;", with only white space between the
5421 * ')' and ';'. The condition may be spread over several lines.
5422 */
5423 static int
5424cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5425 char_u *p;
5426 linenr_T lnum;
5427 int ind_maxparen;
5428{
5429 pos_T cursor_save;
5430 pos_T *trypos;
5431 int retval = FALSE;
5432
5433 p = cin_skipcomment(p);
5434 if (*p == '}') /* accept "} while (cond);" */
5435 p = cin_skipcomment(p + 1);
5436 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5437 {
5438 cursor_save = curwin->w_cursor;
5439 curwin->w_cursor.lnum = lnum;
5440 curwin->w_cursor.col = 0;
5441 p = ml_get_curline();
5442 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5443 {
5444 ++p;
5445 ++curwin->w_cursor.col;
5446 }
5447 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5448 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5449 retval = TRUE;
5450 curwin->w_cursor = cursor_save;
5451 }
5452 return retval;
5453}
5454
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005455/*
5456 * Return TRUE if we are at the end of a do-while.
5457 * do
5458 * nothing;
5459 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005460 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005461 * Adjust the cursor to the line with "while".
5462 */
5463 static int
5464cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5465 int terminated;
5466 int ind_maxparen;
5467 int ind_maxcomment;
5468{
5469 char_u *line;
5470 char_u *p;
5471 char_u *s;
5472 pos_T *trypos;
5473 int i;
5474
5475 if (terminated != ';') /* there must be a ';' at the end */
5476 return FALSE;
5477
5478 p = line = ml_get_curline();
5479 while (*p != NUL)
5480 {
5481 p = cin_skipcomment(p);
5482 if (*p == ')')
5483 {
5484 s = skipwhite(p + 1);
5485 if (*s == ';' && cin_nocode(s + 1))
5486 {
5487 /* Found ");" at end of the line, now check there is "while"
5488 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005489 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005490 curwin->w_cursor.col = i;
5491 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5492 if (trypos != NULL)
5493 {
5494 s = cin_skipcomment(ml_get(trypos->lnum));
5495 if (*s == '}') /* accept "} while (cond);" */
5496 s = cin_skipcomment(s + 1);
5497 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5498 {
5499 curwin->w_cursor.lnum = trypos->lnum;
5500 return TRUE;
5501 }
5502 }
5503
5504 /* Searching may have made "line" invalid, get it again. */
5505 line = ml_get_curline();
5506 p = line + i;
5507 }
5508 }
5509 if (*p != NUL)
5510 ++p;
5511 }
5512 return FALSE;
5513}
5514
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 static int
5516cin_isbreak(p)
5517 char_u *p;
5518{
5519 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5520}
5521
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005522/*
5523 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524 * constructor-initialization. eg:
5525 *
5526 * class MyClass :
5527 * baseClass <-- here
5528 * class MyClass : public baseClass,
5529 * anotherBaseClass <-- here (should probably lineup ??)
5530 * MyClass::MyClass(...) :
5531 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005532 *
5533 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005534 */
5535 static int
5536cin_is_cpp_baseclass(line, col)
5537 char_u *line;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005538 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005539{
5540 char_u *s;
5541 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005542 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543
5544 *col = 0;
5545
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005546 s = skipwhite(line);
5547 if (*s == '#') /* skip #define FOO x ? (x) : x */
5548 return FALSE;
5549 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550 if (*s == NUL)
5551 return FALSE;
5552
5553 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5554
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005555 /* Search for a line starting with '#', empty, ending in ';' or containing
5556 * '{' or '}' and start below it. This handles the following situations:
5557 * a = cond ?
5558 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005559 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005560 * func::foo()
5561 * : something
5562 * {}
5563 * Foo::Foo (int one, int two)
5564 * : something(4),
5565 * somethingelse(3)
5566 * {}
5567 */
5568 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005569 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005570 s = skipwhite(ml_get(lnum - 1));
5571 if (*s == '#' || *s == NUL)
5572 break;
5573 while (*s != NUL)
5574 {
5575 s = cin_skipcomment(s);
5576 if (*s == '{' || *s == '}'
5577 || (*s == ';' && cin_nocode(s + 1)))
5578 break;
5579 if (*s != NUL)
5580 ++s;
5581 }
5582 if (*s != NUL)
5583 break;
5584 --lnum;
5585 }
5586
5587 s = cin_skipcomment(ml_get(lnum));
5588 for (;;)
5589 {
5590 if (*s == NUL)
5591 {
5592 if (lnum == curwin->w_cursor.lnum)
5593 break;
5594 /* Continue in the cursor line. */
5595 s = cin_skipcomment(ml_get(++lnum));
5596 }
5597
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 if (s[0] == ':')
5599 {
5600 if (s[1] == ':')
5601 {
5602 /* skip double colon. It can't be a constructor
5603 * initialization any more */
5604 lookfor_ctor_init = FALSE;
5605 s = cin_skipcomment(s + 2);
5606 }
5607 else if (lookfor_ctor_init || class_or_struct)
5608 {
5609 /* we have something found, that looks like the start of
5610 * cpp-base-class-declaration or contructor-initialization */
5611 cpp_base_class = TRUE;
5612 lookfor_ctor_init = class_or_struct = FALSE;
5613 *col = 0;
5614 s = cin_skipcomment(s + 1);
5615 }
5616 else
5617 s = cin_skipcomment(s + 1);
5618 }
5619 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5620 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5621 {
5622 class_or_struct = TRUE;
5623 lookfor_ctor_init = FALSE;
5624
5625 if (*s == 'c')
5626 s = cin_skipcomment(s + 5);
5627 else
5628 s = cin_skipcomment(s + 6);
5629 }
5630 else
5631 {
5632 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5633 {
5634 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5635 }
5636 else if (s[0] == ')')
5637 {
5638 /* Constructor-initialization is assumed if we come across
5639 * something like "):" */
5640 class_or_struct = FALSE;
5641 lookfor_ctor_init = TRUE;
5642 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00005643 else if (s[0] == '?')
5644 {
5645 /* Avoid seeing '() :' after '?' as constructor init. */
5646 return FALSE;
5647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005648 else if (!vim_isIDc(s[0]))
5649 {
5650 /* if it is not an identifier, we are wrong */
5651 class_or_struct = FALSE;
5652 lookfor_ctor_init = FALSE;
5653 }
5654 else if (*col == 0)
5655 {
5656 /* it can't be a constructor-initialization any more */
5657 lookfor_ctor_init = FALSE;
5658
5659 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005660 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005661 *col = (colnr_T)(s - line);
5662 }
5663
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005664 /* When the line ends in a comma don't align with it. */
5665 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5666 *col = 0;
5667
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 s = cin_skipcomment(s + 1);
5669 }
5670 }
5671
5672 return cpp_base_class;
5673}
5674
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005675 static int
5676get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5677 int col;
5678 int ind_maxparen;
5679 int ind_maxcomment;
5680 int ind_cpp_baseclass;
5681{
5682 int amount;
5683 colnr_T vcol;
5684 pos_T *trypos;
5685
5686 if (col == 0)
5687 {
5688 amount = get_indent();
5689 if (find_last_paren(ml_get_curline(), '(', ')')
5690 && (trypos = find_match_paren(ind_maxparen,
5691 ind_maxcomment)) != NULL)
5692 amount = get_indent_lnum(trypos->lnum); /* XXX */
5693 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5694 amount += ind_cpp_baseclass;
5695 }
5696 else
5697 {
5698 curwin->w_cursor.col = col;
5699 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5700 amount = (int)vcol;
5701 }
5702 if (amount < ind_cpp_baseclass)
5703 amount = ind_cpp_baseclass;
5704 return amount;
5705}
5706
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707/*
5708 * Return TRUE if string "s" ends with the string "find", possibly followed by
5709 * white space and comments. Skip strings and comments.
5710 * Ignore "ignore" after "find" if it's not NULL.
5711 */
5712 static int
5713cin_ends_in(s, find, ignore)
5714 char_u *s;
5715 char_u *find;
5716 char_u *ignore;
5717{
5718 char_u *p = s;
5719 char_u *r;
5720 int len = (int)STRLEN(find);
5721
5722 while (*p != NUL)
5723 {
5724 p = cin_skipcomment(p);
5725 if (STRNCMP(p, find, len) == 0)
5726 {
5727 r = skipwhite(p + len);
5728 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5729 r = skipwhite(r + STRLEN(ignore));
5730 if (cin_nocode(r))
5731 return TRUE;
5732 }
5733 if (*p != NUL)
5734 ++p;
5735 }
5736 return FALSE;
5737}
5738
5739/*
5740 * Skip strings, chars and comments until at or past "trypos".
5741 * Return the column found.
5742 */
5743 static int
5744cin_skip2pos(trypos)
5745 pos_T *trypos;
5746{
5747 char_u *line;
5748 char_u *p;
5749
5750 p = line = ml_get(trypos->lnum);
5751 while (*p && (colnr_T)(p - line) < trypos->col)
5752 {
5753 if (cin_iscomment(p))
5754 p = cin_skipcomment(p);
5755 else
5756 {
5757 p = skip_string(p);
5758 ++p;
5759 }
5760 }
5761 return (int)(p - line);
5762}
5763
5764/*
5765 * Find the '{' at the start of the block we are in.
5766 * Return NULL if no match found.
5767 * Ignore a '{' that is in a comment, makes indenting the next three lines
5768 * work. */
5769/* foo() */
5770/* { */
5771/* } */
5772
5773 static pos_T *
5774find_start_brace(ind_maxcomment) /* XXX */
5775 int ind_maxcomment;
5776{
5777 pos_T cursor_save;
5778 pos_T *trypos;
5779 pos_T *pos;
5780 static pos_T pos_copy;
5781
5782 cursor_save = curwin->w_cursor;
5783 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5784 {
5785 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5786 trypos = &pos_copy;
5787 curwin->w_cursor = *trypos;
5788 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005789 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5791 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5792 break;
5793 if (pos != NULL)
5794 curwin->w_cursor.lnum = pos->lnum;
5795 }
5796 curwin->w_cursor = cursor_save;
5797 return trypos;
5798}
5799
5800/*
5801 * Find the matching '(', failing if it is in a comment.
5802 * Return NULL of no match found.
5803 */
5804 static pos_T *
5805find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5806 int ind_maxparen;
5807 int ind_maxcomment;
5808{
5809 pos_T cursor_save;
5810 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005811 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812
5813 cursor_save = curwin->w_cursor;
5814 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5815 {
5816 /* check if the ( is in a // comment */
5817 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5818 trypos = NULL;
5819 else
5820 {
5821 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5822 trypos = &pos_copy;
5823 curwin->w_cursor = *trypos;
5824 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5825 trypos = NULL;
5826 }
5827 }
5828 curwin->w_cursor = cursor_save;
5829 return trypos;
5830}
5831
5832/*
5833 * Return ind_maxparen corrected for the difference in line number between the
5834 * cursor position and "startpos". This makes sure that searching for a
5835 * matching paren above the cursor line doesn't find a match because of
5836 * looking a few lines further.
5837 */
5838 static int
5839corr_ind_maxparen(ind_maxparen, startpos)
5840 int ind_maxparen;
5841 pos_T *startpos;
5842{
5843 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5844
5845 if (n > 0 && n < ind_maxparen / 2)
5846 return ind_maxparen - (int)n;
5847 return ind_maxparen;
5848}
5849
5850/*
5851 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5852 * line "l".
5853 */
5854 static int
5855find_last_paren(l, start, end)
5856 char_u *l;
5857 int start, end;
5858{
5859 int i;
5860 int retval = FALSE;
5861 int open_count = 0;
5862
5863 curwin->w_cursor.col = 0; /* default is start of line */
5864
5865 for (i = 0; l[i]; i++)
5866 {
5867 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5868 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5869 if (l[i] == start)
5870 ++open_count;
5871 else if (l[i] == end)
5872 {
5873 if (open_count > 0)
5874 --open_count;
5875 else
5876 {
5877 curwin->w_cursor.col = i;
5878 retval = TRUE;
5879 }
5880 }
5881 }
5882 return retval;
5883}
5884
5885 int
5886get_c_indent()
5887{
5888 /*
5889 * spaces from a block's opening brace the prevailing indent for that
5890 * block should be
5891 */
5892 int ind_level = curbuf->b_p_sw;
5893
5894 /*
5895 * spaces from the edge of the line an open brace that's at the end of a
5896 * line is imagined to be.
5897 */
5898 int ind_open_imag = 0;
5899
5900 /*
5901 * spaces from the prevailing indent for a line that is not precededof by
5902 * an opening brace.
5903 */
5904 int ind_no_brace = 0;
5905
5906 /*
5907 * column where the first { of a function should be located }
5908 */
5909 int ind_first_open = 0;
5910
5911 /*
5912 * spaces from the prevailing indent a leftmost open brace should be
5913 * located
5914 */
5915 int ind_open_extra = 0;
5916
5917 /*
5918 * spaces from the matching open brace (real location for one at the left
5919 * edge; imaginary location from one that ends a line) the matching close
5920 * brace should be located
5921 */
5922 int ind_close_extra = 0;
5923
5924 /*
5925 * spaces from the edge of the line an open brace sitting in the leftmost
5926 * column is imagined to be
5927 */
5928 int ind_open_left_imag = 0;
5929
5930 /*
5931 * spaces from the switch() indent a "case xx" label should be located
5932 */
5933 int ind_case = curbuf->b_p_sw;
5934
5935 /*
5936 * spaces from the "case xx:" code after a switch() should be located
5937 */
5938 int ind_case_code = curbuf->b_p_sw;
5939
5940 /*
5941 * lineup break at end of case in switch() with case label
5942 */
5943 int ind_case_break = 0;
5944
5945 /*
5946 * spaces from the class declaration indent a scope declaration label
5947 * should be located
5948 */
5949 int ind_scopedecl = curbuf->b_p_sw;
5950
5951 /*
5952 * spaces from the scope declaration label code should be located
5953 */
5954 int ind_scopedecl_code = curbuf->b_p_sw;
5955
5956 /*
5957 * amount K&R-style parameters should be indented
5958 */
5959 int ind_param = curbuf->b_p_sw;
5960
5961 /*
5962 * amount a function type spec should be indented
5963 */
5964 int ind_func_type = curbuf->b_p_sw;
5965
5966 /*
5967 * amount a cpp base class declaration or constructor initialization
5968 * should be indented
5969 */
5970 int ind_cpp_baseclass = curbuf->b_p_sw;
5971
5972 /*
5973 * additional spaces beyond the prevailing indent a continuation line
5974 * should be located
5975 */
5976 int ind_continuation = curbuf->b_p_sw;
5977
5978 /*
5979 * spaces from the indent of the line with an unclosed parentheses
5980 */
5981 int ind_unclosed = curbuf->b_p_sw * 2;
5982
5983 /*
5984 * spaces from the indent of the line with an unclosed parentheses, which
5985 * itself is also unclosed
5986 */
5987 int ind_unclosed2 = curbuf->b_p_sw;
5988
5989 /*
5990 * suppress ignoring spaces from the indent of a line starting with an
5991 * unclosed parentheses.
5992 */
5993 int ind_unclosed_noignore = 0;
5994
5995 /*
5996 * If the opening paren is the last nonwhite character on the line, and
5997 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
5998 * context (for very long lines).
5999 */
6000 int ind_unclosed_wrapped = 0;
6001
6002 /*
6003 * suppress ignoring white space when lining up with the character after
6004 * an unclosed parentheses.
6005 */
6006 int ind_unclosed_whiteok = 0;
6007
6008 /*
6009 * indent a closing parentheses under the line start of the matching
6010 * opening parentheses.
6011 */
6012 int ind_matching_paren = 0;
6013
6014 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006015 * indent a closing parentheses under the previous line.
6016 */
6017 int ind_paren_prev = 0;
6018
6019 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020 * Extra indent for comments.
6021 */
6022 int ind_comment = 0;
6023
6024 /*
6025 * spaces from the comment opener when there is nothing after it.
6026 */
6027 int ind_in_comment = 3;
6028
6029 /*
6030 * boolean: if non-zero, use ind_in_comment even if there is something
6031 * after the comment opener.
6032 */
6033 int ind_in_comment2 = 0;
6034
6035 /*
6036 * max lines to search for an open paren
6037 */
6038 int ind_maxparen = 20;
6039
6040 /*
6041 * max lines to search for an open comment
6042 */
6043 int ind_maxcomment = 70;
6044
6045 /*
6046 * handle braces for java code
6047 */
6048 int ind_java = 0;
6049
6050 /*
6051 * handle blocked cases correctly
6052 */
6053 int ind_keep_case_label = 0;
6054
6055 pos_T cur_curpos;
6056 int amount;
6057 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006058 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059 colnr_T col;
6060 char_u *theline;
6061 char_u *linecopy;
6062 pos_T *trypos;
6063 pos_T *tryposBrace = NULL;
6064 pos_T our_paren_pos;
6065 char_u *start;
6066 int start_brace;
6067#define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
6068#define BRACE_AT_START 2 /* '{' is at start of line */
6069#define BRACE_AT_END 3 /* '{' is at end of line */
6070 linenr_T ourscope;
6071 char_u *l;
6072 char_u *look;
6073 char_u terminated;
6074 int lookfor;
6075#define LOOKFOR_INITIAL 0
6076#define LOOKFOR_IF 1
6077#define LOOKFOR_DO 2
6078#define LOOKFOR_CASE 3
6079#define LOOKFOR_ANY 4
6080#define LOOKFOR_TERM 5
6081#define LOOKFOR_UNTERM 6
6082#define LOOKFOR_SCOPEDECL 7
6083#define LOOKFOR_NOBREAK 8
6084#define LOOKFOR_CPP_BASECLASS 9
6085#define LOOKFOR_ENUM_OR_INIT 10
6086
6087 int whilelevel;
6088 linenr_T lnum;
6089 char_u *options;
6090 int fraction = 0; /* init for GCC */
6091 int divider;
6092 int n;
6093 int iscase;
6094 int lookfor_break;
6095 int cont_amount = 0; /* amount for continuation line */
6096
6097 for (options = curbuf->b_p_cino; *options; )
6098 {
6099 l = options++;
6100 if (*options == '-')
6101 ++options;
6102 n = getdigits(&options);
6103 divider = 0;
6104 if (*options == '.') /* ".5s" means a fraction */
6105 {
6106 fraction = atol((char *)++options);
6107 while (VIM_ISDIGIT(*options))
6108 {
6109 ++options;
6110 if (divider)
6111 divider *= 10;
6112 else
6113 divider = 10;
6114 }
6115 }
6116 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6117 {
6118 if (n == 0 && fraction == 0)
6119 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6120 else
6121 {
6122 n *= curbuf->b_p_sw;
6123 if (divider)
6124 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6125 }
6126 ++options;
6127 }
6128 if (l[1] == '-')
6129 n = -n;
6130 /* When adding an entry here, also update the default 'cinoptions' in
6131 * change.txt, and add explanation for it! */
6132 switch (*l)
6133 {
6134 case '>': ind_level = n; break;
6135 case 'e': ind_open_imag = n; break;
6136 case 'n': ind_no_brace = n; break;
6137 case 'f': ind_first_open = n; break;
6138 case '{': ind_open_extra = n; break;
6139 case '}': ind_close_extra = n; break;
6140 case '^': ind_open_left_imag = n; break;
6141 case ':': ind_case = n; break;
6142 case '=': ind_case_code = n; break;
6143 case 'b': ind_case_break = n; break;
6144 case 'p': ind_param = n; break;
6145 case 't': ind_func_type = n; break;
6146 case '/': ind_comment = n; break;
6147 case 'c': ind_in_comment = n; break;
6148 case 'C': ind_in_comment2 = n; break;
6149 case 'i': ind_cpp_baseclass = n; break;
6150 case '+': ind_continuation = n; break;
6151 case '(': ind_unclosed = n; break;
6152 case 'u': ind_unclosed2 = n; break;
6153 case 'U': ind_unclosed_noignore = n; break;
6154 case 'W': ind_unclosed_wrapped = n; break;
6155 case 'w': ind_unclosed_whiteok = n; break;
6156 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006157 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006158 case ')': ind_maxparen = n; break;
6159 case '*': ind_maxcomment = n; break;
6160 case 'g': ind_scopedecl = n; break;
6161 case 'h': ind_scopedecl_code = n; break;
6162 case 'j': ind_java = n; break;
6163 case 'l': ind_keep_case_label = n; break;
6164 }
6165 }
6166
6167 /* remember where the cursor was when we started */
6168 cur_curpos = curwin->w_cursor;
6169
6170 /* Get a copy of the current contents of the line.
6171 * This is required, because only the most recent line obtained with
6172 * ml_get is valid! */
6173 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6174 if (linecopy == NULL)
6175 return 0;
6176
6177 /*
6178 * In insert mode and the cursor is on a ')' truncate the line at the
6179 * cursor position. We don't want to line up with the matching '(' when
6180 * inserting new stuff.
6181 * For unknown reasons the cursor might be past the end of the line, thus
6182 * check for that.
6183 */
6184 if ((State & INSERT)
6185 && curwin->w_cursor.col < STRLEN(linecopy)
6186 && linecopy[curwin->w_cursor.col] == ')')
6187 linecopy[curwin->w_cursor.col] = NUL;
6188
6189 theline = skipwhite(linecopy);
6190
6191 /* move the cursor to the start of the line */
6192
6193 curwin->w_cursor.col = 0;
6194
6195 /*
6196 * #defines and so on always go at the left when included in 'cinkeys'.
6197 */
6198 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6199 {
6200 amount = 0;
6201 }
6202
6203 /*
6204 * Is it a non-case label? Then that goes at the left margin too.
6205 */
6206 else if (cin_islabel(ind_maxcomment)) /* XXX */
6207 {
6208 amount = 0;
6209 }
6210
6211 /*
6212 * If we're inside a "//" comment and there is a "//" comment in a
6213 * previous line, lineup with that one.
6214 */
6215 else if (cin_islinecomment(theline)
6216 && (trypos = find_line_comment()) != NULL) /* XXX */
6217 {
6218 /* find how indented the line beginning the comment is */
6219 getvcol(curwin, trypos, &col, NULL, NULL);
6220 amount = col;
6221 }
6222
6223 /*
6224 * If we're inside a comment and not looking at the start of the
6225 * comment, try using the 'comments' option.
6226 */
6227 else if (!cin_iscomment(theline)
6228 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6229 {
6230 int lead_start_len = 2;
6231 int lead_middle_len = 1;
6232 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6233 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6234 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6235 char_u *p;
6236 int start_align = 0;
6237 int start_off = 0;
6238 int done = FALSE;
6239
6240 /* find how indented the line beginning the comment is */
6241 getvcol(curwin, trypos, &col, NULL, NULL);
6242 amount = col;
6243
6244 p = curbuf->b_p_com;
6245 while (*p != NUL)
6246 {
6247 int align = 0;
6248 int off = 0;
6249 int what = 0;
6250
6251 while (*p != NUL && *p != ':')
6252 {
6253 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6254 what = *p++;
6255 else if (*p == COM_LEFT || *p == COM_RIGHT)
6256 align = *p++;
6257 else if (VIM_ISDIGIT(*p) || *p == '-')
6258 off = getdigits(&p);
6259 else
6260 ++p;
6261 }
6262
6263 if (*p == ':')
6264 ++p;
6265 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6266 if (what == COM_START)
6267 {
6268 STRCPY(lead_start, lead_end);
6269 lead_start_len = (int)STRLEN(lead_start);
6270 start_off = off;
6271 start_align = align;
6272 }
6273 else if (what == COM_MIDDLE)
6274 {
6275 STRCPY(lead_middle, lead_end);
6276 lead_middle_len = (int)STRLEN(lead_middle);
6277 }
6278 else if (what == COM_END)
6279 {
6280 /* If our line starts with the middle comment string, line it
6281 * up with the comment opener per the 'comments' option. */
6282 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6283 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6284 {
6285 done = TRUE;
6286 if (curwin->w_cursor.lnum > 1)
6287 {
6288 /* If the start comment string matches in the previous
6289 * line, use the indent of that line pluss offset. If
6290 * the middle comment string matches in the previous
6291 * line, use the indent of that line. XXX */
6292 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6293 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6294 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6295 else if (STRNCMP(look, lead_middle,
6296 lead_middle_len) == 0)
6297 {
6298 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6299 break;
6300 }
6301 /* If the start comment string doesn't match with the
6302 * start of the comment, skip this entry. XXX */
6303 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6304 lead_start, lead_start_len) != 0)
6305 continue;
6306 }
6307 if (start_off != 0)
6308 amount += start_off;
6309 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006310 amount += vim_strsize(lead_start)
6311 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 break;
6313 }
6314
6315 /* If our line starts with the end comment string, line it up
6316 * with the middle comment */
6317 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6318 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6319 {
6320 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6321 /* XXX */
6322 if (off != 0)
6323 amount += off;
6324 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006325 amount += vim_strsize(lead_start)
6326 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 done = TRUE;
6328 break;
6329 }
6330 }
6331 }
6332
6333 /* If our line starts with an asterisk, line up with the
6334 * asterisk in the comment opener; otherwise, line up
6335 * with the first character of the comment text.
6336 */
6337 if (done)
6338 ;
6339 else if (theline[0] == '*')
6340 amount += 1;
6341 else
6342 {
6343 /*
6344 * If we are more than one line away from the comment opener, take
6345 * the indent of the previous non-empty line. If 'cino' has "CO"
6346 * and we are just below the comment opener and there are any
6347 * white characters after it line up with the text after it;
6348 * otherwise, add the amount specified by "c" in 'cino'
6349 */
6350 amount = -1;
6351 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6352 {
6353 if (linewhite(lnum)) /* skip blank lines */
6354 continue;
6355 amount = get_indent_lnum(lnum); /* XXX */
6356 break;
6357 }
6358 if (amount == -1) /* use the comment opener */
6359 {
6360 if (!ind_in_comment2)
6361 {
6362 start = ml_get(trypos->lnum);
6363 look = start + trypos->col + 2; /* skip / and * */
6364 if (*look != NUL) /* if something after it */
6365 trypos->col = (colnr_T)(skipwhite(look) - start);
6366 }
6367 getvcol(curwin, trypos, &col, NULL, NULL);
6368 amount = col;
6369 if (ind_in_comment2 || *look == NUL)
6370 amount += ind_in_comment;
6371 }
6372 }
6373 }
6374
6375 /*
6376 * Are we inside parentheses or braces?
6377 */ /* XXX */
6378 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6379 && ind_java == 0)
6380 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6381 || trypos != NULL)
6382 {
6383 if (trypos != NULL && tryposBrace != NULL)
6384 {
6385 /* Both an unmatched '(' and '{' is found. Use the one which is
6386 * closer to the current cursor position, set the other to NULL. */
6387 if (trypos->lnum != tryposBrace->lnum
6388 ? trypos->lnum < tryposBrace->lnum
6389 : trypos->col < tryposBrace->col)
6390 trypos = NULL;
6391 else
6392 tryposBrace = NULL;
6393 }
6394
6395 if (trypos != NULL)
6396 {
6397 /*
6398 * If the matching paren is more than one line away, use the indent of
6399 * a previous non-empty line that matches the same paren.
6400 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006401 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006402 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006403 /* Line up with the start of the matching paren line. */
6404 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6405 }
6406 else
6407 {
6408 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006409 our_paren_pos = *trypos;
6410 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006411 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006412 l = skipwhite(ml_get(lnum));
6413 if (cin_nocode(l)) /* skip comment lines */
6414 continue;
6415 if (cin_ispreproc_cont(&l, &lnum))
6416 continue; /* ignore #define, #if, etc. */
6417 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006419 /* Skip a comment. XXX */
6420 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6421 {
6422 lnum = trypos->lnum + 1;
6423 continue;
6424 }
6425
6426 /* XXX */
6427 if ((trypos = find_match_paren(
6428 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006430 && trypos->lnum == our_paren_pos.lnum
6431 && trypos->col == our_paren_pos.col)
6432 {
6433 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006434
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006435 if (theline[0] == ')')
6436 {
6437 if (our_paren_pos.lnum != lnum
6438 && cur_amount > amount)
6439 cur_amount = amount;
6440 amount = -1;
6441 }
6442 break;
6443 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444 }
6445 }
6446
6447 /*
6448 * Line up with line where the matching paren is. XXX
6449 * If the line starts with a '(' or the indent for unclosed
6450 * parentheses is zero, line up with the unclosed parentheses.
6451 */
6452 if (amount == -1)
6453 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006454 int ignore_paren_col = 0;
6455
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006457 look = skipwhite(look);
6458 if (*look == '(')
6459 {
6460 linenr_T save_lnum = curwin->w_cursor.lnum;
6461 char_u *line;
6462 int look_col;
6463
6464 /* Ignore a '(' in front of the line that has a match before
6465 * our matching '('. */
6466 curwin->w_cursor.lnum = our_paren_pos.lnum;
6467 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006468 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006469 curwin->w_cursor.col = look_col + 1;
6470 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6471 != NULL
6472 && trypos->lnum == our_paren_pos.lnum
6473 && trypos->col < our_paren_pos.col)
6474 ignore_paren_col = trypos->col + 1;
6475
6476 curwin->w_cursor.lnum = save_lnum;
6477 look = ml_get(our_paren_pos.lnum) + look_col;
6478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479 if (theline[0] == ')' || ind_unclosed == 0
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006480 || (!ind_unclosed_noignore && *look == '('
6481 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006482 {
6483 /*
6484 * If we're looking at a close paren, line up right there;
6485 * otherwise, line up with the next (non-white) character.
6486 * When ind_unclosed_wrapped is set and the matching paren is
6487 * the last nonwhite character of the line, use either the
6488 * indent of the current line or the indentation of the next
6489 * outer paren and add ind_unclosed_wrapped (for very long
6490 * lines).
6491 */
6492 if (theline[0] != ')')
6493 {
6494 cur_amount = MAXCOL;
6495 l = ml_get(our_paren_pos.lnum);
6496 if (ind_unclosed_wrapped
6497 && cin_ends_in(l, (char_u *)"(", NULL))
6498 {
6499 /* look for opening unmatched paren, indent one level
6500 * for each additional level */
6501 n = 1;
6502 for (col = 0; col < our_paren_pos.col; ++col)
6503 {
6504 switch (l[col])
6505 {
6506 case '(':
6507 case '{': ++n;
6508 break;
6509
6510 case ')':
6511 case '}': if (n > 1)
6512 --n;
6513 break;
6514 }
6515 }
6516
6517 our_paren_pos.col = 0;
6518 amount += n * ind_unclosed_wrapped;
6519 }
6520 else if (ind_unclosed_whiteok)
6521 our_paren_pos.col++;
6522 else
6523 {
6524 col = our_paren_pos.col + 1;
6525 while (vim_iswhite(l[col]))
6526 col++;
6527 if (l[col] != NUL) /* In case of trailing space */
6528 our_paren_pos.col = col;
6529 else
6530 our_paren_pos.col++;
6531 }
6532 }
6533
6534 /*
6535 * Find how indented the paren is, or the character after it
6536 * if we did the above "if".
6537 */
6538 if (our_paren_pos.col > 0)
6539 {
6540 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6541 if (cur_amount > (int)col)
6542 cur_amount = col;
6543 }
6544 }
6545
6546 if (theline[0] == ')' && ind_matching_paren)
6547 {
6548 /* Line up with the start of the matching paren line. */
6549 }
6550 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006551 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 {
6553 if (cur_amount != MAXCOL)
6554 amount = cur_amount;
6555 }
6556 else
6557 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006558 /* Add ind_unclosed2 for each '(' before our matching one, but
6559 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006561 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 {
6563 --our_paren_pos.col;
6564 switch (*ml_get_pos(&our_paren_pos))
6565 {
6566 case '(': amount += ind_unclosed2;
6567 col = our_paren_pos.col;
6568 break;
6569 case ')': amount -= ind_unclosed2;
6570 col = MAXCOL;
6571 break;
6572 }
6573 }
6574
6575 /* Use ind_unclosed once, when the first '(' is not inside
6576 * braces */
6577 if (col == MAXCOL)
6578 amount += ind_unclosed;
6579 else
6580 {
6581 curwin->w_cursor.lnum = our_paren_pos.lnum;
6582 curwin->w_cursor.col = col;
6583 if ((trypos = find_match_paren(ind_maxparen,
6584 ind_maxcomment)) != NULL)
6585 amount += ind_unclosed2;
6586 else
6587 amount += ind_unclosed;
6588 }
6589 /*
6590 * For a line starting with ')' use the minimum of the two
6591 * positions, to avoid giving it more indent than the previous
6592 * lines:
6593 * func_long_name( if (x
6594 * arg && yy
6595 * ) ^ not here ) ^ not here
6596 */
6597 if (cur_amount < amount)
6598 amount = cur_amount;
6599 }
6600 }
6601
6602 /* add extra indent for a comment */
6603 if (cin_iscomment(theline))
6604 amount += ind_comment;
6605 }
6606
6607 /*
6608 * Are we at least inside braces, then?
6609 */
6610 else
6611 {
6612 trypos = tryposBrace;
6613
6614 ourscope = trypos->lnum;
6615 start = ml_get(ourscope);
6616
6617 /*
6618 * Now figure out how indented the line is in general.
6619 * If the brace was at the start of the line, we use that;
6620 * otherwise, check out the indentation of the line as
6621 * a whole and then add the "imaginary indent" to that.
6622 */
6623 look = skipwhite(start);
6624 if (*look == '{')
6625 {
6626 getvcol(curwin, trypos, &col, NULL, NULL);
6627 amount = col;
6628 if (*start == '{')
6629 start_brace = BRACE_IN_COL0;
6630 else
6631 start_brace = BRACE_AT_START;
6632 }
6633 else
6634 {
6635 /*
6636 * that opening brace might have been on a continuation
6637 * line. if so, find the start of the line.
6638 */
6639 curwin->w_cursor.lnum = ourscope;
6640
6641 /*
6642 * position the cursor over the rightmost paren, so that
6643 * matching it will take us back to the start of the line.
6644 */
6645 lnum = ourscope;
6646 if (find_last_paren(start, '(', ')')
6647 && (trypos = find_match_paren(ind_maxparen,
6648 ind_maxcomment)) != NULL)
6649 lnum = trypos->lnum;
6650
6651 /*
6652 * It could have been something like
6653 * case 1: if (asdf &&
6654 * ldfd) {
6655 * }
6656 */
6657 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6658 amount = get_indent();
6659 else
6660 amount = skip_label(lnum, &l, ind_maxcomment);
6661
6662 start_brace = BRACE_AT_END;
6663 }
6664
6665 /*
6666 * if we're looking at a closing brace, that's where
6667 * we want to be. otherwise, add the amount of room
6668 * that an indent is supposed to be.
6669 */
6670 if (theline[0] == '}')
6671 {
6672 /*
6673 * they may want closing braces to line up with something
6674 * other than the open brace. indulge them, if so.
6675 */
6676 amount += ind_close_extra;
6677 }
6678 else
6679 {
6680 /*
6681 * If we're looking at an "else", try to find an "if"
6682 * to match it with.
6683 * If we're looking at a "while", try to find a "do"
6684 * to match it with.
6685 */
6686 lookfor = LOOKFOR_INITIAL;
6687 if (cin_iselse(theline))
6688 lookfor = LOOKFOR_IF;
6689 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6690 /* XXX */
6691 lookfor = LOOKFOR_DO;
6692 if (lookfor != LOOKFOR_INITIAL)
6693 {
6694 curwin->w_cursor.lnum = cur_curpos.lnum;
6695 if (find_match(lookfor, ourscope, ind_maxparen,
6696 ind_maxcomment) == OK)
6697 {
6698 amount = get_indent(); /* XXX */
6699 goto theend;
6700 }
6701 }
6702
6703 /*
6704 * We get here if we are not on an "while-of-do" or "else" (or
6705 * failed to find a matching "if").
6706 * Search backwards for something to line up with.
6707 * First set amount for when we don't find anything.
6708 */
6709
6710 /*
6711 * if the '{' is _really_ at the left margin, use the imaginary
6712 * location of a left-margin brace. Otherwise, correct the
6713 * location for ind_open_extra.
6714 */
6715
6716 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6717 {
6718 amount = ind_open_left_imag;
6719 }
6720 else
6721 {
6722 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6723 amount += ind_open_imag;
6724 else
6725 {
6726 /* Compensate for adding ind_open_extra later. */
6727 amount -= ind_open_extra;
6728 if (amount < 0)
6729 amount = 0;
6730 }
6731 }
6732
6733 lookfor_break = FALSE;
6734
6735 if (cin_iscase(theline)) /* it's a switch() label */
6736 {
6737 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6738 amount += ind_case;
6739 }
6740 else if (cin_isscopedecl(theline)) /* private:, ... */
6741 {
6742 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6743 amount += ind_scopedecl;
6744 }
6745 else
6746 {
6747 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6748 lookfor_break = TRUE;
6749
6750 lookfor = LOOKFOR_INITIAL;
6751 amount += ind_level; /* ind_level from start of block */
6752 }
6753 scope_amount = amount;
6754 whilelevel = 0;
6755
6756 /*
6757 * Search backwards. If we find something we recognize, line up
6758 * with that.
6759 *
6760 * if we're looking at an open brace, indent
6761 * the usual amount relative to the conditional
6762 * that opens the block.
6763 */
6764 curwin->w_cursor = cur_curpos;
6765 for (;;)
6766 {
6767 curwin->w_cursor.lnum--;
6768 curwin->w_cursor.col = 0;
6769
6770 /*
6771 * If we went all the way back to the start of our scope, line
6772 * up with it.
6773 */
6774 if (curwin->w_cursor.lnum <= ourscope)
6775 {
6776 /* we reached end of scope:
6777 * if looking for a enum or structure initialization
6778 * go further back:
6779 * if it is an initializer (enum xxx or xxx =), then
6780 * don't add ind_continuation, otherwise it is a variable
6781 * declaration:
6782 * int x,
6783 * here; <-- add ind_continuation
6784 */
6785 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6786 {
6787 if (curwin->w_cursor.lnum == 0
6788 || curwin->w_cursor.lnum
6789 < ourscope - ind_maxparen)
6790 {
6791 /* nothing found (abuse ind_maxparen as limit)
6792 * assume terminated line (i.e. a variable
6793 * initialization) */
6794 if (cont_amount > 0)
6795 amount = cont_amount;
6796 else
6797 amount += ind_continuation;
6798 break;
6799 }
6800
6801 l = ml_get_curline();
6802
6803 /*
6804 * If we're in a comment now, skip to the start of the
6805 * comment.
6806 */
6807 trypos = find_start_comment(ind_maxcomment);
6808 if (trypos != NULL)
6809 {
6810 curwin->w_cursor.lnum = trypos->lnum + 1;
6811 continue;
6812 }
6813
6814 /*
6815 * Skip preprocessor directives and blank lines.
6816 */
6817 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6818 continue;
6819
6820 if (cin_nocode(l))
6821 continue;
6822
6823 terminated = cin_isterminated(l, FALSE, TRUE);
6824
6825 /*
6826 * If we are at top level and the line looks like a
6827 * function declaration, we are done
6828 * (it's a variable declaration).
6829 */
6830 if (start_brace != BRACE_IN_COL0
6831 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6832 {
6833 /* if the line is terminated with another ','
6834 * it is a continued variable initialization.
6835 * don't add extra indent.
6836 * TODO: does not work, if a function
6837 * declaration is split over multiple lines:
6838 * cin_isfuncdecl returns FALSE then.
6839 */
6840 if (terminated == ',')
6841 break;
6842
6843 /* if it es a enum declaration or an assignment,
6844 * we are done.
6845 */
6846 if (terminated != ';' && cin_isinit())
6847 break;
6848
6849 /* nothing useful found */
6850 if (terminated == 0 || terminated == '{')
6851 continue;
6852 }
6853
6854 if (terminated != ';')
6855 {
6856 /* Skip parens and braces. Position the cursor
6857 * over the rightmost paren, so that matching it
6858 * will take us back to the start of the line.
6859 */ /* XXX */
6860 trypos = NULL;
6861 if (find_last_paren(l, '(', ')'))
6862 trypos = find_match_paren(ind_maxparen,
6863 ind_maxcomment);
6864
6865 if (trypos == NULL && find_last_paren(l, '{', '}'))
6866 trypos = find_start_brace(ind_maxcomment);
6867
6868 if (trypos != NULL)
6869 {
6870 curwin->w_cursor.lnum = trypos->lnum + 1;
6871 continue;
6872 }
6873 }
6874
6875 /* it's a variable declaration, add indentation
6876 * like in
6877 * int a,
6878 * b;
6879 */
6880 if (cont_amount > 0)
6881 amount = cont_amount;
6882 else
6883 amount += ind_continuation;
6884 }
6885 else if (lookfor == LOOKFOR_UNTERM)
6886 {
6887 if (cont_amount > 0)
6888 amount = cont_amount;
6889 else
6890 amount += ind_continuation;
6891 }
6892 else if (lookfor != LOOKFOR_TERM
6893 && lookfor != LOOKFOR_CPP_BASECLASS)
6894 {
6895 amount = scope_amount;
6896 if (theline[0] == '{')
6897 amount += ind_open_extra;
6898 }
6899 break;
6900 }
6901
6902 /*
6903 * If we're in a comment now, skip to the start of the comment.
6904 */ /* XXX */
6905 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6906 {
6907 curwin->w_cursor.lnum = trypos->lnum + 1;
6908 continue;
6909 }
6910
6911 l = ml_get_curline();
6912
6913 /*
6914 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00006915 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006916 */
6917 iscase = cin_iscase(l);
6918 if (iscase || cin_isscopedecl(l))
6919 {
6920 /* we are only looking for cpp base class
6921 * declaration/initialization any longer */
6922 if (lookfor == LOOKFOR_CPP_BASECLASS)
6923 break;
6924
6925 /* When looking for a "do" we are not interested in
6926 * labels. */
6927 if (whilelevel > 0)
6928 continue;
6929
6930 /*
6931 * case xx:
6932 * c = 99 + <- this indent plus continuation
6933 *-> here;
6934 */
6935 if (lookfor == LOOKFOR_UNTERM
6936 || lookfor == LOOKFOR_ENUM_OR_INIT)
6937 {
6938 if (cont_amount > 0)
6939 amount = cont_amount;
6940 else
6941 amount += ind_continuation;
6942 break;
6943 }
6944
6945 /*
6946 * case xx: <- line up with this case
6947 * x = 333;
6948 * case yy:
6949 */
6950 if ( (iscase && lookfor == LOOKFOR_CASE)
6951 || (iscase && lookfor_break)
6952 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
6953 {
6954 /*
6955 * Check that this case label is not for another
6956 * switch()
6957 */ /* XXX */
6958 if ((trypos = find_start_brace(ind_maxcomment)) ==
6959 NULL || trypos->lnum == ourscope)
6960 {
6961 amount = get_indent(); /* XXX */
6962 break;
6963 }
6964 continue;
6965 }
6966
6967 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
6968
6969 /*
6970 * case xx: if (cond) <- line up with this if
6971 * y = y + 1;
6972 * -> s = 99;
6973 *
6974 * case xx:
6975 * if (cond) <- line up with this line
6976 * y = y + 1;
6977 * -> s = 99;
6978 */
6979 if (lookfor == LOOKFOR_TERM)
6980 {
6981 if (n)
6982 amount = n;
6983
6984 if (!lookfor_break)
6985 break;
6986 }
6987
6988 /*
6989 * case xx: x = x + 1; <- line up with this x
6990 * -> y = y + 1;
6991 *
6992 * case xx: if (cond) <- line up with this if
6993 * -> y = y + 1;
6994 */
6995 if (n)
6996 {
6997 amount = n;
6998 l = after_label(ml_get_curline());
6999 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007000 {
7001 if (theline[0] == '{')
7002 amount += ind_open_extra;
7003 else
7004 amount += ind_level + ind_no_brace;
7005 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006 break;
7007 }
7008
7009 /*
7010 * Try to get the indent of a statement before the switch
7011 * label. If nothing is found, line up relative to the
7012 * switch label.
7013 * break; <- may line up with this line
7014 * case xx:
7015 * -> y = 1;
7016 */
7017 scope_amount = get_indent() + (iscase /* XXX */
7018 ? ind_case_code : ind_scopedecl_code);
7019 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7020 continue;
7021 }
7022
7023 /*
7024 * Looking for a switch() label or C++ scope declaration,
7025 * ignore other lines, skip {}-blocks.
7026 */
7027 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7028 {
7029 if (find_last_paren(l, '{', '}') && (trypos =
7030 find_start_brace(ind_maxcomment)) != NULL)
7031 curwin->w_cursor.lnum = trypos->lnum + 1;
7032 continue;
7033 }
7034
7035 /*
7036 * Ignore jump labels with nothing after them.
7037 */
7038 if (cin_islabel(ind_maxcomment))
7039 {
7040 l = after_label(ml_get_curline());
7041 if (l == NULL || cin_nocode(l))
7042 continue;
7043 }
7044
7045 /*
7046 * Ignore #defines, #if, etc.
7047 * Ignore comment and empty lines.
7048 * (need to get the line again, cin_islabel() may have
7049 * unlocked it)
7050 */
7051 l = ml_get_curline();
7052 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7053 || cin_nocode(l))
7054 continue;
7055
7056 /*
7057 * Are we at the start of a cpp base class declaration or
7058 * constructor initialization?
7059 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007060 n = FALSE;
7061 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7062 {
7063 n = cin_is_cpp_baseclass(l, &col);
7064 l = ml_get_curline();
7065 }
7066 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067 {
7068 if (lookfor == LOOKFOR_UNTERM)
7069 {
7070 if (cont_amount > 0)
7071 amount = cont_amount;
7072 else
7073 amount += ind_continuation;
7074 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007075 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007077 /* Need to find start of the declaration. */
7078 lookfor = LOOKFOR_UNTERM;
7079 ind_continuation = 0;
7080 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 }
7082 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007083 /* XXX */
7084 amount = get_baseclass_amount(col, ind_maxparen,
7085 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007086 break;
7087 }
7088 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7089 {
7090 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007091 * declaration or initialization before the opening brace.
7092 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 if (cin_isterminated(l, TRUE, FALSE))
7094 break;
7095 else
7096 continue;
7097 }
7098
7099 /*
7100 * What happens next depends on the line being terminated.
7101 * If terminated with a ',' only consider it terminating if
7102 * there is anoter unterminated statement behind, eg:
7103 * 123,
7104 * sizeof
7105 * here
7106 * Otherwise check whether it is a enumeration or structure
7107 * initialisation (not indented) or a variable declaration
7108 * (indented).
7109 */
7110 terminated = cin_isterminated(l, FALSE, TRUE);
7111
7112 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7113 && terminated == ','))
7114 {
7115 /*
7116 * if we're in the middle of a paren thing,
7117 * go back to the line that starts it so
7118 * we can get the right prevailing indent
7119 * if ( foo &&
7120 * bar )
7121 */
7122 /*
7123 * position the cursor over the rightmost paren, so that
7124 * matching it will take us back to the start of the line.
7125 */
7126 (void)find_last_paren(l, '(', ')');
7127 trypos = find_match_paren(
7128 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7129 ind_maxcomment);
7130
7131 /*
7132 * If we are looking for ',', we also look for matching
7133 * braces.
7134 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007135 if (trypos == NULL && terminated == ','
7136 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007137 trypos = find_start_brace(ind_maxcomment);
7138
7139 if (trypos != NULL)
7140 {
7141 /*
7142 * Check if we are on a case label now. This is
7143 * handled above.
7144 * case xx: if ( asdf &&
7145 * asdf)
7146 */
7147 curwin->w_cursor.lnum = trypos->lnum;
7148 l = ml_get_curline();
7149 if (cin_iscase(l) || cin_isscopedecl(l))
7150 {
7151 ++curwin->w_cursor.lnum;
7152 continue;
7153 }
7154 }
7155
7156 /*
7157 * Skip over continuation lines to find the one to get the
7158 * indent from
7159 * char *usethis = "bla\
7160 * bla",
7161 * here;
7162 */
7163 if (terminated == ',')
7164 {
7165 while (curwin->w_cursor.lnum > 1)
7166 {
7167 l = ml_get(curwin->w_cursor.lnum - 1);
7168 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7169 break;
7170 --curwin->w_cursor.lnum;
7171 }
7172 }
7173
7174 /*
7175 * Get indent and pointer to text for current line,
7176 * ignoring any jump label. XXX
7177 */
7178 cur_amount = skip_label(curwin->w_cursor.lnum,
7179 &l, ind_maxcomment);
7180
7181 /*
7182 * If this is just above the line we are indenting, and it
7183 * starts with a '{', line it up with this line.
7184 * while (not)
7185 * -> {
7186 * }
7187 */
7188 if (terminated != ',' && lookfor != LOOKFOR_TERM
7189 && theline[0] == '{')
7190 {
7191 amount = cur_amount;
7192 /*
7193 * Only add ind_open_extra when the current line
7194 * doesn't start with a '{', which must have a match
7195 * in the same line (scope is the same). Probably:
7196 * { 1, 2 },
7197 * -> { 3, 4 }
7198 */
7199 if (*skipwhite(l) != '{')
7200 amount += ind_open_extra;
7201
7202 if (ind_cpp_baseclass)
7203 {
7204 /* have to look back, whether it is a cpp base
7205 * class declaration or initialization */
7206 lookfor = LOOKFOR_CPP_BASECLASS;
7207 continue;
7208 }
7209 break;
7210 }
7211
7212 /*
7213 * Check if we are after an "if", "while", etc.
7214 * Also allow " } else".
7215 */
7216 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7217 {
7218 /*
7219 * Found an unterminated line after an if (), line up
7220 * with the last one.
7221 * if (cond)
7222 * 100 +
7223 * -> here;
7224 */
7225 if (lookfor == LOOKFOR_UNTERM
7226 || lookfor == LOOKFOR_ENUM_OR_INIT)
7227 {
7228 if (cont_amount > 0)
7229 amount = cont_amount;
7230 else
7231 amount += ind_continuation;
7232 break;
7233 }
7234
7235 /*
7236 * If this is just above the line we are indenting, we
7237 * are finished.
7238 * while (not)
7239 * -> here;
7240 * Otherwise this indent can be used when the line
7241 * before this is terminated.
7242 * yyy;
7243 * if (stat)
7244 * while (not)
7245 * xxx;
7246 * -> here;
7247 */
7248 amount = cur_amount;
7249 if (theline[0] == '{')
7250 amount += ind_open_extra;
7251 if (lookfor != LOOKFOR_TERM)
7252 {
7253 amount += ind_level + ind_no_brace;
7254 break;
7255 }
7256
7257 /*
7258 * Special trick: when expecting the while () after a
7259 * do, line up with the while()
7260 * do
7261 * x = 1;
7262 * -> here
7263 */
7264 l = skipwhite(ml_get_curline());
7265 if (cin_isdo(l))
7266 {
7267 if (whilelevel == 0)
7268 break;
7269 --whilelevel;
7270 }
7271
7272 /*
7273 * When searching for a terminated line, don't use the
7274 * one between the "if" and the "else".
7275 * Need to use the scope of this "else". XXX
7276 * If whilelevel != 0 continue looking for a "do {".
7277 */
7278 if (cin_iselse(l)
7279 && whilelevel == 0
7280 && ((trypos = find_start_brace(ind_maxcomment))
7281 == NULL
7282 || find_match(LOOKFOR_IF, trypos->lnum,
7283 ind_maxparen, ind_maxcomment) == FAIL))
7284 break;
7285 }
7286
7287 /*
7288 * If we're below an unterminated line that is not an
7289 * "if" or something, we may line up with this line or
7290 * add someting for a continuation line, depending on
7291 * the line before this one.
7292 */
7293 else
7294 {
7295 /*
7296 * Found two unterminated lines on a row, line up with
7297 * the last one.
7298 * c = 99 +
7299 * 100 +
7300 * -> here;
7301 */
7302 if (lookfor == LOOKFOR_UNTERM)
7303 {
7304 /* When line ends in a comma add extra indent */
7305 if (terminated == ',')
7306 amount += ind_continuation;
7307 break;
7308 }
7309
7310 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7311 {
7312 /* Found two lines ending in ',', lineup with the
7313 * lowest one, but check for cpp base class
7314 * declaration/initialization, if it is an
7315 * opening brace or we are looking just for
7316 * enumerations/initializations. */
7317 if (terminated == ',')
7318 {
7319 if (ind_cpp_baseclass == 0)
7320 break;
7321
7322 lookfor = LOOKFOR_CPP_BASECLASS;
7323 continue;
7324 }
7325
7326 /* Ignore unterminated lines in between, but
7327 * reduce indent. */
7328 if (amount > cur_amount)
7329 amount = cur_amount;
7330 }
7331 else
7332 {
7333 /*
7334 * Found first unterminated line on a row, may
7335 * line up with this line, remember its indent
7336 * 100 +
7337 * -> here;
7338 */
7339 amount = cur_amount;
7340
7341 /*
7342 * If previous line ends in ',', check whether we
7343 * are in an initialization or enum
7344 * struct xxx =
7345 * {
7346 * sizeof a,
7347 * 124 };
7348 * or a normal possible continuation line.
7349 * but only, of no other statement has been found
7350 * yet.
7351 */
7352 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7353 {
7354 lookfor = LOOKFOR_ENUM_OR_INIT;
7355 cont_amount = cin_first_id_amount();
7356 }
7357 else
7358 {
7359 if (lookfor == LOOKFOR_INITIAL
7360 && *l != NUL
7361 && l[STRLEN(l) - 1] == '\\')
7362 /* XXX */
7363 cont_amount = cin_get_equal_amount(
7364 curwin->w_cursor.lnum);
7365 if (lookfor != LOOKFOR_TERM)
7366 lookfor = LOOKFOR_UNTERM;
7367 }
7368 }
7369 }
7370 }
7371
7372 /*
7373 * Check if we are after a while (cond);
7374 * If so: Ignore until the matching "do".
7375 */
7376 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007377 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7378 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379 {
7380 /*
7381 * Found an unterminated line after a while ();, line up
7382 * with the last one.
7383 * while (cond);
7384 * 100 + <- line up with this one
7385 * -> here;
7386 */
7387 if (lookfor == LOOKFOR_UNTERM
7388 || lookfor == LOOKFOR_ENUM_OR_INIT)
7389 {
7390 if (cont_amount > 0)
7391 amount = cont_amount;
7392 else
7393 amount += ind_continuation;
7394 break;
7395 }
7396
7397 if (whilelevel == 0)
7398 {
7399 lookfor = LOOKFOR_TERM;
7400 amount = get_indent(); /* XXX */
7401 if (theline[0] == '{')
7402 amount += ind_open_extra;
7403 }
7404 ++whilelevel;
7405 }
7406
7407 /*
7408 * We are after a "normal" statement.
7409 * If we had another statement we can stop now and use the
7410 * indent of that other statement.
7411 * Otherwise the indent of the current statement may be used,
7412 * search backwards for the next "normal" statement.
7413 */
7414 else
7415 {
7416 /*
7417 * Skip single break line, if before a switch label. It
7418 * may be lined up with the case label.
7419 */
7420 if (lookfor == LOOKFOR_NOBREAK
7421 && cin_isbreak(skipwhite(ml_get_curline())))
7422 {
7423 lookfor = LOOKFOR_ANY;
7424 continue;
7425 }
7426
7427 /*
7428 * Handle "do {" line.
7429 */
7430 if (whilelevel > 0)
7431 {
7432 l = cin_skipcomment(ml_get_curline());
7433 if (cin_isdo(l))
7434 {
7435 amount = get_indent(); /* XXX */
7436 --whilelevel;
7437 continue;
7438 }
7439 }
7440
7441 /*
7442 * Found a terminated line above an unterminated line. Add
7443 * the amount for a continuation line.
7444 * x = 1;
7445 * y = foo +
7446 * -> here;
7447 * or
7448 * int x = 1;
7449 * int foo,
7450 * -> here;
7451 */
7452 if (lookfor == LOOKFOR_UNTERM
7453 || lookfor == LOOKFOR_ENUM_OR_INIT)
7454 {
7455 if (cont_amount > 0)
7456 amount = cont_amount;
7457 else
7458 amount += ind_continuation;
7459 break;
7460 }
7461
7462 /*
7463 * Found a terminated line above a terminated line or "if"
7464 * etc. line. Use the amount of the line below us.
7465 * x = 1; x = 1;
7466 * if (asdf) y = 2;
7467 * while (asdf) ->here;
7468 * here;
7469 * ->foo;
7470 */
7471 if (lookfor == LOOKFOR_TERM)
7472 {
7473 if (!lookfor_break && whilelevel == 0)
7474 break;
7475 }
7476
7477 /*
7478 * First line above the one we're indenting is terminated.
7479 * To know what needs to be done look further backward for
7480 * a terminated line.
7481 */
7482 else
7483 {
7484 /*
7485 * position the cursor over the rightmost paren, so
7486 * that matching it will take us back to the start of
7487 * the line. Helps for:
7488 * func(asdr,
7489 * asdfasdf);
7490 * here;
7491 */
7492term_again:
7493 l = ml_get_curline();
7494 if (find_last_paren(l, '(', ')')
7495 && (trypos = find_match_paren(ind_maxparen,
7496 ind_maxcomment)) != NULL)
7497 {
7498 /*
7499 * Check if we are on a case label now. This is
7500 * handled above.
7501 * case xx: if ( asdf &&
7502 * asdf)
7503 */
7504 curwin->w_cursor.lnum = trypos->lnum;
7505 l = ml_get_curline();
7506 if (cin_iscase(l) || cin_isscopedecl(l))
7507 {
7508 ++curwin->w_cursor.lnum;
7509 continue;
7510 }
7511 }
7512
7513 /* When aligning with the case statement, don't align
7514 * with a statement after it.
7515 * case 1: { <-- don't use this { position
7516 * stat;
7517 * }
7518 * case 2:
7519 * stat;
7520 * }
7521 */
7522 iscase = (ind_keep_case_label && cin_iscase(l));
7523
7524 /*
7525 * Get indent and pointer to text for current line,
7526 * ignoring any jump label.
7527 */
7528 amount = skip_label(curwin->w_cursor.lnum,
7529 &l, ind_maxcomment);
7530
7531 if (theline[0] == '{')
7532 amount += ind_open_extra;
7533 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007534 l = skipwhite(l);
7535 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007536 amount -= ind_open_extra;
7537 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7538
7539 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007540 * When a terminated line starts with "else" skip to
7541 * the matching "if":
7542 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007543 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00007544 * Need to use the scope of this "else". XXX
7545 * If whilelevel != 0 continue looking for a "do {".
7546 */
7547 if (lookfor == LOOKFOR_TERM
7548 && *l != '}'
7549 && cin_iselse(l)
7550 && whilelevel == 0)
7551 {
7552 if ((trypos = find_start_brace(ind_maxcomment))
7553 == NULL
7554 || find_match(LOOKFOR_IF, trypos->lnum,
7555 ind_maxparen, ind_maxcomment) == FAIL)
7556 break;
7557 continue;
7558 }
7559
7560 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007561 * If we're at the end of a block, skip to the start of
7562 * that block.
7563 */
7564 curwin->w_cursor.col = 0;
7565 if (*cin_skipcomment(l) == '}'
7566 && (trypos = find_start_brace(ind_maxcomment))
7567 != NULL) /* XXX */
7568 {
7569 curwin->w_cursor.lnum = trypos->lnum;
7570 /* if not "else {" check for terminated again */
7571 /* but skip block for "} else {" */
7572 l = cin_skipcomment(ml_get_curline());
7573 if (*l == '}' || !cin_iselse(l))
7574 goto term_again;
7575 ++curwin->w_cursor.lnum;
7576 }
7577 }
7578 }
7579 }
7580 }
7581 }
7582
7583 /* add extra indent for a comment */
7584 if (cin_iscomment(theline))
7585 amount += ind_comment;
7586 }
7587
7588 /*
7589 * ok -- we're not inside any sort of structure at all!
7590 *
7591 * this means we're at the top level, and everything should
7592 * basically just match where the previous line is, except
7593 * for the lines immediately following a function declaration,
7594 * which are K&R-style parameters and need to be indented.
7595 */
7596 else
7597 {
7598 /*
7599 * if our line starts with an open brace, forget about any
7600 * prevailing indent and make sure it looks like the start
7601 * of a function
7602 */
7603
7604 if (theline[0] == '{')
7605 {
7606 amount = ind_first_open;
7607 }
7608
7609 /*
7610 * If the NEXT line is a function declaration, the current
7611 * line needs to be indented as a function type spec.
7612 * Don't do this if the current line looks like a comment
7613 * or if the current line is terminated, ie. ends in ';'.
7614 */
7615 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7616 && !cin_nocode(theline)
7617 && !cin_ends_in(theline, (char_u *)":", NULL)
7618 && !cin_ends_in(theline, (char_u *)",", NULL)
7619 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7620 && !cin_isterminated(theline, FALSE, TRUE))
7621 {
7622 amount = ind_func_type;
7623 }
7624 else
7625 {
7626 amount = 0;
7627 curwin->w_cursor = cur_curpos;
7628
7629 /* search backwards until we find something we recognize */
7630
7631 while (curwin->w_cursor.lnum > 1)
7632 {
7633 curwin->w_cursor.lnum--;
7634 curwin->w_cursor.col = 0;
7635
7636 l = ml_get_curline();
7637
7638 /*
7639 * If we're in a comment now, skip to the start of the comment.
7640 */ /* XXX */
7641 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7642 {
7643 curwin->w_cursor.lnum = trypos->lnum + 1;
7644 continue;
7645 }
7646
7647 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007648 * Are we at the start of a cpp base class declaration or
7649 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00007650 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007651 n = FALSE;
7652 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7653 {
7654 n = cin_is_cpp_baseclass(l, &col);
7655 l = ml_get_curline();
7656 }
7657 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007658 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007659 /* XXX */
7660 amount = get_baseclass_amount(col, ind_maxparen,
7661 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007662 break;
7663 }
7664
7665 /*
7666 * Skip preprocessor directives and blank lines.
7667 */
7668 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7669 continue;
7670
7671 if (cin_nocode(l))
7672 continue;
7673
7674 /*
7675 * If the previous line ends in ',', use one level of
7676 * indentation:
7677 * int foo,
7678 * bar;
7679 * do this before checking for '}' in case of eg.
7680 * enum foobar
7681 * {
7682 * ...
7683 * } foo,
7684 * bar;
7685 */
7686 n = 0;
7687 if (cin_ends_in(l, (char_u *)",", NULL)
7688 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7689 {
7690 /* take us back to opening paren */
7691 if (find_last_paren(l, '(', ')')
7692 && (trypos = find_match_paren(ind_maxparen,
7693 ind_maxcomment)) != NULL)
7694 curwin->w_cursor.lnum = trypos->lnum;
7695
7696 /* For a line ending in ',' that is a continuation line go
7697 * back to the first line with a backslash:
7698 * char *foo = "bla\
7699 * bla",
7700 * here;
7701 */
7702 while (n == 0 && curwin->w_cursor.lnum > 1)
7703 {
7704 l = ml_get(curwin->w_cursor.lnum - 1);
7705 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7706 break;
7707 --curwin->w_cursor.lnum;
7708 }
7709
7710 amount = get_indent(); /* XXX */
7711
7712 if (amount == 0)
7713 amount = cin_first_id_amount();
7714 if (amount == 0)
7715 amount = ind_continuation;
7716 break;
7717 }
7718
7719 /*
7720 * If the line looks like a function declaration, and we're
7721 * not in a comment, put it the left margin.
7722 */
7723 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7724 break;
7725 l = ml_get_curline();
7726
7727 /*
7728 * Finding the closing '}' of a previous function. Put
7729 * current line at the left margin. For when 'cino' has "fs".
7730 */
7731 if (*skipwhite(l) == '}')
7732 break;
7733
7734 /* (matching {)
7735 * If the previous line ends on '};' (maybe followed by
7736 * comments) align at column 0. For example:
7737 * char *string_array[] = { "foo",
7738 * / * x * / "b};ar" }; / * foobar * /
7739 */
7740 if (cin_ends_in(l, (char_u *)"};", NULL))
7741 break;
7742
7743 /*
7744 * If the PREVIOUS line is a function declaration, the current
7745 * line (and the ones that follow) needs to be indented as
7746 * parameters.
7747 */
7748 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7749 {
7750 amount = ind_param;
7751 break;
7752 }
7753
7754 /*
7755 * If the previous line ends in ';' and the line before the
7756 * previous line ends in ',' or '\', ident to column zero:
7757 * int foo,
7758 * bar;
7759 * indent_to_0 here;
7760 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007761 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007762 {
7763 l = ml_get(curwin->w_cursor.lnum - 1);
7764 if (cin_ends_in(l, (char_u *)",", NULL)
7765 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7766 break;
7767 l = ml_get_curline();
7768 }
7769
7770 /*
7771 * Doesn't look like anything interesting -- so just
7772 * use the indent of this line.
7773 *
7774 * Position the cursor over the rightmost paren, so that
7775 * matching it will take us back to the start of the line.
7776 */
7777 find_last_paren(l, '(', ')');
7778
7779 if ((trypos = find_match_paren(ind_maxparen,
7780 ind_maxcomment)) != NULL)
7781 curwin->w_cursor.lnum = trypos->lnum;
7782 amount = get_indent(); /* XXX */
7783 break;
7784 }
7785
7786 /* add extra indent for a comment */
7787 if (cin_iscomment(theline))
7788 amount += ind_comment;
7789
7790 /* add extra indent if the previous line ended in a backslash:
7791 * "asdfasdf\
7792 * here";
7793 * char *foo = "asdf\
7794 * here";
7795 */
7796 if (cur_curpos.lnum > 1)
7797 {
7798 l = ml_get(cur_curpos.lnum - 1);
7799 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7800 {
7801 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7802 if (cur_amount > 0)
7803 amount = cur_amount;
7804 else if (cur_amount == 0)
7805 amount += ind_continuation;
7806 }
7807 }
7808 }
7809 }
7810
7811theend:
7812 /* put the cursor back where it belongs */
7813 curwin->w_cursor = cur_curpos;
7814
7815 vim_free(linecopy);
7816
7817 if (amount < 0)
7818 return 0;
7819 return amount;
7820}
7821
7822 static int
7823find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7824 int lookfor;
7825 linenr_T ourscope;
7826 int ind_maxparen;
7827 int ind_maxcomment;
7828{
7829 char_u *look;
7830 pos_T *theirscope;
7831 char_u *mightbeif;
7832 int elselevel;
7833 int whilelevel;
7834
7835 if (lookfor == LOOKFOR_IF)
7836 {
7837 elselevel = 1;
7838 whilelevel = 0;
7839 }
7840 else
7841 {
7842 elselevel = 0;
7843 whilelevel = 1;
7844 }
7845
7846 curwin->w_cursor.col = 0;
7847
7848 while (curwin->w_cursor.lnum > ourscope + 1)
7849 {
7850 curwin->w_cursor.lnum--;
7851 curwin->w_cursor.col = 0;
7852
7853 look = cin_skipcomment(ml_get_curline());
7854 if (cin_iselse(look)
7855 || cin_isif(look)
7856 || cin_isdo(look) /* XXX */
7857 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7858 {
7859 /*
7860 * if we've gone outside the braces entirely,
7861 * we must be out of scope...
7862 */
7863 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7864 if (theirscope == NULL)
7865 break;
7866
7867 /*
7868 * and if the brace enclosing this is further
7869 * back than the one enclosing the else, we're
7870 * out of luck too.
7871 */
7872 if (theirscope->lnum < ourscope)
7873 break;
7874
7875 /*
7876 * and if they're enclosed in a *deeper* brace,
7877 * then we can ignore it because it's in a
7878 * different scope...
7879 */
7880 if (theirscope->lnum > ourscope)
7881 continue;
7882
7883 /*
7884 * if it was an "else" (that's not an "else if")
7885 * then we need to go back to another if, so
7886 * increment elselevel
7887 */
7888 look = cin_skipcomment(ml_get_curline());
7889 if (cin_iselse(look))
7890 {
7891 mightbeif = cin_skipcomment(look + 4);
7892 if (!cin_isif(mightbeif))
7893 ++elselevel;
7894 continue;
7895 }
7896
7897 /*
7898 * if it was a "while" then we need to go back to
7899 * another "do", so increment whilelevel. XXX
7900 */
7901 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7902 {
7903 ++whilelevel;
7904 continue;
7905 }
7906
7907 /* If it's an "if" decrement elselevel */
7908 look = cin_skipcomment(ml_get_curline());
7909 if (cin_isif(look))
7910 {
7911 elselevel--;
7912 /*
7913 * When looking for an "if" ignore "while"s that
7914 * get in the way.
7915 */
7916 if (elselevel == 0 && lookfor == LOOKFOR_IF)
7917 whilelevel = 0;
7918 }
7919
7920 /* If it's a "do" decrement whilelevel */
7921 if (cin_isdo(look))
7922 whilelevel--;
7923
7924 /*
7925 * if we've used up all the elses, then
7926 * this must be the if that we want!
7927 * match the indent level of that if.
7928 */
7929 if (elselevel <= 0 && whilelevel <= 0)
7930 {
7931 return OK;
7932 }
7933 }
7934 }
7935 return FAIL;
7936}
7937
7938# if defined(FEAT_EVAL) || defined(PROTO)
7939/*
7940 * Get indent level from 'indentexpr'.
7941 */
7942 int
7943get_expr_indent()
7944{
7945 int indent;
7946 pos_T pos;
7947 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00007948 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
7949 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007950
7951 pos = curwin->w_cursor;
7952 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00007953 if (use_sandbox)
7954 ++sandbox;
7955 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007956 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00007957 if (use_sandbox)
7958 --sandbox;
7959 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007960
7961 /* Restore the cursor position so that 'indentexpr' doesn't need to.
7962 * Pretend to be in Insert mode, allow cursor past end of line for "o"
7963 * command. */
7964 save_State = State;
7965 State = INSERT;
7966 curwin->w_cursor = pos;
7967 check_cursor();
7968 State = save_State;
7969
7970 /* If there is an error, just keep the current indent. */
7971 if (indent < 0)
7972 indent = get_indent();
7973
7974 return indent;
7975}
7976# endif
7977
7978#endif /* FEAT_CINDENT */
7979
7980#if defined(FEAT_LISP) || defined(PROTO)
7981
7982static int lisp_match __ARGS((char_u *p));
7983
7984 static int
7985lisp_match(p)
7986 char_u *p;
7987{
7988 char_u buf[LSIZE];
7989 int len;
7990 char_u *word = p_lispwords;
7991
7992 while (*word != NUL)
7993 {
7994 (void)copy_option_part(&word, buf, LSIZE, ",");
7995 len = (int)STRLEN(buf);
7996 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
7997 return TRUE;
7998 }
7999 return FALSE;
8000}
8001
8002/*
8003 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8004 * The incompatible newer method is quite a bit better at indenting
8005 * code in lisp-like languages than the traditional one; it's still
8006 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8007 *
8008 * TODO:
8009 * Findmatch() should be adapted for lisp, also to make showmatch
8010 * work correctly: now (v5.3) it seems all C/C++ oriented:
8011 * - it does not recognize the #\( and #\) notations as character literals
8012 * - it doesn't know about comments starting with a semicolon
8013 * - it incorrectly interprets '(' as a character literal
8014 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008015 * Update from Sergey Khorev:
8016 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008017 */
8018 int
8019get_lisp_indent()
8020{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008021 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008022 int amount;
8023 char_u *that;
8024 colnr_T col;
8025 colnr_T firsttry;
8026 int parencount, quotecount;
8027 int vi_lisp;
8028
8029 /* Set vi_lisp to use the vi-compatible method */
8030 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8031
8032 realpos = curwin->w_cursor;
8033 curwin->w_cursor.col = 0;
8034
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008035 if ((pos = findmatch(NULL, '(')) == NULL)
8036 pos = findmatch(NULL, '[');
8037 else
8038 {
8039 paren = *pos;
8040 pos = findmatch(NULL, '[');
8041 if (pos == NULL || ltp(pos, &paren))
8042 pos = &paren;
8043 }
8044 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008045 {
8046 /* Extra trick: Take the indent of the first previous non-white
8047 * line that is at the same () level. */
8048 amount = -1;
8049 parencount = 0;
8050
8051 while (--curwin->w_cursor.lnum >= pos->lnum)
8052 {
8053 if (linewhite(curwin->w_cursor.lnum))
8054 continue;
8055 for (that = ml_get_curline(); *that != NUL; ++that)
8056 {
8057 if (*that == ';')
8058 {
8059 while (*(that + 1) != NUL)
8060 ++that;
8061 continue;
8062 }
8063 if (*that == '\\')
8064 {
8065 if (*(that + 1) != NUL)
8066 ++that;
8067 continue;
8068 }
8069 if (*that == '"' && *(that + 1) != NUL)
8070 {
8071 that++;
8072 while (*that && (*that != '"' || *(that - 1) == '\\'))
8073 ++that;
8074 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008075 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008076 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008077 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008078 --parencount;
8079 }
8080 if (parencount == 0)
8081 {
8082 amount = get_indent();
8083 break;
8084 }
8085 }
8086
8087 if (amount == -1)
8088 {
8089 curwin->w_cursor.lnum = pos->lnum;
8090 curwin->w_cursor.col = pos->col;
8091 col = pos->col;
8092
8093 that = ml_get_curline();
8094
8095 if (vi_lisp && get_indent() == 0)
8096 amount = 2;
8097 else
8098 {
8099 amount = 0;
8100 while (*that && col)
8101 {
8102 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8103 col--;
8104 }
8105
8106 /*
8107 * Some keywords require "body" indenting rules (the
8108 * non-standard-lisp ones are Scheme special forms):
8109 *
8110 * (let ((a 1)) instead (let ((a 1))
8111 * (...)) of (...))
8112 */
8113
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008114 if (!vi_lisp && (*that == '(' || *that == '[')
8115 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008116 amount += 2;
8117 else
8118 {
8119 that++;
8120 amount++;
8121 firsttry = amount;
8122
8123 while (vim_iswhite(*that))
8124 {
8125 amount += lbr_chartabsize(that, (colnr_T)amount);
8126 ++that;
8127 }
8128
8129 if (*that && *that != ';') /* not a comment line */
8130 {
8131 /* test *that != '(' to accomodate first let/do
8132 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008133 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008134 firsttry++;
8135
8136 parencount = 0;
8137 quotecount = 0;
8138
8139 if (vi_lisp
8140 || (*that != '"'
8141 && *that != '\''
8142 && *that != '#'
8143 && (*that < '0' || *that > '9')))
8144 {
8145 while (*that
8146 && (!vim_iswhite(*that)
8147 || quotecount
8148 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008149 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008150 && !quotecount
8151 && !parencount
8152 && vi_lisp)))
8153 {
8154 if (*that == '"')
8155 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008156 if ((*that == '(' || *that == '[')
8157 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008158 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008159 if ((*that == ')' || *that == ']')
8160 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008161 --parencount;
8162 if (*that == '\\' && *(that+1) != NUL)
8163 amount += lbr_chartabsize_adv(&that,
8164 (colnr_T)amount);
8165 amount += lbr_chartabsize_adv(&that,
8166 (colnr_T)amount);
8167 }
8168 }
8169 while (vim_iswhite(*that))
8170 {
8171 amount += lbr_chartabsize(that, (colnr_T)amount);
8172 that++;
8173 }
8174 if (!*that || *that == ';')
8175 amount = firsttry;
8176 }
8177 }
8178 }
8179 }
8180 }
8181 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008182 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008183
8184 curwin->w_cursor = realpos;
8185
8186 return amount;
8187}
8188#endif /* FEAT_LISP */
8189
8190 void
8191prepare_to_exit()
8192{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008193#if defined(SIGHUP) && defined(SIG_IGN)
8194 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8195 * makes Vim exit and then handling SIGHUP causes various reentrance
8196 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008197 signal(SIGHUP, SIG_IGN);
8198#endif
8199
Bram Moolenaar071d4272004-06-13 20:20:40 +00008200#ifdef FEAT_GUI
8201 if (gui.in_use)
8202 {
8203 gui.dying = TRUE;
8204 out_trash(); /* trash any pending output */
8205 }
8206 else
8207#endif
8208 {
8209 windgoto((int)Rows - 1, 0);
8210
8211 /*
8212 * Switch terminal mode back now, so messages end up on the "normal"
8213 * screen (if there are two screens).
8214 */
8215 settmode(TMODE_COOK);
8216#ifdef WIN3264
8217 if (can_end_termcap_mode(FALSE) == TRUE)
8218#endif
8219 stoptermcap();
8220 out_flush();
8221 }
8222}
8223
8224/*
8225 * Preserve files and exit.
8226 * When called IObuff must contain a message.
8227 */
8228 void
8229preserve_exit()
8230{
8231 buf_T *buf;
8232
8233 prepare_to_exit();
8234
Bram Moolenaar4770d092006-01-12 23:22:24 +00008235 /* Setting this will prevent free() calls. That avoids calling free()
8236 * recursively when free() was invoked with a bad pointer. */
8237 really_exiting = TRUE;
8238
Bram Moolenaar071d4272004-06-13 20:20:40 +00008239 out_str(IObuff);
8240 screen_start(); /* don't know where cursor is now */
8241 out_flush();
8242
8243 ml_close_notmod(); /* close all not-modified buffers */
8244
8245 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8246 {
8247 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8248 {
8249 OUT_STR(_("Vim: preserving files...\n"));
8250 screen_start(); /* don't know where cursor is now */
8251 out_flush();
8252 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8253 break;
8254 }
8255 }
8256
8257 ml_close_all(FALSE); /* close all memfiles, without deleting */
8258
8259 OUT_STR(_("Vim: Finished.\n"));
8260
8261 getout(1);
8262}
8263
8264/*
8265 * return TRUE if "fname" exists.
8266 */
8267 int
8268vim_fexists(fname)
8269 char_u *fname;
8270{
8271 struct stat st;
8272
8273 if (mch_stat((char *)fname, &st))
8274 return FALSE;
8275 return TRUE;
8276}
8277
8278/*
8279 * Check for CTRL-C pressed, but only once in a while.
8280 * Should be used instead of ui_breakcheck() for functions that check for
8281 * each line in the file. Calling ui_breakcheck() each time takes too much
8282 * time, because it can be a system call.
8283 */
8284
8285#ifndef BREAKCHECK_SKIP
8286# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8287# define BREAKCHECK_SKIP 200
8288# else
8289# define BREAKCHECK_SKIP 32
8290# endif
8291#endif
8292
8293static int breakcheck_count = 0;
8294
8295 void
8296line_breakcheck()
8297{
8298 if (++breakcheck_count >= BREAKCHECK_SKIP)
8299 {
8300 breakcheck_count = 0;
8301 ui_breakcheck();
8302 }
8303}
8304
8305/*
8306 * Like line_breakcheck() but check 10 times less often.
8307 */
8308 void
8309fast_breakcheck()
8310{
8311 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8312 {
8313 breakcheck_count = 0;
8314 ui_breakcheck();
8315 }
8316}
8317
8318/*
8319 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8320 * 'wildignore'.
Bram Moolenaar362e1a32006-03-06 23:29:24 +00008321 * Returns OK or FAIL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008322 */
8323 int
8324expand_wildcards(num_pat, pat, num_file, file, flags)
8325 int num_pat; /* number of input patterns */
8326 char_u **pat; /* array of input patterns */
8327 int *num_file; /* resulting number of files */
8328 char_u ***file; /* array of resulting files */
8329 int flags; /* EW_DIR, etc. */
8330{
8331 int retval;
8332 int i, j;
8333 char_u *p;
8334 int non_suf_match; /* number without matching suffix */
8335
8336 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8337
8338 /* When keeping all matches, return here */
8339 if (flags & EW_KEEPALL)
8340 return retval;
8341
8342#ifdef FEAT_WILDIGN
8343 /*
8344 * Remove names that match 'wildignore'.
8345 */
8346 if (*p_wig)
8347 {
8348 char_u *ffname;
8349
8350 /* check all files in (*file)[] */
8351 for (i = 0; i < *num_file; ++i)
8352 {
8353 ffname = FullName_save((*file)[i], FALSE);
8354 if (ffname == NULL) /* out of memory */
8355 break;
8356# ifdef VMS
8357 vms_remove_version(ffname);
8358# endif
8359 if (match_file_list(p_wig, (*file)[i], ffname))
8360 {
8361 /* remove this matching file from the list */
8362 vim_free((*file)[i]);
8363 for (j = i; j + 1 < *num_file; ++j)
8364 (*file)[j] = (*file)[j + 1];
8365 --*num_file;
8366 --i;
8367 }
8368 vim_free(ffname);
8369 }
8370 }
8371#endif
8372
8373 /*
8374 * Move the names where 'suffixes' match to the end.
8375 */
8376 if (*num_file > 1)
8377 {
8378 non_suf_match = 0;
8379 for (i = 0; i < *num_file; ++i)
8380 {
8381 if (!match_suffix((*file)[i]))
8382 {
8383 /*
8384 * Move the name without matching suffix to the front
8385 * of the list.
8386 */
8387 p = (*file)[i];
8388 for (j = i; j > non_suf_match; --j)
8389 (*file)[j] = (*file)[j - 1];
8390 (*file)[non_suf_match++] = p;
8391 }
8392 }
8393 }
8394
8395 return retval;
8396}
8397
8398/*
8399 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8400 */
8401 int
8402match_suffix(fname)
8403 char_u *fname;
8404{
8405 int fnamelen, setsuflen;
8406 char_u *setsuf;
8407#define MAXSUFLEN 30 /* maximum length of a file suffix */
8408 char_u suf_buf[MAXSUFLEN];
8409
8410 fnamelen = (int)STRLEN(fname);
8411 setsuflen = 0;
8412 for (setsuf = p_su; *setsuf; )
8413 {
8414 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
8415 if (fnamelen >= setsuflen
8416 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8417 (size_t)setsuflen) == 0)
8418 break;
8419 setsuflen = 0;
8420 }
8421 return (setsuflen != 0);
8422}
8423
8424#if !defined(NO_EXPANDPATH) || defined(PROTO)
8425
8426# ifdef VIM_BACKTICK
8427static int vim_backtick __ARGS((char_u *p));
8428static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8429# endif
8430
8431# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8432/*
8433 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8434 * it's shared between these systems.
8435 */
8436# if defined(DJGPP) || defined(PROTO)
8437# define _cdecl /* DJGPP doesn't have this */
8438# else
8439# ifdef __BORLANDC__
8440# define _cdecl _RTLENTRYF
8441# endif
8442# endif
8443
8444/*
8445 * comparison function for qsort in dos_expandpath()
8446 */
8447 static int _cdecl
8448pstrcmp(const void *a, const void *b)
8449{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008450 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008451}
8452
8453# ifndef WIN3264
8454 static void
8455namelowcpy(
8456 char_u *d,
8457 char_u *s)
8458{
8459# ifdef DJGPP
8460 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8461 while (*s)
8462 *d++ = *s++;
8463 else
8464# endif
8465 while (*s)
8466 *d++ = TOLOWER_LOC(*s++);
8467 *d = NUL;
8468}
8469# endif
8470
8471/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00008472 * Recursively expand one path component into all matching files and/or
8473 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008474 * Return the number of matches found.
8475 * "path" has backslashes before chars that are not to be expanded, starting
8476 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00008477 * Return the number of matches found.
8478 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00008479 */
8480 static int
8481dos_expandpath(
8482 garray_T *gap,
8483 char_u *path,
8484 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00008485 int flags, /* EW_* flags */
8486 int didstar) /* expaneded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008487{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008488 char_u *buf;
8489 char_u *path_end;
8490 char_u *p, *s, *e;
8491 int start_len = gap->ga_len;
8492 char_u *pat;
8493 regmatch_T regmatch;
8494 int starts_with_dot;
8495 int matches;
8496 int len;
8497 int starstar = FALSE;
8498 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008499#ifdef WIN3264
8500 WIN32_FIND_DATA fb;
8501 HANDLE hFind = (HANDLE)0;
8502# ifdef FEAT_MBYTE
8503 WIN32_FIND_DATAW wfb;
8504 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8505# endif
8506#else
8507 struct ffblk fb;
8508#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008509 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00008510 int ok;
8511
8512 /* Expanding "**" may take a long time, check for CTRL-C. */
8513 if (stardepth > 0)
8514 {
8515 ui_breakcheck();
8516 if (got_int)
8517 return 0;
8518 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008519
8520 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008521 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008522 if (buf == NULL)
8523 return 0;
8524
8525 /*
8526 * Find the first part in the path name that contains a wildcard or a ~1.
8527 * Copy it into buf, including the preceding characters.
8528 */
8529 p = buf;
8530 s = buf;
8531 e = NULL;
8532 path_end = path;
8533 while (*path_end != NUL)
8534 {
8535 /* May ignore a wildcard that has a backslash before it; it will
8536 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8537 if (path_end >= path + wildoff && rem_backslash(path_end))
8538 *p++ = *path_end++;
8539 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8540 {
8541 if (e != NULL)
8542 break;
8543 s = p + 1;
8544 }
8545 else if (path_end >= path + wildoff
8546 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8547 e = p;
8548#ifdef FEAT_MBYTE
8549 if (has_mbyte)
8550 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008551 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008552 STRNCPY(p, path_end, len);
8553 p += len;
8554 path_end += len;
8555 }
8556 else
8557#endif
8558 *p++ = *path_end++;
8559 }
8560 e = p;
8561 *e = NUL;
8562
8563 /* now we have one wildcard component between s and e */
8564 /* Remove backslashes between "wildoff" and the start of the wildcard
8565 * component. */
8566 for (p = buf + wildoff; p < s; ++p)
8567 if (rem_backslash(p))
8568 {
8569 STRCPY(p, p + 1);
8570 --e;
8571 --s;
8572 }
8573
Bram Moolenaar231334e2005-07-25 20:46:57 +00008574 /* Check for "**" between "s" and "e". */
8575 for (p = s; p < e; ++p)
8576 if (p[0] == '*' && p[1] == '*')
8577 starstar = TRUE;
8578
Bram Moolenaar071d4272004-06-13 20:20:40 +00008579 starts_with_dot = (*s == '.');
8580 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8581 if (pat == NULL)
8582 {
8583 vim_free(buf);
8584 return 0;
8585 }
8586
8587 /* compile the regexp into a program */
8588 regmatch.rm_ic = TRUE; /* Always ignore case */
8589 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8590 vim_free(pat);
8591
8592 if (regmatch.regprog == NULL)
8593 {
8594 vim_free(buf);
8595 return 0;
8596 }
8597
8598 /* remember the pattern or file name being looked for */
8599 matchname = vim_strsave(s);
8600
Bram Moolenaar231334e2005-07-25 20:46:57 +00008601 /* If "**" is by itself, this is the first time we encounter it and more
8602 * is following then find matches without any directory. */
8603 if (!didstar && stardepth < 100 && starstar && e - s == 2
8604 && *path_end == '/')
8605 {
8606 STRCPY(s, path_end + 1);
8607 ++stardepth;
8608 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8609 --stardepth;
8610 }
8611
Bram Moolenaar071d4272004-06-13 20:20:40 +00008612 /* Scan all files in the directory with "dir/ *.*" */
8613 STRCPY(s, "*.*");
8614#ifdef WIN3264
8615# ifdef FEAT_MBYTE
8616 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8617 {
8618 /* The active codepage differs from 'encoding'. Attempt using the
8619 * wide function. If it fails because it is not implemented fall back
8620 * to the non-wide version (for Windows 98) */
8621 wn = enc_to_ucs2(buf, NULL);
8622 if (wn != NULL)
8623 {
8624 hFind = FindFirstFileW(wn, &wfb);
8625 if (hFind == INVALID_HANDLE_VALUE
8626 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8627 {
8628 vim_free(wn);
8629 wn = NULL;
8630 }
8631 }
8632 }
8633
8634 if (wn == NULL)
8635# endif
8636 hFind = FindFirstFile(buf, &fb);
8637 ok = (hFind != INVALID_HANDLE_VALUE);
8638#else
8639 /* If we are expanding wildcards we try both files and directories */
8640 ok = (findfirst((char *)buf, &fb,
8641 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8642#endif
8643
8644 while (ok)
8645 {
8646#ifdef WIN3264
8647# ifdef FEAT_MBYTE
8648 if (wn != NULL)
8649 p = ucs2_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8650 else
8651# endif
8652 p = (char_u *)fb.cFileName;
8653#else
8654 p = (char_u *)fb.ff_name;
8655#endif
8656 /* Ignore entries starting with a dot, unless when asked for. Accept
8657 * all entries found with "matchname". */
8658 if ((p[0] != '.' || starts_with_dot)
8659 && (matchname == NULL
8660 || vim_regexec(&regmatch, p, (colnr_T)0)))
8661 {
8662#ifdef WIN3264
8663 STRCPY(s, p);
8664#else
8665 namelowcpy(s, p);
8666#endif
8667 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008668
8669 if (starstar && stardepth < 100)
8670 {
8671 /* For "**" in the pattern first go deeper in the tree to
8672 * find matches. */
8673 STRCPY(buf + len, "/**");
8674 STRCPY(buf + len + 3, path_end);
8675 ++stardepth;
8676 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8677 --stardepth;
8678 }
8679
Bram Moolenaar071d4272004-06-13 20:20:40 +00008680 STRCPY(buf + len, path_end);
8681 if (mch_has_exp_wildcard(path_end))
8682 {
8683 /* need to expand another component of the path */
8684 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008685 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008686 }
8687 else
8688 {
8689 /* no more wildcards, check if there is a match */
8690 /* remove backslashes for the remaining components only */
8691 if (*path_end != 0)
8692 backslash_halve(buf + len + 1);
8693 if (mch_getperm(buf) >= 0) /* add existing file */
8694 addfile(gap, buf, flags);
8695 }
8696 }
8697
8698#ifdef WIN3264
8699# ifdef FEAT_MBYTE
8700 if (wn != NULL)
8701 {
8702 vim_free(p);
8703 ok = FindNextFileW(hFind, &wfb);
8704 }
8705 else
8706# endif
8707 ok = FindNextFile(hFind, &fb);
8708#else
8709 ok = (findnext(&fb) == 0);
8710#endif
8711
8712 /* If no more matches and no match was used, try expanding the name
8713 * itself. Finds the long name of a short filename. */
8714 if (!ok && matchname != NULL && gap->ga_len == start_len)
8715 {
8716 STRCPY(s, matchname);
8717#ifdef WIN3264
8718 FindClose(hFind);
8719# ifdef FEAT_MBYTE
8720 if (wn != NULL)
8721 {
8722 vim_free(wn);
8723 wn = enc_to_ucs2(buf, NULL);
8724 if (wn != NULL)
8725 hFind = FindFirstFileW(wn, &wfb);
8726 }
8727 if (wn == NULL)
8728# endif
8729 hFind = FindFirstFile(buf, &fb);
8730 ok = (hFind != INVALID_HANDLE_VALUE);
8731#else
8732 ok = (findfirst((char *)buf, &fb,
8733 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8734#endif
8735 vim_free(matchname);
8736 matchname = NULL;
8737 }
8738 }
8739
8740#ifdef WIN3264
8741 FindClose(hFind);
8742# ifdef FEAT_MBYTE
8743 vim_free(wn);
8744# endif
8745#endif
8746 vim_free(buf);
8747 vim_free(regmatch.regprog);
8748 vim_free(matchname);
8749
8750 matches = gap->ga_len - start_len;
8751 if (matches > 0)
8752 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8753 sizeof(char_u *), pstrcmp);
8754 return matches;
8755}
8756
8757 int
8758mch_expandpath(
8759 garray_T *gap,
8760 char_u *path,
8761 int flags) /* EW_* flags */
8762{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008763 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008764}
8765# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8766
Bram Moolenaar231334e2005-07-25 20:46:57 +00008767#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8768 || defined(PROTO)
8769/*
8770 * Unix style wildcard expansion code.
8771 * It's here because it's used both for Unix and Mac.
8772 */
8773static int pstrcmp __ARGS((const void *, const void *));
8774
8775 static int
8776pstrcmp(a, b)
8777 const void *a, *b;
8778{
8779 return (pathcmp(*(char **)a, *(char **)b, -1));
8780}
8781
8782/*
8783 * Recursively expand one path component into all matching files and/or
8784 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8785 * "path" has backslashes before chars that are not to be expanded, starting
8786 * at "path + wildoff".
8787 * Return the number of matches found.
8788 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8789 */
8790 int
8791unix_expandpath(gap, path, wildoff, flags, didstar)
8792 garray_T *gap;
8793 char_u *path;
8794 int wildoff;
8795 int flags; /* EW_* flags */
8796 int didstar; /* expanded "**" once already */
8797{
8798 char_u *buf;
8799 char_u *path_end;
8800 char_u *p, *s, *e;
8801 int start_len = gap->ga_len;
8802 char_u *pat;
8803 regmatch_T regmatch;
8804 int starts_with_dot;
8805 int matches;
8806 int len;
8807 int starstar = FALSE;
8808 static int stardepth = 0; /* depth for "**" expansion */
8809
8810 DIR *dirp;
8811 struct dirent *dp;
8812
8813 /* Expanding "**" may take a long time, check for CTRL-C. */
8814 if (stardepth > 0)
8815 {
8816 ui_breakcheck();
8817 if (got_int)
8818 return 0;
8819 }
8820
8821 /* make room for file name */
8822 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8823 if (buf == NULL)
8824 return 0;
8825
8826 /*
8827 * Find the first part in the path name that contains a wildcard.
8828 * Copy it into "buf", including the preceding characters.
8829 */
8830 p = buf;
8831 s = buf;
8832 e = NULL;
8833 path_end = path;
8834 while (*path_end != NUL)
8835 {
8836 /* May ignore a wildcard that has a backslash before it; it will
8837 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8838 if (path_end >= path + wildoff && rem_backslash(path_end))
8839 *p++ = *path_end++;
8840 else if (*path_end == '/')
8841 {
8842 if (e != NULL)
8843 break;
8844 s = p + 1;
8845 }
8846 else if (path_end >= path + wildoff
8847 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
8848 e = p;
8849#ifdef FEAT_MBYTE
8850 if (has_mbyte)
8851 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008852 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008853 STRNCPY(p, path_end, len);
8854 p += len;
8855 path_end += len;
8856 }
8857 else
8858#endif
8859 *p++ = *path_end++;
8860 }
8861 e = p;
8862 *e = NUL;
8863
8864 /* now we have one wildcard component between "s" and "e" */
8865 /* Remove backslashes between "wildoff" and the start of the wildcard
8866 * component. */
8867 for (p = buf + wildoff; p < s; ++p)
8868 if (rem_backslash(p))
8869 {
8870 STRCPY(p, p + 1);
8871 --e;
8872 --s;
8873 }
8874
8875 /* Check for "**" between "s" and "e". */
8876 for (p = s; p < e; ++p)
8877 if (p[0] == '*' && p[1] == '*')
8878 starstar = TRUE;
8879
8880 /* convert the file pattern to a regexp pattern */
8881 starts_with_dot = (*s == '.');
8882 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8883 if (pat == NULL)
8884 {
8885 vim_free(buf);
8886 return 0;
8887 }
8888
8889 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00008890#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00008891 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
8892#else
8893 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
8894#endif
8895 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8896 vim_free(pat);
8897
8898 if (regmatch.regprog == NULL)
8899 {
8900 vim_free(buf);
8901 return 0;
8902 }
8903
8904 /* If "**" is by itself, this is the first time we encounter it and more
8905 * is following then find matches without any directory. */
8906 if (!didstar && stardepth < 100 && starstar && e - s == 2
8907 && *path_end == '/')
8908 {
8909 STRCPY(s, path_end + 1);
8910 ++stardepth;
8911 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8912 --stardepth;
8913 }
8914
8915 /* open the directory for scanning */
8916 *s = NUL;
8917 dirp = opendir(*buf == NUL ? "." : (char *)buf);
8918
8919 /* Find all matching entries */
8920 if (dirp != NULL)
8921 {
8922 for (;;)
8923 {
8924 dp = readdir(dirp);
8925 if (dp == NULL)
8926 break;
8927 if ((dp->d_name[0] != '.' || starts_with_dot)
8928 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
8929 {
8930 STRCPY(s, dp->d_name);
8931 len = STRLEN(buf);
8932
8933 if (starstar && stardepth < 100)
8934 {
8935 /* For "**" in the pattern first go deeper in the tree to
8936 * find matches. */
8937 STRCPY(buf + len, "/**");
8938 STRCPY(buf + len + 3, path_end);
8939 ++stardepth;
8940 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
8941 --stardepth;
8942 }
8943
8944 STRCPY(buf + len, path_end);
8945 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
8946 {
8947 /* need to expand another component of the path */
8948 /* remove backslashes for the remaining components only */
8949 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
8950 }
8951 else
8952 {
8953 /* no more wildcards, check if there is a match */
8954 /* remove backslashes for the remaining components only */
8955 if (*path_end != NUL)
8956 backslash_halve(buf + len + 1);
8957 if (mch_getperm(buf) >= 0) /* add existing file */
8958 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00008959#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00008960 size_t precomp_len = STRLEN(buf)+1;
8961 char_u *precomp_buf =
8962 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00008963
Bram Moolenaar231334e2005-07-25 20:46:57 +00008964 if (precomp_buf)
8965 {
8966 mch_memmove(buf, precomp_buf, precomp_len);
8967 vim_free(precomp_buf);
8968 }
8969#endif
8970 addfile(gap, buf, flags);
8971 }
8972 }
8973 }
8974 }
8975
8976 closedir(dirp);
8977 }
8978
8979 vim_free(buf);
8980 vim_free(regmatch.regprog);
8981
8982 matches = gap->ga_len - start_len;
8983 if (matches > 0)
8984 qsort(((char_u **)gap->ga_data) + start_len, matches,
8985 sizeof(char_u *), pstrcmp);
8986 return matches;
8987}
8988#endif
8989
Bram Moolenaar071d4272004-06-13 20:20:40 +00008990/*
8991 * Generic wildcard expansion code.
8992 *
8993 * Characters in "pat" that should not be expanded must be preceded with a
8994 * backslash. E.g., "/path\ with\ spaces/my\*star*"
8995 *
8996 * Return FAIL when no single file was found. In this case "num_file" is not
8997 * set, and "file" may contain an error message.
8998 * Return OK when some files found. "num_file" is set to the number of
8999 * matches, "file" to the array of matches. Call FreeWild() later.
9000 */
9001 int
9002gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9003 int num_pat; /* number of input patterns */
9004 char_u **pat; /* array of input patterns */
9005 int *num_file; /* resulting number of files */
9006 char_u ***file; /* array of resulting files */
9007 int flags; /* EW_* flags */
9008{
9009 int i;
9010 garray_T ga;
9011 char_u *p;
9012 static int recursive = FALSE;
9013 int add_pat;
9014
9015 /*
9016 * expand_env() is called to expand things like "~user". If this fails,
9017 * it calls ExpandOne(), which brings us back here. In this case, always
9018 * call the machine specific expansion function, if possible. Otherwise,
9019 * return FAIL.
9020 */
9021 if (recursive)
9022#ifdef SPECIAL_WILDCHAR
9023 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9024#else
9025 return FAIL;
9026#endif
9027
9028#ifdef SPECIAL_WILDCHAR
9029 /*
9030 * If there are any special wildcard characters which we cannot handle
9031 * here, call machine specific function for all the expansion. This
9032 * avoids starting the shell for each argument separately.
9033 * For `=expr` do use the internal function.
9034 */
9035 for (i = 0; i < num_pat; i++)
9036 {
9037 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9038# ifdef VIM_BACKTICK
9039 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9040# endif
9041 )
9042 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9043 }
9044#endif
9045
9046 recursive = TRUE;
9047
9048 /*
9049 * The matching file names are stored in a growarray. Init it empty.
9050 */
9051 ga_init2(&ga, (int)sizeof(char_u *), 30);
9052
9053 for (i = 0; i < num_pat; ++i)
9054 {
9055 add_pat = -1;
9056 p = pat[i];
9057
9058#ifdef VIM_BACKTICK
9059 if (vim_backtick(p))
9060 add_pat = expand_backtick(&ga, p, flags);
9061 else
9062#endif
9063 {
9064 /*
9065 * First expand environment variables, "~/" and "~user/".
9066 */
9067 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9068 {
9069 p = expand_env_save(p);
9070 if (p == NULL)
9071 p = pat[i];
9072#ifdef UNIX
9073 /*
9074 * On Unix, if expand_env() can't expand an environment
9075 * variable, use the shell to do that. Discard previously
9076 * found file names and start all over again.
9077 */
9078 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9079 {
9080 vim_free(p);
9081 ga_clear(&ga);
9082 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9083 flags);
9084 recursive = FALSE;
9085 return i;
9086 }
9087#endif
9088 }
9089
9090 /*
9091 * If there are wildcards: Expand file names and add each match to
9092 * the list. If there is no match, and EW_NOTFOUND is given, add
9093 * the pattern.
9094 * If there are no wildcards: Add the file name if it exists or
9095 * when EW_NOTFOUND is given.
9096 */
9097 if (mch_has_exp_wildcard(p))
9098 add_pat = mch_expandpath(&ga, p, flags);
9099 }
9100
9101 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9102 {
9103 char_u *t = backslash_halve_save(p);
9104
9105#if defined(MACOS_CLASSIC)
9106 slash_to_colon(t);
9107#endif
9108 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9109 * "vim c:/" work. */
9110 if (flags & EW_NOTFOUND)
9111 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9112 else if (mch_getperm(t) >= 0)
9113 addfile(&ga, t, flags);
9114 vim_free(t);
9115 }
9116
9117 if (p != pat[i])
9118 vim_free(p);
9119 }
9120
9121 *num_file = ga.ga_len;
9122 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9123
9124 recursive = FALSE;
9125
9126 return (ga.ga_data != NULL) ? OK : FAIL;
9127}
9128
9129# ifdef VIM_BACKTICK
9130
9131/*
9132 * Return TRUE if we can expand this backtick thing here.
9133 */
9134 static int
9135vim_backtick(p)
9136 char_u *p;
9137{
9138 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9139}
9140
9141/*
9142 * Expand an item in `backticks` by executing it as a command.
9143 * Currently only works when pat[] starts and ends with a `.
9144 * Returns number of file names found.
9145 */
9146 static int
9147expand_backtick(gap, pat, flags)
9148 garray_T *gap;
9149 char_u *pat;
9150 int flags; /* EW_* flags */
9151{
9152 char_u *p;
9153 char_u *cmd;
9154 char_u *buffer;
9155 int cnt = 0;
9156 int i;
9157
9158 /* Create the command: lop off the backticks. */
9159 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9160 if (cmd == NULL)
9161 return 0;
9162
9163#ifdef FEAT_EVAL
9164 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +00009165 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009166 else
9167#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009168 buffer = get_cmd_output(cmd, NULL,
9169 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009170 vim_free(cmd);
9171 if (buffer == NULL)
9172 return 0;
9173
9174 cmd = buffer;
9175 while (*cmd != NUL)
9176 {
9177 cmd = skipwhite(cmd); /* skip over white space */
9178 p = cmd;
9179 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9180 ++p;
9181 /* add an entry if it is not empty */
9182 if (p > cmd)
9183 {
9184 i = *p;
9185 *p = NUL;
9186 addfile(gap, cmd, flags);
9187 *p = i;
9188 ++cnt;
9189 }
9190 cmd = p;
9191 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9192 ++cmd;
9193 }
9194
9195 vim_free(buffer);
9196 return cnt;
9197}
9198# endif /* VIM_BACKTICK */
9199
9200/*
9201 * Add a file to a file list. Accepted flags:
9202 * EW_DIR add directories
9203 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009204 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +00009205 * EW_NOTFOUND add even when it doesn't exist
9206 * EW_ADDSLASH add slash after directory name
9207 */
9208 void
9209addfile(gap, f, flags)
9210 garray_T *gap;
9211 char_u *f; /* filename */
9212 int flags;
9213{
9214 char_u *p;
9215 int isdir;
9216
9217 /* if the file/dir doesn't exist, may not add it */
9218 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9219 return;
9220
9221#ifdef FNAME_ILLEGAL
9222 /* if the file/dir contains illegal characters, don't add it */
9223 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9224 return;
9225#endif
9226
9227 isdir = mch_isdir(f);
9228 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9229 return;
9230
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009231 /* If the file isn't executable, may not add it. Do accept directories. */
9232 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9233 return;
9234
Bram Moolenaar071d4272004-06-13 20:20:40 +00009235 /* Make room for another item in the file list. */
9236 if (ga_grow(gap, 1) == FAIL)
9237 return;
9238
9239 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9240 if (p == NULL)
9241 return;
9242
9243 STRCPY(p, f);
9244#ifdef BACKSLASH_IN_FILENAME
9245 slash_adjust(p);
9246#endif
9247 /*
9248 * Append a slash or backslash after directory names if none is present.
9249 */
9250#ifndef DONT_ADD_PATHSEP_TO_DIR
9251 if (isdir && (flags & EW_ADDSLASH))
9252 add_pathsep(p);
9253#endif
9254 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009255}
9256#endif /* !NO_EXPANDPATH */
9257
9258#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9259
9260#ifndef SEEK_SET
9261# define SEEK_SET 0
9262#endif
9263#ifndef SEEK_END
9264# define SEEK_END 2
9265#endif
9266
9267/*
9268 * Get the stdout of an external command.
9269 * Returns an allocated string, or NULL for error.
9270 */
9271 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009272get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009273 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009274 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009275 int flags; /* can be SHELL_SILENT */
9276{
9277 char_u *tempname;
9278 char_u *command;
9279 char_u *buffer = NULL;
9280 int len;
9281 int i = 0;
9282 FILE *fd;
9283
9284 if (check_restricted() || check_secure())
9285 return NULL;
9286
9287 /* get a name for the temp file */
9288 if ((tempname = vim_tempname('o')) == NULL)
9289 {
9290 EMSG(_(e_notmp));
9291 return NULL;
9292 }
9293
9294 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009295 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009296 if (command == NULL)
9297 goto done;
9298
9299 /*
9300 * Call the shell to execute the command (errors are ignored).
9301 * Don't check timestamps here.
9302 */
9303 ++no_check_timestamps;
9304 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9305 --no_check_timestamps;
9306
9307 vim_free(command);
9308
9309 /*
9310 * read the names from the file into memory
9311 */
9312# ifdef VMS
9313 /* created temporary file is not allways readable as binary */
9314 fd = mch_fopen((char *)tempname, "r");
9315# else
9316 fd = mch_fopen((char *)tempname, READBIN);
9317# endif
9318
9319 if (fd == NULL)
9320 {
9321 EMSG2(_(e_notopen), tempname);
9322 goto done;
9323 }
9324
9325 fseek(fd, 0L, SEEK_END);
9326 len = ftell(fd); /* get size of temp file */
9327 fseek(fd, 0L, SEEK_SET);
9328
9329 buffer = alloc(len + 1);
9330 if (buffer != NULL)
9331 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9332 fclose(fd);
9333 mch_remove(tempname);
9334 if (buffer == NULL)
9335 goto done;
9336#ifdef VMS
9337 len = i; /* VMS doesn't give us what we asked for... */
9338#endif
9339 if (i != len)
9340 {
9341 EMSG2(_(e_notread), tempname);
9342 vim_free(buffer);
9343 buffer = NULL;
9344 }
9345 else
9346 buffer[len] = '\0'; /* make sure the buffer is terminated */
9347
9348done:
9349 vim_free(tempname);
9350 return buffer;
9351}
9352#endif
9353
9354/*
9355 * Free the list of files returned by expand_wildcards() or other expansion
9356 * functions.
9357 */
9358 void
9359FreeWild(count, files)
9360 int count;
9361 char_u **files;
9362{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00009363 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009364 return;
9365#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9366 /*
9367 * Is this still OK for when other functions than expand_wildcards() have
9368 * been used???
9369 */
9370 _fnexplodefree((char **)files);
9371#else
9372 while (count--)
9373 vim_free(files[count]);
9374 vim_free(files);
9375#endif
9376}
9377
9378/*
9379 * return TRUE when need to go to Insert mode because of 'insertmode'.
9380 * Don't do this when still processing a command or a mapping.
9381 * Don't do this when inside a ":normal" command.
9382 */
9383 int
9384goto_im()
9385{
9386 return (p_im && stuff_empty() && typebuf_typed());
9387}