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