blob: ed6c62994908e49fe5620ef10a889792022bd232 [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 */
Bram Moolenaare163f1c2006-10-17 09:12:21 +00002845 if (lnum <= curwin->w_cursor.lnum
2846 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002847 last_cursormoved.lnum = 0;
2848#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849}
2850
2851/*
2852 * unchanged() is called when the changed flag must be reset for buffer 'buf'
2853 */
2854 void
2855unchanged(buf, ff)
2856 buf_T *buf;
2857 int ff; /* also reset 'fileformat' */
2858{
2859 if (buf->b_changed || (ff && file_ff_differs(buf)))
2860 {
2861 buf->b_changed = 0;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002862 ml_setflags(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 if (ff)
2864 save_file_ff(buf);
2865#ifdef FEAT_WINDOWS
2866 check_status(buf);
Bram Moolenaar997fb4b2006-02-17 21:53:23 +00002867 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868#endif
2869#ifdef FEAT_TITLE
2870 need_maketitle = TRUE; /* set window title later */
2871#endif
2872 }
2873 ++buf->b_changedtick;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874#ifdef FEAT_NETBEANS_INTG
2875 netbeans_unmodified(buf);
2876#endif
2877}
2878
2879#if defined(FEAT_WINDOWS) || defined(PROTO)
2880/*
2881 * check_status: called when the status bars for the buffer 'buf'
2882 * need to be updated
2883 */
2884 void
2885check_status(buf)
2886 buf_T *buf;
2887{
2888 win_T *wp;
2889
2890 for (wp = firstwin; wp != NULL; wp = wp->w_next)
2891 if (wp->w_buffer == buf && wp->w_status_height)
2892 {
2893 wp->w_redr_status = TRUE;
2894 if (must_redraw < VALID)
2895 must_redraw = VALID;
2896 }
2897}
2898#endif
2899
2900/*
2901 * If the file is readonly, give a warning message with the first change.
2902 * Don't do this for autocommands.
2903 * Don't use emsg(), because it flushes the macro buffer.
Bram Moolenaard5cdbeb2005-10-10 20:59:28 +00002904 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905 * will be TRUE.
2906 */
2907 void
2908change_warning(col)
2909 int col; /* column for message; non-zero when in insert
2910 mode and 'showmode' is on */
2911{
2912 if (curbuf->b_did_warn == FALSE
2913 && curbufIsChanged() == 0
2914#ifdef FEAT_AUTOCMD
2915 && !autocmd_busy
2916#endif
2917 && curbuf->b_p_ro)
2918 {
2919#ifdef FEAT_AUTOCMD
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002920 ++curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002922 --curbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 if (!curbuf->b_p_ro)
2924 return;
2925#endif
2926 /*
2927 * Do what msg() does, but with a column offset if the warning should
2928 * be after the mode message.
2929 */
2930 msg_start();
2931 if (msg_row == Rows - 1)
2932 msg_col = col;
Bram Moolenaar2df6dcc2004-07-12 15:53:54 +00002933 msg_source(hl_attr(HLF_W));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 MSG_PUTS_ATTR(_("W10: Warning: Changing a readonly file"),
2935 hl_attr(HLF_W) | MSG_HIST);
2936 msg_clr_eos();
2937 (void)msg_end();
2938 if (msg_silent == 0 && !silent_mode)
2939 {
2940 out_flush();
2941 ui_delay(1000L, TRUE); /* give the user time to think about it */
2942 }
2943 curbuf->b_did_warn = TRUE;
2944 redraw_cmdline = FALSE; /* don't redraw and erase the message */
2945 if (msg_row < Rows - 1)
2946 showmode();
2947 }
2948}
2949
2950/*
2951 * Ask for a reply from the user, a 'y' or a 'n'.
2952 * No other characters are accepted, the message is repeated until a valid
2953 * reply is entered or CTRL-C is hit.
2954 * If direct is TRUE, don't use vgetc() but ui_inchar(), don't get characters
2955 * from any buffers but directly from the user.
2956 *
2957 * return the 'y' or 'n'
2958 */
2959 int
2960ask_yesno(str, direct)
2961 char_u *str;
2962 int direct;
2963{
2964 int r = ' ';
2965 int save_State = State;
2966
2967 if (exiting) /* put terminal in raw mode for this question */
2968 settmode(TMODE_RAW);
2969 ++no_wait_return;
2970#ifdef USE_ON_FLY_SCROLL
2971 dont_scroll = TRUE; /* disallow scrolling here */
2972#endif
2973 State = CONFIRM; /* mouse behaves like with :confirm */
2974#ifdef FEAT_MOUSE
2975 setmouse(); /* disables mouse for xterm */
2976#endif
2977 ++no_mapping;
2978 ++allow_keys; /* no mapping here, but recognize keys */
2979
2980 while (r != 'y' && r != 'n')
2981 {
2982 /* same highlighting as for wait_return */
2983 smsg_attr(hl_attr(HLF_R), (char_u *)"%s (y/n)?", str);
2984 if (direct)
2985 r = get_keystroke();
2986 else
2987 r = safe_vgetc();
2988 if (r == Ctrl_C || r == ESC)
2989 r = 'n';
2990 msg_putchar(r); /* show what you typed */
2991 out_flush();
2992 }
2993 --no_wait_return;
2994 State = save_State;
2995#ifdef FEAT_MOUSE
2996 setmouse();
2997#endif
2998 --no_mapping;
2999 --allow_keys;
3000
3001 return r;
3002}
3003
3004/*
3005 * Get a key stroke directly from the user.
3006 * Ignores mouse clicks and scrollbar events, except a click for the left
3007 * button (used at the more prompt).
3008 * Doesn't use vgetc(), because it syncs undo and eats mapped characters.
3009 * Disadvantage: typeahead is ignored.
3010 * Translates the interrupt character for unix to ESC.
3011 */
3012 int
3013get_keystroke()
3014{
3015#define CBUFLEN 151
3016 char_u buf[CBUFLEN];
3017 int len = 0;
3018 int n;
3019 int save_mapped_ctrl_c = mapped_ctrl_c;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003020 int waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021
3022 mapped_ctrl_c = FALSE; /* mappings are not used here */
3023 for (;;)
3024 {
3025 cursor_on();
3026 out_flush();
3027
3028 /* First time: blocking wait. Second time: wait up to 100ms for a
3029 * terminal code to complete. Leave some room for check_termcode() to
3030 * insert a key code into (max 5 chars plus NUL). And
3031 * fix_input_buffer() can triple the number of bytes. */
3032 n = ui_inchar(buf + len, (CBUFLEN - 6 - len) / 3,
3033 len == 0 ? -1L : 100L, 0);
3034 if (n > 0)
3035 {
3036 /* Replace zero and CSI by a special key code. */
3037 n = fix_input_buffer(buf + len, n, FALSE);
3038 len += n;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003039 waited = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 }
Bram Moolenaar4395a712006-09-05 18:57:57 +00003041 else if (len > 0)
3042 ++waited; /* keep track of the waiting time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043
Bram Moolenaar4395a712006-09-05 18:57:57 +00003044 /* Incomplete termcode and not timed out yet: get more characters */
3045 if ((n = check_termcode(1, buf, len)) < 0
3046 && (!p_ttimeout || waited * 100L < (p_ttm < 0 ? p_tm : p_ttm)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 continue;
Bram Moolenaar4395a712006-09-05 18:57:57 +00003048
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049 /* found a termcode: adjust length */
3050 if (n > 0)
3051 len = n;
3052 if (len == 0) /* nothing typed yet */
3053 continue;
3054
3055 /* Handle modifier and/or special key code. */
3056 n = buf[0];
3057 if (n == K_SPECIAL)
3058 {
3059 n = TO_SPECIAL(buf[1], buf[2]);
3060 if (buf[1] == KS_MODIFIER
3061 || n == K_IGNORE
3062#ifdef FEAT_MOUSE
3063 || n == K_LEFTMOUSE_NM
3064 || n == K_LEFTDRAG
3065 || n == K_LEFTRELEASE
3066 || n == K_LEFTRELEASE_NM
3067 || n == K_MIDDLEMOUSE
3068 || n == K_MIDDLEDRAG
3069 || n == K_MIDDLERELEASE
3070 || n == K_RIGHTMOUSE
3071 || n == K_RIGHTDRAG
3072 || n == K_RIGHTRELEASE
3073 || n == K_MOUSEDOWN
3074 || n == K_MOUSEUP
3075 || n == K_X1MOUSE
3076 || n == K_X1DRAG
3077 || n == K_X1RELEASE
3078 || n == K_X2MOUSE
3079 || n == K_X2DRAG
3080 || n == K_X2RELEASE
3081# ifdef FEAT_GUI
3082 || n == K_VER_SCROLLBAR
3083 || n == K_HOR_SCROLLBAR
3084# endif
3085#endif
3086 )
3087 {
3088 if (buf[1] == KS_MODIFIER)
3089 mod_mask = buf[2];
3090 len -= 3;
3091 if (len > 0)
3092 mch_memmove(buf, buf + 3, (size_t)len);
3093 continue;
3094 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00003095 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096 }
3097#ifdef FEAT_MBYTE
3098 if (has_mbyte)
3099 {
3100 if (MB_BYTE2LEN(n) > len)
3101 continue; /* more bytes to get */
3102 buf[len >= CBUFLEN ? CBUFLEN - 1 : len] = NUL;
3103 n = (*mb_ptr2char)(buf);
3104 }
3105#endif
3106#ifdef UNIX
3107 if (n == intr_char)
3108 n = ESC;
3109#endif
3110 break;
3111 }
3112
3113 mapped_ctrl_c = save_mapped_ctrl_c;
3114 return n;
3115}
3116
3117/*
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003118 * Get a number from the user.
3119 * When "mouse_used" is not NULL allow using the mouse.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120 */
3121 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003122get_number(colon, mouse_used)
3123 int colon; /* allow colon to abort */
3124 int *mouse_used;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003125{
3126 int n = 0;
3127 int c;
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003128 int typed = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003130 if (mouse_used != NULL)
3131 *mouse_used = FALSE;
3132
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133 /* When not printing messages, the user won't know what to type, return a
3134 * zero (as if CR was hit). */
3135 if (msg_silent != 0)
3136 return 0;
3137
3138#ifdef USE_ON_FLY_SCROLL
3139 dont_scroll = TRUE; /* disallow scrolling here */
3140#endif
3141 ++no_mapping;
3142 ++allow_keys; /* no mapping here, but recognize keys */
3143 for (;;)
3144 {
3145 windgoto(msg_row, msg_col);
3146 c = safe_vgetc();
3147 if (VIM_ISDIGIT(c))
3148 {
3149 n = n * 10 + c - '0';
3150 msg_putchar(c);
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003151 ++typed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152 }
3153 else if (c == K_DEL || c == K_KDEL || c == K_BS || c == Ctrl_H)
3154 {
Bram Moolenaar3991dab2006-03-27 17:01:56 +00003155 if (typed > 0)
3156 {
3157 MSG_PUTS("\b \b");
3158 --typed;
3159 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 n /= 10;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161 }
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003162#ifdef FEAT_MOUSE
3163 else if (mouse_used != NULL && c == K_LEFTMOUSE)
3164 {
3165 *mouse_used = TRUE;
3166 n = mouse_row + 1;
3167 break;
3168 }
3169#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 else if (n == 0 && c == ':' && colon)
3171 {
3172 stuffcharReadbuff(':');
3173 if (!exmode_active)
3174 cmdline_row = msg_row;
3175 skip_redraw = TRUE; /* skip redraw once */
3176 do_redraw = FALSE;
3177 break;
3178 }
3179 else if (c == CAR || c == NL || c == Ctrl_C || c == ESC)
3180 break;
3181 }
3182 --no_mapping;
3183 --allow_keys;
3184 return n;
3185}
3186
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003187/*
3188 * Ask the user to enter a number.
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003189 * When "mouse_used" is not NULL allow using the mouse and in that case return
3190 * the line number.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003191 */
3192 int
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003193prompt_for_number(mouse_used)
3194 int *mouse_used;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003195{
3196 int i;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003197 int save_cmdline_row;
3198 int save_State;
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003199
3200 /* When using ":silent" assume that <CR> was entered. */
Bram Moolenaar42eeac32005-06-29 22:40:58 +00003201 if (mouse_used != NULL)
3202 MSG_PUTS(_("Type number or click with mouse (<Enter> cancels): "));
3203 else
3204 MSG_PUTS(_("Choice number (<Enter> cancels): "));
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003205
Bram Moolenaar203335e2006-09-03 14:35:42 +00003206 /* Set the state such that text can be selected/copied/pasted and we still
3207 * get mouse events. */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003208 save_cmdline_row = cmdline_row;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003209 cmdline_row = 0;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003210 save_State = State;
Bram Moolenaar203335e2006-09-03 14:35:42 +00003211 State = CMDLINE;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003212
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003213 i = get_number(TRUE, mouse_used);
3214 if (KeyTyped)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003215 {
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003216 /* don't call wait_return() now */
3217 /* msg_putchar('\n'); */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003218 cmdline_row = msg_row - 1;
3219 need_wait_return = FALSE;
3220 msg_didany = FALSE;
3221 }
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003222 else
3223 cmdline_row = save_cmdline_row;
3224 State = save_State;
3225
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003226 return i;
3227}
3228
Bram Moolenaar071d4272004-06-13 20:20:40 +00003229 void
3230msgmore(n)
3231 long n;
3232{
3233 long pn;
3234
3235 if (global_busy /* no messages now, wait until global is finished */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 || !messaging()) /* 'lazyredraw' set, don't do messages now */
3237 return;
3238
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003239 /* We don't want to overwrite another important message, but do overwrite
3240 * a previous "more lines" or "fewer lines" message, so that "5dd" and
3241 * then "put" reports the last action. */
3242 if (keep_msg != NULL && !keep_msg_more)
3243 return;
3244
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 if (n > 0)
3246 pn = n;
3247 else
3248 pn = -n;
3249
3250 if (pn > p_report)
3251 {
3252 if (pn == 1)
3253 {
3254 if (n > 0)
3255 STRCPY(msg_buf, _("1 more line"));
3256 else
3257 STRCPY(msg_buf, _("1 line less"));
3258 }
3259 else
3260 {
3261 if (n > 0)
3262 sprintf((char *)msg_buf, _("%ld more lines"), pn);
3263 else
3264 sprintf((char *)msg_buf, _("%ld fewer lines"), pn);
3265 }
3266 if (got_int)
3267 STRCAT(msg_buf, _(" (Interrupted)"));
3268 if (msg(msg_buf))
3269 {
Bram Moolenaar238a5642006-02-21 22:12:05 +00003270 set_keep_msg(msg_buf, 0);
Bram Moolenaar7df2d662005-01-25 22:18:08 +00003271 keep_msg_more = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003272 }
3273 }
3274}
3275
3276/*
3277 * flush map and typeahead buffers and give a warning for an error
3278 */
3279 void
3280beep_flush()
3281{
3282 if (emsg_silent == 0)
3283 {
3284 flush_buffers(FALSE);
3285 vim_beep();
3286 }
3287}
3288
3289/*
3290 * give a warning for an error
3291 */
3292 void
3293vim_beep()
3294{
3295 if (emsg_silent == 0)
3296 {
3297 if (p_vb
3298#ifdef FEAT_GUI
3299 /* While the GUI is starting up the termcap is set for the GUI
3300 * but the output still goes to a terminal. */
3301 && !(gui.in_use && gui.starting)
3302#endif
3303 )
3304 {
3305 out_str(T_VB);
3306 }
3307 else
3308 {
3309#ifdef MSDOS
3310 /*
3311 * The number of beeps outputted is reduced to avoid having to wait
3312 * for all the beeps to finish. This is only a problem on systems
3313 * where the beeps don't overlap.
3314 */
3315 if (beep_count == 0 || beep_count == 10)
3316 {
3317 out_char(BELL);
3318 beep_count = 1;
3319 }
3320 else
3321 ++beep_count;
3322#else
3323 out_char(BELL);
3324#endif
3325 }
Bram Moolenaar5313dcb2005-02-22 08:56:13 +00003326
3327 /* When 'verbose' is set and we are sourcing a script or executing a
3328 * function give the user a hint where the beep comes from. */
3329 if (vim_strchr(p_debug, 'e') != NULL)
3330 {
3331 msg_source(hl_attr(HLF_W));
3332 msg_attr((char_u *)_("Beep!"), hl_attr(HLF_W));
3333 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334 }
3335}
3336
3337/*
3338 * To get the "real" home directory:
3339 * - get value of $HOME
3340 * For Unix:
3341 * - go to that directory
3342 * - do mch_dirname() to get the real name of that directory.
3343 * This also works with mounts and links.
3344 * Don't do this for MS-DOS, it will change the "current dir" for a drive.
3345 */
3346static char_u *homedir = NULL;
3347
3348 void
3349init_homedir()
3350{
3351 char_u *var;
3352
Bram Moolenaar05159a02005-02-26 23:04:13 +00003353 /* In case we are called a second time (when 'encoding' changes). */
3354 vim_free(homedir);
3355 homedir = NULL;
3356
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357#ifdef VMS
3358 var = mch_getenv((char_u *)"SYS$LOGIN");
3359#else
3360 var = mch_getenv((char_u *)"HOME");
3361#endif
3362
3363 if (var != NULL && *var == NUL) /* empty is same as not set */
3364 var = NULL;
3365
3366#ifdef WIN3264
3367 /*
3368 * Weird but true: $HOME may contain an indirect reference to another
3369 * variable, esp. "%USERPROFILE%". Happens when $USERPROFILE isn't set
3370 * when $HOME is being set.
3371 */
3372 if (var != NULL && *var == '%')
3373 {
3374 char_u *p;
3375 char_u *exp;
3376
3377 p = vim_strchr(var + 1, '%');
3378 if (p != NULL)
3379 {
Bram Moolenaarce0842a2005-07-18 21:58:11 +00003380 vim_strncpy(NameBuff, var + 1, p - (var + 1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003381 exp = mch_getenv(NameBuff);
3382 if (exp != NULL && *exp != NUL
3383 && STRLEN(exp) + STRLEN(p) < MAXPATHL)
3384 {
Bram Moolenaar555b2802005-05-19 21:08:39 +00003385 vim_snprintf((char *)NameBuff, MAXPATHL, "%s%s", exp, p + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386 var = NameBuff;
3387 /* Also set $HOME, it's needed for _viminfo. */
3388 vim_setenv((char_u *)"HOME", NameBuff);
3389 }
3390 }
3391 }
3392
3393 /*
3394 * Typically, $HOME is not defined on Windows, unless the user has
3395 * specifically defined it for Vim's sake. However, on Windows NT
3396 * platforms, $HOMEDRIVE and $HOMEPATH are automatically defined for
3397 * each user. Try constructing $HOME from these.
3398 */
3399 if (var == NULL)
3400 {
3401 char_u *homedrive, *homepath;
3402
3403 homedrive = mch_getenv((char_u *)"HOMEDRIVE");
3404 homepath = mch_getenv((char_u *)"HOMEPATH");
3405 if (homedrive != NULL && homepath != NULL
3406 && STRLEN(homedrive) + STRLEN(homepath) < MAXPATHL)
3407 {
3408 sprintf((char *)NameBuff, "%s%s", homedrive, homepath);
3409 if (NameBuff[0] != NUL)
3410 {
3411 var = NameBuff;
3412 /* Also set $HOME, it's needed for _viminfo. */
3413 vim_setenv((char_u *)"HOME", NameBuff);
3414 }
3415 }
3416 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00003417
3418# if defined(FEAT_MBYTE)
3419 if (enc_utf8 && var != NULL)
3420 {
3421 int len;
3422 char_u *pp;
3423
3424 /* Convert from active codepage to UTF-8. Other conversions are
3425 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003426 acp_to_enc(var, (int)STRLEN(var), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003427 if (pp != NULL)
3428 {
3429 homedir = pp;
3430 return;
3431 }
3432 }
3433# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003434#endif
3435
3436#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3437 /*
3438 * Default home dir is C:/
3439 * Best assumption we can make in such a situation.
3440 */
3441 if (var == NULL)
3442 var = "C:/";
3443#endif
3444 if (var != NULL)
3445 {
3446#ifdef UNIX
3447 /*
3448 * Change to the directory and get the actual path. This resolves
3449 * links. Don't do it when we can't return.
3450 */
3451 if (mch_dirname(NameBuff, MAXPATHL) == OK
3452 && mch_chdir((char *)NameBuff) == 0)
3453 {
3454 if (!mch_chdir((char *)var) && mch_dirname(IObuff, IOSIZE) == OK)
3455 var = IObuff;
3456 if (mch_chdir((char *)NameBuff) != 0)
3457 EMSG(_(e_prev_dir));
3458 }
3459#endif
3460 homedir = vim_strsave(var);
3461 }
3462}
3463
Bram Moolenaarf461c8e2005-06-25 23:04:51 +00003464#if defined(EXITFREE) || defined(PROTO)
3465 void
3466free_homedir()
3467{
3468 vim_free(homedir);
3469}
3470#endif
3471
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472/*
3473 * Expand environment variable with path name.
3474 * "~/" is also expanded, using $HOME. For Unix "~user/" is expanded.
3475 * Skips over "\ ", "\~" and "\$".
3476 * If anything fails no expansion is done and dst equals src.
3477 */
3478 void
3479expand_env(src, dst, dstlen)
3480 char_u *src; /* input string e.g. "$HOME/vim.hlp" */
3481 char_u *dst; /* where to put the result */
3482 int dstlen; /* maximum length of the result */
3483{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003484 expand_env_esc(src, dst, dstlen, FALSE, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485}
3486
3487 void
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003488expand_env_esc(srcp, dst, dstlen, esc, startstr)
3489 char_u *srcp; /* input string e.g. "$HOME/vim.hlp" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 char_u *dst; /* where to put the result */
3491 int dstlen; /* maximum length of the result */
3492 int esc; /* escape spaces in expanded variables */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003493 char_u *startstr; /* start again after this (can be NULL) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003494{
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003495 char_u *src;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496 char_u *tail;
3497 int c;
3498 char_u *var;
3499 int copy_char;
3500 int mustfree; /* var was allocated, need to free it later */
3501 int at_start = TRUE; /* at start of a name */
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003502 int startstr_len = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003504 if (startstr != NULL)
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003505 startstr_len = (int)STRLEN(startstr);
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003506
3507 src = skipwhite(srcp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508 --dstlen; /* leave one char space for "\," */
3509 while (*src && dstlen > 0)
3510 {
3511 copy_char = TRUE;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003512 if ((*src == '$'
3513#ifdef VMS
3514 && at_start
3515#endif
3516 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3518 || *src == '%'
3519#endif
3520 || (*src == '~' && at_start))
3521 {
3522 mustfree = FALSE;
3523
3524 /*
3525 * The variable name is copied into dst temporarily, because it may
3526 * be a string in read-only memory and a NUL needs to be appended.
3527 */
3528 if (*src != '~') /* environment var */
3529 {
3530 tail = src + 1;
3531 var = dst;
3532 c = dstlen - 1;
3533
3534#ifdef UNIX
3535 /* Unix has ${var-name} type environment vars */
3536 if (*tail == '{' && !vim_isIDc('{'))
3537 {
3538 tail++; /* ignore '{' */
3539 while (c-- > 0 && *tail && *tail != '}')
3540 *var++ = *tail++;
3541 }
3542 else
3543#endif
3544 {
3545 while (c-- > 0 && *tail != NUL && ((vim_isIDc(*tail))
3546#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3547 || (*src == '%' && *tail != '%')
3548#endif
3549 ))
3550 {
3551#ifdef OS2 /* env vars only in uppercase */
3552 *var++ = TOUPPER_LOC(*tail);
3553 tail++; /* toupper() may be a macro! */
3554#else
3555 *var++ = *tail++;
3556#endif
3557 }
3558 }
3559
3560#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3561# ifdef UNIX
3562 if (src[1] == '{' && *tail != '}')
3563# else
3564 if (*src == '%' && *tail != '%')
3565# endif
3566 var = NULL;
3567 else
3568 {
3569# ifdef UNIX
3570 if (src[1] == '{')
3571# else
3572 if (*src == '%')
3573#endif
3574 ++tail;
3575#endif
3576 *var = NUL;
3577 var = vim_getenv(dst, &mustfree);
3578#if defined(MSDOS) || defined(MSWIN) || defined(OS2) || defined(UNIX)
3579 }
3580#endif
3581 }
3582 /* home directory */
3583 else if ( src[1] == NUL
3584 || vim_ispathsep(src[1])
3585 || vim_strchr((char_u *)" ,\t\n", src[1]) != NULL)
3586 {
3587 var = homedir;
3588 tail = src + 1;
3589 }
3590 else /* user directory */
3591 {
3592#if defined(UNIX) || (defined(VMS) && defined(USER_HOME))
3593 /*
3594 * Copy ~user to dst[], so we can put a NUL after it.
3595 */
3596 tail = src;
3597 var = dst;
3598 c = dstlen - 1;
3599 while ( c-- > 0
3600 && *tail
3601 && vim_isfilec(*tail)
3602 && !vim_ispathsep(*tail))
3603 *var++ = *tail++;
3604 *var = NUL;
3605# ifdef UNIX
3606 /*
3607 * If the system supports getpwnam(), use it.
3608 * Otherwise, or if getpwnam() fails, the shell is used to
3609 * expand ~user. This is slower and may fail if the shell
3610 * does not support ~user (old versions of /bin/sh).
3611 */
3612# if defined(HAVE_GETPWNAM) && defined(HAVE_PWD_H)
3613 {
3614 struct passwd *pw;
3615
Bram Moolenaara40ceaf2006-01-13 22:35:40 +00003616 /* Note: memory allocated by getpwnam() is never freed.
3617 * Calling endpwent() apparently doesn't help. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 pw = getpwnam((char *)dst + 1);
3619 if (pw != NULL)
3620 var = (char_u *)pw->pw_dir;
3621 else
3622 var = NULL;
3623 }
3624 if (var == NULL)
3625# endif
3626 {
3627 expand_T xpc;
3628
3629 ExpandInit(&xpc);
3630 xpc.xp_context = EXPAND_FILES;
3631 var = ExpandOne(&xpc, dst, NULL,
3632 WILD_ADD_SLASH|WILD_SILENT, WILD_EXPAND_FREE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633 mustfree = TRUE;
3634 }
3635
3636# else /* !UNIX, thus VMS */
3637 /*
3638 * USER_HOME is a comma-separated list of
3639 * directories to search for the user account in.
3640 */
3641 {
3642 char_u test[MAXPATHL], paths[MAXPATHL];
3643 char_u *path, *next_path, *ptr;
3644 struct stat st;
3645
3646 STRCPY(paths, USER_HOME);
3647 next_path = paths;
3648 while (*next_path)
3649 {
3650 for (path = next_path; *next_path && *next_path != ',';
3651 next_path++);
3652 if (*next_path)
3653 *next_path++ = NUL;
3654 STRCPY(test, path);
3655 STRCAT(test, "/");
3656 STRCAT(test, dst + 1);
3657 if (mch_stat(test, &st) == 0)
3658 {
3659 var = alloc(STRLEN(test) + 1);
3660 STRCPY(var, test);
3661 mustfree = TRUE;
3662 break;
3663 }
3664 }
3665 }
3666# endif /* UNIX */
3667#else
3668 /* cannot expand user's home directory, so don't try */
3669 var = NULL;
3670 tail = (char_u *)""; /* for gcc */
3671#endif /* UNIX || VMS */
3672 }
3673
3674#ifdef BACKSLASH_IN_FILENAME
3675 /* If 'shellslash' is set change backslashes to forward slashes.
3676 * Can't use slash_adjust(), p_ssl may be set temporarily. */
3677 if (p_ssl && var != NULL && vim_strchr(var, '\\') != NULL)
3678 {
3679 char_u *p = vim_strsave(var);
3680
3681 if (p != NULL)
3682 {
3683 if (mustfree)
3684 vim_free(var);
3685 var = p;
3686 mustfree = TRUE;
3687 forward_slash(var);
3688 }
3689 }
3690#endif
3691
3692 /* If "var" contains white space, escape it with a backslash.
3693 * Required for ":e ~/tt" when $HOME includes a space. */
3694 if (esc && var != NULL && vim_strpbrk(var, (char_u *)" \t") != NULL)
3695 {
3696 char_u *p = vim_strsave_escaped(var, (char_u *)" \t");
3697
3698 if (p != NULL)
3699 {
3700 if (mustfree)
3701 vim_free(var);
3702 var = p;
3703 mustfree = TRUE;
3704 }
3705 }
3706
3707 if (var != NULL && *var != NUL
3708 && (STRLEN(var) + STRLEN(tail) + 1 < (unsigned)dstlen))
3709 {
3710 STRCPY(dst, var);
3711 dstlen -= (int)STRLEN(var);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003712 c = (int)STRLEN(var);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 /* if var[] ends in a path separator and tail[] starts
3714 * with it, skip a character */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003715 if (*var != NUL && after_pathsep(dst, dst + c)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716#if defined(BACKSLASH_IN_FILENAME) || defined(AMIGA)
3717 && dst[-1] != ':'
3718#endif
3719 && vim_ispathsep(*tail))
3720 ++tail;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003721 dst += c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722 src = tail;
3723 copy_char = FALSE;
3724 }
3725 if (mustfree)
3726 vim_free(var);
3727 }
3728
3729 if (copy_char) /* copy at least one char */
3730 {
3731 /*
3732 * Recogize the start of a new name, for '~'.
3733 */
3734 at_start = FALSE;
3735 if (src[0] == '\\' && src[1] != NUL)
3736 {
3737 *dst++ = *src++;
3738 --dstlen;
3739 }
3740 else if (src[0] == ' ' || src[0] == ',')
3741 at_start = TRUE;
3742 *dst++ = *src++;
3743 --dstlen;
Bram Moolenaar24bbcfe2005-06-28 23:32:02 +00003744
3745 if (startstr != NULL && src - startstr_len >= srcp
3746 && STRNCMP(src - startstr_len, startstr, startstr_len) == 0)
3747 at_start = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 }
3749 }
3750 *dst = NUL;
3751}
3752
3753/*
3754 * Vim's version of getenv().
3755 * Special handling of $HOME, $VIM and $VIMRUNTIME.
Bram Moolenaar2f6b0b82005-03-08 22:43:10 +00003756 * Also does ACP to 'enc' conversion for Win32.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757 */
3758 char_u *
3759vim_getenv(name, mustfree)
3760 char_u *name;
3761 int *mustfree; /* set to TRUE when returned is allocated */
3762{
3763 char_u *p;
3764 char_u *pend;
3765 int vimruntime;
3766
3767#if defined(OS2) || defined(MSDOS) || defined(MSWIN)
3768 /* use "C:/" when $HOME is not set */
3769 if (STRCMP(name, "HOME") == 0)
3770 return homedir;
3771#endif
3772
3773 p = mch_getenv(name);
3774 if (p != NULL && *p == NUL) /* empty is the same as not set */
3775 p = NULL;
3776
3777 if (p != NULL)
Bram Moolenaar05159a02005-02-26 23:04:13 +00003778 {
3779#if defined(FEAT_MBYTE) && defined(WIN3264)
3780 if (enc_utf8)
3781 {
3782 int len;
3783 char_u *pp;
3784
3785 /* Convert from active codepage to UTF-8. Other conversions are
3786 * not done, because they would fail for non-ASCII characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003787 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003788 if (pp != NULL)
3789 {
3790 p = pp;
3791 *mustfree = TRUE;
3792 }
3793 }
3794#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003795 return p;
Bram Moolenaar05159a02005-02-26 23:04:13 +00003796 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797
3798 vimruntime = (STRCMP(name, "VIMRUNTIME") == 0);
3799 if (!vimruntime && STRCMP(name, "VIM") != 0)
3800 return NULL;
3801
3802 /*
3803 * When expanding $VIMRUNTIME fails, try using $VIM/vim<version> or $VIM.
3804 * Don't do this when default_vimruntime_dir is non-empty.
3805 */
3806 if (vimruntime
3807#ifdef HAVE_PATHDEF
3808 && *default_vimruntime_dir == NUL
3809#endif
3810 )
3811 {
3812 p = mch_getenv((char_u *)"VIM");
3813 if (p != NULL && *p == NUL) /* empty is the same as not set */
3814 p = NULL;
3815 if (p != NULL)
3816 {
3817 p = vim_version_dir(p);
3818 if (p != NULL)
3819 *mustfree = TRUE;
3820 else
3821 p = mch_getenv((char_u *)"VIM");
Bram Moolenaar05159a02005-02-26 23:04:13 +00003822
3823#if defined(FEAT_MBYTE) && defined(WIN3264)
3824 if (enc_utf8)
3825 {
3826 int len;
3827 char_u *pp;
3828
3829 /* Convert from active codepage to UTF-8. Other conversions
3830 * are not done, because they would fail for non-ASCII
3831 * characters. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003832 acp_to_enc(p, (int)STRLEN(p), &pp, &len);
Bram Moolenaar05159a02005-02-26 23:04:13 +00003833 if (pp != NULL)
3834 {
3835 if (mustfree)
3836 vim_free(p);
3837 p = pp;
3838 *mustfree = TRUE;
3839 }
3840 }
3841#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 }
3843 }
3844
3845 /*
3846 * When expanding $VIM or $VIMRUNTIME fails, try using:
3847 * - the directory name from 'helpfile' (unless it contains '$')
3848 * - the executable name from argv[0]
3849 */
3850 if (p == NULL)
3851 {
3852 if (p_hf != NULL && vim_strchr(p_hf, '$') == NULL)
3853 p = p_hf;
3854#ifdef USE_EXE_NAME
3855 /*
3856 * Use the name of the executable, obtained from argv[0].
3857 */
3858 else
3859 p = exe_name;
3860#endif
3861 if (p != NULL)
3862 {
3863 /* remove the file name */
3864 pend = gettail(p);
3865
3866 /* remove "doc/" from 'helpfile', if present */
3867 if (p == p_hf)
3868 pend = remove_tail(p, pend, (char_u *)"doc");
3869
3870#ifdef USE_EXE_NAME
3871# ifdef MACOS_X
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003872 /* remove "MacOS" from exe_name and add "Resources/vim" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873 if (p == exe_name)
3874 {
3875 char_u *pend1;
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003876 char_u *pnew;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003878 pend1 = remove_tail(p, pend, (char_u *)"MacOS");
3879 if (pend1 != pend)
3880 {
3881 pnew = alloc((unsigned)(pend1 - p) + 15);
3882 if (pnew != NULL)
3883 {
3884 STRNCPY(pnew, p, (pend1 - p));
3885 STRCPY(pnew + (pend1 - p), "Resources/vim");
3886 p = pnew;
3887 pend = p + STRLEN(p);
3888 }
3889 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 }
3891# endif
3892 /* remove "src/" from exe_name, if present */
3893 if (p == exe_name)
3894 pend = remove_tail(p, pend, (char_u *)"src");
3895#endif
3896
3897 /* for $VIM, remove "runtime/" or "vim54/", if present */
3898 if (!vimruntime)
3899 {
3900 pend = remove_tail(p, pend, (char_u *)RUNTIME_DIRNAME);
3901 pend = remove_tail(p, pend, (char_u *)VIM_VERSION_NODOT);
3902 }
3903
3904 /* remove trailing path separator */
3905#ifndef MACOS_CLASSIC
3906 /* With MacOS path (with colons) the final colon is required */
3907 /* to avoid confusion between absoulute and relative path */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003908 if (pend > p && after_pathsep(p, pend))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 --pend;
3910#endif
3911
Bram Moolenaar95e9b492006-03-15 23:04:43 +00003912#ifdef MACOS_X
3913 if (p == exe_name || p == p_hf)
3914#endif
3915 /* check that the result is a directory name */
3916 p = vim_strnsave(p, (int)(pend - p));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003917
3918 if (p != NULL && !mch_isdir(p))
3919 {
3920 vim_free(p);
3921 p = NULL;
3922 }
3923 else
3924 {
3925#ifdef USE_EXE_NAME
3926 /* may add "/vim54" or "/runtime" if it exists */
3927 if (vimruntime && (pend = vim_version_dir(p)) != NULL)
3928 {
3929 vim_free(p);
3930 p = pend;
3931 }
3932#endif
3933 *mustfree = TRUE;
3934 }
3935 }
3936 }
3937
3938#ifdef HAVE_PATHDEF
3939 /* When there is a pathdef.c file we can use default_vim_dir and
3940 * default_vimruntime_dir */
3941 if (p == NULL)
3942 {
3943 /* Only use default_vimruntime_dir when it is not empty */
3944 if (vimruntime && *default_vimruntime_dir != NUL)
3945 {
3946 p = default_vimruntime_dir;
3947 *mustfree = FALSE;
3948 }
3949 else if (*default_vim_dir != NUL)
3950 {
3951 if (vimruntime && (p = vim_version_dir(default_vim_dir)) != NULL)
3952 *mustfree = TRUE;
3953 else
3954 {
3955 p = default_vim_dir;
3956 *mustfree = FALSE;
3957 }
3958 }
3959 }
3960#endif
3961
3962 /*
3963 * Set the environment variable, so that the new value can be found fast
3964 * next time, and others can also use it (e.g. Perl).
3965 */
3966 if (p != NULL)
3967 {
3968 if (vimruntime)
3969 {
3970 vim_setenv((char_u *)"VIMRUNTIME", p);
3971 didset_vimruntime = TRUE;
3972#ifdef FEAT_GETTEXT
3973 {
Bram Moolenaard6754642005-01-17 22:18:45 +00003974 char_u *buf = concat_str(p, (char_u *)"/lang");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975
3976 if (buf != NULL)
3977 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978 bindtextdomain(VIMPACKAGE, (char *)buf);
3979 vim_free(buf);
3980 }
3981 }
3982#endif
3983 }
3984 else
3985 {
3986 vim_setenv((char_u *)"VIM", p);
3987 didset_vim = TRUE;
3988 }
3989 }
3990 return p;
3991}
3992
3993/*
3994 * Check if the directory "vimdir/<version>" or "vimdir/runtime" exists.
3995 * Return NULL if not, return its name in allocated memory otherwise.
3996 */
3997 static char_u *
3998vim_version_dir(vimdir)
3999 char_u *vimdir;
4000{
4001 char_u *p;
4002
4003 if (vimdir == NULL || *vimdir == NUL)
4004 return NULL;
4005 p = concat_fnames(vimdir, (char_u *)VIM_VERSION_NODOT, TRUE);
4006 if (p != NULL && mch_isdir(p))
4007 return p;
4008 vim_free(p);
4009 p = concat_fnames(vimdir, (char_u *)RUNTIME_DIRNAME, TRUE);
4010 if (p != NULL && mch_isdir(p))
4011 return p;
4012 vim_free(p);
4013 return NULL;
4014}
4015
4016/*
4017 * If the string between "p" and "pend" ends in "name/", return "pend" minus
4018 * the length of "name/". Otherwise return "pend".
4019 */
4020 static char_u *
4021remove_tail(p, pend, name)
4022 char_u *p;
4023 char_u *pend;
4024 char_u *name;
4025{
4026 int len = (int)STRLEN(name) + 1;
4027 char_u *newend = pend - len;
4028
4029 if (newend >= p
4030 && fnamencmp(newend, name, len - 1) == 0
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004031 && (newend == p || after_pathsep(p, newend)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032 return newend;
4033 return pend;
4034}
4035
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036/*
4037 * Call expand_env() and store the result in an allocated string.
4038 * This is not very memory efficient, this expects the result to be freed
4039 * again soon.
4040 */
4041 char_u *
4042expand_env_save(src)
4043 char_u *src;
4044{
4045 char_u *p;
4046
4047 p = alloc(MAXPATHL);
4048 if (p != NULL)
4049 expand_env(src, p, MAXPATHL);
4050 return p;
4051}
4052
4053/*
4054 * Our portable version of setenv.
4055 */
4056 void
4057vim_setenv(name, val)
4058 char_u *name;
4059 char_u *val;
4060{
4061#ifdef HAVE_SETENV
4062 mch_setenv((char *)name, (char *)val, 1);
4063#else
4064 char_u *envbuf;
4065
4066 /*
4067 * Putenv does not copy the string, it has to remain
4068 * valid. The allocated memory will never be freed.
4069 */
4070 envbuf = alloc((unsigned)(STRLEN(name) + STRLEN(val) + 2));
4071 if (envbuf != NULL)
4072 {
4073 sprintf((char *)envbuf, "%s=%s", name, val);
4074 putenv((char *)envbuf);
4075 }
4076#endif
4077}
4078
4079#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
4080/*
4081 * Function given to ExpandGeneric() to obtain an environment variable name.
4082 */
4083/*ARGSUSED*/
4084 char_u *
4085get_env_name(xp, idx)
4086 expand_T *xp;
4087 int idx;
4088{
4089# if defined(AMIGA) || defined(__MRC__) || defined(__SC__)
4090 /*
4091 * No environ[] on the Amiga and on the Mac (using MPW).
4092 */
4093 return NULL;
4094# else
4095# ifndef __WIN32__
4096 /* Borland C++ 5.2 has this in a header file. */
4097 extern char **environ;
4098# endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004099# define ENVNAMELEN 100
4100 static char_u name[ENVNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004101 char_u *str;
4102 int n;
4103
4104 str = (char_u *)environ[idx];
4105 if (str == NULL)
4106 return NULL;
4107
Bram Moolenaar21cf8232004-07-16 20:18:37 +00004108 for (n = 0; n < ENVNAMELEN - 1; ++n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109 {
4110 if (str[n] == '=' || str[n] == NUL)
4111 break;
4112 name[n] = str[n];
4113 }
4114 name[n] = NUL;
4115 return name;
4116# endif
4117}
4118#endif
4119
4120/*
4121 * Replace home directory by "~" in each space or comma separated file name in
4122 * 'src'.
4123 * If anything fails (except when out of space) dst equals src.
4124 */
4125 void
4126home_replace(buf, src, dst, dstlen, one)
4127 buf_T *buf; /* when not NULL, check for help files */
4128 char_u *src; /* input file name */
4129 char_u *dst; /* where to put the result */
4130 int dstlen; /* maximum length of the result */
4131 int one; /* if TRUE, only replace one file name, include
4132 spaces and commas in the file name. */
4133{
4134 size_t dirlen = 0, envlen = 0;
4135 size_t len;
4136 char_u *homedir_env;
4137 char_u *p;
4138
4139 if (src == NULL)
4140 {
4141 *dst = NUL;
4142 return;
4143 }
4144
4145 /*
4146 * If the file is a help file, remove the path completely.
4147 */
4148 if (buf != NULL && buf->b_help)
4149 {
4150 STRCPY(dst, gettail(src));
4151 return;
4152 }
4153
4154 /*
4155 * We check both the value of the $HOME environment variable and the
4156 * "real" home directory.
4157 */
4158 if (homedir != NULL)
4159 dirlen = STRLEN(homedir);
4160
4161#ifdef VMS
4162 homedir_env = mch_getenv((char_u *)"SYS$LOGIN");
4163#else
4164 homedir_env = mch_getenv((char_u *)"HOME");
4165#endif
4166
4167 if (homedir_env != NULL && *homedir_env == NUL)
4168 homedir_env = NULL;
4169 if (homedir_env != NULL)
4170 envlen = STRLEN(homedir_env);
4171
4172 if (!one)
4173 src = skipwhite(src);
4174 while (*src && dstlen > 0)
4175 {
4176 /*
4177 * Here we are at the beginning of a file name.
4178 * First, check to see if the beginning of the file name matches
4179 * $HOME or the "real" home directory. Check that there is a '/'
4180 * after the match (so that if e.g. the file is "/home/pieter/bla",
4181 * and the home directory is "/home/piet", the file does not end up
4182 * as "~er/bla" (which would seem to indicate the file "bla" in user
4183 * er's home directory)).
4184 */
4185 p = homedir;
4186 len = dirlen;
4187 for (;;)
4188 {
4189 if ( len
4190 && fnamencmp(src, p, len) == 0
4191 && (vim_ispathsep(src[len])
4192 || (!one && (src[len] == ',' || src[len] == ' '))
4193 || src[len] == NUL))
4194 {
4195 src += len;
4196 if (--dstlen > 0)
4197 *dst++ = '~';
4198
4199 /*
4200 * If it's just the home directory, add "/".
4201 */
4202 if (!vim_ispathsep(src[0]) && --dstlen > 0)
4203 *dst++ = '/';
4204 break;
4205 }
4206 if (p == homedir_env)
4207 break;
4208 p = homedir_env;
4209 len = envlen;
4210 }
4211
4212 /* if (!one) skip to separator: space or comma */
4213 while (*src && (one || (*src != ',' && *src != ' ')) && --dstlen > 0)
4214 *dst++ = *src++;
4215 /* skip separator */
4216 while ((*src == ' ' || *src == ',') && --dstlen > 0)
4217 *dst++ = *src++;
4218 }
4219 /* if (dstlen == 0) out of space, what to do??? */
4220
4221 *dst = NUL;
4222}
4223
4224/*
4225 * Like home_replace, store the replaced string in allocated memory.
4226 * When something fails, NULL is returned.
4227 */
4228 char_u *
4229home_replace_save(buf, src)
4230 buf_T *buf; /* when not NULL, check for help files */
4231 char_u *src; /* input file name */
4232{
4233 char_u *dst;
4234 unsigned len;
4235
4236 len = 3; /* space for "~/" and trailing NUL */
4237 if (src != NULL) /* just in case */
4238 len += (unsigned)STRLEN(src);
4239 dst = alloc(len);
4240 if (dst != NULL)
4241 home_replace(buf, src, dst, len, TRUE);
4242 return dst;
4243}
4244
4245/*
4246 * Compare two file names and return:
4247 * FPC_SAME if they both exist and are the same file.
4248 * FPC_SAMEX if they both don't exist and have the same file name.
4249 * FPC_DIFF if they both exist and are different files.
4250 * FPC_NOTX if they both don't exist.
4251 * FPC_DIFFX if one of them doesn't exist.
4252 * For the first name environment variables are expanded
4253 */
4254 int
4255fullpathcmp(s1, s2, checkname)
4256 char_u *s1, *s2;
4257 int checkname; /* when both don't exist, check file names */
4258{
4259#ifdef UNIX
4260 char_u exp1[MAXPATHL];
4261 char_u full1[MAXPATHL];
4262 char_u full2[MAXPATHL];
4263 struct stat st1, st2;
4264 int r1, r2;
4265
4266 expand_env(s1, exp1, MAXPATHL);
4267 r1 = mch_stat((char *)exp1, &st1);
4268 r2 = mch_stat((char *)s2, &st2);
4269 if (r1 != 0 && r2 != 0)
4270 {
4271 /* if mch_stat() doesn't work, may compare the names */
4272 if (checkname)
4273 {
4274 if (fnamecmp(exp1, s2) == 0)
4275 return FPC_SAMEX;
4276 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4277 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4278 if (r1 == OK && r2 == OK && fnamecmp(full1, full2) == 0)
4279 return FPC_SAMEX;
4280 }
4281 return FPC_NOTX;
4282 }
4283 if (r1 != 0 || r2 != 0)
4284 return FPC_DIFFX;
4285 if (st1.st_dev == st2.st_dev && st1.st_ino == st2.st_ino)
4286 return FPC_SAME;
4287 return FPC_DIFF;
4288#else
4289 char_u *exp1; /* expanded s1 */
4290 char_u *full1; /* full path of s1 */
4291 char_u *full2; /* full path of s2 */
4292 int retval = FPC_DIFF;
4293 int r1, r2;
4294
4295 /* allocate one buffer to store three paths (alloc()/free() is slow!) */
4296 if ((exp1 = alloc(MAXPATHL * 3)) != NULL)
4297 {
4298 full1 = exp1 + MAXPATHL;
4299 full2 = full1 + MAXPATHL;
4300
4301 expand_env(s1, exp1, MAXPATHL);
4302 r1 = vim_FullName(exp1, full1, MAXPATHL, FALSE);
4303 r2 = vim_FullName(s2, full2, MAXPATHL, FALSE);
4304
4305 /* If vim_FullName() fails, the file probably doesn't exist. */
4306 if (r1 != OK && r2 != OK)
4307 {
4308 if (checkname && fnamecmp(exp1, s2) == 0)
4309 retval = FPC_SAMEX;
4310 else
4311 retval = FPC_NOTX;
4312 }
4313 else if (r1 != OK || r2 != OK)
4314 retval = FPC_DIFFX;
4315 else if (fnamecmp(full1, full2))
4316 retval = FPC_DIFF;
4317 else
4318 retval = FPC_SAME;
4319 vim_free(exp1);
4320 }
4321 return retval;
4322#endif
4323}
4324
4325/*
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004326 * Get the tail of a path: the file name.
4327 * Fail safe: never returns NULL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004328 */
4329 char_u *
4330gettail(fname)
4331 char_u *fname;
4332{
4333 char_u *p1, *p2;
4334
4335 if (fname == NULL)
4336 return (char_u *)"";
4337 for (p1 = p2 = fname; *p2; ) /* find last part of path */
4338 {
4339 if (vim_ispathsep(*p2))
4340 p1 = p2 + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004341 mb_ptr_adv(p2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004342 }
4343 return p1;
4344}
4345
4346/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004347 * Get pointer to tail of "fname", including path separators. Putting a NUL
4348 * here leaves the directory name. Takes care of "c:/" and "//".
4349 * Always returns a valid pointer.
4350 */
4351 char_u *
4352gettail_sep(fname)
4353 char_u *fname;
4354{
4355 char_u *p;
4356 char_u *t;
4357
4358 p = get_past_head(fname); /* don't remove the '/' from "c:/file" */
4359 t = gettail(fname);
4360 while (t > p && after_pathsep(fname, t))
4361 --t;
4362#ifdef VMS
4363 /* path separator is part of the path */
4364 ++t;
4365#endif
4366 return t;
4367}
4368
4369/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004370 * get the next path component (just after the next path separator).
4371 */
4372 char_u *
4373getnextcomp(fname)
4374 char_u *fname;
4375{
4376 while (*fname && !vim_ispathsep(*fname))
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004377 mb_ptr_adv(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378 if (*fname)
4379 ++fname;
4380 return fname;
4381}
4382
Bram Moolenaar071d4272004-06-13 20:20:40 +00004383/*
4384 * Get a pointer to one character past the head of a path name.
4385 * Unix: after "/"; DOS: after "c:\"; Amiga: after "disk:/"; Mac: no head.
4386 * If there is no head, path is returned.
4387 */
4388 char_u *
4389get_past_head(path)
4390 char_u *path;
4391{
4392 char_u *retval;
4393
4394#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
4395 /* may skip "c:" */
4396 if (isalpha(path[0]) && path[1] == ':')
4397 retval = path + 2;
4398 else
4399 retval = path;
4400#else
4401# if defined(AMIGA)
4402 /* may skip "label:" */
4403 retval = vim_strchr(path, ':');
4404 if (retval == NULL)
4405 retval = path;
4406# else /* Unix */
4407 retval = path;
4408# endif
4409#endif
4410
4411 while (vim_ispathsep(*retval))
4412 ++retval;
4413
4414 return retval;
4415}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416
4417/*
4418 * return TRUE if 'c' is a path separator.
4419 */
4420 int
4421vim_ispathsep(c)
4422 int c;
4423{
4424#ifdef RISCOS
4425 return (c == '.' || c == ':');
4426#else
4427# ifdef UNIX
4428 return (c == '/'); /* UNIX has ':' inside file names */
4429# else
4430# ifdef BACKSLASH_IN_FILENAME
4431 return (c == ':' || c == '/' || c == '\\');
4432# else
4433# ifdef VMS
4434 /* server"user passwd"::device:[full.path.name]fname.extension;version" */
4435 return (c == ':' || c == '[' || c == ']' || c == '/'
4436 || c == '<' || c == '>' || c == '"' );
Bram Moolenaar1056d982006-03-09 22:37:52 +00004437# else /* Amiga */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004438 return (c == ':' || c == '/');
Bram Moolenaar071d4272004-06-13 20:20:40 +00004439# endif /* VMS */
4440# endif
4441# endif
4442#endif /* RISC OS */
4443}
4444
4445#if defined(FEAT_SEARCHPATH) || defined(PROTO)
4446/*
4447 * return TRUE if 'c' is a path list separator.
4448 */
4449 int
4450vim_ispathlistsep(c)
4451 int c;
4452{
4453#ifdef UNIX
4454 return (c == ':');
4455#else
4456 return (c == ';'); /* might not be rigth for every system... */
4457#endif
4458}
4459#endif
4460
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004461#if defined(FEAT_GUI_TABLINE) || defined(FEAT_WINDOWS) \
4462 || defined(FEAT_EVAL) || defined(PROTO)
4463/*
4464 * Shorten the path of a file from "~/foo/../.bar/fname" to "~/f/../.b/fname"
4465 * It's done in-place.
4466 */
4467 void
4468shorten_dir(str)
4469 char_u *str;
4470{
4471 char_u *tail, *s, *d;
4472 int skip = FALSE;
4473
4474 tail = gettail(str);
4475 d = str;
4476 for (s = str; ; ++s)
4477 {
4478 if (s >= tail) /* copy the whole tail */
4479 {
4480 *d++ = *s;
4481 if (*s == NUL)
4482 break;
4483 }
4484 else if (vim_ispathsep(*s)) /* copy '/' and next char */
4485 {
4486 *d++ = *s;
4487 skip = FALSE;
4488 }
4489 else if (!skip)
4490 {
4491 *d++ = *s; /* copy next char */
4492 if (*s != '~' && *s != '.') /* and leading "~" and "." */
4493 skip = TRUE;
4494# ifdef FEAT_MBYTE
4495 if (has_mbyte)
4496 {
4497 int l = mb_ptr2len(s);
4498
4499 while (--l > 0)
Bram Moolenaarb6baca52006-08-15 20:24:14 +00004500 *d++ = *++s;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004501 }
4502# endif
4503 }
4504 }
4505}
4506#endif
4507
Bram Moolenaar900b4d72005-12-12 22:05:50 +00004508/*
4509 * Return TRUE if the directory of "fname" exists, FALSE otherwise.
4510 * Also returns TRUE if there is no directory name.
4511 * "fname" must be writable!.
4512 */
4513 int
4514dir_of_file_exists(fname)
4515 char_u *fname;
4516{
4517 char_u *p;
4518 int c;
4519 int retval;
4520
4521 p = gettail_sep(fname);
4522 if (p == fname)
4523 return TRUE;
4524 c = *p;
4525 *p = NUL;
4526 retval = mch_isdir(fname);
4527 *p = c;
4528 return retval;
4529}
4530
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531#if (defined(CASE_INSENSITIVE_FILENAME) && defined(BACKSLASH_IN_FILENAME)) \
4532 || defined(PROTO)
4533/*
4534 * Versions of fnamecmp() and fnamencmp() that handle '/' and '\' equally.
4535 */
4536 int
4537vim_fnamecmp(x, y)
4538 char_u *x, *y;
4539{
4540 return vim_fnamencmp(x, y, MAXPATHL);
4541}
4542
4543 int
4544vim_fnamencmp(x, y, len)
4545 char_u *x, *y;
4546 size_t len;
4547{
4548 while (len > 0 && *x && *y)
4549 {
4550 if (TOLOWER_LOC(*x) != TOLOWER_LOC(*y)
4551 && !(*x == '/' && *y == '\\')
4552 && !(*x == '\\' && *y == '/'))
4553 break;
4554 ++x;
4555 ++y;
4556 --len;
4557 }
4558 if (len == 0)
4559 return 0;
4560 return (*x - *y);
4561}
4562#endif
4563
4564/*
4565 * Concatenate file names fname1 and fname2 into allocated memory.
4566 * Only add a '/' or '\\' when 'sep' is TRUE and it is neccesary.
4567 */
4568 char_u *
4569concat_fnames(fname1, fname2, sep)
4570 char_u *fname1;
4571 char_u *fname2;
4572 int sep;
4573{
4574 char_u *dest;
4575
4576 dest = alloc((unsigned)(STRLEN(fname1) + STRLEN(fname2) + 3));
4577 if (dest != NULL)
4578 {
4579 STRCPY(dest, fname1);
4580 if (sep)
4581 add_pathsep(dest);
4582 STRCAT(dest, fname2);
4583 }
4584 return dest;
4585}
4586
Bram Moolenaard6754642005-01-17 22:18:45 +00004587#if defined(FEAT_EVAL) || defined(FEAT_GETTEXT) || defined(PROTO)
4588/*
4589 * Concatenate two strings and return the result in allocated memory.
4590 * Returns NULL when out of memory.
4591 */
4592 char_u *
4593concat_str(str1, str2)
4594 char_u *str1;
4595 char_u *str2;
4596{
4597 char_u *dest;
4598 size_t l = STRLEN(str1);
4599
4600 dest = alloc((unsigned)(l + STRLEN(str2) + 1L));
4601 if (dest != NULL)
4602 {
4603 STRCPY(dest, str1);
4604 STRCPY(dest + l, str2);
4605 }
4606 return dest;
4607}
4608#endif
4609
Bram Moolenaar071d4272004-06-13 20:20:40 +00004610/*
4611 * Add a path separator to a file name, unless it already ends in a path
4612 * separator.
4613 */
4614 void
4615add_pathsep(p)
4616 char_u *p;
4617{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004618 if (*p != NUL && !after_pathsep(p, p + STRLEN(p)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619 STRCAT(p, PATHSEPSTR);
4620}
4621
4622/*
4623 * FullName_save - Make an allocated copy of a full file name.
4624 * Returns NULL when out of memory.
4625 */
4626 char_u *
4627FullName_save(fname, force)
4628 char_u *fname;
4629 int force; /* force expansion, even when it already looks
4630 like a full path name */
4631{
4632 char_u *buf;
4633 char_u *new_fname = NULL;
4634
4635 if (fname == NULL)
4636 return NULL;
4637
4638 buf = alloc((unsigned)MAXPATHL);
4639 if (buf != NULL)
4640 {
4641 if (vim_FullName(fname, buf, MAXPATHL, force) != FAIL)
4642 new_fname = vim_strsave(buf);
4643 else
4644 new_fname = vim_strsave(fname);
4645 vim_free(buf);
4646 }
4647 return new_fname;
4648}
4649
4650#if defined(FEAT_CINDENT) || defined(FEAT_SYN_HL)
4651
4652static char_u *skip_string __ARGS((char_u *p));
4653
4654/*
4655 * Find the start of a comment, not knowing if we are in a comment right now.
4656 * Search starts at w_cursor.lnum and goes backwards.
4657 */
4658 pos_T *
4659find_start_comment(ind_maxcomment) /* XXX */
4660 int ind_maxcomment;
4661{
4662 pos_T *pos;
4663 char_u *line;
4664 char_u *p;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004665 int cur_maxcomment = ind_maxcomment;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004666
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004667 for (;;)
4668 {
4669 pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
4670 if (pos == NULL)
4671 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004673 /*
4674 * Check if the comment start we found is inside a string.
4675 * If it is then restrict the search to below this line and try again.
4676 */
4677 line = ml_get(pos->lnum);
4678 for (p = line; *p && (unsigned)(p - line) < pos->col; ++p)
4679 p = skip_string(p);
4680 if ((unsigned)(p - line) <= pos->col)
4681 break;
4682 cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
4683 if (cur_maxcomment <= 0)
4684 {
4685 pos = NULL;
4686 break;
4687 }
4688 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004689 return pos;
4690}
4691
4692/*
4693 * Skip to the end of a "string" and a 'c' character.
4694 * If there is no string or character, return argument unmodified.
4695 */
4696 static char_u *
4697skip_string(p)
4698 char_u *p;
4699{
4700 int i;
4701
4702 /*
4703 * We loop, because strings may be concatenated: "date""time".
4704 */
4705 for ( ; ; ++p)
4706 {
4707 if (p[0] == '\'') /* 'c' or '\n' or '\000' */
4708 {
4709 if (!p[1]) /* ' at end of line */
4710 break;
4711 i = 2;
4712 if (p[1] == '\\') /* '\n' or '\000' */
4713 {
4714 ++i;
4715 while (vim_isdigit(p[i - 1])) /* '\000' */
4716 ++i;
4717 }
4718 if (p[i] == '\'') /* check for trailing ' */
4719 {
4720 p += i;
4721 continue;
4722 }
4723 }
4724 else if (p[0] == '"') /* start of string */
4725 {
4726 for (++p; p[0]; ++p)
4727 {
4728 if (p[0] == '\\' && p[1] != NUL)
4729 ++p;
4730 else if (p[0] == '"') /* end of string */
4731 break;
4732 }
4733 if (p[0] == '"')
4734 continue;
4735 }
4736 break; /* no string found */
4737 }
4738 if (!*p)
4739 --p; /* backup from NUL */
4740 return p;
4741}
4742#endif /* FEAT_CINDENT || FEAT_SYN_HL */
4743
4744#if defined(FEAT_CINDENT) || defined(PROTO)
4745
4746/*
4747 * Do C or expression indenting on the current line.
4748 */
4749 void
4750do_c_expr_indent()
4751{
4752# ifdef FEAT_EVAL
4753 if (*curbuf->b_p_inde != NUL)
4754 fixthisline(get_expr_indent);
4755 else
4756# endif
4757 fixthisline(get_c_indent);
4758}
4759
4760/*
4761 * Functions for C-indenting.
4762 * Most of this originally comes from Eric Fischer.
4763 */
4764/*
4765 * Below "XXX" means that this function may unlock the current line.
4766 */
4767
4768static char_u *cin_skipcomment __ARGS((char_u *));
4769static int cin_nocode __ARGS((char_u *));
4770static pos_T *find_line_comment __ARGS((void));
4771static int cin_islabel_skip __ARGS((char_u **));
4772static int cin_isdefault __ARGS((char_u *));
4773static char_u *after_label __ARGS((char_u *l));
4774static int get_indent_nolabel __ARGS((linenr_T lnum));
4775static int skip_label __ARGS((linenr_T, char_u **pp, int ind_maxcomment));
4776static int cin_first_id_amount __ARGS((void));
4777static int cin_get_equal_amount __ARGS((linenr_T lnum));
4778static int cin_ispreproc __ARGS((char_u *));
4779static int cin_ispreproc_cont __ARGS((char_u **pp, linenr_T *lnump));
4780static int cin_iscomment __ARGS((char_u *));
4781static int cin_islinecomment __ARGS((char_u *));
4782static int cin_isterminated __ARGS((char_u *, int, int));
4783static int cin_isinit __ARGS((void));
4784static int cin_isfuncdecl __ARGS((char_u **, linenr_T));
4785static int cin_isif __ARGS((char_u *));
4786static int cin_iselse __ARGS((char_u *));
4787static int cin_isdo __ARGS((char_u *));
4788static int cin_iswhileofdo __ARGS((char_u *, linenr_T, int));
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00004789static int cin_iswhileofdo_end __ARGS((int terminated, int ind_maxparen, int ind_maxcomment));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790static int cin_isbreak __ARGS((char_u *));
4791static int cin_is_cpp_baseclass __ARGS((char_u *line, colnr_T *col));
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00004792static int get_baseclass_amount __ARGS((int col, int ind_maxparen, int ind_maxcomment, int ind_cpp_baseclass));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004793static int cin_ends_in __ARGS((char_u *, char_u *, char_u *));
4794static int cin_skip2pos __ARGS((pos_T *trypos));
4795static pos_T *find_start_brace __ARGS((int));
4796static pos_T *find_match_paren __ARGS((int, int));
4797static int corr_ind_maxparen __ARGS((int ind_maxparen, pos_T *startpos));
4798static int find_last_paren __ARGS((char_u *l, int start, int end));
4799static int find_match __ARGS((int lookfor, linenr_T ourscope, int ind_maxparen, int ind_maxcomment));
4800
4801/*
4802 * Skip over white space and C comments within the line.
4803 */
4804 static char_u *
4805cin_skipcomment(s)
4806 char_u *s;
4807{
4808 while (*s)
4809 {
4810 s = skipwhite(s);
4811 if (*s != '/')
4812 break;
4813 ++s;
4814 if (*s == '/') /* slash-slash comment continues till eol */
4815 {
4816 s += STRLEN(s);
4817 break;
4818 }
4819 if (*s != '*')
4820 break;
4821 for (++s; *s; ++s) /* skip slash-star comment */
4822 if (s[0] == '*' && s[1] == '/')
4823 {
4824 s += 2;
4825 break;
4826 }
4827 }
4828 return s;
4829}
4830
4831/*
4832 * Return TRUE if there there is no code at *s. White space and comments are
4833 * not considered code.
4834 */
4835 static int
4836cin_nocode(s)
4837 char_u *s;
4838{
4839 return *cin_skipcomment(s) == NUL;
4840}
4841
4842/*
4843 * Check previous lines for a "//" line comment, skipping over blank lines.
4844 */
4845 static pos_T *
4846find_line_comment() /* XXX */
4847{
4848 static pos_T pos;
4849 char_u *line;
4850 char_u *p;
4851
4852 pos = curwin->w_cursor;
4853 while (--pos.lnum > 0)
4854 {
4855 line = ml_get(pos.lnum);
4856 p = skipwhite(line);
4857 if (cin_islinecomment(p))
4858 {
4859 pos.col = (int)(p - line);
4860 return &pos;
4861 }
4862 if (*p != NUL)
4863 break;
4864 }
4865 return NULL;
4866}
4867
4868/*
4869 * Check if string matches "label:"; move to character after ':' if true.
4870 */
4871 static int
4872cin_islabel_skip(s)
4873 char_u **s;
4874{
4875 if (!vim_isIDc(**s)) /* need at least one ID character */
4876 return FALSE;
4877
4878 while (vim_isIDc(**s))
4879 (*s)++;
4880
4881 *s = cin_skipcomment(*s);
4882
4883 /* "::" is not a label, it's C++ */
4884 return (**s == ':' && *++*s != ':');
4885}
4886
4887/*
4888 * Recognize a label: "label:".
4889 * Note: curwin->w_cursor must be where we are looking for the label.
4890 */
4891 int
4892cin_islabel(ind_maxcomment) /* XXX */
4893 int ind_maxcomment;
4894{
4895 char_u *s;
4896
4897 s = cin_skipcomment(ml_get_curline());
4898
4899 /*
4900 * Exclude "default" from labels, since it should be indented
4901 * like a switch label. Same for C++ scope declarations.
4902 */
4903 if (cin_isdefault(s))
4904 return FALSE;
4905 if (cin_isscopedecl(s))
4906 return FALSE;
4907
4908 if (cin_islabel_skip(&s))
4909 {
4910 /*
4911 * Only accept a label if the previous line is terminated or is a case
4912 * label.
4913 */
4914 pos_T cursor_save;
4915 pos_T *trypos;
4916 char_u *line;
4917
4918 cursor_save = curwin->w_cursor;
4919 while (curwin->w_cursor.lnum > 1)
4920 {
4921 --curwin->w_cursor.lnum;
4922
4923 /*
4924 * If we're in a comment now, skip to the start of the comment.
4925 */
4926 curwin->w_cursor.col = 0;
4927 if ((trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
4928 curwin->w_cursor = *trypos;
4929
4930 line = ml_get_curline();
4931 if (cin_ispreproc(line)) /* ignore #defines, #if, etc. */
4932 continue;
4933 if (*(line = cin_skipcomment(line)) == NUL)
4934 continue;
4935
4936 curwin->w_cursor = cursor_save;
4937 if (cin_isterminated(line, TRUE, FALSE)
4938 || cin_isscopedecl(line)
4939 || cin_iscase(line)
4940 || (cin_islabel_skip(&line) && cin_nocode(line)))
4941 return TRUE;
4942 return FALSE;
4943 }
4944 curwin->w_cursor = cursor_save;
4945 return TRUE; /* label at start of file??? */
4946 }
4947 return FALSE;
4948}
4949
4950/*
4951 * Recognize structure initialization and enumerations.
4952 * Q&D-Implementation:
4953 * check for "=" at end or "[typedef] enum" at beginning of line.
4954 */
4955 static int
4956cin_isinit(void)
4957{
4958 char_u *s;
4959
4960 s = cin_skipcomment(ml_get_curline());
4961
4962 if (STRNCMP(s, "typedef", 7) == 0 && !vim_isIDc(s[7]))
4963 s = cin_skipcomment(s + 7);
4964
4965 if (STRNCMP(s, "enum", 4) == 0 && !vim_isIDc(s[4]))
4966 return TRUE;
4967
4968 if (cin_ends_in(s, (char_u *)"=", (char_u *)"{"))
4969 return TRUE;
4970
4971 return FALSE;
4972}
4973
4974/*
4975 * Recognize a switch label: "case .*:" or "default:".
4976 */
4977 int
4978cin_iscase(s)
4979 char_u *s;
4980{
4981 s = cin_skipcomment(s);
4982 if (STRNCMP(s, "case", 4) == 0 && !vim_isIDc(s[4]))
4983 {
4984 for (s += 4; *s; ++s)
4985 {
4986 s = cin_skipcomment(s);
4987 if (*s == ':')
4988 {
4989 if (s[1] == ':') /* skip over "::" for C++ */
4990 ++s;
4991 else
4992 return TRUE;
4993 }
4994 if (*s == '\'' && s[1] && s[2] == '\'')
4995 s += 2; /* skip over '.' */
4996 else if (*s == '/' && (s[1] == '*' || s[1] == '/'))
4997 return FALSE; /* stop at comment */
4998 else if (*s == '"')
4999 return FALSE; /* stop at string */
5000 }
5001 return FALSE;
5002 }
5003
5004 if (cin_isdefault(s))
5005 return TRUE;
5006 return FALSE;
5007}
5008
5009/*
5010 * Recognize a "default" switch label.
5011 */
5012 static int
5013cin_isdefault(s)
5014 char_u *s;
5015{
5016 return (STRNCMP(s, "default", 7) == 0
5017 && *(s = cin_skipcomment(s + 7)) == ':'
5018 && s[1] != ':');
5019}
5020
5021/*
5022 * Recognize a "public/private/proctected" scope declaration label.
5023 */
5024 int
5025cin_isscopedecl(s)
5026 char_u *s;
5027{
5028 int i;
5029
5030 s = cin_skipcomment(s);
5031 if (STRNCMP(s, "public", 6) == 0)
5032 i = 6;
5033 else if (STRNCMP(s, "protected", 9) == 0)
5034 i = 9;
5035 else if (STRNCMP(s, "private", 7) == 0)
5036 i = 7;
5037 else
5038 return FALSE;
5039 return (*(s = cin_skipcomment(s + i)) == ':' && s[1] != ':');
5040}
5041
5042/*
5043 * Return a pointer to the first non-empty non-comment character after a ':'.
5044 * Return NULL if not found.
5045 * case 234: a = b;
5046 * ^
5047 */
5048 static char_u *
5049after_label(l)
5050 char_u *l;
5051{
5052 for ( ; *l; ++l)
5053 {
5054 if (*l == ':')
5055 {
5056 if (l[1] == ':') /* skip over "::" for C++ */
5057 ++l;
5058 else if (!cin_iscase(l + 1))
5059 break;
5060 }
5061 else if (*l == '\'' && l[1] && l[2] == '\'')
5062 l += 2; /* skip over 'x' */
5063 }
5064 if (*l == NUL)
5065 return NULL;
5066 l = cin_skipcomment(l + 1);
5067 if (*l == NUL)
5068 return NULL;
5069 return l;
5070}
5071
5072/*
5073 * Get indent of line "lnum", skipping a label.
5074 * Return 0 if there is nothing after the label.
5075 */
5076 static int
5077get_indent_nolabel(lnum) /* XXX */
5078 linenr_T lnum;
5079{
5080 char_u *l;
5081 pos_T fp;
5082 colnr_T col;
5083 char_u *p;
5084
5085 l = ml_get(lnum);
5086 p = after_label(l);
5087 if (p == NULL)
5088 return 0;
5089
5090 fp.col = (colnr_T)(p - l);
5091 fp.lnum = lnum;
5092 getvcol(curwin, &fp, &col, NULL, NULL);
5093 return (int)col;
5094}
5095
5096/*
5097 * Find indent for line "lnum", ignoring any case or jump label.
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005098 * Also return a pointer to the text (after the label) in "pp".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005099 * label: if (asdf && asdfasdf)
5100 * ^
5101 */
5102 static int
5103skip_label(lnum, pp, ind_maxcomment)
5104 linenr_T lnum;
5105 char_u **pp;
5106 int ind_maxcomment;
5107{
5108 char_u *l;
5109 int amount;
5110 pos_T cursor_save;
5111
5112 cursor_save = curwin->w_cursor;
5113 curwin->w_cursor.lnum = lnum;
5114 l = ml_get_curline();
5115 /* XXX */
5116 if (cin_iscase(l) || cin_isscopedecl(l) || cin_islabel(ind_maxcomment))
5117 {
5118 amount = get_indent_nolabel(lnum);
5119 l = after_label(ml_get_curline());
5120 if (l == NULL) /* just in case */
5121 l = ml_get_curline();
5122 }
5123 else
5124 {
5125 amount = get_indent();
5126 l = ml_get_curline();
5127 }
5128 *pp = l;
5129
5130 curwin->w_cursor = cursor_save;
5131 return amount;
5132}
5133
5134/*
5135 * Return the indent of the first variable name after a type in a declaration.
5136 * int a, indent of "a"
5137 * static struct foo b, indent of "b"
5138 * enum bla c, indent of "c"
5139 * Returns zero when it doesn't look like a declaration.
5140 */
5141 static int
5142cin_first_id_amount()
5143{
5144 char_u *line, *p, *s;
5145 int len;
5146 pos_T fp;
5147 colnr_T col;
5148
5149 line = ml_get_curline();
5150 p = skipwhite(line);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005151 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005152 if (len == 6 && STRNCMP(p, "static", 6) == 0)
5153 {
5154 p = skipwhite(p + 6);
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005155 len = (int)(skiptowhite(p) - p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005156 }
5157 if (len == 6 && STRNCMP(p, "struct", 6) == 0)
5158 p = skipwhite(p + 6);
5159 else if (len == 4 && STRNCMP(p, "enum", 4) == 0)
5160 p = skipwhite(p + 4);
5161 else if ((len == 8 && STRNCMP(p, "unsigned", 8) == 0)
5162 || (len == 6 && STRNCMP(p, "signed", 6) == 0))
5163 {
5164 s = skipwhite(p + len);
5165 if ((STRNCMP(s, "int", 3) == 0 && vim_iswhite(s[3]))
5166 || (STRNCMP(s, "long", 4) == 0 && vim_iswhite(s[4]))
5167 || (STRNCMP(s, "short", 5) == 0 && vim_iswhite(s[5]))
5168 || (STRNCMP(s, "char", 4) == 0 && vim_iswhite(s[4])))
5169 p = s;
5170 }
5171 for (len = 0; vim_isIDc(p[len]); ++len)
5172 ;
5173 if (len == 0 || !vim_iswhite(p[len]) || cin_nocode(p))
5174 return 0;
5175
5176 p = skipwhite(p + len);
5177 fp.lnum = curwin->w_cursor.lnum;
5178 fp.col = (colnr_T)(p - line);
5179 getvcol(curwin, &fp, &col, NULL, NULL);
5180 return (int)col;
5181}
5182
5183/*
5184 * Return the indent of the first non-blank after an equal sign.
5185 * char *foo = "here";
5186 * Return zero if no (useful) equal sign found.
5187 * Return -1 if the line above "lnum" ends in a backslash.
5188 * foo = "asdf\
5189 * asdf\
5190 * here";
5191 */
5192 static int
5193cin_get_equal_amount(lnum)
5194 linenr_T lnum;
5195{
5196 char_u *line;
5197 char_u *s;
5198 colnr_T col;
5199 pos_T fp;
5200
5201 if (lnum > 1)
5202 {
5203 line = ml_get(lnum - 1);
5204 if (*line != NUL && line[STRLEN(line) - 1] == '\\')
5205 return -1;
5206 }
5207
5208 line = s = ml_get(lnum);
5209 while (*s != NUL && vim_strchr((char_u *)"=;{}\"'", *s) == NULL)
5210 {
5211 if (cin_iscomment(s)) /* ignore comments */
5212 s = cin_skipcomment(s);
5213 else
5214 ++s;
5215 }
5216 if (*s != '=')
5217 return 0;
5218
5219 s = skipwhite(s + 1);
5220 if (cin_nocode(s))
5221 return 0;
5222
5223 if (*s == '"') /* nice alignment for continued strings */
5224 ++s;
5225
5226 fp.lnum = lnum;
5227 fp.col = (colnr_T)(s - line);
5228 getvcol(curwin, &fp, &col, NULL, NULL);
5229 return (int)col;
5230}
5231
5232/*
5233 * Recognize a preprocessor statement: Any line that starts with '#'.
5234 */
5235 static int
5236cin_ispreproc(s)
5237 char_u *s;
5238{
5239 s = skipwhite(s);
5240 if (*s == '#')
5241 return TRUE;
5242 return FALSE;
5243}
5244
5245/*
5246 * Return TRUE if line "*pp" at "*lnump" is a preprocessor statement or a
5247 * continuation line of a preprocessor statement. Decrease "*lnump" to the
5248 * start and return the line in "*pp".
5249 */
5250 static int
5251cin_ispreproc_cont(pp, lnump)
5252 char_u **pp;
5253 linenr_T *lnump;
5254{
5255 char_u *line = *pp;
5256 linenr_T lnum = *lnump;
5257 int retval = FALSE;
5258
Bram Moolenaard8e9bb22005-07-09 21:14:46 +00005259 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005260 {
5261 if (cin_ispreproc(line))
5262 {
5263 retval = TRUE;
5264 *lnump = lnum;
5265 break;
5266 }
5267 if (lnum == 1)
5268 break;
5269 line = ml_get(--lnum);
5270 if (*line == NUL || line[STRLEN(line) - 1] != '\\')
5271 break;
5272 }
5273
5274 if (lnum != *lnump)
5275 *pp = ml_get(*lnump);
5276 return retval;
5277}
5278
5279/*
5280 * Recognize the start of a C or C++ comment.
5281 */
5282 static int
5283cin_iscomment(p)
5284 char_u *p;
5285{
5286 return (p[0] == '/' && (p[1] == '*' || p[1] == '/'));
5287}
5288
5289/*
5290 * Recognize the start of a "//" comment.
5291 */
5292 static int
5293cin_islinecomment(p)
5294 char_u *p;
5295{
5296 return (p[0] == '/' && p[1] == '/');
5297}
5298
5299/*
5300 * Recognize a line that starts with '{' or '}', or ends with ';', '{' or '}'.
5301 * Don't consider "} else" a terminated line.
5302 * Return the character terminating the line (ending char's have precedence if
5303 * both apply in order to determine initializations).
5304 */
5305 static int
5306cin_isterminated(s, incl_open, incl_comma)
5307 char_u *s;
5308 int incl_open; /* include '{' at the end as terminator */
5309 int incl_comma; /* recognize a trailing comma */
5310{
5311 char_u found_start = 0;
5312
5313 s = cin_skipcomment(s);
5314
5315 if (*s == '{' || (*s == '}' && !cin_iselse(s)))
5316 found_start = *s;
5317
5318 while (*s)
5319 {
5320 /* skip over comments, "" strings and 'c'haracters */
5321 s = skip_string(cin_skipcomment(s));
5322 if ((*s == ';' || (incl_open && *s == '{') || *s == '}'
5323 || (incl_comma && *s == ','))
5324 && cin_nocode(s + 1))
5325 return *s;
5326
5327 if (*s)
5328 s++;
5329 }
5330 return found_start;
5331}
5332
5333/*
5334 * Recognize the basic picture of a function declaration -- it needs to
5335 * have an open paren somewhere and a close paren at the end of the line and
5336 * no semicolons anywhere.
5337 * When a line ends in a comma we continue looking in the next line.
5338 * "sp" points to a string with the line. When looking at other lines it must
5339 * be restored to the line. When it's NULL fetch lines here.
5340 * "lnum" is where we start looking.
5341 */
5342 static int
5343cin_isfuncdecl(sp, first_lnum)
5344 char_u **sp;
5345 linenr_T first_lnum;
5346{
5347 char_u *s;
5348 linenr_T lnum = first_lnum;
5349 int retval = FALSE;
5350
5351 if (sp == NULL)
5352 s = ml_get(lnum);
5353 else
5354 s = *sp;
5355
5356 while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"')
5357 {
5358 if (cin_iscomment(s)) /* ignore comments */
5359 s = cin_skipcomment(s);
5360 else
5361 ++s;
5362 }
5363 if (*s != '(')
5364 return FALSE; /* ';', ' or " before any () or no '(' */
5365
5366 while (*s && *s != ';' && *s != '\'' && *s != '"')
5367 {
5368 if (*s == ')' && cin_nocode(s + 1))
5369 {
5370 /* ')' at the end: may have found a match
5371 * Check for he previous line not to end in a backslash:
5372 * #if defined(x) && \
5373 * defined(y)
5374 */
5375 lnum = first_lnum - 1;
5376 s = ml_get(lnum);
5377 if (*s == NUL || s[STRLEN(s) - 1] != '\\')
5378 retval = TRUE;
5379 goto done;
5380 }
5381 if (*s == ',' && cin_nocode(s + 1))
5382 {
5383 /* ',' at the end: continue looking in the next line */
5384 if (lnum >= curbuf->b_ml.ml_line_count)
5385 break;
5386
5387 s = ml_get(++lnum);
5388 }
5389 else if (cin_iscomment(s)) /* ignore comments */
5390 s = cin_skipcomment(s);
5391 else
5392 ++s;
5393 }
5394
5395done:
5396 if (lnum != first_lnum && sp != NULL)
5397 *sp = ml_get(first_lnum);
5398
5399 return retval;
5400}
5401
5402 static int
5403cin_isif(p)
5404 char_u *p;
5405{
5406 return (STRNCMP(p, "if", 2) == 0 && !vim_isIDc(p[2]));
5407}
5408
5409 static int
5410cin_iselse(p)
5411 char_u *p;
5412{
5413 if (*p == '}') /* accept "} else" */
5414 p = cin_skipcomment(p + 1);
5415 return (STRNCMP(p, "else", 4) == 0 && !vim_isIDc(p[4]));
5416}
5417
5418 static int
5419cin_isdo(p)
5420 char_u *p;
5421{
5422 return (STRNCMP(p, "do", 2) == 0 && !vim_isIDc(p[2]));
5423}
5424
5425/*
5426 * Check if this is a "while" that should have a matching "do".
5427 * We only accept a "while (condition) ;", with only white space between the
5428 * ')' and ';'. The condition may be spread over several lines.
5429 */
5430 static int
5431cin_iswhileofdo(p, lnum, ind_maxparen) /* XXX */
5432 char_u *p;
5433 linenr_T lnum;
5434 int ind_maxparen;
5435{
5436 pos_T cursor_save;
5437 pos_T *trypos;
5438 int retval = FALSE;
5439
5440 p = cin_skipcomment(p);
5441 if (*p == '}') /* accept "} while (cond);" */
5442 p = cin_skipcomment(p + 1);
5443 if (STRNCMP(p, "while", 5) == 0 && !vim_isIDc(p[5]))
5444 {
5445 cursor_save = curwin->w_cursor;
5446 curwin->w_cursor.lnum = lnum;
5447 curwin->w_cursor.col = 0;
5448 p = ml_get_curline();
5449 while (*p && *p != 'w') /* skip any '}', until the 'w' of the "while" */
5450 {
5451 ++p;
5452 ++curwin->w_cursor.col;
5453 }
5454 if ((trypos = findmatchlimit(NULL, 0, 0, ind_maxparen)) != NULL
5455 && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';')
5456 retval = TRUE;
5457 curwin->w_cursor = cursor_save;
5458 }
5459 return retval;
5460}
5461
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005462/*
5463 * Return TRUE if we are at the end of a do-while.
5464 * do
5465 * nothing;
5466 * while (foo
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005467 * && bar); <-- here
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005468 * Adjust the cursor to the line with "while".
5469 */
5470 static int
5471cin_iswhileofdo_end(terminated, ind_maxparen, ind_maxcomment)
5472 int terminated;
5473 int ind_maxparen;
5474 int ind_maxcomment;
5475{
5476 char_u *line;
5477 char_u *p;
5478 char_u *s;
5479 pos_T *trypos;
5480 int i;
5481
5482 if (terminated != ';') /* there must be a ';' at the end */
5483 return FALSE;
5484
5485 p = line = ml_get_curline();
5486 while (*p != NUL)
5487 {
5488 p = cin_skipcomment(p);
5489 if (*p == ')')
5490 {
5491 s = skipwhite(p + 1);
5492 if (*s == ';' && cin_nocode(s + 1))
5493 {
5494 /* Found ");" at end of the line, now check there is "while"
5495 * before the matching '('. XXX */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005496 i = (int)(p - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005497 curwin->w_cursor.col = i;
5498 trypos = find_match_paren(ind_maxparen, ind_maxcomment);
5499 if (trypos != NULL)
5500 {
5501 s = cin_skipcomment(ml_get(trypos->lnum));
5502 if (*s == '}') /* accept "} while (cond);" */
5503 s = cin_skipcomment(s + 1);
5504 if (STRNCMP(s, "while", 5) == 0 && !vim_isIDc(s[5]))
5505 {
5506 curwin->w_cursor.lnum = trypos->lnum;
5507 return TRUE;
5508 }
5509 }
5510
5511 /* Searching may have made "line" invalid, get it again. */
5512 line = ml_get_curline();
5513 p = line + i;
5514 }
5515 }
5516 if (*p != NUL)
5517 ++p;
5518 }
5519 return FALSE;
5520}
5521
Bram Moolenaar071d4272004-06-13 20:20:40 +00005522 static int
5523cin_isbreak(p)
5524 char_u *p;
5525{
5526 return (STRNCMP(p, "break", 5) == 0 && !vim_isIDc(p[5]));
5527}
5528
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005529/*
5530 * Find the position of a C++ base-class declaration or
Bram Moolenaar071d4272004-06-13 20:20:40 +00005531 * constructor-initialization. eg:
5532 *
5533 * class MyClass :
5534 * baseClass <-- here
5535 * class MyClass : public baseClass,
5536 * anotherBaseClass <-- here (should probably lineup ??)
5537 * MyClass::MyClass(...) :
5538 * baseClass(...) <-- here (constructor-initialization)
Bram Moolenaar18144c82006-04-12 21:52:12 +00005539 *
5540 * This is a lot of guessing. Watch out for "cond ? func() : foo".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005541 */
5542 static int
5543cin_is_cpp_baseclass(line, col)
5544 char_u *line;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005545 colnr_T *col; /* return: column to align with */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005546{
5547 char_u *s;
5548 int class_or_struct, lookfor_ctor_init, cpp_base_class;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005549 linenr_T lnum = curwin->w_cursor.lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550
5551 *col = 0;
5552
Bram Moolenaar21cf8232004-07-16 20:18:37 +00005553 s = skipwhite(line);
5554 if (*s == '#') /* skip #define FOO x ? (x) : x */
5555 return FALSE;
5556 s = cin_skipcomment(s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557 if (*s == NUL)
5558 return FALSE;
5559
5560 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5561
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005562 /* Search for a line starting with '#', empty, ending in ';' or containing
5563 * '{' or '}' and start below it. This handles the following situations:
5564 * a = cond ?
5565 * func() :
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00005566 * asdf;
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005567 * func::foo()
5568 * : something
5569 * {}
5570 * Foo::Foo (int one, int two)
5571 * : something(4),
5572 * somethingelse(3)
5573 * {}
5574 */
5575 while (lnum > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005576 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005577 s = skipwhite(ml_get(lnum - 1));
5578 if (*s == '#' || *s == NUL)
5579 break;
5580 while (*s != NUL)
5581 {
5582 s = cin_skipcomment(s);
5583 if (*s == '{' || *s == '}'
5584 || (*s == ';' && cin_nocode(s + 1)))
5585 break;
5586 if (*s != NUL)
5587 ++s;
5588 }
5589 if (*s != NUL)
5590 break;
5591 --lnum;
5592 }
5593
5594 s = cin_skipcomment(ml_get(lnum));
5595 for (;;)
5596 {
5597 if (*s == NUL)
5598 {
5599 if (lnum == curwin->w_cursor.lnum)
5600 break;
5601 /* Continue in the cursor line. */
5602 s = cin_skipcomment(ml_get(++lnum));
5603 }
5604
Bram Moolenaar071d4272004-06-13 20:20:40 +00005605 if (s[0] == ':')
5606 {
5607 if (s[1] == ':')
5608 {
5609 /* skip double colon. It can't be a constructor
5610 * initialization any more */
5611 lookfor_ctor_init = FALSE;
5612 s = cin_skipcomment(s + 2);
5613 }
5614 else if (lookfor_ctor_init || class_or_struct)
5615 {
5616 /* we have something found, that looks like the start of
5617 * cpp-base-class-declaration or contructor-initialization */
5618 cpp_base_class = TRUE;
5619 lookfor_ctor_init = class_or_struct = FALSE;
5620 *col = 0;
5621 s = cin_skipcomment(s + 1);
5622 }
5623 else
5624 s = cin_skipcomment(s + 1);
5625 }
5626 else if ((STRNCMP(s, "class", 5) == 0 && !vim_isIDc(s[5]))
5627 || (STRNCMP(s, "struct", 6) == 0 && !vim_isIDc(s[6])))
5628 {
5629 class_or_struct = TRUE;
5630 lookfor_ctor_init = FALSE;
5631
5632 if (*s == 'c')
5633 s = cin_skipcomment(s + 5);
5634 else
5635 s = cin_skipcomment(s + 6);
5636 }
5637 else
5638 {
5639 if (s[0] == '{' || s[0] == '}' || s[0] == ';')
5640 {
5641 cpp_base_class = lookfor_ctor_init = class_or_struct = FALSE;
5642 }
5643 else if (s[0] == ')')
5644 {
5645 /* Constructor-initialization is assumed if we come across
5646 * something like "):" */
5647 class_or_struct = FALSE;
5648 lookfor_ctor_init = TRUE;
5649 }
Bram Moolenaar18144c82006-04-12 21:52:12 +00005650 else if (s[0] == '?')
5651 {
5652 /* Avoid seeing '() :' after '?' as constructor init. */
5653 return FALSE;
5654 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005655 else if (!vim_isIDc(s[0]))
5656 {
5657 /* if it is not an identifier, we are wrong */
5658 class_or_struct = FALSE;
5659 lookfor_ctor_init = FALSE;
5660 }
5661 else if (*col == 0)
5662 {
5663 /* it can't be a constructor-initialization any more */
5664 lookfor_ctor_init = FALSE;
5665
5666 /* the first statement starts here: lineup with this one... */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005667 if (cpp_base_class)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005668 *col = (colnr_T)(s - line);
5669 }
5670
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005671 /* When the line ends in a comma don't align with it. */
5672 if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1))
5673 *col = 0;
5674
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675 s = cin_skipcomment(s + 1);
5676 }
5677 }
5678
5679 return cpp_base_class;
5680}
5681
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00005682 static int
5683get_baseclass_amount(col, ind_maxparen, ind_maxcomment, ind_cpp_baseclass)
5684 int col;
5685 int ind_maxparen;
5686 int ind_maxcomment;
5687 int ind_cpp_baseclass;
5688{
5689 int amount;
5690 colnr_T vcol;
5691 pos_T *trypos;
5692
5693 if (col == 0)
5694 {
5695 amount = get_indent();
5696 if (find_last_paren(ml_get_curline(), '(', ')')
5697 && (trypos = find_match_paren(ind_maxparen,
5698 ind_maxcomment)) != NULL)
5699 amount = get_indent_lnum(trypos->lnum); /* XXX */
5700 if (!cin_ends_in(ml_get_curline(), (char_u *)",", NULL))
5701 amount += ind_cpp_baseclass;
5702 }
5703 else
5704 {
5705 curwin->w_cursor.col = col;
5706 getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL);
5707 amount = (int)vcol;
5708 }
5709 if (amount < ind_cpp_baseclass)
5710 amount = ind_cpp_baseclass;
5711 return amount;
5712}
5713
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714/*
5715 * Return TRUE if string "s" ends with the string "find", possibly followed by
5716 * white space and comments. Skip strings and comments.
5717 * Ignore "ignore" after "find" if it's not NULL.
5718 */
5719 static int
5720cin_ends_in(s, find, ignore)
5721 char_u *s;
5722 char_u *find;
5723 char_u *ignore;
5724{
5725 char_u *p = s;
5726 char_u *r;
5727 int len = (int)STRLEN(find);
5728
5729 while (*p != NUL)
5730 {
5731 p = cin_skipcomment(p);
5732 if (STRNCMP(p, find, len) == 0)
5733 {
5734 r = skipwhite(p + len);
5735 if (ignore != NULL && STRNCMP(r, ignore, STRLEN(ignore)) == 0)
5736 r = skipwhite(r + STRLEN(ignore));
5737 if (cin_nocode(r))
5738 return TRUE;
5739 }
5740 if (*p != NUL)
5741 ++p;
5742 }
5743 return FALSE;
5744}
5745
5746/*
5747 * Skip strings, chars and comments until at or past "trypos".
5748 * Return the column found.
5749 */
5750 static int
5751cin_skip2pos(trypos)
5752 pos_T *trypos;
5753{
5754 char_u *line;
5755 char_u *p;
5756
5757 p = line = ml_get(trypos->lnum);
5758 while (*p && (colnr_T)(p - line) < trypos->col)
5759 {
5760 if (cin_iscomment(p))
5761 p = cin_skipcomment(p);
5762 else
5763 {
5764 p = skip_string(p);
5765 ++p;
5766 }
5767 }
5768 return (int)(p - line);
5769}
5770
5771/*
5772 * Find the '{' at the start of the block we are in.
5773 * Return NULL if no match found.
5774 * Ignore a '{' that is in a comment, makes indenting the next three lines
5775 * work. */
5776/* foo() */
5777/* { */
5778/* } */
5779
5780 static pos_T *
5781find_start_brace(ind_maxcomment) /* XXX */
5782 int ind_maxcomment;
5783{
5784 pos_T cursor_save;
5785 pos_T *trypos;
5786 pos_T *pos;
5787 static pos_T pos_copy;
5788
5789 cursor_save = curwin->w_cursor;
5790 while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP, 0)) != NULL)
5791 {
5792 pos_copy = *trypos; /* copy pos_T, next findmatch will change it */
5793 trypos = &pos_copy;
5794 curwin->w_cursor = *trypos;
5795 pos = NULL;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005796 /* ignore the { if it's in a // or / * * / comment */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 if ((colnr_T)cin_skip2pos(trypos) == trypos->col
5798 && (pos = find_start_comment(ind_maxcomment)) == NULL) /* XXX */
5799 break;
5800 if (pos != NULL)
5801 curwin->w_cursor.lnum = pos->lnum;
5802 }
5803 curwin->w_cursor = cursor_save;
5804 return trypos;
5805}
5806
5807/*
5808 * Find the matching '(', failing if it is in a comment.
5809 * Return NULL of no match found.
5810 */
5811 static pos_T *
5812find_match_paren(ind_maxparen, ind_maxcomment) /* XXX */
5813 int ind_maxparen;
5814 int ind_maxcomment;
5815{
5816 pos_T cursor_save;
5817 pos_T *trypos;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00005818 static pos_T pos_copy;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005819
5820 cursor_save = curwin->w_cursor;
5821 if ((trypos = findmatchlimit(NULL, '(', 0, ind_maxparen)) != NULL)
5822 {
5823 /* check if the ( is in a // comment */
5824 if ((colnr_T)cin_skip2pos(trypos) > trypos->col)
5825 trypos = NULL;
5826 else
5827 {
5828 pos_copy = *trypos; /* copy trypos, findmatch will change it */
5829 trypos = &pos_copy;
5830 curwin->w_cursor = *trypos;
5831 if (find_start_comment(ind_maxcomment) != NULL) /* XXX */
5832 trypos = NULL;
5833 }
5834 }
5835 curwin->w_cursor = cursor_save;
5836 return trypos;
5837}
5838
5839/*
5840 * Return ind_maxparen corrected for the difference in line number between the
5841 * cursor position and "startpos". This makes sure that searching for a
5842 * matching paren above the cursor line doesn't find a match because of
5843 * looking a few lines further.
5844 */
5845 static int
5846corr_ind_maxparen(ind_maxparen, startpos)
5847 int ind_maxparen;
5848 pos_T *startpos;
5849{
5850 long n = (long)startpos->lnum - (long)curwin->w_cursor.lnum;
5851
5852 if (n > 0 && n < ind_maxparen / 2)
5853 return ind_maxparen - (int)n;
5854 return ind_maxparen;
5855}
5856
5857/*
5858 * Set w_cursor.col to the column number of the last unmatched ')' or '{' in
5859 * line "l".
5860 */
5861 static int
5862find_last_paren(l, start, end)
5863 char_u *l;
5864 int start, end;
5865{
5866 int i;
5867 int retval = FALSE;
5868 int open_count = 0;
5869
5870 curwin->w_cursor.col = 0; /* default is start of line */
5871
5872 for (i = 0; l[i]; i++)
5873 {
5874 i = (int)(cin_skipcomment(l + i) - l); /* ignore parens in comments */
5875 i = (int)(skip_string(l + i) - l); /* ignore parens in quotes */
5876 if (l[i] == start)
5877 ++open_count;
5878 else if (l[i] == end)
5879 {
5880 if (open_count > 0)
5881 --open_count;
5882 else
5883 {
5884 curwin->w_cursor.col = i;
5885 retval = TRUE;
5886 }
5887 }
5888 }
5889 return retval;
5890}
5891
5892 int
5893get_c_indent()
5894{
5895 /*
5896 * spaces from a block's opening brace the prevailing indent for that
5897 * block should be
5898 */
5899 int ind_level = curbuf->b_p_sw;
5900
5901 /*
5902 * spaces from the edge of the line an open brace that's at the end of a
5903 * line is imagined to be.
5904 */
5905 int ind_open_imag = 0;
5906
5907 /*
5908 * spaces from the prevailing indent for a line that is not precededof by
5909 * an opening brace.
5910 */
5911 int ind_no_brace = 0;
5912
5913 /*
5914 * column where the first { of a function should be located }
5915 */
5916 int ind_first_open = 0;
5917
5918 /*
5919 * spaces from the prevailing indent a leftmost open brace should be
5920 * located
5921 */
5922 int ind_open_extra = 0;
5923
5924 /*
5925 * spaces from the matching open brace (real location for one at the left
5926 * edge; imaginary location from one that ends a line) the matching close
5927 * brace should be located
5928 */
5929 int ind_close_extra = 0;
5930
5931 /*
5932 * spaces from the edge of the line an open brace sitting in the leftmost
5933 * column is imagined to be
5934 */
5935 int ind_open_left_imag = 0;
5936
5937 /*
5938 * spaces from the switch() indent a "case xx" label should be located
5939 */
5940 int ind_case = curbuf->b_p_sw;
5941
5942 /*
5943 * spaces from the "case xx:" code after a switch() should be located
5944 */
5945 int ind_case_code = curbuf->b_p_sw;
5946
5947 /*
5948 * lineup break at end of case in switch() with case label
5949 */
5950 int ind_case_break = 0;
5951
5952 /*
5953 * spaces from the class declaration indent a scope declaration label
5954 * should be located
5955 */
5956 int ind_scopedecl = curbuf->b_p_sw;
5957
5958 /*
5959 * spaces from the scope declaration label code should be located
5960 */
5961 int ind_scopedecl_code = curbuf->b_p_sw;
5962
5963 /*
5964 * amount K&R-style parameters should be indented
5965 */
5966 int ind_param = curbuf->b_p_sw;
5967
5968 /*
5969 * amount a function type spec should be indented
5970 */
5971 int ind_func_type = curbuf->b_p_sw;
5972
5973 /*
5974 * amount a cpp base class declaration or constructor initialization
5975 * should be indented
5976 */
5977 int ind_cpp_baseclass = curbuf->b_p_sw;
5978
5979 /*
5980 * additional spaces beyond the prevailing indent a continuation line
5981 * should be located
5982 */
5983 int ind_continuation = curbuf->b_p_sw;
5984
5985 /*
5986 * spaces from the indent of the line with an unclosed parentheses
5987 */
5988 int ind_unclosed = curbuf->b_p_sw * 2;
5989
5990 /*
5991 * spaces from the indent of the line with an unclosed parentheses, which
5992 * itself is also unclosed
5993 */
5994 int ind_unclosed2 = curbuf->b_p_sw;
5995
5996 /*
5997 * suppress ignoring spaces from the indent of a line starting with an
5998 * unclosed parentheses.
5999 */
6000 int ind_unclosed_noignore = 0;
6001
6002 /*
6003 * If the opening paren is the last nonwhite character on the line, and
6004 * ind_unclosed_wrapped is nonzero, use this indent relative to the outer
6005 * context (for very long lines).
6006 */
6007 int ind_unclosed_wrapped = 0;
6008
6009 /*
6010 * suppress ignoring white space when lining up with the character after
6011 * an unclosed parentheses.
6012 */
6013 int ind_unclosed_whiteok = 0;
6014
6015 /*
6016 * indent a closing parentheses under the line start of the matching
6017 * opening parentheses.
6018 */
6019 int ind_matching_paren = 0;
6020
6021 /*
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006022 * indent a closing parentheses under the previous line.
6023 */
6024 int ind_paren_prev = 0;
6025
6026 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027 * Extra indent for comments.
6028 */
6029 int ind_comment = 0;
6030
6031 /*
6032 * spaces from the comment opener when there is nothing after it.
6033 */
6034 int ind_in_comment = 3;
6035
6036 /*
6037 * boolean: if non-zero, use ind_in_comment even if there is something
6038 * after the comment opener.
6039 */
6040 int ind_in_comment2 = 0;
6041
6042 /*
6043 * max lines to search for an open paren
6044 */
6045 int ind_maxparen = 20;
6046
6047 /*
6048 * max lines to search for an open comment
6049 */
6050 int ind_maxcomment = 70;
6051
6052 /*
6053 * handle braces for java code
6054 */
6055 int ind_java = 0;
6056
6057 /*
6058 * handle blocked cases correctly
6059 */
6060 int ind_keep_case_label = 0;
6061
6062 pos_T cur_curpos;
6063 int amount;
6064 int scope_amount;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006065 int cur_amount = MAXCOL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066 colnr_T col;
6067 char_u *theline;
6068 char_u *linecopy;
6069 pos_T *trypos;
6070 pos_T *tryposBrace = NULL;
6071 pos_T our_paren_pos;
6072 char_u *start;
6073 int start_brace;
6074#define BRACE_IN_COL0 1 /* '{' is in comumn 0 */
6075#define BRACE_AT_START 2 /* '{' is at start of line */
6076#define BRACE_AT_END 3 /* '{' is at end of line */
6077 linenr_T ourscope;
6078 char_u *l;
6079 char_u *look;
6080 char_u terminated;
6081 int lookfor;
6082#define LOOKFOR_INITIAL 0
6083#define LOOKFOR_IF 1
6084#define LOOKFOR_DO 2
6085#define LOOKFOR_CASE 3
6086#define LOOKFOR_ANY 4
6087#define LOOKFOR_TERM 5
6088#define LOOKFOR_UNTERM 6
6089#define LOOKFOR_SCOPEDECL 7
6090#define LOOKFOR_NOBREAK 8
6091#define LOOKFOR_CPP_BASECLASS 9
6092#define LOOKFOR_ENUM_OR_INIT 10
6093
6094 int whilelevel;
6095 linenr_T lnum;
6096 char_u *options;
6097 int fraction = 0; /* init for GCC */
6098 int divider;
6099 int n;
6100 int iscase;
6101 int lookfor_break;
6102 int cont_amount = 0; /* amount for continuation line */
6103
6104 for (options = curbuf->b_p_cino; *options; )
6105 {
6106 l = options++;
6107 if (*options == '-')
6108 ++options;
6109 n = getdigits(&options);
6110 divider = 0;
6111 if (*options == '.') /* ".5s" means a fraction */
6112 {
6113 fraction = atol((char *)++options);
6114 while (VIM_ISDIGIT(*options))
6115 {
6116 ++options;
6117 if (divider)
6118 divider *= 10;
6119 else
6120 divider = 10;
6121 }
6122 }
6123 if (*options == 's') /* "2s" means two times 'shiftwidth' */
6124 {
6125 if (n == 0 && fraction == 0)
6126 n = curbuf->b_p_sw; /* just "s" is one 'shiftwidth' */
6127 else
6128 {
6129 n *= curbuf->b_p_sw;
6130 if (divider)
6131 n += (curbuf->b_p_sw * fraction + divider / 2) / divider;
6132 }
6133 ++options;
6134 }
6135 if (l[1] == '-')
6136 n = -n;
6137 /* When adding an entry here, also update the default 'cinoptions' in
6138 * change.txt, and add explanation for it! */
6139 switch (*l)
6140 {
6141 case '>': ind_level = n; break;
6142 case 'e': ind_open_imag = n; break;
6143 case 'n': ind_no_brace = n; break;
6144 case 'f': ind_first_open = n; break;
6145 case '{': ind_open_extra = n; break;
6146 case '}': ind_close_extra = n; break;
6147 case '^': ind_open_left_imag = n; break;
6148 case ':': ind_case = n; break;
6149 case '=': ind_case_code = n; break;
6150 case 'b': ind_case_break = n; break;
6151 case 'p': ind_param = n; break;
6152 case 't': ind_func_type = n; break;
6153 case '/': ind_comment = n; break;
6154 case 'c': ind_in_comment = n; break;
6155 case 'C': ind_in_comment2 = n; break;
6156 case 'i': ind_cpp_baseclass = n; break;
6157 case '+': ind_continuation = n; break;
6158 case '(': ind_unclosed = n; break;
6159 case 'u': ind_unclosed2 = n; break;
6160 case 'U': ind_unclosed_noignore = n; break;
6161 case 'W': ind_unclosed_wrapped = n; break;
6162 case 'w': ind_unclosed_whiteok = n; break;
6163 case 'm': ind_matching_paren = n; break;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006164 case 'M': ind_paren_prev = n; break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165 case ')': ind_maxparen = n; break;
6166 case '*': ind_maxcomment = n; break;
6167 case 'g': ind_scopedecl = n; break;
6168 case 'h': ind_scopedecl_code = n; break;
6169 case 'j': ind_java = n; break;
6170 case 'l': ind_keep_case_label = n; break;
6171 }
6172 }
6173
6174 /* remember where the cursor was when we started */
6175 cur_curpos = curwin->w_cursor;
6176
6177 /* Get a copy of the current contents of the line.
6178 * This is required, because only the most recent line obtained with
6179 * ml_get is valid! */
6180 linecopy = vim_strsave(ml_get(cur_curpos.lnum));
6181 if (linecopy == NULL)
6182 return 0;
6183
6184 /*
6185 * In insert mode and the cursor is on a ')' truncate the line at the
6186 * cursor position. We don't want to line up with the matching '(' when
6187 * inserting new stuff.
6188 * For unknown reasons the cursor might be past the end of the line, thus
6189 * check for that.
6190 */
6191 if ((State & INSERT)
6192 && curwin->w_cursor.col < STRLEN(linecopy)
6193 && linecopy[curwin->w_cursor.col] == ')')
6194 linecopy[curwin->w_cursor.col] = NUL;
6195
6196 theline = skipwhite(linecopy);
6197
6198 /* move the cursor to the start of the line */
6199
6200 curwin->w_cursor.col = 0;
6201
6202 /*
6203 * #defines and so on always go at the left when included in 'cinkeys'.
6204 */
6205 if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', TRUE)))
6206 {
6207 amount = 0;
6208 }
6209
6210 /*
6211 * Is it a non-case label? Then that goes at the left margin too.
6212 */
6213 else if (cin_islabel(ind_maxcomment)) /* XXX */
6214 {
6215 amount = 0;
6216 }
6217
6218 /*
6219 * If we're inside a "//" comment and there is a "//" comment in a
6220 * previous line, lineup with that one.
6221 */
6222 else if (cin_islinecomment(theline)
6223 && (trypos = find_line_comment()) != NULL) /* XXX */
6224 {
6225 /* find how indented the line beginning the comment is */
6226 getvcol(curwin, trypos, &col, NULL, NULL);
6227 amount = col;
6228 }
6229
6230 /*
6231 * If we're inside a comment and not looking at the start of the
6232 * comment, try using the 'comments' option.
6233 */
6234 else if (!cin_iscomment(theline)
6235 && (trypos = find_start_comment(ind_maxcomment)) != NULL) /* XXX */
6236 {
6237 int lead_start_len = 2;
6238 int lead_middle_len = 1;
6239 char_u lead_start[COM_MAX_LEN]; /* start-comment string */
6240 char_u lead_middle[COM_MAX_LEN]; /* middle-comment string */
6241 char_u lead_end[COM_MAX_LEN]; /* end-comment string */
6242 char_u *p;
6243 int start_align = 0;
6244 int start_off = 0;
6245 int done = FALSE;
6246
6247 /* find how indented the line beginning the comment is */
6248 getvcol(curwin, trypos, &col, NULL, NULL);
6249 amount = col;
6250
6251 p = curbuf->b_p_com;
6252 while (*p != NUL)
6253 {
6254 int align = 0;
6255 int off = 0;
6256 int what = 0;
6257
6258 while (*p != NUL && *p != ':')
6259 {
6260 if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE)
6261 what = *p++;
6262 else if (*p == COM_LEFT || *p == COM_RIGHT)
6263 align = *p++;
6264 else if (VIM_ISDIGIT(*p) || *p == '-')
6265 off = getdigits(&p);
6266 else
6267 ++p;
6268 }
6269
6270 if (*p == ':')
6271 ++p;
6272 (void)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
6273 if (what == COM_START)
6274 {
6275 STRCPY(lead_start, lead_end);
6276 lead_start_len = (int)STRLEN(lead_start);
6277 start_off = off;
6278 start_align = align;
6279 }
6280 else if (what == COM_MIDDLE)
6281 {
6282 STRCPY(lead_middle, lead_end);
6283 lead_middle_len = (int)STRLEN(lead_middle);
6284 }
6285 else if (what == COM_END)
6286 {
6287 /* If our line starts with the middle comment string, line it
6288 * up with the comment opener per the 'comments' option. */
6289 if (STRNCMP(theline, lead_middle, lead_middle_len) == 0
6290 && STRNCMP(theline, lead_end, STRLEN(lead_end)) != 0)
6291 {
6292 done = TRUE;
6293 if (curwin->w_cursor.lnum > 1)
6294 {
6295 /* If the start comment string matches in the previous
6296 * line, use the indent of that line pluss offset. If
6297 * the middle comment string matches in the previous
6298 * line, use the indent of that line. XXX */
6299 look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
6300 if (STRNCMP(look, lead_start, lead_start_len) == 0)
6301 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6302 else if (STRNCMP(look, lead_middle,
6303 lead_middle_len) == 0)
6304 {
6305 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6306 break;
6307 }
6308 /* If the start comment string doesn't match with the
6309 * start of the comment, skip this entry. XXX */
6310 else if (STRNCMP(ml_get(trypos->lnum) + trypos->col,
6311 lead_start, lead_start_len) != 0)
6312 continue;
6313 }
6314 if (start_off != 0)
6315 amount += start_off;
6316 else if (start_align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006317 amount += vim_strsize(lead_start)
6318 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 break;
6320 }
6321
6322 /* If our line starts with the end comment string, line it up
6323 * with the middle comment */
6324 if (STRNCMP(theline, lead_middle, lead_middle_len) != 0
6325 && STRNCMP(theline, lead_end, STRLEN(lead_end)) == 0)
6326 {
6327 amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
6328 /* XXX */
6329 if (off != 0)
6330 amount += off;
6331 else if (align == COM_RIGHT)
Bram Moolenaar21cf8232004-07-16 20:18:37 +00006332 amount += vim_strsize(lead_start)
6333 - vim_strsize(lead_middle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 done = TRUE;
6335 break;
6336 }
6337 }
6338 }
6339
6340 /* If our line starts with an asterisk, line up with the
6341 * asterisk in the comment opener; otherwise, line up
6342 * with the first character of the comment text.
6343 */
6344 if (done)
6345 ;
6346 else if (theline[0] == '*')
6347 amount += 1;
6348 else
6349 {
6350 /*
6351 * If we are more than one line away from the comment opener, take
6352 * the indent of the previous non-empty line. If 'cino' has "CO"
6353 * and we are just below the comment opener and there are any
6354 * white characters after it line up with the text after it;
6355 * otherwise, add the amount specified by "c" in 'cino'
6356 */
6357 amount = -1;
6358 for (lnum = cur_curpos.lnum - 1; lnum > trypos->lnum; --lnum)
6359 {
6360 if (linewhite(lnum)) /* skip blank lines */
6361 continue;
6362 amount = get_indent_lnum(lnum); /* XXX */
6363 break;
6364 }
6365 if (amount == -1) /* use the comment opener */
6366 {
6367 if (!ind_in_comment2)
6368 {
6369 start = ml_get(trypos->lnum);
6370 look = start + trypos->col + 2; /* skip / and * */
6371 if (*look != NUL) /* if something after it */
6372 trypos->col = (colnr_T)(skipwhite(look) - start);
6373 }
6374 getvcol(curwin, trypos, &col, NULL, NULL);
6375 amount = col;
6376 if (ind_in_comment2 || *look == NUL)
6377 amount += ind_in_comment;
6378 }
6379 }
6380 }
6381
6382 /*
6383 * Are we inside parentheses or braces?
6384 */ /* XXX */
6385 else if (((trypos = find_match_paren(ind_maxparen, ind_maxcomment)) != NULL
6386 && ind_java == 0)
6387 || (tryposBrace = find_start_brace(ind_maxcomment)) != NULL
6388 || trypos != NULL)
6389 {
6390 if (trypos != NULL && tryposBrace != NULL)
6391 {
6392 /* Both an unmatched '(' and '{' is found. Use the one which is
6393 * closer to the current cursor position, set the other to NULL. */
6394 if (trypos->lnum != tryposBrace->lnum
6395 ? trypos->lnum < tryposBrace->lnum
6396 : trypos->col < tryposBrace->col)
6397 trypos = NULL;
6398 else
6399 tryposBrace = NULL;
6400 }
6401
6402 if (trypos != NULL)
6403 {
6404 /*
6405 * If the matching paren is more than one line away, use the indent of
6406 * a previous non-empty line that matches the same paren.
6407 */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006408 if (theline[0] == ')' && ind_paren_prev)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006409 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006410 /* Line up with the start of the matching paren line. */
6411 amount = get_indent_lnum(curwin->w_cursor.lnum - 1); /* XXX */
6412 }
6413 else
6414 {
6415 amount = -1;
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006416 our_paren_pos = *trypos;
6417 for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; --lnum)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006419 l = skipwhite(ml_get(lnum));
6420 if (cin_nocode(l)) /* skip comment lines */
6421 continue;
6422 if (cin_ispreproc_cont(&l, &lnum))
6423 continue; /* ignore #define, #if, etc. */
6424 curwin->w_cursor.lnum = lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006426 /* Skip a comment. XXX */
6427 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6428 {
6429 lnum = trypos->lnum + 1;
6430 continue;
6431 }
6432
6433 /* XXX */
6434 if ((trypos = find_match_paren(
6435 corr_ind_maxparen(ind_maxparen, &cur_curpos),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436 ind_maxcomment)) != NULL
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006437 && trypos->lnum == our_paren_pos.lnum
6438 && trypos->col == our_paren_pos.col)
6439 {
6440 amount = get_indent_lnum(lnum); /* XXX */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006442 if (theline[0] == ')')
6443 {
6444 if (our_paren_pos.lnum != lnum
6445 && cur_amount > amount)
6446 cur_amount = amount;
6447 amount = -1;
6448 }
6449 break;
6450 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451 }
6452 }
6453
6454 /*
6455 * Line up with line where the matching paren is. XXX
6456 * If the line starts with a '(' or the indent for unclosed
6457 * parentheses is zero, line up with the unclosed parentheses.
6458 */
6459 if (amount == -1)
6460 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006461 int ignore_paren_col = 0;
6462
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463 amount = skip_label(our_paren_pos.lnum, &look, ind_maxcomment);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006464 look = skipwhite(look);
6465 if (*look == '(')
6466 {
6467 linenr_T save_lnum = curwin->w_cursor.lnum;
6468 char_u *line;
6469 int look_col;
6470
6471 /* Ignore a '(' in front of the line that has a match before
6472 * our matching '('. */
6473 curwin->w_cursor.lnum = our_paren_pos.lnum;
6474 line = ml_get_curline();
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006475 look_col = (int)(look - line);
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006476 curwin->w_cursor.col = look_col + 1;
6477 if ((trypos = findmatchlimit(NULL, ')', 0, ind_maxparen))
6478 != NULL
6479 && trypos->lnum == our_paren_pos.lnum
6480 && trypos->col < our_paren_pos.col)
6481 ignore_paren_col = trypos->col + 1;
6482
6483 curwin->w_cursor.lnum = save_lnum;
6484 look = ml_get(our_paren_pos.lnum) + look_col;
6485 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486 if (theline[0] == ')' || ind_unclosed == 0
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006487 || (!ind_unclosed_noignore && *look == '('
6488 && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 {
6490 /*
6491 * If we're looking at a close paren, line up right there;
6492 * otherwise, line up with the next (non-white) character.
6493 * When ind_unclosed_wrapped is set and the matching paren is
6494 * the last nonwhite character of the line, use either the
6495 * indent of the current line or the indentation of the next
6496 * outer paren and add ind_unclosed_wrapped (for very long
6497 * lines).
6498 */
6499 if (theline[0] != ')')
6500 {
6501 cur_amount = MAXCOL;
6502 l = ml_get(our_paren_pos.lnum);
6503 if (ind_unclosed_wrapped
6504 && cin_ends_in(l, (char_u *)"(", NULL))
6505 {
6506 /* look for opening unmatched paren, indent one level
6507 * for each additional level */
6508 n = 1;
6509 for (col = 0; col < our_paren_pos.col; ++col)
6510 {
6511 switch (l[col])
6512 {
6513 case '(':
6514 case '{': ++n;
6515 break;
6516
6517 case ')':
6518 case '}': if (n > 1)
6519 --n;
6520 break;
6521 }
6522 }
6523
6524 our_paren_pos.col = 0;
6525 amount += n * ind_unclosed_wrapped;
6526 }
6527 else if (ind_unclosed_whiteok)
6528 our_paren_pos.col++;
6529 else
6530 {
6531 col = our_paren_pos.col + 1;
6532 while (vim_iswhite(l[col]))
6533 col++;
6534 if (l[col] != NUL) /* In case of trailing space */
6535 our_paren_pos.col = col;
6536 else
6537 our_paren_pos.col++;
6538 }
6539 }
6540
6541 /*
6542 * Find how indented the paren is, or the character after it
6543 * if we did the above "if".
6544 */
6545 if (our_paren_pos.col > 0)
6546 {
6547 getvcol(curwin, &our_paren_pos, &col, NULL, NULL);
6548 if (cur_amount > (int)col)
6549 cur_amount = col;
6550 }
6551 }
6552
6553 if (theline[0] == ')' && ind_matching_paren)
6554 {
6555 /* Line up with the start of the matching paren line. */
6556 }
6557 else if (ind_unclosed == 0 || (!ind_unclosed_noignore
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006558 && *look == '(' && ignore_paren_col == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006559 {
6560 if (cur_amount != MAXCOL)
6561 amount = cur_amount;
6562 }
6563 else
6564 {
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00006565 /* Add ind_unclosed2 for each '(' before our matching one, but
6566 * ignore (void) before the line (ignore_paren_col). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006567 col = our_paren_pos.col;
Bram Moolenaarb21e5842006-04-16 18:30:08 +00006568 while ((int)our_paren_pos.col > ignore_paren_col)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569 {
6570 --our_paren_pos.col;
6571 switch (*ml_get_pos(&our_paren_pos))
6572 {
6573 case '(': amount += ind_unclosed2;
6574 col = our_paren_pos.col;
6575 break;
6576 case ')': amount -= ind_unclosed2;
6577 col = MAXCOL;
6578 break;
6579 }
6580 }
6581
6582 /* Use ind_unclosed once, when the first '(' is not inside
6583 * braces */
6584 if (col == MAXCOL)
6585 amount += ind_unclosed;
6586 else
6587 {
6588 curwin->w_cursor.lnum = our_paren_pos.lnum;
6589 curwin->w_cursor.col = col;
6590 if ((trypos = find_match_paren(ind_maxparen,
6591 ind_maxcomment)) != NULL)
6592 amount += ind_unclosed2;
6593 else
6594 amount += ind_unclosed;
6595 }
6596 /*
6597 * For a line starting with ')' use the minimum of the two
6598 * positions, to avoid giving it more indent than the previous
6599 * lines:
6600 * func_long_name( if (x
6601 * arg && yy
6602 * ) ^ not here ) ^ not here
6603 */
6604 if (cur_amount < amount)
6605 amount = cur_amount;
6606 }
6607 }
6608
6609 /* add extra indent for a comment */
6610 if (cin_iscomment(theline))
6611 amount += ind_comment;
6612 }
6613
6614 /*
6615 * Are we at least inside braces, then?
6616 */
6617 else
6618 {
6619 trypos = tryposBrace;
6620
6621 ourscope = trypos->lnum;
6622 start = ml_get(ourscope);
6623
6624 /*
6625 * Now figure out how indented the line is in general.
6626 * If the brace was at the start of the line, we use that;
6627 * otherwise, check out the indentation of the line as
6628 * a whole and then add the "imaginary indent" to that.
6629 */
6630 look = skipwhite(start);
6631 if (*look == '{')
6632 {
6633 getvcol(curwin, trypos, &col, NULL, NULL);
6634 amount = col;
6635 if (*start == '{')
6636 start_brace = BRACE_IN_COL0;
6637 else
6638 start_brace = BRACE_AT_START;
6639 }
6640 else
6641 {
6642 /*
6643 * that opening brace might have been on a continuation
6644 * line. if so, find the start of the line.
6645 */
6646 curwin->w_cursor.lnum = ourscope;
6647
6648 /*
6649 * position the cursor over the rightmost paren, so that
6650 * matching it will take us back to the start of the line.
6651 */
6652 lnum = ourscope;
6653 if (find_last_paren(start, '(', ')')
6654 && (trypos = find_match_paren(ind_maxparen,
6655 ind_maxcomment)) != NULL)
6656 lnum = trypos->lnum;
6657
6658 /*
6659 * It could have been something like
6660 * case 1: if (asdf &&
6661 * ldfd) {
6662 * }
6663 */
6664 if (ind_keep_case_label && cin_iscase(skipwhite(ml_get_curline())))
6665 amount = get_indent();
6666 else
6667 amount = skip_label(lnum, &l, ind_maxcomment);
6668
6669 start_brace = BRACE_AT_END;
6670 }
6671
6672 /*
6673 * if we're looking at a closing brace, that's where
6674 * we want to be. otherwise, add the amount of room
6675 * that an indent is supposed to be.
6676 */
6677 if (theline[0] == '}')
6678 {
6679 /*
6680 * they may want closing braces to line up with something
6681 * other than the open brace. indulge them, if so.
6682 */
6683 amount += ind_close_extra;
6684 }
6685 else
6686 {
6687 /*
6688 * If we're looking at an "else", try to find an "if"
6689 * to match it with.
6690 * If we're looking at a "while", try to find a "do"
6691 * to match it with.
6692 */
6693 lookfor = LOOKFOR_INITIAL;
6694 if (cin_iselse(theline))
6695 lookfor = LOOKFOR_IF;
6696 else if (cin_iswhileofdo(theline, cur_curpos.lnum, ind_maxparen))
6697 /* XXX */
6698 lookfor = LOOKFOR_DO;
6699 if (lookfor != LOOKFOR_INITIAL)
6700 {
6701 curwin->w_cursor.lnum = cur_curpos.lnum;
6702 if (find_match(lookfor, ourscope, ind_maxparen,
6703 ind_maxcomment) == OK)
6704 {
6705 amount = get_indent(); /* XXX */
6706 goto theend;
6707 }
6708 }
6709
6710 /*
6711 * We get here if we are not on an "while-of-do" or "else" (or
6712 * failed to find a matching "if").
6713 * Search backwards for something to line up with.
6714 * First set amount for when we don't find anything.
6715 */
6716
6717 /*
6718 * if the '{' is _really_ at the left margin, use the imaginary
6719 * location of a left-margin brace. Otherwise, correct the
6720 * location for ind_open_extra.
6721 */
6722
6723 if (start_brace == BRACE_IN_COL0) /* '{' is in column 0 */
6724 {
6725 amount = ind_open_left_imag;
6726 }
6727 else
6728 {
6729 if (start_brace == BRACE_AT_END) /* '{' is at end of line */
6730 amount += ind_open_imag;
6731 else
6732 {
6733 /* Compensate for adding ind_open_extra later. */
6734 amount -= ind_open_extra;
6735 if (amount < 0)
6736 amount = 0;
6737 }
6738 }
6739
6740 lookfor_break = FALSE;
6741
6742 if (cin_iscase(theline)) /* it's a switch() label */
6743 {
6744 lookfor = LOOKFOR_CASE; /* find a previous switch() label */
6745 amount += ind_case;
6746 }
6747 else if (cin_isscopedecl(theline)) /* private:, ... */
6748 {
6749 lookfor = LOOKFOR_SCOPEDECL; /* class decl is this block */
6750 amount += ind_scopedecl;
6751 }
6752 else
6753 {
6754 if (ind_case_break && cin_isbreak(theline)) /* break; ... */
6755 lookfor_break = TRUE;
6756
6757 lookfor = LOOKFOR_INITIAL;
6758 amount += ind_level; /* ind_level from start of block */
6759 }
6760 scope_amount = amount;
6761 whilelevel = 0;
6762
6763 /*
6764 * Search backwards. If we find something we recognize, line up
6765 * with that.
6766 *
6767 * if we're looking at an open brace, indent
6768 * the usual amount relative to the conditional
6769 * that opens the block.
6770 */
6771 curwin->w_cursor = cur_curpos;
6772 for (;;)
6773 {
6774 curwin->w_cursor.lnum--;
6775 curwin->w_cursor.col = 0;
6776
6777 /*
6778 * If we went all the way back to the start of our scope, line
6779 * up with it.
6780 */
6781 if (curwin->w_cursor.lnum <= ourscope)
6782 {
6783 /* we reached end of scope:
6784 * if looking for a enum or structure initialization
6785 * go further back:
6786 * if it is an initializer (enum xxx or xxx =), then
6787 * don't add ind_continuation, otherwise it is a variable
6788 * declaration:
6789 * int x,
6790 * here; <-- add ind_continuation
6791 */
6792 if (lookfor == LOOKFOR_ENUM_OR_INIT)
6793 {
6794 if (curwin->w_cursor.lnum == 0
6795 || curwin->w_cursor.lnum
6796 < ourscope - ind_maxparen)
6797 {
6798 /* nothing found (abuse ind_maxparen as limit)
6799 * assume terminated line (i.e. a variable
6800 * initialization) */
6801 if (cont_amount > 0)
6802 amount = cont_amount;
6803 else
6804 amount += ind_continuation;
6805 break;
6806 }
6807
6808 l = ml_get_curline();
6809
6810 /*
6811 * If we're in a comment now, skip to the start of the
6812 * comment.
6813 */
6814 trypos = find_start_comment(ind_maxcomment);
6815 if (trypos != NULL)
6816 {
6817 curwin->w_cursor.lnum = trypos->lnum + 1;
6818 continue;
6819 }
6820
6821 /*
6822 * Skip preprocessor directives and blank lines.
6823 */
6824 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
6825 continue;
6826
6827 if (cin_nocode(l))
6828 continue;
6829
6830 terminated = cin_isterminated(l, FALSE, TRUE);
6831
6832 /*
6833 * If we are at top level and the line looks like a
6834 * function declaration, we are done
6835 * (it's a variable declaration).
6836 */
6837 if (start_brace != BRACE_IN_COL0
6838 || !cin_isfuncdecl(&l, curwin->w_cursor.lnum))
6839 {
6840 /* if the line is terminated with another ','
6841 * it is a continued variable initialization.
6842 * don't add extra indent.
6843 * TODO: does not work, if a function
6844 * declaration is split over multiple lines:
6845 * cin_isfuncdecl returns FALSE then.
6846 */
6847 if (terminated == ',')
6848 break;
6849
6850 /* if it es a enum declaration or an assignment,
6851 * we are done.
6852 */
6853 if (terminated != ';' && cin_isinit())
6854 break;
6855
6856 /* nothing useful found */
6857 if (terminated == 0 || terminated == '{')
6858 continue;
6859 }
6860
6861 if (terminated != ';')
6862 {
6863 /* Skip parens and braces. Position the cursor
6864 * over the rightmost paren, so that matching it
6865 * will take us back to the start of the line.
6866 */ /* XXX */
6867 trypos = NULL;
6868 if (find_last_paren(l, '(', ')'))
6869 trypos = find_match_paren(ind_maxparen,
6870 ind_maxcomment);
6871
6872 if (trypos == NULL && find_last_paren(l, '{', '}'))
6873 trypos = find_start_brace(ind_maxcomment);
6874
6875 if (trypos != NULL)
6876 {
6877 curwin->w_cursor.lnum = trypos->lnum + 1;
6878 continue;
6879 }
6880 }
6881
6882 /* it's a variable declaration, add indentation
6883 * like in
6884 * int a,
6885 * b;
6886 */
6887 if (cont_amount > 0)
6888 amount = cont_amount;
6889 else
6890 amount += ind_continuation;
6891 }
6892 else if (lookfor == LOOKFOR_UNTERM)
6893 {
6894 if (cont_amount > 0)
6895 amount = cont_amount;
6896 else
6897 amount += ind_continuation;
6898 }
6899 else if (lookfor != LOOKFOR_TERM
6900 && lookfor != LOOKFOR_CPP_BASECLASS)
6901 {
6902 amount = scope_amount;
6903 if (theline[0] == '{')
6904 amount += ind_open_extra;
6905 }
6906 break;
6907 }
6908
6909 /*
6910 * If we're in a comment now, skip to the start of the comment.
6911 */ /* XXX */
6912 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
6913 {
6914 curwin->w_cursor.lnum = trypos->lnum + 1;
6915 continue;
6916 }
6917
6918 l = ml_get_curline();
6919
6920 /*
6921 * If this is a switch() label, may line up relative to that.
Bram Moolenaar18144c82006-04-12 21:52:12 +00006922 * If this is a C++ scope declaration, do the same.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923 */
6924 iscase = cin_iscase(l);
6925 if (iscase || cin_isscopedecl(l))
6926 {
6927 /* we are only looking for cpp base class
6928 * declaration/initialization any longer */
6929 if (lookfor == LOOKFOR_CPP_BASECLASS)
6930 break;
6931
6932 /* When looking for a "do" we are not interested in
6933 * labels. */
6934 if (whilelevel > 0)
6935 continue;
6936
6937 /*
6938 * case xx:
6939 * c = 99 + <- this indent plus continuation
6940 *-> here;
6941 */
6942 if (lookfor == LOOKFOR_UNTERM
6943 || lookfor == LOOKFOR_ENUM_OR_INIT)
6944 {
6945 if (cont_amount > 0)
6946 amount = cont_amount;
6947 else
6948 amount += ind_continuation;
6949 break;
6950 }
6951
6952 /*
6953 * case xx: <- line up with this case
6954 * x = 333;
6955 * case yy:
6956 */
6957 if ( (iscase && lookfor == LOOKFOR_CASE)
6958 || (iscase && lookfor_break)
6959 || (!iscase && lookfor == LOOKFOR_SCOPEDECL))
6960 {
6961 /*
6962 * Check that this case label is not for another
6963 * switch()
6964 */ /* XXX */
6965 if ((trypos = find_start_brace(ind_maxcomment)) ==
6966 NULL || trypos->lnum == ourscope)
6967 {
6968 amount = get_indent(); /* XXX */
6969 break;
6970 }
6971 continue;
6972 }
6973
6974 n = get_indent_nolabel(curwin->w_cursor.lnum); /* XXX */
6975
6976 /*
6977 * case xx: if (cond) <- line up with this if
6978 * y = y + 1;
6979 * -> s = 99;
6980 *
6981 * case xx:
6982 * if (cond) <- line up with this line
6983 * y = y + 1;
6984 * -> s = 99;
6985 */
6986 if (lookfor == LOOKFOR_TERM)
6987 {
6988 if (n)
6989 amount = n;
6990
6991 if (!lookfor_break)
6992 break;
6993 }
6994
6995 /*
6996 * case xx: x = x + 1; <- line up with this x
6997 * -> y = y + 1;
6998 *
6999 * case xx: if (cond) <- line up with this if
7000 * -> y = y + 1;
7001 */
7002 if (n)
7003 {
7004 amount = n;
7005 l = after_label(ml_get_curline());
7006 if (l != NULL && cin_is_cinword(l))
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007007 {
7008 if (theline[0] == '{')
7009 amount += ind_open_extra;
7010 else
7011 amount += ind_level + ind_no_brace;
7012 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 break;
7014 }
7015
7016 /*
7017 * Try to get the indent of a statement before the switch
7018 * label. If nothing is found, line up relative to the
7019 * switch label.
7020 * break; <- may line up with this line
7021 * case xx:
7022 * -> y = 1;
7023 */
7024 scope_amount = get_indent() + (iscase /* XXX */
7025 ? ind_case_code : ind_scopedecl_code);
7026 lookfor = ind_case_break ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
7027 continue;
7028 }
7029
7030 /*
7031 * Looking for a switch() label or C++ scope declaration,
7032 * ignore other lines, skip {}-blocks.
7033 */
7034 if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL)
7035 {
7036 if (find_last_paren(l, '{', '}') && (trypos =
7037 find_start_brace(ind_maxcomment)) != NULL)
7038 curwin->w_cursor.lnum = trypos->lnum + 1;
7039 continue;
7040 }
7041
7042 /*
7043 * Ignore jump labels with nothing after them.
7044 */
7045 if (cin_islabel(ind_maxcomment))
7046 {
7047 l = after_label(ml_get_curline());
7048 if (l == NULL || cin_nocode(l))
7049 continue;
7050 }
7051
7052 /*
7053 * Ignore #defines, #if, etc.
7054 * Ignore comment and empty lines.
7055 * (need to get the line again, cin_islabel() may have
7056 * unlocked it)
7057 */
7058 l = ml_get_curline();
7059 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum)
7060 || cin_nocode(l))
7061 continue;
7062
7063 /*
7064 * Are we at the start of a cpp base class declaration or
7065 * constructor initialization?
7066 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007067 n = FALSE;
7068 if (lookfor != LOOKFOR_TERM && ind_cpp_baseclass > 0)
7069 {
7070 n = cin_is_cpp_baseclass(l, &col);
7071 l = ml_get_curline();
7072 }
7073 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074 {
7075 if (lookfor == LOOKFOR_UNTERM)
7076 {
7077 if (cont_amount > 0)
7078 amount = cont_amount;
7079 else
7080 amount += ind_continuation;
7081 }
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007082 else if (theline[0] == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007084 /* Need to find start of the declaration. */
7085 lookfor = LOOKFOR_UNTERM;
7086 ind_continuation = 0;
7087 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088 }
7089 else
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007090 /* XXX */
7091 amount = get_baseclass_amount(col, ind_maxparen,
7092 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093 break;
7094 }
7095 else if (lookfor == LOOKFOR_CPP_BASECLASS)
7096 {
7097 /* only look, whether there is a cpp base class
Bram Moolenaar18144c82006-04-12 21:52:12 +00007098 * declaration or initialization before the opening brace.
7099 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007100 if (cin_isterminated(l, TRUE, FALSE))
7101 break;
7102 else
7103 continue;
7104 }
7105
7106 /*
7107 * What happens next depends on the line being terminated.
7108 * If terminated with a ',' only consider it terminating if
7109 * there is anoter unterminated statement behind, eg:
7110 * 123,
7111 * sizeof
7112 * here
7113 * Otherwise check whether it is a enumeration or structure
7114 * initialisation (not indented) or a variable declaration
7115 * (indented).
7116 */
7117 terminated = cin_isterminated(l, FALSE, TRUE);
7118
7119 if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
7120 && terminated == ','))
7121 {
7122 /*
7123 * if we're in the middle of a paren thing,
7124 * go back to the line that starts it so
7125 * we can get the right prevailing indent
7126 * if ( foo &&
7127 * bar )
7128 */
7129 /*
7130 * position the cursor over the rightmost paren, so that
7131 * matching it will take us back to the start of the line.
7132 */
7133 (void)find_last_paren(l, '(', ')');
7134 trypos = find_match_paren(
7135 corr_ind_maxparen(ind_maxparen, &cur_curpos),
7136 ind_maxcomment);
7137
7138 /*
7139 * If we are looking for ',', we also look for matching
7140 * braces.
7141 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007142 if (trypos == NULL && terminated == ','
7143 && find_last_paren(l, '{', '}'))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144 trypos = find_start_brace(ind_maxcomment);
7145
7146 if (trypos != NULL)
7147 {
7148 /*
7149 * Check if we are on a case label now. This is
7150 * handled above.
7151 * case xx: if ( asdf &&
7152 * asdf)
7153 */
7154 curwin->w_cursor.lnum = trypos->lnum;
7155 l = ml_get_curline();
7156 if (cin_iscase(l) || cin_isscopedecl(l))
7157 {
7158 ++curwin->w_cursor.lnum;
7159 continue;
7160 }
7161 }
7162
7163 /*
7164 * Skip over continuation lines to find the one to get the
7165 * indent from
7166 * char *usethis = "bla\
7167 * bla",
7168 * here;
7169 */
7170 if (terminated == ',')
7171 {
7172 while (curwin->w_cursor.lnum > 1)
7173 {
7174 l = ml_get(curwin->w_cursor.lnum - 1);
7175 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7176 break;
7177 --curwin->w_cursor.lnum;
7178 }
7179 }
7180
7181 /*
7182 * Get indent and pointer to text for current line,
7183 * ignoring any jump label. XXX
7184 */
7185 cur_amount = skip_label(curwin->w_cursor.lnum,
7186 &l, ind_maxcomment);
7187
7188 /*
7189 * If this is just above the line we are indenting, and it
7190 * starts with a '{', line it up with this line.
7191 * while (not)
7192 * -> {
7193 * }
7194 */
7195 if (terminated != ',' && lookfor != LOOKFOR_TERM
7196 && theline[0] == '{')
7197 {
7198 amount = cur_amount;
7199 /*
7200 * Only add ind_open_extra when the current line
7201 * doesn't start with a '{', which must have a match
7202 * in the same line (scope is the same). Probably:
7203 * { 1, 2 },
7204 * -> { 3, 4 }
7205 */
7206 if (*skipwhite(l) != '{')
7207 amount += ind_open_extra;
7208
7209 if (ind_cpp_baseclass)
7210 {
7211 /* have to look back, whether it is a cpp base
7212 * class declaration or initialization */
7213 lookfor = LOOKFOR_CPP_BASECLASS;
7214 continue;
7215 }
7216 break;
7217 }
7218
7219 /*
7220 * Check if we are after an "if", "while", etc.
7221 * Also allow " } else".
7222 */
7223 if (cin_is_cinword(l) || cin_iselse(skipwhite(l)))
7224 {
7225 /*
7226 * Found an unterminated line after an if (), line up
7227 * with the last one.
7228 * if (cond)
7229 * 100 +
7230 * -> here;
7231 */
7232 if (lookfor == LOOKFOR_UNTERM
7233 || lookfor == LOOKFOR_ENUM_OR_INIT)
7234 {
7235 if (cont_amount > 0)
7236 amount = cont_amount;
7237 else
7238 amount += ind_continuation;
7239 break;
7240 }
7241
7242 /*
7243 * If this is just above the line we are indenting, we
7244 * are finished.
7245 * while (not)
7246 * -> here;
7247 * Otherwise this indent can be used when the line
7248 * before this is terminated.
7249 * yyy;
7250 * if (stat)
7251 * while (not)
7252 * xxx;
7253 * -> here;
7254 */
7255 amount = cur_amount;
7256 if (theline[0] == '{')
7257 amount += ind_open_extra;
7258 if (lookfor != LOOKFOR_TERM)
7259 {
7260 amount += ind_level + ind_no_brace;
7261 break;
7262 }
7263
7264 /*
7265 * Special trick: when expecting the while () after a
7266 * do, line up with the while()
7267 * do
7268 * x = 1;
7269 * -> here
7270 */
7271 l = skipwhite(ml_get_curline());
7272 if (cin_isdo(l))
7273 {
7274 if (whilelevel == 0)
7275 break;
7276 --whilelevel;
7277 }
7278
7279 /*
7280 * When searching for a terminated line, don't use the
7281 * one between the "if" and the "else".
7282 * Need to use the scope of this "else". XXX
7283 * If whilelevel != 0 continue looking for a "do {".
7284 */
7285 if (cin_iselse(l)
7286 && whilelevel == 0
7287 && ((trypos = find_start_brace(ind_maxcomment))
7288 == NULL
7289 || find_match(LOOKFOR_IF, trypos->lnum,
7290 ind_maxparen, ind_maxcomment) == FAIL))
7291 break;
7292 }
7293
7294 /*
7295 * If we're below an unterminated line that is not an
7296 * "if" or something, we may line up with this line or
7297 * add someting for a continuation line, depending on
7298 * the line before this one.
7299 */
7300 else
7301 {
7302 /*
7303 * Found two unterminated lines on a row, line up with
7304 * the last one.
7305 * c = 99 +
7306 * 100 +
7307 * -> here;
7308 */
7309 if (lookfor == LOOKFOR_UNTERM)
7310 {
7311 /* When line ends in a comma add extra indent */
7312 if (terminated == ',')
7313 amount += ind_continuation;
7314 break;
7315 }
7316
7317 if (lookfor == LOOKFOR_ENUM_OR_INIT)
7318 {
7319 /* Found two lines ending in ',', lineup with the
7320 * lowest one, but check for cpp base class
7321 * declaration/initialization, if it is an
7322 * opening brace or we are looking just for
7323 * enumerations/initializations. */
7324 if (terminated == ',')
7325 {
7326 if (ind_cpp_baseclass == 0)
7327 break;
7328
7329 lookfor = LOOKFOR_CPP_BASECLASS;
7330 continue;
7331 }
7332
7333 /* Ignore unterminated lines in between, but
7334 * reduce indent. */
7335 if (amount > cur_amount)
7336 amount = cur_amount;
7337 }
7338 else
7339 {
7340 /*
7341 * Found first unterminated line on a row, may
7342 * line up with this line, remember its indent
7343 * 100 +
7344 * -> here;
7345 */
7346 amount = cur_amount;
7347
7348 /*
7349 * If previous line ends in ',', check whether we
7350 * are in an initialization or enum
7351 * struct xxx =
7352 * {
7353 * sizeof a,
7354 * 124 };
7355 * or a normal possible continuation line.
7356 * but only, of no other statement has been found
7357 * yet.
7358 */
7359 if (lookfor == LOOKFOR_INITIAL && terminated == ',')
7360 {
7361 lookfor = LOOKFOR_ENUM_OR_INIT;
7362 cont_amount = cin_first_id_amount();
7363 }
7364 else
7365 {
7366 if (lookfor == LOOKFOR_INITIAL
7367 && *l != NUL
7368 && l[STRLEN(l) - 1] == '\\')
7369 /* XXX */
7370 cont_amount = cin_get_equal_amount(
7371 curwin->w_cursor.lnum);
7372 if (lookfor != LOOKFOR_TERM)
7373 lookfor = LOOKFOR_UNTERM;
7374 }
7375 }
7376 }
7377 }
7378
7379 /*
7380 * Check if we are after a while (cond);
7381 * If so: Ignore until the matching "do".
7382 */
7383 /* XXX */
Bram Moolenaar9e54a0e2006-04-14 20:42:25 +00007384 else if (cin_iswhileofdo_end(terminated, ind_maxparen,
7385 ind_maxcomment))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007386 {
7387 /*
7388 * Found an unterminated line after a while ();, line up
7389 * with the last one.
7390 * while (cond);
7391 * 100 + <- line up with this one
7392 * -> here;
7393 */
7394 if (lookfor == LOOKFOR_UNTERM
7395 || lookfor == LOOKFOR_ENUM_OR_INIT)
7396 {
7397 if (cont_amount > 0)
7398 amount = cont_amount;
7399 else
7400 amount += ind_continuation;
7401 break;
7402 }
7403
7404 if (whilelevel == 0)
7405 {
7406 lookfor = LOOKFOR_TERM;
7407 amount = get_indent(); /* XXX */
7408 if (theline[0] == '{')
7409 amount += ind_open_extra;
7410 }
7411 ++whilelevel;
7412 }
7413
7414 /*
7415 * We are after a "normal" statement.
7416 * If we had another statement we can stop now and use the
7417 * indent of that other statement.
7418 * Otherwise the indent of the current statement may be used,
7419 * search backwards for the next "normal" statement.
7420 */
7421 else
7422 {
7423 /*
7424 * Skip single break line, if before a switch label. It
7425 * may be lined up with the case label.
7426 */
7427 if (lookfor == LOOKFOR_NOBREAK
7428 && cin_isbreak(skipwhite(ml_get_curline())))
7429 {
7430 lookfor = LOOKFOR_ANY;
7431 continue;
7432 }
7433
7434 /*
7435 * Handle "do {" line.
7436 */
7437 if (whilelevel > 0)
7438 {
7439 l = cin_skipcomment(ml_get_curline());
7440 if (cin_isdo(l))
7441 {
7442 amount = get_indent(); /* XXX */
7443 --whilelevel;
7444 continue;
7445 }
7446 }
7447
7448 /*
7449 * Found a terminated line above an unterminated line. Add
7450 * the amount for a continuation line.
7451 * x = 1;
7452 * y = foo +
7453 * -> here;
7454 * or
7455 * int x = 1;
7456 * int foo,
7457 * -> here;
7458 */
7459 if (lookfor == LOOKFOR_UNTERM
7460 || lookfor == LOOKFOR_ENUM_OR_INIT)
7461 {
7462 if (cont_amount > 0)
7463 amount = cont_amount;
7464 else
7465 amount += ind_continuation;
7466 break;
7467 }
7468
7469 /*
7470 * Found a terminated line above a terminated line or "if"
7471 * etc. line. Use the amount of the line below us.
7472 * x = 1; x = 1;
7473 * if (asdf) y = 2;
7474 * while (asdf) ->here;
7475 * here;
7476 * ->foo;
7477 */
7478 if (lookfor == LOOKFOR_TERM)
7479 {
7480 if (!lookfor_break && whilelevel == 0)
7481 break;
7482 }
7483
7484 /*
7485 * First line above the one we're indenting is terminated.
7486 * To know what needs to be done look further backward for
7487 * a terminated line.
7488 */
7489 else
7490 {
7491 /*
7492 * position the cursor over the rightmost paren, so
7493 * that matching it will take us back to the start of
7494 * the line. Helps for:
7495 * func(asdr,
7496 * asdfasdf);
7497 * here;
7498 */
7499term_again:
7500 l = ml_get_curline();
7501 if (find_last_paren(l, '(', ')')
7502 && (trypos = find_match_paren(ind_maxparen,
7503 ind_maxcomment)) != NULL)
7504 {
7505 /*
7506 * Check if we are on a case label now. This is
7507 * handled above.
7508 * case xx: if ( asdf &&
7509 * asdf)
7510 */
7511 curwin->w_cursor.lnum = trypos->lnum;
7512 l = ml_get_curline();
7513 if (cin_iscase(l) || cin_isscopedecl(l))
7514 {
7515 ++curwin->w_cursor.lnum;
7516 continue;
7517 }
7518 }
7519
7520 /* When aligning with the case statement, don't align
7521 * with a statement after it.
7522 * case 1: { <-- don't use this { position
7523 * stat;
7524 * }
7525 * case 2:
7526 * stat;
7527 * }
7528 */
7529 iscase = (ind_keep_case_label && cin_iscase(l));
7530
7531 /*
7532 * Get indent and pointer to text for current line,
7533 * ignoring any jump label.
7534 */
7535 amount = skip_label(curwin->w_cursor.lnum,
7536 &l, ind_maxcomment);
7537
7538 if (theline[0] == '{')
7539 amount += ind_open_extra;
7540 /* See remark above: "Only add ind_open_extra.." */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007541 l = skipwhite(l);
7542 if (*l == '{')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007543 amount -= ind_open_extra;
7544 lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
7545
7546 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007547 * When a terminated line starts with "else" skip to
7548 * the matching "if":
7549 * else 3;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00007550 * indent this;
Bram Moolenaar18144c82006-04-12 21:52:12 +00007551 * Need to use the scope of this "else". XXX
7552 * If whilelevel != 0 continue looking for a "do {".
7553 */
7554 if (lookfor == LOOKFOR_TERM
7555 && *l != '}'
7556 && cin_iselse(l)
7557 && whilelevel == 0)
7558 {
7559 if ((trypos = find_start_brace(ind_maxcomment))
7560 == NULL
7561 || find_match(LOOKFOR_IF, trypos->lnum,
7562 ind_maxparen, ind_maxcomment) == FAIL)
7563 break;
7564 continue;
7565 }
7566
7567 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007568 * If we're at the end of a block, skip to the start of
7569 * that block.
7570 */
7571 curwin->w_cursor.col = 0;
7572 if (*cin_skipcomment(l) == '}'
7573 && (trypos = find_start_brace(ind_maxcomment))
7574 != NULL) /* XXX */
7575 {
7576 curwin->w_cursor.lnum = trypos->lnum;
7577 /* if not "else {" check for terminated again */
7578 /* but skip block for "} else {" */
7579 l = cin_skipcomment(ml_get_curline());
7580 if (*l == '}' || !cin_iselse(l))
7581 goto term_again;
7582 ++curwin->w_cursor.lnum;
7583 }
7584 }
7585 }
7586 }
7587 }
7588 }
7589
7590 /* add extra indent for a comment */
7591 if (cin_iscomment(theline))
7592 amount += ind_comment;
7593 }
7594
7595 /*
7596 * ok -- we're not inside any sort of structure at all!
7597 *
7598 * this means we're at the top level, and everything should
7599 * basically just match where the previous line is, except
7600 * for the lines immediately following a function declaration,
7601 * which are K&R-style parameters and need to be indented.
7602 */
7603 else
7604 {
7605 /*
7606 * if our line starts with an open brace, forget about any
7607 * prevailing indent and make sure it looks like the start
7608 * of a function
7609 */
7610
7611 if (theline[0] == '{')
7612 {
7613 amount = ind_first_open;
7614 }
7615
7616 /*
7617 * If the NEXT line is a function declaration, the current
7618 * line needs to be indented as a function type spec.
7619 * Don't do this if the current line looks like a comment
7620 * or if the current line is terminated, ie. ends in ';'.
7621 */
7622 else if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
7623 && !cin_nocode(theline)
7624 && !cin_ends_in(theline, (char_u *)":", NULL)
7625 && !cin_ends_in(theline, (char_u *)",", NULL)
7626 && cin_isfuncdecl(NULL, cur_curpos.lnum + 1)
7627 && !cin_isterminated(theline, FALSE, TRUE))
7628 {
7629 amount = ind_func_type;
7630 }
7631 else
7632 {
7633 amount = 0;
7634 curwin->w_cursor = cur_curpos;
7635
7636 /* search backwards until we find something we recognize */
7637
7638 while (curwin->w_cursor.lnum > 1)
7639 {
7640 curwin->w_cursor.lnum--;
7641 curwin->w_cursor.col = 0;
7642
7643 l = ml_get_curline();
7644
7645 /*
7646 * If we're in a comment now, skip to the start of the comment.
7647 */ /* XXX */
7648 if ((trypos = find_start_comment(ind_maxcomment)) != NULL)
7649 {
7650 curwin->w_cursor.lnum = trypos->lnum + 1;
7651 continue;
7652 }
7653
7654 /*
Bram Moolenaar18144c82006-04-12 21:52:12 +00007655 * Are we at the start of a cpp base class declaration or
7656 * constructor initialization?
Bram Moolenaar071d4272004-06-13 20:20:40 +00007657 */ /* XXX */
Bram Moolenaar18144c82006-04-12 21:52:12 +00007658 n = FALSE;
7659 if (ind_cpp_baseclass != 0 && theline[0] != '{')
7660 {
7661 n = cin_is_cpp_baseclass(l, &col);
7662 l = ml_get_curline();
7663 }
7664 if (n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 {
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007666 /* XXX */
7667 amount = get_baseclass_amount(col, ind_maxparen,
7668 ind_maxcomment, ind_cpp_baseclass);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007669 break;
7670 }
7671
7672 /*
7673 * Skip preprocessor directives and blank lines.
7674 */
7675 if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum))
7676 continue;
7677
7678 if (cin_nocode(l))
7679 continue;
7680
7681 /*
7682 * If the previous line ends in ',', use one level of
7683 * indentation:
7684 * int foo,
7685 * bar;
7686 * do this before checking for '}' in case of eg.
7687 * enum foobar
7688 * {
7689 * ...
7690 * } foo,
7691 * bar;
7692 */
7693 n = 0;
7694 if (cin_ends_in(l, (char_u *)",", NULL)
7695 || (*l != NUL && (n = l[STRLEN(l) - 1]) == '\\'))
7696 {
7697 /* take us back to opening paren */
7698 if (find_last_paren(l, '(', ')')
7699 && (trypos = find_match_paren(ind_maxparen,
7700 ind_maxcomment)) != NULL)
7701 curwin->w_cursor.lnum = trypos->lnum;
7702
7703 /* For a line ending in ',' that is a continuation line go
7704 * back to the first line with a backslash:
7705 * char *foo = "bla\
7706 * bla",
7707 * here;
7708 */
7709 while (n == 0 && curwin->w_cursor.lnum > 1)
7710 {
7711 l = ml_get(curwin->w_cursor.lnum - 1);
7712 if (*l == NUL || l[STRLEN(l) - 1] != '\\')
7713 break;
7714 --curwin->w_cursor.lnum;
7715 }
7716
7717 amount = get_indent(); /* XXX */
7718
7719 if (amount == 0)
7720 amount = cin_first_id_amount();
7721 if (amount == 0)
7722 amount = ind_continuation;
7723 break;
7724 }
7725
7726 /*
7727 * If the line looks like a function declaration, and we're
7728 * not in a comment, put it the left margin.
7729 */
7730 if (cin_isfuncdecl(NULL, cur_curpos.lnum)) /* XXX */
7731 break;
7732 l = ml_get_curline();
7733
7734 /*
7735 * Finding the closing '}' of a previous function. Put
7736 * current line at the left margin. For when 'cino' has "fs".
7737 */
7738 if (*skipwhite(l) == '}')
7739 break;
7740
7741 /* (matching {)
7742 * If the previous line ends on '};' (maybe followed by
7743 * comments) align at column 0. For example:
7744 * char *string_array[] = { "foo",
7745 * / * x * / "b};ar" }; / * foobar * /
7746 */
7747 if (cin_ends_in(l, (char_u *)"};", NULL))
7748 break;
7749
7750 /*
7751 * If the PREVIOUS line is a function declaration, the current
7752 * line (and the ones that follow) needs to be indented as
7753 * parameters.
7754 */
7755 if (cin_isfuncdecl(&l, curwin->w_cursor.lnum))
7756 {
7757 amount = ind_param;
7758 break;
7759 }
7760
7761 /*
7762 * If the previous line ends in ';' and the line before the
7763 * previous line ends in ',' or '\', ident to column zero:
7764 * int foo,
7765 * bar;
7766 * indent_to_0 here;
7767 */
Bram Moolenaar7fc904b2006-04-13 20:37:35 +00007768 if (cin_ends_in(l, (char_u *)";", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007769 {
7770 l = ml_get(curwin->w_cursor.lnum - 1);
7771 if (cin_ends_in(l, (char_u *)",", NULL)
7772 || (*l != NUL && l[STRLEN(l) - 1] == '\\'))
7773 break;
7774 l = ml_get_curline();
7775 }
7776
7777 /*
7778 * Doesn't look like anything interesting -- so just
7779 * use the indent of this line.
7780 *
7781 * Position the cursor over the rightmost paren, so that
7782 * matching it will take us back to the start of the line.
7783 */
7784 find_last_paren(l, '(', ')');
7785
7786 if ((trypos = find_match_paren(ind_maxparen,
7787 ind_maxcomment)) != NULL)
7788 curwin->w_cursor.lnum = trypos->lnum;
7789 amount = get_indent(); /* XXX */
7790 break;
7791 }
7792
7793 /* add extra indent for a comment */
7794 if (cin_iscomment(theline))
7795 amount += ind_comment;
7796
7797 /* add extra indent if the previous line ended in a backslash:
7798 * "asdfasdf\
7799 * here";
7800 * char *foo = "asdf\
7801 * here";
7802 */
7803 if (cur_curpos.lnum > 1)
7804 {
7805 l = ml_get(cur_curpos.lnum - 1);
7806 if (*l != NUL && l[STRLEN(l) - 1] == '\\')
7807 {
7808 cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
7809 if (cur_amount > 0)
7810 amount = cur_amount;
7811 else if (cur_amount == 0)
7812 amount += ind_continuation;
7813 }
7814 }
7815 }
7816 }
7817
7818theend:
7819 /* put the cursor back where it belongs */
7820 curwin->w_cursor = cur_curpos;
7821
7822 vim_free(linecopy);
7823
7824 if (amount < 0)
7825 return 0;
7826 return amount;
7827}
7828
7829 static int
7830find_match(lookfor, ourscope, ind_maxparen, ind_maxcomment)
7831 int lookfor;
7832 linenr_T ourscope;
7833 int ind_maxparen;
7834 int ind_maxcomment;
7835{
7836 char_u *look;
7837 pos_T *theirscope;
7838 char_u *mightbeif;
7839 int elselevel;
7840 int whilelevel;
7841
7842 if (lookfor == LOOKFOR_IF)
7843 {
7844 elselevel = 1;
7845 whilelevel = 0;
7846 }
7847 else
7848 {
7849 elselevel = 0;
7850 whilelevel = 1;
7851 }
7852
7853 curwin->w_cursor.col = 0;
7854
7855 while (curwin->w_cursor.lnum > ourscope + 1)
7856 {
7857 curwin->w_cursor.lnum--;
7858 curwin->w_cursor.col = 0;
7859
7860 look = cin_skipcomment(ml_get_curline());
7861 if (cin_iselse(look)
7862 || cin_isif(look)
7863 || cin_isdo(look) /* XXX */
7864 || cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7865 {
7866 /*
7867 * if we've gone outside the braces entirely,
7868 * we must be out of scope...
7869 */
7870 theirscope = find_start_brace(ind_maxcomment); /* XXX */
7871 if (theirscope == NULL)
7872 break;
7873
7874 /*
7875 * and if the brace enclosing this is further
7876 * back than the one enclosing the else, we're
7877 * out of luck too.
7878 */
7879 if (theirscope->lnum < ourscope)
7880 break;
7881
7882 /*
7883 * and if they're enclosed in a *deeper* brace,
7884 * then we can ignore it because it's in a
7885 * different scope...
7886 */
7887 if (theirscope->lnum > ourscope)
7888 continue;
7889
7890 /*
7891 * if it was an "else" (that's not an "else if")
7892 * then we need to go back to another if, so
7893 * increment elselevel
7894 */
7895 look = cin_skipcomment(ml_get_curline());
7896 if (cin_iselse(look))
7897 {
7898 mightbeif = cin_skipcomment(look + 4);
7899 if (!cin_isif(mightbeif))
7900 ++elselevel;
7901 continue;
7902 }
7903
7904 /*
7905 * if it was a "while" then we need to go back to
7906 * another "do", so increment whilelevel. XXX
7907 */
7908 if (cin_iswhileofdo(look, curwin->w_cursor.lnum, ind_maxparen))
7909 {
7910 ++whilelevel;
7911 continue;
7912 }
7913
7914 /* If it's an "if" decrement elselevel */
7915 look = cin_skipcomment(ml_get_curline());
7916 if (cin_isif(look))
7917 {
7918 elselevel--;
7919 /*
7920 * When looking for an "if" ignore "while"s that
7921 * get in the way.
7922 */
7923 if (elselevel == 0 && lookfor == LOOKFOR_IF)
7924 whilelevel = 0;
7925 }
7926
7927 /* If it's a "do" decrement whilelevel */
7928 if (cin_isdo(look))
7929 whilelevel--;
7930
7931 /*
7932 * if we've used up all the elses, then
7933 * this must be the if that we want!
7934 * match the indent level of that if.
7935 */
7936 if (elselevel <= 0 && whilelevel <= 0)
7937 {
7938 return OK;
7939 }
7940 }
7941 }
7942 return FAIL;
7943}
7944
7945# if defined(FEAT_EVAL) || defined(PROTO)
7946/*
7947 * Get indent level from 'indentexpr'.
7948 */
7949 int
7950get_expr_indent()
7951{
7952 int indent;
7953 pos_T pos;
7954 int save_State;
Bram Moolenaard1f56e62006-02-22 21:25:37 +00007955 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
7956 OPT_LOCAL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007957
7958 pos = curwin->w_cursor;
7959 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00007960 if (use_sandbox)
7961 ++sandbox;
7962 ++textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007963 indent = eval_to_number(curbuf->b_p_inde);
Bram Moolenaarb71eaae2006-01-20 23:10:18 +00007964 if (use_sandbox)
7965 --sandbox;
7966 --textlock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007967
7968 /* Restore the cursor position so that 'indentexpr' doesn't need to.
7969 * Pretend to be in Insert mode, allow cursor past end of line for "o"
7970 * command. */
7971 save_State = State;
7972 State = INSERT;
7973 curwin->w_cursor = pos;
7974 check_cursor();
7975 State = save_State;
7976
7977 /* If there is an error, just keep the current indent. */
7978 if (indent < 0)
7979 indent = get_indent();
7980
7981 return indent;
7982}
7983# endif
7984
7985#endif /* FEAT_CINDENT */
7986
7987#if defined(FEAT_LISP) || defined(PROTO)
7988
7989static int lisp_match __ARGS((char_u *p));
7990
7991 static int
7992lisp_match(p)
7993 char_u *p;
7994{
7995 char_u buf[LSIZE];
7996 int len;
7997 char_u *word = p_lispwords;
7998
7999 while (*word != NUL)
8000 {
8001 (void)copy_option_part(&word, buf, LSIZE, ",");
8002 len = (int)STRLEN(buf);
8003 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
8004 return TRUE;
8005 }
8006 return FALSE;
8007}
8008
8009/*
8010 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
8011 * The incompatible newer method is quite a bit better at indenting
8012 * code in lisp-like languages than the traditional one; it's still
8013 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
8014 *
8015 * TODO:
8016 * Findmatch() should be adapted for lisp, also to make showmatch
8017 * work correctly: now (v5.3) it seems all C/C++ oriented:
8018 * - it does not recognize the #\( and #\) notations as character literals
8019 * - it doesn't know about comments starting with a semicolon
8020 * - it incorrectly interprets '(' as a character literal
8021 * All this messes up get_lisp_indent in some rare cases.
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008022 * Update from Sergey Khorev:
8023 * I tried to fix the first two issues.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008024 */
8025 int
8026get_lisp_indent()
8027{
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008028 pos_T *pos, realpos, paren;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008029 int amount;
8030 char_u *that;
8031 colnr_T col;
8032 colnr_T firsttry;
8033 int parencount, quotecount;
8034 int vi_lisp;
8035
8036 /* Set vi_lisp to use the vi-compatible method */
8037 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
8038
8039 realpos = curwin->w_cursor;
8040 curwin->w_cursor.col = 0;
8041
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008042 if ((pos = findmatch(NULL, '(')) == NULL)
8043 pos = findmatch(NULL, '[');
8044 else
8045 {
8046 paren = *pos;
8047 pos = findmatch(NULL, '[');
8048 if (pos == NULL || ltp(pos, &paren))
8049 pos = &paren;
8050 }
8051 if (pos != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008052 {
8053 /* Extra trick: Take the indent of the first previous non-white
8054 * line that is at the same () level. */
8055 amount = -1;
8056 parencount = 0;
8057
8058 while (--curwin->w_cursor.lnum >= pos->lnum)
8059 {
8060 if (linewhite(curwin->w_cursor.lnum))
8061 continue;
8062 for (that = ml_get_curline(); *that != NUL; ++that)
8063 {
8064 if (*that == ';')
8065 {
8066 while (*(that + 1) != NUL)
8067 ++that;
8068 continue;
8069 }
8070 if (*that == '\\')
8071 {
8072 if (*(that + 1) != NUL)
8073 ++that;
8074 continue;
8075 }
8076 if (*that == '"' && *(that + 1) != NUL)
8077 {
Bram Moolenaar15ff6c12006-09-15 18:18:09 +00008078 while (*++that && *that != '"')
8079 {
8080 /* skipping escaped characters in the string */
8081 if (*that == '\\')
8082 {
8083 if (*++that == NUL)
8084 break;
8085 if (that[1] == NUL)
8086 {
8087 ++that;
8088 break;
8089 }
8090 }
8091 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008092 }
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008093 if (*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008094 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008095 else if (*that == ')' || *that == ']')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096 --parencount;
8097 }
8098 if (parencount == 0)
8099 {
8100 amount = get_indent();
8101 break;
8102 }
8103 }
8104
8105 if (amount == -1)
8106 {
8107 curwin->w_cursor.lnum = pos->lnum;
8108 curwin->w_cursor.col = pos->col;
8109 col = pos->col;
8110
8111 that = ml_get_curline();
8112
8113 if (vi_lisp && get_indent() == 0)
8114 amount = 2;
8115 else
8116 {
8117 amount = 0;
8118 while (*that && col)
8119 {
8120 amount += lbr_chartabsize_adv(&that, (colnr_T)amount);
8121 col--;
8122 }
8123
8124 /*
8125 * Some keywords require "body" indenting rules (the
8126 * non-standard-lisp ones are Scheme special forms):
8127 *
8128 * (let ((a 1)) instead (let ((a 1))
8129 * (...)) of (...))
8130 */
8131
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008132 if (!vi_lisp && (*that == '(' || *that == '[')
8133 && lisp_match(that + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008134 amount += 2;
8135 else
8136 {
8137 that++;
8138 amount++;
8139 firsttry = amount;
8140
8141 while (vim_iswhite(*that))
8142 {
8143 amount += lbr_chartabsize(that, (colnr_T)amount);
8144 ++that;
8145 }
8146
8147 if (*that && *that != ';') /* not a comment line */
8148 {
8149 /* test *that != '(' to accomodate first let/do
8150 * argument if it is more than one line */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008151 if (!vi_lisp && *that != '(' && *that != '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008152 firsttry++;
8153
8154 parencount = 0;
8155 quotecount = 0;
8156
8157 if (vi_lisp
8158 || (*that != '"'
8159 && *that != '\''
8160 && *that != '#'
8161 && (*that < '0' || *that > '9')))
8162 {
8163 while (*that
8164 && (!vim_iswhite(*that)
8165 || quotecount
8166 || parencount)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008167 && (!((*that == '(' || *that == '[')
Bram Moolenaar071d4272004-06-13 20:20:40 +00008168 && !quotecount
8169 && !parencount
8170 && vi_lisp)))
8171 {
8172 if (*that == '"')
8173 quotecount = !quotecount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008174 if ((*that == '(' || *that == '[')
8175 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008176 ++parencount;
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008177 if ((*that == ')' || *that == ']')
8178 && !quotecount)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008179 --parencount;
8180 if (*that == '\\' && *(that+1) != NUL)
8181 amount += lbr_chartabsize_adv(&that,
8182 (colnr_T)amount);
8183 amount += lbr_chartabsize_adv(&that,
8184 (colnr_T)amount);
8185 }
8186 }
8187 while (vim_iswhite(*that))
8188 {
8189 amount += lbr_chartabsize(that, (colnr_T)amount);
8190 that++;
8191 }
8192 if (!*that || *that == ';')
8193 amount = firsttry;
8194 }
8195 }
8196 }
8197 }
8198 }
8199 else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00008200 amount = 0; /* no matching '(' or '[' found, use zero indent */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008201
8202 curwin->w_cursor = realpos;
8203
8204 return amount;
8205}
8206#endif /* FEAT_LISP */
8207
8208 void
8209prepare_to_exit()
8210{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008211#if defined(SIGHUP) && defined(SIG_IGN)
8212 /* Ignore SIGHUP, because a dropped connection causes a read error, which
8213 * makes Vim exit and then handling SIGHUP causes various reentrance
8214 * problems. */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00008215 signal(SIGHUP, SIG_IGN);
8216#endif
8217
Bram Moolenaar071d4272004-06-13 20:20:40 +00008218#ifdef FEAT_GUI
8219 if (gui.in_use)
8220 {
8221 gui.dying = TRUE;
8222 out_trash(); /* trash any pending output */
8223 }
8224 else
8225#endif
8226 {
8227 windgoto((int)Rows - 1, 0);
8228
8229 /*
8230 * Switch terminal mode back now, so messages end up on the "normal"
8231 * screen (if there are two screens).
8232 */
8233 settmode(TMODE_COOK);
8234#ifdef WIN3264
8235 if (can_end_termcap_mode(FALSE) == TRUE)
8236#endif
8237 stoptermcap();
8238 out_flush();
8239 }
8240}
8241
8242/*
8243 * Preserve files and exit.
8244 * When called IObuff must contain a message.
8245 */
8246 void
8247preserve_exit()
8248{
8249 buf_T *buf;
8250
8251 prepare_to_exit();
8252
Bram Moolenaar4770d092006-01-12 23:22:24 +00008253 /* Setting this will prevent free() calls. That avoids calling free()
8254 * recursively when free() was invoked with a bad pointer. */
8255 really_exiting = TRUE;
8256
Bram Moolenaar071d4272004-06-13 20:20:40 +00008257 out_str(IObuff);
8258 screen_start(); /* don't know where cursor is now */
8259 out_flush();
8260
8261 ml_close_notmod(); /* close all not-modified buffers */
8262
8263 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8264 {
8265 if (buf->b_ml.ml_mfp != NULL && buf->b_ml.ml_mfp->mf_fname != NULL)
8266 {
8267 OUT_STR(_("Vim: preserving files...\n"));
8268 screen_start(); /* don't know where cursor is now */
8269 out_flush();
8270 ml_sync_all(FALSE, FALSE); /* preserve all swap files */
8271 break;
8272 }
8273 }
8274
8275 ml_close_all(FALSE); /* close all memfiles, without deleting */
8276
8277 OUT_STR(_("Vim: Finished.\n"));
8278
8279 getout(1);
8280}
8281
8282/*
8283 * return TRUE if "fname" exists.
8284 */
8285 int
8286vim_fexists(fname)
8287 char_u *fname;
8288{
8289 struct stat st;
8290
8291 if (mch_stat((char *)fname, &st))
8292 return FALSE;
8293 return TRUE;
8294}
8295
8296/*
8297 * Check for CTRL-C pressed, but only once in a while.
8298 * Should be used instead of ui_breakcheck() for functions that check for
8299 * each line in the file. Calling ui_breakcheck() each time takes too much
8300 * time, because it can be a system call.
8301 */
8302
8303#ifndef BREAKCHECK_SKIP
8304# ifdef FEAT_GUI /* assume the GUI only runs on fast computers */
8305# define BREAKCHECK_SKIP 200
8306# else
8307# define BREAKCHECK_SKIP 32
8308# endif
8309#endif
8310
8311static int breakcheck_count = 0;
8312
8313 void
8314line_breakcheck()
8315{
8316 if (++breakcheck_count >= BREAKCHECK_SKIP)
8317 {
8318 breakcheck_count = 0;
8319 ui_breakcheck();
8320 }
8321}
8322
8323/*
8324 * Like line_breakcheck() but check 10 times less often.
8325 */
8326 void
8327fast_breakcheck()
8328{
8329 if (++breakcheck_count >= BREAKCHECK_SKIP * 10)
8330 {
8331 breakcheck_count = 0;
8332 ui_breakcheck();
8333 }
8334}
8335
8336/*
8337 * Expand wildcards. Calls gen_expand_wildcards() and removes files matching
8338 * 'wildignore'.
Bram Moolenaar362e1a32006-03-06 23:29:24 +00008339 * Returns OK or FAIL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008340 */
8341 int
8342expand_wildcards(num_pat, pat, num_file, file, flags)
8343 int num_pat; /* number of input patterns */
8344 char_u **pat; /* array of input patterns */
8345 int *num_file; /* resulting number of files */
8346 char_u ***file; /* array of resulting files */
8347 int flags; /* EW_DIR, etc. */
8348{
8349 int retval;
8350 int i, j;
8351 char_u *p;
8352 int non_suf_match; /* number without matching suffix */
8353
8354 retval = gen_expand_wildcards(num_pat, pat, num_file, file, flags);
8355
8356 /* When keeping all matches, return here */
8357 if (flags & EW_KEEPALL)
8358 return retval;
8359
8360#ifdef FEAT_WILDIGN
8361 /*
8362 * Remove names that match 'wildignore'.
8363 */
8364 if (*p_wig)
8365 {
8366 char_u *ffname;
8367
8368 /* check all files in (*file)[] */
8369 for (i = 0; i < *num_file; ++i)
8370 {
8371 ffname = FullName_save((*file)[i], FALSE);
8372 if (ffname == NULL) /* out of memory */
8373 break;
8374# ifdef VMS
8375 vms_remove_version(ffname);
8376# endif
8377 if (match_file_list(p_wig, (*file)[i], ffname))
8378 {
8379 /* remove this matching file from the list */
8380 vim_free((*file)[i]);
8381 for (j = i; j + 1 < *num_file; ++j)
8382 (*file)[j] = (*file)[j + 1];
8383 --*num_file;
8384 --i;
8385 }
8386 vim_free(ffname);
8387 }
8388 }
8389#endif
8390
8391 /*
8392 * Move the names where 'suffixes' match to the end.
8393 */
8394 if (*num_file > 1)
8395 {
8396 non_suf_match = 0;
8397 for (i = 0; i < *num_file; ++i)
8398 {
8399 if (!match_suffix((*file)[i]))
8400 {
8401 /*
8402 * Move the name without matching suffix to the front
8403 * of the list.
8404 */
8405 p = (*file)[i];
8406 for (j = i; j > non_suf_match; --j)
8407 (*file)[j] = (*file)[j - 1];
8408 (*file)[non_suf_match++] = p;
8409 }
8410 }
8411 }
8412
8413 return retval;
8414}
8415
8416/*
8417 * Return TRUE if "fname" matches with an entry in 'suffixes'.
8418 */
8419 int
8420match_suffix(fname)
8421 char_u *fname;
8422{
8423 int fnamelen, setsuflen;
8424 char_u *setsuf;
8425#define MAXSUFLEN 30 /* maximum length of a file suffix */
8426 char_u suf_buf[MAXSUFLEN];
8427
8428 fnamelen = (int)STRLEN(fname);
8429 setsuflen = 0;
8430 for (setsuf = p_su; *setsuf; )
8431 {
8432 setsuflen = copy_option_part(&setsuf, suf_buf, MAXSUFLEN, ".,");
8433 if (fnamelen >= setsuflen
8434 && fnamencmp(suf_buf, fname + fnamelen - setsuflen,
8435 (size_t)setsuflen) == 0)
8436 break;
8437 setsuflen = 0;
8438 }
8439 return (setsuflen != 0);
8440}
8441
8442#if !defined(NO_EXPANDPATH) || defined(PROTO)
8443
8444# ifdef VIM_BACKTICK
8445static int vim_backtick __ARGS((char_u *p));
8446static int expand_backtick __ARGS((garray_T *gap, char_u *pat, int flags));
8447# endif
8448
8449# if defined(MSDOS) || defined(FEAT_GUI_W16) || defined(WIN3264)
8450/*
8451 * File name expansion code for MS-DOS, Win16 and Win32. It's here because
8452 * it's shared between these systems.
8453 */
8454# if defined(DJGPP) || defined(PROTO)
8455# define _cdecl /* DJGPP doesn't have this */
8456# else
8457# ifdef __BORLANDC__
8458# define _cdecl _RTLENTRYF
8459# endif
8460# endif
8461
8462/*
8463 * comparison function for qsort in dos_expandpath()
8464 */
8465 static int _cdecl
8466pstrcmp(const void *a, const void *b)
8467{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00008468 return (pathcmp(*(char **)a, *(char **)b, -1));
Bram Moolenaar071d4272004-06-13 20:20:40 +00008469}
8470
8471# ifndef WIN3264
8472 static void
8473namelowcpy(
8474 char_u *d,
8475 char_u *s)
8476{
8477# ifdef DJGPP
8478 if (USE_LONG_FNAME) /* don't lower case on Windows 95/NT systems */
8479 while (*s)
8480 *d++ = *s++;
8481 else
8482# endif
8483 while (*s)
8484 *d++ = TOLOWER_LOC(*s++);
8485 *d = NUL;
8486}
8487# endif
8488
8489/*
Bram Moolenaar231334e2005-07-25 20:46:57 +00008490 * Recursively expand one path component into all matching files and/or
8491 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008492 * Return the number of matches found.
8493 * "path" has backslashes before chars that are not to be expanded, starting
8494 * at "path[wildoff]".
Bram Moolenaar231334e2005-07-25 20:46:57 +00008495 * Return the number of matches found.
8496 * NOTE: much of this is identical to unix_expandpath(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00008497 */
8498 static int
8499dos_expandpath(
8500 garray_T *gap,
8501 char_u *path,
8502 int wildoff,
Bram Moolenaar231334e2005-07-25 20:46:57 +00008503 int flags, /* EW_* flags */
8504 int didstar) /* expaneded "**" once already */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008505{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008506 char_u *buf;
8507 char_u *path_end;
8508 char_u *p, *s, *e;
8509 int start_len = gap->ga_len;
8510 char_u *pat;
8511 regmatch_T regmatch;
8512 int starts_with_dot;
8513 int matches;
8514 int len;
8515 int starstar = FALSE;
8516 static int stardepth = 0; /* depth for "**" expansion */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008517#ifdef WIN3264
8518 WIN32_FIND_DATA fb;
8519 HANDLE hFind = (HANDLE)0;
8520# ifdef FEAT_MBYTE
8521 WIN32_FIND_DATAW wfb;
8522 WCHAR *wn = NULL; /* UCS-2 name, NULL when not used. */
8523# endif
8524#else
8525 struct ffblk fb;
8526#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008527 char_u *matchname;
Bram Moolenaar231334e2005-07-25 20:46:57 +00008528 int ok;
8529
8530 /* Expanding "**" may take a long time, check for CTRL-C. */
8531 if (stardepth > 0)
8532 {
8533 ui_breakcheck();
8534 if (got_int)
8535 return 0;
8536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008537
8538 /* make room for file name */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008539 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008540 if (buf == NULL)
8541 return 0;
8542
8543 /*
8544 * Find the first part in the path name that contains a wildcard or a ~1.
8545 * Copy it into buf, including the preceding characters.
8546 */
8547 p = buf;
8548 s = buf;
8549 e = NULL;
8550 path_end = path;
8551 while (*path_end != NUL)
8552 {
8553 /* May ignore a wildcard that has a backslash before it; it will
8554 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8555 if (path_end >= path + wildoff && rem_backslash(path_end))
8556 *p++ = *path_end++;
8557 else if (*path_end == '\\' || *path_end == ':' || *path_end == '/')
8558 {
8559 if (e != NULL)
8560 break;
8561 s = p + 1;
8562 }
8563 else if (path_end >= path + wildoff
8564 && vim_strchr((char_u *)"*?[~", *path_end) != NULL)
8565 e = p;
8566#ifdef FEAT_MBYTE
8567 if (has_mbyte)
8568 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008569 len = (*mb_ptr2len)(path_end);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008570 STRNCPY(p, path_end, len);
8571 p += len;
8572 path_end += len;
8573 }
8574 else
8575#endif
8576 *p++ = *path_end++;
8577 }
8578 e = p;
8579 *e = NUL;
8580
8581 /* now we have one wildcard component between s and e */
8582 /* Remove backslashes between "wildoff" and the start of the wildcard
8583 * component. */
8584 for (p = buf + wildoff; p < s; ++p)
8585 if (rem_backslash(p))
8586 {
8587 STRCPY(p, p + 1);
8588 --e;
8589 --s;
8590 }
8591
Bram Moolenaar231334e2005-07-25 20:46:57 +00008592 /* Check for "**" between "s" and "e". */
8593 for (p = s; p < e; ++p)
8594 if (p[0] == '*' && p[1] == '*')
8595 starstar = TRUE;
8596
Bram Moolenaar071d4272004-06-13 20:20:40 +00008597 starts_with_dot = (*s == '.');
8598 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8599 if (pat == NULL)
8600 {
8601 vim_free(buf);
8602 return 0;
8603 }
8604
8605 /* compile the regexp into a program */
8606 regmatch.rm_ic = TRUE; /* Always ignore case */
8607 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8608 vim_free(pat);
8609
8610 if (regmatch.regprog == NULL)
8611 {
8612 vim_free(buf);
8613 return 0;
8614 }
8615
8616 /* remember the pattern or file name being looked for */
8617 matchname = vim_strsave(s);
8618
Bram Moolenaar231334e2005-07-25 20:46:57 +00008619 /* If "**" is by itself, this is the first time we encounter it and more
8620 * is following then find matches without any directory. */
8621 if (!didstar && stardepth < 100 && starstar && e - s == 2
8622 && *path_end == '/')
8623 {
8624 STRCPY(s, path_end + 1);
8625 ++stardepth;
8626 (void)dos_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8627 --stardepth;
8628 }
8629
Bram Moolenaar071d4272004-06-13 20:20:40 +00008630 /* Scan all files in the directory with "dir/ *.*" */
8631 STRCPY(s, "*.*");
8632#ifdef WIN3264
8633# ifdef FEAT_MBYTE
8634 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
8635 {
8636 /* The active codepage differs from 'encoding'. Attempt using the
8637 * wide function. If it fails because it is not implemented fall back
8638 * to the non-wide version (for Windows 98) */
8639 wn = enc_to_ucs2(buf, NULL);
8640 if (wn != NULL)
8641 {
8642 hFind = FindFirstFileW(wn, &wfb);
8643 if (hFind == INVALID_HANDLE_VALUE
8644 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
8645 {
8646 vim_free(wn);
8647 wn = NULL;
8648 }
8649 }
8650 }
8651
8652 if (wn == NULL)
8653# endif
8654 hFind = FindFirstFile(buf, &fb);
8655 ok = (hFind != INVALID_HANDLE_VALUE);
8656#else
8657 /* If we are expanding wildcards we try both files and directories */
8658 ok = (findfirst((char *)buf, &fb,
8659 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8660#endif
8661
8662 while (ok)
8663 {
8664#ifdef WIN3264
8665# ifdef FEAT_MBYTE
8666 if (wn != NULL)
8667 p = ucs2_to_enc(wfb.cFileName, NULL); /* p is allocated here */
8668 else
8669# endif
8670 p = (char_u *)fb.cFileName;
8671#else
8672 p = (char_u *)fb.ff_name;
8673#endif
8674 /* Ignore entries starting with a dot, unless when asked for. Accept
8675 * all entries found with "matchname". */
8676 if ((p[0] != '.' || starts_with_dot)
8677 && (matchname == NULL
8678 || vim_regexec(&regmatch, p, (colnr_T)0)))
8679 {
8680#ifdef WIN3264
8681 STRCPY(s, p);
8682#else
8683 namelowcpy(s, p);
8684#endif
8685 len = (int)STRLEN(buf);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008686
8687 if (starstar && stardepth < 100)
8688 {
8689 /* For "**" in the pattern first go deeper in the tree to
8690 * find matches. */
8691 STRCPY(buf + len, "/**");
8692 STRCPY(buf + len + 3, path_end);
8693 ++stardepth;
8694 (void)dos_expandpath(gap, buf, len + 1, flags, TRUE);
8695 --stardepth;
8696 }
8697
Bram Moolenaar071d4272004-06-13 20:20:40 +00008698 STRCPY(buf + len, path_end);
8699 if (mch_has_exp_wildcard(path_end))
8700 {
8701 /* need to expand another component of the path */
8702 /* remove backslashes for the remaining components only */
Bram Moolenaar231334e2005-07-25 20:46:57 +00008703 (void)dos_expandpath(gap, buf, len + 1, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008704 }
8705 else
8706 {
8707 /* no more wildcards, check if there is a match */
8708 /* remove backslashes for the remaining components only */
8709 if (*path_end != 0)
8710 backslash_halve(buf + len + 1);
8711 if (mch_getperm(buf) >= 0) /* add existing file */
8712 addfile(gap, buf, flags);
8713 }
8714 }
8715
8716#ifdef WIN3264
8717# ifdef FEAT_MBYTE
8718 if (wn != NULL)
8719 {
8720 vim_free(p);
8721 ok = FindNextFileW(hFind, &wfb);
8722 }
8723 else
8724# endif
8725 ok = FindNextFile(hFind, &fb);
8726#else
8727 ok = (findnext(&fb) == 0);
8728#endif
8729
8730 /* If no more matches and no match was used, try expanding the name
8731 * itself. Finds the long name of a short filename. */
8732 if (!ok && matchname != NULL && gap->ga_len == start_len)
8733 {
8734 STRCPY(s, matchname);
8735#ifdef WIN3264
8736 FindClose(hFind);
8737# ifdef FEAT_MBYTE
8738 if (wn != NULL)
8739 {
8740 vim_free(wn);
8741 wn = enc_to_ucs2(buf, NULL);
8742 if (wn != NULL)
8743 hFind = FindFirstFileW(wn, &wfb);
8744 }
8745 if (wn == NULL)
8746# endif
8747 hFind = FindFirstFile(buf, &fb);
8748 ok = (hFind != INVALID_HANDLE_VALUE);
8749#else
8750 ok = (findfirst((char *)buf, &fb,
8751 (*path_end != NUL || (flags & EW_DIR)) ? FA_DIREC : 0) == 0);
8752#endif
8753 vim_free(matchname);
8754 matchname = NULL;
8755 }
8756 }
8757
8758#ifdef WIN3264
8759 FindClose(hFind);
8760# ifdef FEAT_MBYTE
8761 vim_free(wn);
8762# endif
8763#endif
8764 vim_free(buf);
8765 vim_free(regmatch.regprog);
8766 vim_free(matchname);
8767
8768 matches = gap->ga_len - start_len;
8769 if (matches > 0)
8770 qsort(((char_u **)gap->ga_data) + start_len, (size_t)matches,
8771 sizeof(char_u *), pstrcmp);
8772 return matches;
8773}
8774
8775 int
8776mch_expandpath(
8777 garray_T *gap,
8778 char_u *path,
8779 int flags) /* EW_* flags */
8780{
Bram Moolenaar231334e2005-07-25 20:46:57 +00008781 return dos_expandpath(gap, path, 0, flags, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008782}
8783# endif /* MSDOS || FEAT_GUI_W16 || WIN3264 */
8784
Bram Moolenaar231334e2005-07-25 20:46:57 +00008785#if (defined(UNIX) && !defined(VMS)) || defined(USE_UNIXFILENAME) \
8786 || defined(PROTO)
8787/*
8788 * Unix style wildcard expansion code.
8789 * It's here because it's used both for Unix and Mac.
8790 */
8791static int pstrcmp __ARGS((const void *, const void *));
8792
8793 static int
8794pstrcmp(a, b)
8795 const void *a, *b;
8796{
8797 return (pathcmp(*(char **)a, *(char **)b, -1));
8798}
8799
8800/*
8801 * Recursively expand one path component into all matching files and/or
8802 * directories. Adds matches to "gap". Handles "*", "?", "[a-z]", "**", etc.
8803 * "path" has backslashes before chars that are not to be expanded, starting
8804 * at "path + wildoff".
8805 * Return the number of matches found.
8806 * NOTE: much of this is identical to dos_expandpath(), keep in sync!
8807 */
8808 int
8809unix_expandpath(gap, path, wildoff, flags, didstar)
8810 garray_T *gap;
8811 char_u *path;
8812 int wildoff;
8813 int flags; /* EW_* flags */
8814 int didstar; /* expanded "**" once already */
8815{
8816 char_u *buf;
8817 char_u *path_end;
8818 char_u *p, *s, *e;
8819 int start_len = gap->ga_len;
8820 char_u *pat;
8821 regmatch_T regmatch;
8822 int starts_with_dot;
8823 int matches;
8824 int len;
8825 int starstar = FALSE;
8826 static int stardepth = 0; /* depth for "**" expansion */
8827
8828 DIR *dirp;
8829 struct dirent *dp;
8830
8831 /* Expanding "**" may take a long time, check for CTRL-C. */
8832 if (stardepth > 0)
8833 {
8834 ui_breakcheck();
8835 if (got_int)
8836 return 0;
8837 }
8838
8839 /* make room for file name */
8840 buf = alloc((int)STRLEN(path) + BASENAMELEN + 5);
8841 if (buf == NULL)
8842 return 0;
8843
8844 /*
8845 * Find the first part in the path name that contains a wildcard.
8846 * Copy it into "buf", including the preceding characters.
8847 */
8848 p = buf;
8849 s = buf;
8850 e = NULL;
8851 path_end = path;
8852 while (*path_end != NUL)
8853 {
8854 /* May ignore a wildcard that has a backslash before it; it will
8855 * be removed by rem_backslash() or file_pat_to_reg_pat() below. */
8856 if (path_end >= path + wildoff && rem_backslash(path_end))
8857 *p++ = *path_end++;
8858 else if (*path_end == '/')
8859 {
8860 if (e != NULL)
8861 break;
8862 s = p + 1;
8863 }
8864 else if (path_end >= path + wildoff
8865 && vim_strchr((char_u *)"*?[{~$", *path_end) != NULL)
8866 e = p;
8867#ifdef FEAT_MBYTE
8868 if (has_mbyte)
8869 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00008870 len = (*mb_ptr2len)(path_end);
Bram Moolenaar231334e2005-07-25 20:46:57 +00008871 STRNCPY(p, path_end, len);
8872 p += len;
8873 path_end += len;
8874 }
8875 else
8876#endif
8877 *p++ = *path_end++;
8878 }
8879 e = p;
8880 *e = NUL;
8881
8882 /* now we have one wildcard component between "s" and "e" */
8883 /* Remove backslashes between "wildoff" and the start of the wildcard
8884 * component. */
8885 for (p = buf + wildoff; p < s; ++p)
8886 if (rem_backslash(p))
8887 {
8888 STRCPY(p, p + 1);
8889 --e;
8890 --s;
8891 }
8892
8893 /* Check for "**" between "s" and "e". */
8894 for (p = s; p < e; ++p)
8895 if (p[0] == '*' && p[1] == '*')
8896 starstar = TRUE;
8897
8898 /* convert the file pattern to a regexp pattern */
8899 starts_with_dot = (*s == '.');
8900 pat = file_pat_to_reg_pat(s, e, NULL, FALSE);
8901 if (pat == NULL)
8902 {
8903 vim_free(buf);
8904 return 0;
8905 }
8906
8907 /* compile the regexp into a program */
Bram Moolenaarcc016f52005-12-10 20:23:46 +00008908#ifdef CASE_INSENSITIVE_FILENAME
Bram Moolenaar231334e2005-07-25 20:46:57 +00008909 regmatch.rm_ic = TRUE; /* Behave like Terminal.app */
8910#else
8911 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
8912#endif
8913 regmatch.regprog = vim_regcomp(pat, RE_MAGIC);
8914 vim_free(pat);
8915
8916 if (regmatch.regprog == NULL)
8917 {
8918 vim_free(buf);
8919 return 0;
8920 }
8921
8922 /* If "**" is by itself, this is the first time we encounter it and more
8923 * is following then find matches without any directory. */
8924 if (!didstar && stardepth < 100 && starstar && e - s == 2
8925 && *path_end == '/')
8926 {
8927 STRCPY(s, path_end + 1);
8928 ++stardepth;
8929 (void)unix_expandpath(gap, buf, (int)(s - buf), flags, TRUE);
8930 --stardepth;
8931 }
8932
8933 /* open the directory for scanning */
8934 *s = NUL;
8935 dirp = opendir(*buf == NUL ? "." : (char *)buf);
8936
8937 /* Find all matching entries */
8938 if (dirp != NULL)
8939 {
8940 for (;;)
8941 {
8942 dp = readdir(dirp);
8943 if (dp == NULL)
8944 break;
8945 if ((dp->d_name[0] != '.' || starts_with_dot)
8946 && vim_regexec(&regmatch, (char_u *)dp->d_name, (colnr_T)0))
8947 {
8948 STRCPY(s, dp->d_name);
8949 len = STRLEN(buf);
8950
8951 if (starstar && stardepth < 100)
8952 {
8953 /* For "**" in the pattern first go deeper in the tree to
8954 * find matches. */
8955 STRCPY(buf + len, "/**");
8956 STRCPY(buf + len + 3, path_end);
8957 ++stardepth;
8958 (void)unix_expandpath(gap, buf, len + 1, flags, TRUE);
8959 --stardepth;
8960 }
8961
8962 STRCPY(buf + len, path_end);
8963 if (mch_has_exp_wildcard(path_end)) /* handle more wildcards */
8964 {
8965 /* need to expand another component of the path */
8966 /* remove backslashes for the remaining components only */
8967 (void)unix_expandpath(gap, buf, len + 1, flags, FALSE);
8968 }
8969 else
8970 {
8971 /* no more wildcards, check if there is a match */
8972 /* remove backslashes for the remaining components only */
8973 if (*path_end != NUL)
8974 backslash_halve(buf + len + 1);
8975 if (mch_getperm(buf) >= 0) /* add existing file */
8976 {
Bram Moolenaar95e9b492006-03-15 23:04:43 +00008977#ifdef MACOS_CONVERT
Bram Moolenaar231334e2005-07-25 20:46:57 +00008978 size_t precomp_len = STRLEN(buf)+1;
8979 char_u *precomp_buf =
8980 mac_precompose_path(buf, precomp_len, &precomp_len);
Bram Moolenaar95e9b492006-03-15 23:04:43 +00008981
Bram Moolenaar231334e2005-07-25 20:46:57 +00008982 if (precomp_buf)
8983 {
8984 mch_memmove(buf, precomp_buf, precomp_len);
8985 vim_free(precomp_buf);
8986 }
8987#endif
8988 addfile(gap, buf, flags);
8989 }
8990 }
8991 }
8992 }
8993
8994 closedir(dirp);
8995 }
8996
8997 vim_free(buf);
8998 vim_free(regmatch.regprog);
8999
9000 matches = gap->ga_len - start_len;
9001 if (matches > 0)
9002 qsort(((char_u **)gap->ga_data) + start_len, matches,
9003 sizeof(char_u *), pstrcmp);
9004 return matches;
9005}
9006#endif
9007
Bram Moolenaar071d4272004-06-13 20:20:40 +00009008/*
9009 * Generic wildcard expansion code.
9010 *
9011 * Characters in "pat" that should not be expanded must be preceded with a
9012 * backslash. E.g., "/path\ with\ spaces/my\*star*"
9013 *
9014 * Return FAIL when no single file was found. In this case "num_file" is not
9015 * set, and "file" may contain an error message.
9016 * Return OK when some files found. "num_file" is set to the number of
9017 * matches, "file" to the array of matches. Call FreeWild() later.
9018 */
9019 int
9020gen_expand_wildcards(num_pat, pat, num_file, file, flags)
9021 int num_pat; /* number of input patterns */
9022 char_u **pat; /* array of input patterns */
9023 int *num_file; /* resulting number of files */
9024 char_u ***file; /* array of resulting files */
9025 int flags; /* EW_* flags */
9026{
9027 int i;
9028 garray_T ga;
9029 char_u *p;
9030 static int recursive = FALSE;
9031 int add_pat;
9032
9033 /*
9034 * expand_env() is called to expand things like "~user". If this fails,
9035 * it calls ExpandOne(), which brings us back here. In this case, always
9036 * call the machine specific expansion function, if possible. Otherwise,
9037 * return FAIL.
9038 */
9039 if (recursive)
9040#ifdef SPECIAL_WILDCHAR
9041 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9042#else
9043 return FAIL;
9044#endif
9045
9046#ifdef SPECIAL_WILDCHAR
9047 /*
9048 * If there are any special wildcard characters which we cannot handle
9049 * here, call machine specific function for all the expansion. This
9050 * avoids starting the shell for each argument separately.
9051 * For `=expr` do use the internal function.
9052 */
9053 for (i = 0; i < num_pat; i++)
9054 {
9055 if (vim_strpbrk(pat[i], (char_u *)SPECIAL_WILDCHAR) != NULL
9056# ifdef VIM_BACKTICK
9057 && !(vim_backtick(pat[i]) && pat[i][1] == '=')
9058# endif
9059 )
9060 return mch_expand_wildcards(num_pat, pat, num_file, file, flags);
9061 }
9062#endif
9063
9064 recursive = TRUE;
9065
9066 /*
9067 * The matching file names are stored in a growarray. Init it empty.
9068 */
9069 ga_init2(&ga, (int)sizeof(char_u *), 30);
9070
9071 for (i = 0; i < num_pat; ++i)
9072 {
9073 add_pat = -1;
9074 p = pat[i];
9075
9076#ifdef VIM_BACKTICK
9077 if (vim_backtick(p))
9078 add_pat = expand_backtick(&ga, p, flags);
9079 else
9080#endif
9081 {
9082 /*
9083 * First expand environment variables, "~/" and "~user/".
9084 */
9085 if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9086 {
9087 p = expand_env_save(p);
9088 if (p == NULL)
9089 p = pat[i];
9090#ifdef UNIX
9091 /*
9092 * On Unix, if expand_env() can't expand an environment
9093 * variable, use the shell to do that. Discard previously
9094 * found file names and start all over again.
9095 */
9096 else if (vim_strpbrk(p, (char_u *)"$~") != NULL)
9097 {
9098 vim_free(p);
9099 ga_clear(&ga);
9100 i = mch_expand_wildcards(num_pat, pat, num_file, file,
9101 flags);
9102 recursive = FALSE;
9103 return i;
9104 }
9105#endif
9106 }
9107
9108 /*
9109 * If there are wildcards: Expand file names and add each match to
9110 * the list. If there is no match, and EW_NOTFOUND is given, add
9111 * the pattern.
9112 * If there are no wildcards: Add the file name if it exists or
9113 * when EW_NOTFOUND is given.
9114 */
9115 if (mch_has_exp_wildcard(p))
9116 add_pat = mch_expandpath(&ga, p, flags);
9117 }
9118
9119 if (add_pat == -1 || (add_pat == 0 && (flags & EW_NOTFOUND)))
9120 {
9121 char_u *t = backslash_halve_save(p);
9122
9123#if defined(MACOS_CLASSIC)
9124 slash_to_colon(t);
9125#endif
9126 /* When EW_NOTFOUND is used, always add files and dirs. Makes
9127 * "vim c:/" work. */
9128 if (flags & EW_NOTFOUND)
9129 addfile(&ga, t, flags | EW_DIR | EW_FILE);
9130 else if (mch_getperm(t) >= 0)
9131 addfile(&ga, t, flags);
9132 vim_free(t);
9133 }
9134
9135 if (p != pat[i])
9136 vim_free(p);
9137 }
9138
9139 *num_file = ga.ga_len;
9140 *file = (ga.ga_data != NULL) ? (char_u **)ga.ga_data : (char_u **)"";
9141
9142 recursive = FALSE;
9143
9144 return (ga.ga_data != NULL) ? OK : FAIL;
9145}
9146
9147# ifdef VIM_BACKTICK
9148
9149/*
9150 * Return TRUE if we can expand this backtick thing here.
9151 */
9152 static int
9153vim_backtick(p)
9154 char_u *p;
9155{
9156 return (*p == '`' && *(p + 1) != NUL && *(p + STRLEN(p) - 1) == '`');
9157}
9158
9159/*
9160 * Expand an item in `backticks` by executing it as a command.
9161 * Currently only works when pat[] starts and ends with a `.
9162 * Returns number of file names found.
9163 */
9164 static int
9165expand_backtick(gap, pat, flags)
9166 garray_T *gap;
9167 char_u *pat;
9168 int flags; /* EW_* flags */
9169{
9170 char_u *p;
9171 char_u *cmd;
9172 char_u *buffer;
9173 int cnt = 0;
9174 int i;
9175
9176 /* Create the command: lop off the backticks. */
9177 cmd = vim_strnsave(pat + 1, (int)STRLEN(pat) - 2);
9178 if (cmd == NULL)
9179 return 0;
9180
9181#ifdef FEAT_EVAL
9182 if (*cmd == '=') /* `={expr}`: Expand expression */
Bram Moolenaar362e1a32006-03-06 23:29:24 +00009183 buffer = eval_to_string(cmd + 1, &p, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009184 else
9185#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009186 buffer = get_cmd_output(cmd, NULL,
9187 (flags & EW_SILENT) ? SHELL_SILENT : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009188 vim_free(cmd);
9189 if (buffer == NULL)
9190 return 0;
9191
9192 cmd = buffer;
9193 while (*cmd != NUL)
9194 {
9195 cmd = skipwhite(cmd); /* skip over white space */
9196 p = cmd;
9197 while (*p != NUL && *p != '\r' && *p != '\n') /* skip over entry */
9198 ++p;
9199 /* add an entry if it is not empty */
9200 if (p > cmd)
9201 {
9202 i = *p;
9203 *p = NUL;
9204 addfile(gap, cmd, flags);
9205 *p = i;
9206 ++cnt;
9207 }
9208 cmd = p;
9209 while (*cmd != NUL && (*cmd == '\r' || *cmd == '\n'))
9210 ++cmd;
9211 }
9212
9213 vim_free(buffer);
9214 return cnt;
9215}
9216# endif /* VIM_BACKTICK */
9217
9218/*
9219 * Add a file to a file list. Accepted flags:
9220 * EW_DIR add directories
9221 * EW_FILE add files
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009222 * EW_EXEC add executable files
Bram Moolenaar071d4272004-06-13 20:20:40 +00009223 * EW_NOTFOUND add even when it doesn't exist
9224 * EW_ADDSLASH add slash after directory name
9225 */
9226 void
9227addfile(gap, f, flags)
9228 garray_T *gap;
9229 char_u *f; /* filename */
9230 int flags;
9231{
9232 char_u *p;
9233 int isdir;
9234
9235 /* if the file/dir doesn't exist, may not add it */
9236 if (!(flags & EW_NOTFOUND) && mch_getperm(f) < 0)
9237 return;
9238
9239#ifdef FNAME_ILLEGAL
9240 /* if the file/dir contains illegal characters, don't add it */
9241 if (vim_strpbrk(f, (char_u *)FNAME_ILLEGAL) != NULL)
9242 return;
9243#endif
9244
9245 isdir = mch_isdir(f);
9246 if ((isdir && !(flags & EW_DIR)) || (!isdir && !(flags & EW_FILE)))
9247 return;
9248
Bram Moolenaar1f35bf92006-03-07 22:38:47 +00009249 /* If the file isn't executable, may not add it. Do accept directories. */
9250 if (!isdir && (flags & EW_EXEC) && !mch_can_exe(f))
9251 return;
9252
Bram Moolenaar071d4272004-06-13 20:20:40 +00009253 /* Make room for another item in the file list. */
9254 if (ga_grow(gap, 1) == FAIL)
9255 return;
9256
9257 p = alloc((unsigned)(STRLEN(f) + 1 + isdir));
9258 if (p == NULL)
9259 return;
9260
9261 STRCPY(p, f);
9262#ifdef BACKSLASH_IN_FILENAME
9263 slash_adjust(p);
9264#endif
9265 /*
9266 * Append a slash or backslash after directory names if none is present.
9267 */
9268#ifndef DONT_ADD_PATHSEP_TO_DIR
9269 if (isdir && (flags & EW_ADDSLASH))
9270 add_pathsep(p);
9271#endif
9272 ((char_u **)gap->ga_data)[gap->ga_len++] = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009273}
9274#endif /* !NO_EXPANDPATH */
9275
9276#if defined(VIM_BACKTICK) || defined(FEAT_EVAL) || defined(PROTO)
9277
9278#ifndef SEEK_SET
9279# define SEEK_SET 0
9280#endif
9281#ifndef SEEK_END
9282# define SEEK_END 2
9283#endif
9284
9285/*
9286 * Get the stdout of an external command.
9287 * Returns an allocated string, or NULL for error.
9288 */
9289 char_u *
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009290get_cmd_output(cmd, infile, flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009291 char_u *cmd;
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009292 char_u *infile; /* optional input file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009293 int flags; /* can be SHELL_SILENT */
9294{
9295 char_u *tempname;
9296 char_u *command;
9297 char_u *buffer = NULL;
9298 int len;
9299 int i = 0;
9300 FILE *fd;
9301
9302 if (check_restricted() || check_secure())
9303 return NULL;
9304
9305 /* get a name for the temp file */
9306 if ((tempname = vim_tempname('o')) == NULL)
9307 {
9308 EMSG(_(e_notmp));
9309 return NULL;
9310 }
9311
9312 /* Add the redirection stuff */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00009313 command = make_filter_cmd(cmd, infile, tempname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009314 if (command == NULL)
9315 goto done;
9316
9317 /*
9318 * Call the shell to execute the command (errors are ignored).
9319 * Don't check timestamps here.
9320 */
9321 ++no_check_timestamps;
9322 call_shell(command, SHELL_DOOUT | SHELL_EXPAND | flags);
9323 --no_check_timestamps;
9324
9325 vim_free(command);
9326
9327 /*
9328 * read the names from the file into memory
9329 */
9330# ifdef VMS
9331 /* created temporary file is not allways readable as binary */
9332 fd = mch_fopen((char *)tempname, "r");
9333# else
9334 fd = mch_fopen((char *)tempname, READBIN);
9335# endif
9336
9337 if (fd == NULL)
9338 {
9339 EMSG2(_(e_notopen), tempname);
9340 goto done;
9341 }
9342
9343 fseek(fd, 0L, SEEK_END);
9344 len = ftell(fd); /* get size of temp file */
9345 fseek(fd, 0L, SEEK_SET);
9346
9347 buffer = alloc(len + 1);
9348 if (buffer != NULL)
9349 i = (int)fread((char *)buffer, (size_t)1, (size_t)len, fd);
9350 fclose(fd);
9351 mch_remove(tempname);
9352 if (buffer == NULL)
9353 goto done;
9354#ifdef VMS
9355 len = i; /* VMS doesn't give us what we asked for... */
9356#endif
9357 if (i != len)
9358 {
9359 EMSG2(_(e_notread), tempname);
9360 vim_free(buffer);
9361 buffer = NULL;
9362 }
9363 else
9364 buffer[len] = '\0'; /* make sure the buffer is terminated */
9365
9366done:
9367 vim_free(tempname);
9368 return buffer;
9369}
9370#endif
9371
9372/*
9373 * Free the list of files returned by expand_wildcards() or other expansion
9374 * functions.
9375 */
9376 void
9377FreeWild(count, files)
9378 int count;
9379 char_u **files;
9380{
Bram Moolenaarfc1421e2006-04-20 22:17:20 +00009381 if (count <= 0 || files == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009382 return;
9383#if defined(__EMX__) && defined(__ALWAYS_HAS_TRAILING_NULL_POINTER) /* XXX */
9384 /*
9385 * Is this still OK for when other functions than expand_wildcards() have
9386 * been used???
9387 */
9388 _fnexplodefree((char **)files);
9389#else
9390 while (count--)
9391 vim_free(files[count]);
9392 vim_free(files);
9393#endif
9394}
9395
9396/*
9397 * return TRUE when need to go to Insert mode because of 'insertmode'.
9398 * Don't do this when still processing a command or a mapping.
9399 * Don't do this when inside a ":normal" command.
9400 */
9401 int
9402goto_im()
9403{
9404 return (p_im && stuff_empty() && typebuf_typed());
9405}